diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1b2954b --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/dist/ +/build/ +/store diff --git a/README.md b/README.md new file mode 100644 index 0000000..89a22f1 --- /dev/null +++ b/README.md @@ -0,0 +1,7 @@ +## PG EDITOR + +Project developed in 2014 + +![1](icons/image.png?raw=true "1") + +https://sourceforge.net/projects/portugol-editor/ diff --git a/SyntaxPane/.gitignore b/SyntaxPane/.gitignore new file mode 100644 index 0000000..08bc1a3 --- /dev/null +++ b/SyntaxPane/.gitignore @@ -0,0 +1,6 @@ +target/ +lib_managed/ +src_managed/ +project/boot/ +.idea/ +.idea_modules/ diff --git a/SyntaxPane/CHANGELOG.txt b/SyntaxPane/CHANGELOG.txt new file mode 100644 index 0000000..eb90417 --- /dev/null +++ b/SyntaxPane/CHANGELOG.txt @@ -0,0 +1,106 @@ +Version 1.1.3 + * Fixes various issues with line-numbers-ruler + * Fixes some keyboard shortcuts on Mac and Linux + * Fixes a NPE when not using scroll-pane + * Fixes a bug with undo-buffer and copy/paste + +Version 1.1.0 + * Rename to SyntaxPane + * Use fully qualified package name de.sciss.syntaxpane + * Enabling/disabling of Undo/Redo actions + * Fix multiple OS X shortcuts + * Fix some Scala related problems + * All tracking of document's dirty state + +Original JSyntaxPane Changelog: + +Version 0.9.5 - Java Reflection Completions additions + * Configuration class overhaul. Each kit now has its own Configuration file + which merges the superclass(es) Configurations. + * Usable Reflect Completions Dialog (Java with F1 or Menu) + * Java ENTER key responds properly to multi line comments + * Font can be changed for each Kit + * Kits for XHTML and Xpath added. XHTML has a simple Preview Action. + * Added Execute Script to JavaScript (can also be used for Groovy if Groovy + Scripting support is installed properly). + * Hotkeys for actions are displayed in Popup Menus + * Word Completion action can also do CamelCase matches + * Smart Home Action (and Smart Home Extend Selection) + * Enhanced JavaScript support. Issue 115 + * Better Undo grouping + * Replace Dialog Enhancement. Only for updatedable editors and added single replace. + * Added append method to SyntaxDocument + * Fixed Issue 130 - Compound Undo on multiple lines. +Version 0.9.4 - IntelliSense additions + * Adding IntelliSense to Java with simple List of selectable keywords + * Added Toggle Comment Actions using Control SLASH + * Fixed Issue 47. + * Added Clojure, Scala, DOS Batch and 'nix bash support + * Added Configurable Popup menus with default Tango Desktop icons + * Added configurable format for the CaretMonitor class + * Toggle Comments Action selects the lines affected after being performed + * Added multi-line support in ActionUtils.insertMagicString method. + * GotoLine dialog responds to ESC key +Version 0.9.3 - Start of scripts for the document: + * Added new methods getLine() to SyntaxDocument + * SyntaxDocument getIndexOf methods deprecated, use getMatchers instead + * Added Line Numbering to Java + * Added CaretMonitor Class + * Merged Find And Replace dialogs into one. + * Created SyntaxComponent interface and have all UI components implement + that interface. DefaultSyntaxKit will use config.properties class to + dynamically install these components. + * Added Right Margin option and Single Color Selection Options + * Added Python, C and C++ Support + * Added Ruby Syntax Support + * Fixed Issue 37 (NPE for LineNumbersRuler) + * Fixed Issue 39 (Highlighting Tokens overrides selection highlights) + * Fixed some JavaDoc comments. + * Fixed Line Numbers being displayed for the height of the editor and now + just for the actual available lines. + * Fixed Margin typo in all project. Issue 43 + * Changing Actions to be more configurable: + * SyntaxActions renamed to ActionUtils + * Removed all inner classes from SyntaxActions + * Will create new SyntaxAction interface that will allow dynamic addition + actions (in the addKeyActions of DefaultSyntaxKit + * Added Text AA property to SyntaxView +Version 0.9.2: + * Fixing Java Indentation and Un-Indentation Actions + * Added and used (in the Tester) clearUndoes on the SyntaxDocument + * Added Basic JFlex Syntax + * Added getContentTypes to DefaultSyntaxKit to get all registered + ContentTypes. This is now also used in the SyntaxTester instead of + hardcoding the types. + * Cleanup and optimization of Lexers by removing duplicate Java Code + (replaced with Regex OR) + * Removed calls to deprecated calls in SyntaxView + * Modified the SyntaxDOcument to override the fireXXX methods and parse + the document at that time instead of overriding the inserUpdate method. + This fixes issue 24. + * Added Groovy GString expression highlights + * Removed getLanguages method from Lexer interface and implementations. + * Added WARNING and ERROR TokenTypes and added their default styles. + * Moved Keymaps and install methods to SyntaxKits instead of the Lexers + * Removed deprecated methods from SyntaxActions class + * Split SyntaxActions into new package and moved inner classes to the new + package + * Added Token HighLighter to Java + * Added Pairs Highlighter to Java + * Token class made immutable (all final fields) + * Added Find and Replace Dialogs and Action to Java (mapped to C-F and + C-H ) + * Added pair matching to XML tags + * Added CDATA matching and pair highlights for XML + * Added Comment Pair Highlighting in XML + * Fixed highlighting with selections so the selection always appears + * Merged Find and Replace Dialogs into one + * Fixed issue 33 (undoable to add new line after final closing brace for + Java) + * Added Groovy Multi-Line strings and fixed Comments as Regex issue. + * Fixes to empty find text field causing NPE +Version 0.9.1 + * Fixed empty strings in XML syntax Issue 29 + * Fixed TAL lexer using incorrect package name +Version 0.9.0 + * Initial version after major overhaul \ No newline at end of file diff --git a/SyntaxPane/README.md b/SyntaxPane/README.md new file mode 100644 index 0000000..dce4a53 --- /dev/null +++ b/SyntaxPane/README.md @@ -0,0 +1,22 @@ +# SyntaxPane + +SyntaxPane is an extension to Java Swing's JEditorKit component which adds syntax highlighting support for various languages, including Scala and Java. The original project JSyntaxPane can be found [on google-code](http://code.google.com/p/jsyntaxpane/). This is a fork from the 0.9.6 branch. + +The original project is (C)opyright by Ayman Al-Sairafi and released under the [Apache License, Version 2.0](http://github.com/Sciss/JSyntaxPane/blob/master/licenses/JSyntaxPane-License.txt). + +All changes, reworkings and extensions in SyntaxPane (C)opyright 2011–2014 by Hanns Holger Rutz. Released under that same license. + +## linking + +The group-id and version have been adjusted to use my name space at Maven Central: + + "de.sciss" % "syntaxpane" % v + +The current version `v` is `"1.1.3"` + +## building + +JSyntaxPane builds with sbt 0.13. The source code is purely Java at the moment, so no Scala compilation is run. The project uses the [sbt-jflex](https://github.com/sbt/sbt-jflex) plugin v0.1-SNAPSHOT, which in turn uses [JFlex](http://jflex.de/) 1.4.3 to generate the lexer Java sources for the supported languages. + +To build run `sbt compile`. To run a demo application, run `sbt run`. + diff --git a/SyntaxPane/build.sbt b/SyntaxPane/build.sbt new file mode 100644 index 0000000..85cdcbe --- /dev/null +++ b/SyntaxPane/build.sbt @@ -0,0 +1,56 @@ +name := "SyntaxPane" + +version := "1.1.4-SNAPSHOT" + +organization := "de.sciss" + +description := "An extension of Java Swing's JEditorKit that supports syntax highlighting for several languages." + +homepage := Some(url("https://github.com/Sciss/" + name.value)) + +licenses := Seq("Apache 2.0 License" -> url("http://www.apache.org/licenses/LICENSE-2.0.txt")) + +scalaVersion := "2.11.2" + +crossPaths := false // this is just a Java project right now! + +// retrieveManaged := true + +autoScalaLibrary := false + +mainClass in Compile := Some("de.sciss.syntaxpane.SyntaxTester") + +javacOptions in (Compile, compile) ++= Seq("-g", "-source", "1.6", "-target", "1.6") + +// ---- JFlex ---- + +seq(jflexSettings: _*) + +// ---- publishing ---- + +publishMavenStyle := true + +publishTo := + Some(if (isSnapshot.value) + "Sonatype Snapshots" at "https://oss.sonatype.org/content/repositories/snapshots" + else + "Sonatype Releases" at "https://oss.sonatype.org/service/local/staging/deploy/maven2" + ) + +publishArtifact in Test := false + +pomIncludeRepository := { _ => false } + +pomExtra := { val n = name.value + + git@github.com:Sciss/{n}.git + scm:git:git@github.com:Sciss/{n}.git + + + + sciss + Hanns Holger Rutz + http://www.sciss.de + + +} diff --git a/SyntaxPane/licenses/JSyntaxPane-License.txt b/SyntaxPane/licenses/JSyntaxPane-License.txt new file mode 100644 index 0000000..7926399 --- /dev/null +++ b/SyntaxPane/licenses/JSyntaxPane-License.txt @@ -0,0 +1,71 @@ +/* + * JSyntaxPane + * + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +Apache License + +Version 2.0, January 2004 + +http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + +"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. + +"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. + +"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. + +"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. + +"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. + +"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). + +"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. + +"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." + +"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: + + You must give any other recipients of the Work or Derivative Works a copy of this License; and + + You must cause any modified files to carry prominent notices stating that You changed the files; and + + You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and + + If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/SyntaxPane/project/build.properties b/SyntaxPane/project/build.properties new file mode 100644 index 0000000..64abd37 --- /dev/null +++ b/SyntaxPane/project/build.properties @@ -0,0 +1 @@ +sbt.version=0.13.6 diff --git a/SyntaxPane/project/plugins.sbt b/SyntaxPane/project/plugins.sbt new file mode 100644 index 0000000..d0e0f9f --- /dev/null +++ b/SyntaxPane/project/plugins.sbt @@ -0,0 +1 @@ +addSbtPlugin("de.sciss" % "sbt-jflex" % "0.3.0") diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/CompoundUndoManager.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/CompoundUndoManager.java new file mode 100644 index 0000000..2565922 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/CompoundUndoManager.java @@ -0,0 +1,179 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * Copyright 2013-2014 Hanns Holger Rutz. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane; + +import javax.swing.event.UndoableEditEvent; +import javax.swing.text.AbstractDocument; +import javax.swing.text.AbstractDocument.DefaultDocumentEvent; +import javax.swing.undo.*; + +/** + * A revised UndoManager that groups undos based on positions. If the change is relatively next to the + * previous change, like when continuous typing, then the undoes are grouped together. + * + * This is customized from the + * + * http://www.camick.com/java/source/CompoundUndoManager.java + * + * from the blog: + * + * http://tips4java.wordpress.com/2008/10/27/compound-undo-manager/ + * + * @author Ayman Al-Sairafi, Hanns Holger Rutz + */ +public class CompoundUndoManager extends UndoManager { + private final SyntaxDocument doc; + + private CompoundEdit compoundEdit; + // This allows us to start combining operations. + // it will be reset after the first change. + private boolean startCombine = false; + // This holds the start of the last line edited, if edits are on multiple + // lines, then they will not be combined. + private int lastLine = -1; + + public CompoundUndoManager(SyntaxDocument doc) { + this.doc = doc; + doc.addUndoableEditListener(this); + lastLine = doc.getStartPosition().getOffset(); + } + + /** + * Whenever an UndoableEdit happens the edit will either be absorbed + * by the current compound edit or a new compound edit will be started + */ + @Override + public void undoableEditHappened(UndoableEditEvent e) { + // Start a new compound edit + + AbstractDocument.DefaultDocumentEvent docEvt = (DefaultDocumentEvent) e.getEdit(); + + if (compoundEdit == null) { + compoundEdit = startCompoundEdit(e.getEdit()); + startCombine = false; + updateDirty(); + return; + } + + int editLine = ((SyntaxDocument)docEvt.getDocument()).getLineNumberAt(docEvt.getOffset()); + + // Check for an incremental edit or backspace. + // The Change in Caret position and Document length should both be + // either 1 or -1. + if ((startCombine || Math.abs(docEvt.getLength()) == 1) && editLine == lastLine) { + compoundEdit.addEdit(e.getEdit()); + startCombine = false; + updateDirty(); + return; + } + + // Not incremental edit, end previous edit and start a new one + lastLine = editLine; + + compoundEdit.end(); + compoundEdit = startCompoundEdit(e.getEdit()); + + updateDirty(); + } + + private void updateDirty() { + doc.setCanUndo(canUndo()); + doc.setCanRedo(canRedo()); + } + + @Override + protected void undoTo(UndoableEdit edit) throws CannotUndoException { + super.undoTo(edit); + updateDirty(); + } + + @Override + public synchronized void undo() throws CannotUndoException { + super.undo(); + updateDirty(); + } + + @Override + protected void redoTo(UndoableEdit edit) throws CannotRedoException { + super.redoTo(edit); + updateDirty(); + } + + @Override + public synchronized void redo() throws CannotRedoException { + super.redo(); + updateDirty(); + } + + @Override + public synchronized void discardAllEdits() { + super.discardAllEdits(); + updateDirty(); + } + + /* + ** Each CompoundEdit will store a group of related incremental edits + ** (ie. each character typed or backspaced is an incremental edit) + */ + private CompoundEdit startCompoundEdit(UndoableEdit anEdit) { + // Track Caret and Document information of this compound edit + // AbstractDocument.DefaultDocumentEvent docEvt = (DefaultDocumentEvent) anEdit; + + // The compound edit is used to store incremental edits + + compoundEdit = new MyCompoundEdit(); + compoundEdit.addEdit(anEdit); + + // The compound edit is added to the UndoManager. All incremental + // edits stored in the compound edit will be undone/redone at once + + addEdit(compoundEdit); + + return compoundEdit; + } + + class MyCompoundEdit extends CompoundEdit { + + @Override + public boolean isInProgress() { + // in order for the canUndo() and canRedo() methods to work + // assume that the compound edit is never in progress + return false; + } + + @Override + public void undo() throws CannotUndoException { + // End the edit so future edits don't get absorbed by this edit + + if (compoundEdit != null) { + compoundEdit.end(); + } + + super.undo(); + + // Always start a new compound edit after an undo + + compoundEdit = null; + } + } + + /** + * Start to combine the next operations together. Only the next operation is combined. + * The flag is then automatically reset. + */ + public void startCombine() { + startCombine = true; + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/DefaultSyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/DefaultSyntaxKit.java new file mode 100644 index 0000000..5d1db02 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/DefaultSyntaxKit.java @@ -0,0 +1,668 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * Copyright 2013-2014 Hanns Holger Rutz. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane; + +import java.awt.Color; +import java.awt.Container; +import java.io.IOException; +import java.io.Reader; +import java.util.logging.Level; +import java.awt.Font; +import java.awt.GraphicsEnvironment; +import java.awt.Toolkit; +import java.awt.event.KeyEvent; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.WeakHashMap; +import java.util.logging.Logger; +import java.util.regex.Pattern; +import javax.swing.Action; +import javax.swing.ActionMap; +import javax.swing.BorderFactory; +import javax.swing.ImageIcon; +import javax.swing.InputMap; +import javax.swing.JButton; +import javax.swing.JCheckBoxMenuItem; +import javax.swing.JEditorPane; +import javax.swing.JMenu; +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; +import javax.swing.JToolBar; +import javax.swing.KeyStroke; +import javax.swing.text.*; + +import de.sciss.syntaxpane.actions.DefaultSyntaxAction; +import de.sciss.syntaxpane.actions.SyntaxAction; +import de.sciss.syntaxpane.components.SyntaxComponent; +import de.sciss.syntaxpane.util.Configuration; +import de.sciss.syntaxpane.util.JarServiceProvider; + +/** + * The DefaultSyntaxKit is the main entry to SyntaxPane. To use the package, just + * set the EditorKit of the EditorPane to a new instance of this class. + * + * You need to pass a proper lexer to the class. + * + * @author ayman, Hanns Holger Rutz + */ +public class DefaultSyntaxKit extends DefaultEditorKit implements ViewFactory { + + public static final String CONFIG_CARETCOLOR = "CaretColor"; + public static final String CONFIG_SELECTION = "SelectionColor"; + public static final String CONFIG_COMPONENTS = "Components"; + public static final String CONFIG_MENU = "PopupMenu"; + public static final String CONFIG_TOOLBAR = "Toolbar"; + public static final String CONFIG_TOOLBAR_ROLLOVER = "Toolbar.Buttons.Rollover"; + public static final String CONFIG_TOOLBAR_BORDER = "Toolbar.Buttons.BorderPainted"; + public static final String CONFIG_TOOLBAR_OPAQUE = "Toolbar.Buttons.Opaque"; + public static final String CONFIG_TOOLBAR_BORDER_SIZE = "Toolbar.Buttons.BorderSize"; + private static final Pattern ACTION_KEY_PATTERN = Pattern.compile("Action\\.((\\w|-)+)"); + private static final Pattern DEFAULT_ACTION_PATTERN = Pattern.compile("(DefaultAction.((\\w|-)+)).*"); + private static Font DEFAULT_FONT; + private static Set CONTENT_TYPES = new HashSet(); + private static Boolean initialized = false; + private static Map abbreviations; + private static String MENU_MASK_STRING = "control "; + private Lexer lexer; + private static final Logger LOG = Logger.getLogger(DefaultSyntaxKit.class.getName()); + private Map> editorComponents = + new WeakHashMap>(); + private Map popupMenu = + new WeakHashMap(); + /** + * Main Configuration of SyntaxPane EditorKits + */ + private static Map, Configuration> CONFIGS; + + private static final String PLATFORM_KEY; + + static { + // we only need to initialize once. + if (!initialized) { + initKit(); + } + int menuMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); + if ((menuMask & (KeyEvent.ALT_DOWN_MASK | KeyEvent.ALT_MASK)) != 0) { + MENU_MASK_STRING = "alt "; + } else if ((menuMask & (KeyEvent.META_DOWN_MASK | KeyEvent.META_MASK)) != 0) { + MENU_MASK_STRING = "meta "; + } + + String osName = System.getProperty("os.name"); + if (osName.contains("Linux")) + PLATFORM_KEY = ".LinuxKey"; + else if (osName.contains("Mac")) + PLATFORM_KEY = ".MacKey"; + else + PLATFORM_KEY = ".WindowsKey"; + } + private static final String ACTION_MENU_TEXT = "MenuText"; + + /** + * Creates a new Kit for the given language + */ + public DefaultSyntaxKit(Lexer lexer) { + super(); + this.lexer = lexer; + } + + /** + * Adds UI components to the pane + * + * @param editorPane a component to install this kit for + */ + public void addComponents(JEditorPane editorPane) { + // install the components to the editor: + String[] components = getConfig().getPropertyList(CONFIG_COMPONENTS); + for (String c : components) { + installComponent(editorPane, c); + } + } + + /** + * Creates a SyntaxComponent of the the given class name and installs it on the pane + */ + public void installComponent(JEditorPane pane, String className) { + try { + @SuppressWarnings(value = "unchecked") + Class compClass = Class.forName(className); + SyntaxComponent comp = (SyntaxComponent) compClass.newInstance(); + comp.config(getConfig()); + comp.install(pane); + if (editorComponents.get(pane) == null) { + editorComponents.put(pane, new ArrayList()); + } + editorComponents.get(pane).add(comp); + } catch (InstantiationException ex) { + LOG.log(Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) { + LOG.log(Level.SEVERE, null, ex); + } catch (ClassNotFoundException ex) { + LOG.log(Level.SEVERE, null, ex); + } + } + + /** + * Finds the SyntaxComponent with given class name that is installed + * on the given pane, then de-installs and removes it fom the + * editorComponents list + */ + public void deinstallComponent(JEditorPane pane, String className) { + for (SyntaxComponent c : editorComponents.get(pane)) { + if (c.getClass().getName().equals(className)) { + c.deinstall(pane); + editorComponents.get(pane).remove(c); + break; + } + } + } + + /** + * Checks if the component with given class-name is installed on the pane. + * + * @return true if component is installed, false otherwise + */ + public boolean isComponentInstalled(JEditorPane pane, String className) { + for (SyntaxComponent c : editorComponents.get(pane)) { + if (c.getClass().getName().equals(className)) { + return true; + } + } + return false; + } + + /** + * Toggles the component with given class-name. If component is found + * and installed, then it is uninstalled. Otherwise a new one is + * installed + * + * @return true if component was installed, false if it was removed + */ + public boolean toggleComponent(JEditorPane pane, String className) { + for (SyntaxComponent c : editorComponents.get(pane)) { + if (c.getClass().getName().equals(className)) { + c.deinstall(pane); + editorComponents.get(pane).remove(c); + return false; + } + } + installComponent(pane, className); + return true; + } + + @Override + public void read(Reader in, Document doc, int pos) + throws IOException, BadLocationException { + super.read(in, doc, pos); + // ((SyntaxDocument) doc).clearUndos(); + } + + /** + * Adds a popup menu to the editorPane if needed. + */ + public void addPopupMenu(JEditorPane editorPane) { + String[] menuItems = getConfig().getPropertyList(CONFIG_MENU); + if (menuItems == null || menuItems.length == 0) { + return; + } + popupMenu.put(editorPane, new JPopupMenu()); + JMenu stack = null; + for (String menuString : menuItems) { + + // create the Popup menu + if (menuString.equals("-")) { + popupMenu.get(editorPane).addSeparator(); + } else if (menuString.startsWith(">")) { + JMenu sub = new JMenu(menuString.substring(1)); + popupMenu.get(editorPane).add(sub); + stack = sub; + } else if (menuString.startsWith("<")) { + Container parent = stack == null ? null : stack.getParent(); + if (parent instanceof JMenu) { + stack = (JMenu) parent; + } else { + stack = null; + } + } else { + Action action = editorPane.getActionMap().get(menuString); + if (action != null) { + JMenuItem menuItem; + if (action.getValue(Action.SELECTED_KEY) != null) { + menuItem = new JCheckBoxMenuItem(action); + } else { + menuItem = new JMenuItem(action); + } + // Use our own property if it was set for the menu text + if (action.getValue(ACTION_MENU_TEXT) != null) { + menuItem.setText((String) action.getValue(ACTION_MENU_TEXT)); + } + if (stack == null) { + popupMenu.get(editorPane).add(menuItem); + } else { + stack.add(menuItem); + } + } + } + } + editorPane.setComponentPopupMenu(popupMenu.get(editorPane)); + } + + /** + * Adds all pop-up menu items to a Toolbar. You need to call the validate method + * on the toolbar after this is done to layout the buttons. + * Only Actions which have a SMALL_ICON property will be added to the toolbar + * There are three Configuration Keys that affect the appearance of the added buttons: + * CONFIG_TOOLBAR_ROLLOVER, CONFIG_TOOLBAR_BORDER, CONFIG_TOOLBAR_OPAQUE + */ + public void addToolBarActions(JEditorPane editorPane, JToolBar toolbar) { + String[] toolBarItems = getConfig().getPropertyList(CONFIG_TOOLBAR); + if (toolBarItems == null || toolBarItems.length == 0) { + toolBarItems = getConfig().getPropertyList(CONFIG_MENU); + if (toolBarItems == null || toolBarItems.length == 0) { + return; + } + } + boolean btnRolloverEnabled = getConfig().getBoolean(CONFIG_TOOLBAR_ROLLOVER, true); + boolean btnBorderPainted = getConfig().getBoolean(CONFIG_TOOLBAR_BORDER, false); + boolean btnOpaque = getConfig().getBoolean(CONFIG_TOOLBAR_OPAQUE, false); + int btnBorderSize = getConfig().getInteger(CONFIG_TOOLBAR_BORDER_SIZE, 2); + for (String menuString : toolBarItems) { + if (menuString.equals("-") || + menuString.startsWith("<") || + menuString.startsWith(">")) { + toolbar.addSeparator(); + } else { + Action action = editorPane.getActionMap().get(menuString); + if (action != null && action.getValue(Action.SMALL_ICON) != null) { + JButton b = toolbar.add(action); + b.setRolloverEnabled(btnRolloverEnabled); + b.setBorderPainted(btnBorderPainted); + b.setOpaque(btnOpaque); + b.setFocusable(false); + b.setBorder(BorderFactory.createEmptyBorder(btnBorderSize, + btnBorderSize, btnBorderSize, btnBorderSize)); + } + } + } + } + + @Override + public ViewFactory getViewFactory() { + return this; + } + + @Override + public View create(Element element) { + return new SyntaxView(element, getConfig()); + } + + /** + * Installs the View on the given EditorPane. This is called by Swing and + * can be used to do anything you need on the JEditorPane control. Here + * I set some default Actions. + */ + @Override + public void install(JEditorPane editorPane) { + super.install(editorPane); + // get our font + String fontName = getProperty("DefaultFont"); + Font font = DEFAULT_FONT; + if (fontName != null) { + font = Font.decode(fontName); + } + editorPane.setFont(font); + Configuration conf = getConfig(); + Color caretColor = conf.getColor(CONFIG_CARETCOLOR, Color.BLACK); + editorPane.setCaretColor(caretColor); + Color selectionColor = getConfig().getColor(CONFIG_SELECTION, new Color(0x99ccff)); + editorPane.setSelectionColor(selectionColor); + addActions(editorPane); + addComponents(editorPane); + addPopupMenu(editorPane); + } + + @Override + public void deinstall(JEditorPane editorPane) { + for (SyntaxComponent c : editorComponents.get(editorPane)) { + c.deinstall(editorPane); + } + editorComponents.clear(); + editorPane.getInputMap().clear(); + ActionMap m = editorPane.getActionMap(); + for (Object key : editorPane.getActionMap().keys()) { + Action a = m.get(key); + if (a instanceof SyntaxAction) { + ((SyntaxAction) a).deinstall(editorPane); + } + } + m.clear(); + } + + /** + * Adds keyboard actions to this control using the Configuration we have + * This is revised to properly use InputMap and ActionMap of the component + * instead of using the KeyMaps directly. + * + * @param editorPane the component to attach the actions to + */ + public void addActions(JEditorPane editorPane) { + InputMap imap = new InputMap(); + imap.setParent(editorPane.getInputMap()); + ActionMap amap = new ActionMap(); + amap.setParent(editorPane.getActionMap()); + + for (Configuration.StringKeyMatcher m : getConfig().getKeys(ACTION_KEY_PATTERN)) { + String[] values = Configuration.COMMA_SEPARATOR.split( + m.value); + String actionClass = values[0]; + String actionName = m.group1; + SyntaxAction action = createAction(actionClass); + // The configuration keys will need to be prefixed by Action + // to make it more readable in the Configuration files. + action.install(editorPane, getConfig(), DefaultSyntaxAction.ACTION_PREFIX + actionName); + // Add the action to the component also + amap.put(actionName, action); + // Now bind all the keys to the Action we have using the InputMap + String platformKey = getProperty(m.key + PLATFORM_KEY); + for (int i = 1; i < values.length; i++) { + String ksString = values[i].replace("menu ", MENU_MASK_STRING); + String keyStrokeString = platformKey == null ? ksString : platformKey; + KeyStroke ks = KeyStroke.getKeyStroke(keyStrokeString); + // we may have more than onr value ( for key action ), but we will use the + // last one in the single value here. This will display the key in the + // popup menus. Pretty neat. + if (ks == null) { + throw new IllegalArgumentException("Invalid KeyStroke: " + + keyStrokeString); + } + action.putValue(Action.ACCELERATOR_KEY, ks); + imap.put(ks, actionName); + } + } + + // Now configure the Default actions for better display in the popup menu + for (Configuration.StringKeyMatcher m : getConfig().getKeys(DEFAULT_ACTION_PATTERN)) { + String name = m.matcher.group(2); + Action action = editorPane.getActionMap().get(name); + if (action != null) { + configActionProperties(action, name, m.group1); + } + // The below commented block does find the keys for the default Actions + // using InputMap, however there are multiple bound keys for the + // default actions that displaying them in the menu will probably not + // be the most obvious binding + /* + for (KeyStroke key : imap.allKeys()) { + Object o = imap.get(key); + if(name.equals(o)) { + action.putValue(Action.ACCELERATOR_KEY, key); + break; + } + } + */ + } + editorPane.setActionMap(amap); + editorPane.setInputMap(JTextComponent.WHEN_FOCUSED, imap); + } + + private void configActionProperties(Action action, String actionName, String configKey) { + + // if we have an icon, then load it: + String iconLoc = getConfig().getString(configKey + ".SmallIcon", actionName + ".png"); + URL loc = this.getClass().getClassLoader().getResource(DefaultSyntaxAction.SMALL_ICONS_LOC_PREFIX + iconLoc); + if (loc != null) { + ImageIcon i = new ImageIcon(loc); + action.putValue(Action.SMALL_ICON, i); + } + // Set the menu text. Use the Action.NAME property, unless it is + // already set. + // The NAME would be set for default actions, and we should not change those names. + // so we will put another property and use it for the menu text + String name = getProperty(configKey + ".MenuText"); + if (action.getValue(Action.NAME) == null) { + action.putValue(Action.NAME, name); + } else { + action.putValue(ACTION_MENU_TEXT, name); + } + // Set the menu tooltips + String shortDesc = getProperty(configKey + ".ToolTip"); + if (shortDesc != null) { + action.putValue(Action.SHORT_DESCRIPTION, shortDesc); + } else { + action.putValue(Action.SHORT_DESCRIPTION, name); + } + } + + private SyntaxAction createAction(String actionClassName) { + SyntaxAction action; + try { + Class clazz = Class.forName(actionClassName); + action = (SyntaxAction) clazz.newInstance(); + } catch (InstantiationException ex) { + throw new IllegalArgumentException("Cannot create action class: " + + actionClassName + ". Ensure it has default constructor.", ex); + } catch (IllegalAccessException ex) { + throw new IllegalArgumentException("Cannot create action class: " + + actionClassName, ex); + } catch (ClassNotFoundException ex) { + throw new IllegalArgumentException("Cannot create action class: " + + actionClassName, ex); + } catch (ClassCastException ex) { + throw new IllegalArgumentException("Cannot create action class: " + + actionClassName, ex); + } + return action; + } + + /** + * This is called by Swing to create a Document for the JEditorPane document + * This may be called before you actually get a reference to the control. + * We use it here to create a proper lexer and pass it to the + * SyntaxDocument we return. + */ + @Override + public Document createDefaultDocument() { + return new SyntaxDocument(lexer); + } + + /** + * This is called to initialize the list of Lexers we have. + * You can call this at initialization, or it will be called when needed. + * The method will also add the appropriate EditorKit classes to the + * corresponding ContentType of the JEditorPane. After this is called, + * you can simply call the editor.setContentType("text/java") on the + * control and you will be done. + */ + public synchronized static void initKit() { + // attempt to find a suitable default font + String defaultFont = getConfig(DefaultSyntaxKit.class).getString("DefaultFont"); + if (defaultFont != null) { + DEFAULT_FONT = Font.decode(defaultFont); + } else { + GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); + String[] fonts = ge.getAvailableFontFamilyNames(); + Arrays.sort(fonts); + if (Arrays.binarySearch(fonts, "Courier New") >= 0) { + DEFAULT_FONT = new Font("Courier New", Font.PLAIN, 12); + } else if (Arrays.binarySearch(fonts, "Courier") >= 0) { + DEFAULT_FONT = new Font("Courier", Font.PLAIN, 12); + } else if (Arrays.binarySearch(fonts, "Monospaced") >= 0) { + DEFAULT_FONT = new Font("Monospaced", Font.PLAIN, 13); + } + } + + // read the Default Kits and their associated types + Properties kitsForTypes = JarServiceProvider.readProperties("de/sciss/syntaxpane/kitsfortypes"); + for (Map.Entry e : kitsForTypes.entrySet()) { + String type = e.getKey().toString(); + String className = e.getValue().toString(); + registerContentType(type, className); + } + initialized = true; + } + + /** + * Registers the given content type to use the given class name as its kit + * When this is called, an entry is added into the private HashMap of the + * registered editors kits. This is needed so that the SyntaxPane library + * has it's own registration of all the EditorKits + */ + public static void registerContentType(String type, String className) { + try { + // ensure the class is available and that it does supply a no args + // constructor. This saves debugging later if the class-name is incorrect + // or does not behave correctly: + Class c = Class.forName(className); + // attempt to create the class, if we cannot with an empty argument + // then the class is invalid + Object kit = c.newInstance(); + if (!(kit instanceof EditorKit)) { + throw new IllegalArgumentException("Cannot register class: " + className + + ". It does not extend EditorKit"); + } + JEditorPane.registerEditorKitForContentType(type, className); + CONTENT_TYPES.add(type); + } catch (InstantiationException ex) { + throw new IllegalArgumentException("Cannot register class: " + className + + ". Ensure it has Default Constructor.", ex); + } catch (IllegalAccessException ex) { + throw new IllegalArgumentException("Cannot register class: " + className, ex); + } catch (ClassNotFoundException ex) { + throw new IllegalArgumentException("Cannot register class: " + className, ex); + } catch (RuntimeException ex) { + throw new IllegalArgumentException("Cannot register class: " + className, ex); + } + } + + /** + * Return all the content types supported by this library. This will be the + * content types in the file WEB-INF/services/resources/de/sciss/syntaxpane/kitsfortypes + * @return sorted array of all registered content types + */ + public static String[] getContentTypes() { + String[] types = CONTENT_TYPES.toArray(new String[0]); + Arrays.sort(types); + return types; + } + + /** + * Merges the given properties with the configurations for this Object + */ + public void setConfig(Properties config) { + getConfig().putAll(config); + } + + /** + * Sets the given property to the given value. If the kit is not + * initialized, then calls initKit + */ + public void setProperty(String key, String value) { + getConfig().put(key, value); + } + + /** + * Return the property with the given key. If the kit is not + * initialized, then calls initKit + * Be careful when changing property as the default property may be used + * + * @return value for given key + */ + public String getProperty(String key) { + return getConfig().getString(key); + } + + /** + * Gets the configuration for this Object + */ + public Configuration getConfig() { + return getConfig(this.getClass()); + } + + /** + * Returns the Configurations object for a Kit. Perform lazy creation of a + * Configuration object if nothing is created. + */ + public static synchronized Configuration getConfig(Class kit) { + if (CONFIGS == null) { + CONFIGS = new WeakHashMap, Configuration>(); + Configuration defaultConfig = new Configuration(DefaultSyntaxKit.class); + loadConfig(defaultConfig, DefaultSyntaxKit.class); + CONFIGS.put(DefaultSyntaxKit.class, defaultConfig); + } + + if (CONFIGS.containsKey(kit)) { + return CONFIGS.get(kit); + } else { + // recursive call until we read the Super duper DefaultSyntaxKit + Class superKit = kit.getSuperclass(); + @SuppressWarnings("unchecked") + Configuration defaults = getConfig(superKit); + Configuration mine = new Configuration(kit, defaults); + loadConfig(mine, kit); + CONFIGS.put(kit, mine); + return mine; + } + } + + public Map getAbbreviations() { + // if we have not loaded the abbreviations, then load them now: + if (abbreviations == null) { + String cl = this.getClass().getName().replace('.', '/').toLowerCase(); + abbreviations = JarServiceProvider.readStringsMap(cl + "/abbreviations.properties"); + } + return abbreviations; + } + + /** + * Adds an abbreviation to this kit's abbreviations. + */ + public static void addAbbreviation(String abbr, String template) { + if (abbreviations == null) { + abbreviations = new HashMap(); + } + abbreviations.put(abbr, template); + } + + /** + * Gets the template for the given abbreviation + */ + public static String getAbbreviation(String abbr) { + return abbreviations == null ? null : abbreviations.get(abbr); + } + + private static void loadConfig(Configuration conf, Class kit) { + String url = kit.getName().replace(".", "/") + "/config"; + Properties p = JarServiceProvider.readProperties(url, Locale.getDefault()); + if (p.size() == 0) { + LOG.log(Level.INFO, "unable to load configuration for: {0} from: {1}.properties", + new Object[]{kit, url}); + } else { + conf.putAll(p); + } + } + + @Override + public String getContentType() { + return "text/" + this.getClass().getSimpleName().replace("SyntaxKit", "").toLowerCase(); + } +} \ No newline at end of file diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/JavaRegexKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/JavaRegexKit.java new file mode 100644 index 0000000..0f9e013 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/JavaRegexKit.java @@ -0,0 +1,28 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane; + +import java.io.IOException; +import de.sciss.syntaxpane.lexers.SimpleRegexLexer; + +/** + * + * @author Ayman Al-Sairafi + */ +public class JavaRegexKit extends DefaultSyntaxKit { + + public JavaRegexKit() throws IOException { + super(new SimpleRegexLexer("javaRegex.properties")); + } +} \ No newline at end of file diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/Lexer.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/Lexer.java new file mode 100644 index 0000000..46aefbf --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/Lexer.java @@ -0,0 +1,37 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane; + +import java.util.List; +import javax.swing.text.Segment; + +/** + * Lexers must implement these methods. These are used in the Tokenizer + * + * A Lexer should be tied to one document. + * + * @author Ayman Al-Sairafi + */ +public interface Lexer { + /** + * This is the only method a Lexer needs to implement. It will be passed + * a Reader, and it should return non-overlapping Tokens for each recognized token + * in the stream. + * @param segment Text to parse. + * @param ofst offset to add to start of each token (useful for nesting) + * @param tokens List of Tokens to be added. This is done so that the caller creates the + * appropriate List implementation and size. The parse method just adds to the list + */ + public void parse(Segment segment, int ofst, List tokens); +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/SyntaxDocument.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/SyntaxDocument.java new file mode 100644 index 0000000..9042fda --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/SyntaxDocument.java @@ -0,0 +1,606 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * Copyright 2013-2014 Hanns Holger Rutz. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane; + +import java.beans.PropertyChangeListener; +import java.beans.PropertyChangeSupport; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.swing.event.DocumentEvent; +import javax.swing.text.AttributeSet; +import javax.swing.text.BadLocationException; +import javax.swing.text.Element; +import javax.swing.text.PlainDocument; +import javax.swing.text.Segment; + +/** + * A document that supports being highlighted. The document maintains an + * internal List of all the Tokens. The Tokens are updated using + * a Lexer, passed to it during construction. + * + * @author Ayman Al-Sairafi, Hanns Holger Rutz + */ +public class SyntaxDocument extends PlainDocument { + public static final String CAN_UNDO = "can-undo"; + public static final String CAN_REDO = "can-redo"; + + Lexer lexer; + List tokens; + CompoundUndoManager undo; + + private final PropertyChangeSupport propSupport; + private boolean canUndoState = false; + private boolean canRedoState = false; + + public SyntaxDocument(Lexer lexer) { + super(); + putProperty(PlainDocument.tabSizeAttribute, 4); + this.lexer = lexer; + undo = new CompoundUndoManager(this); // Listen for undo and redo events + propSupport = new PropertyChangeSupport(this); + } + + /* + * Parse the entire document and return list of tokens that do not already + * exist in the tokens list. There may be overlaps, and replacements, + * which we will cleanup later. + * + * @return list of tokens that do not exist in the tokens field + */ + private void parse() { + // if we have no lexer, then we must have no tokens... + if (lexer == null) { + tokens = null; + return; + } + List toks = new ArrayList(getLength() / 10); + long ts = System.nanoTime(); + int len = getLength(); + try { + Segment seg = new Segment(); + getText(0, getLength(), seg); + lexer.parse(seg, 0, toks); + } catch (BadLocationException ex) { + log.log(Level.SEVERE, null, ex); + } finally { + if (log.isLoggable(Level.FINEST)) { + log.finest(String.format("Parsed %d in %d ms, giving %d tokens\n", + len, (System.nanoTime() - ts) / 1000000, toks.size())); + } + tokens = toks; + } + } + + @Override + protected void fireChangedUpdate(DocumentEvent e) { + parse(); + super.fireChangedUpdate(e); + } + + @Override + protected void fireInsertUpdate(DocumentEvent e) { + parse(); + super.fireInsertUpdate(e); + } + + @Override + protected void fireRemoveUpdate(DocumentEvent e) { + parse(); + super.fireRemoveUpdate(e); + } + + /** + * Replaces the token with the replacement string + */ + public void replaceToken(Token token, String replacement) { + try { + replace(token.start, token.length, replacement, null); + } catch (BadLocationException ex) { + log.log(Level.WARNING, "unable to replace token: " + token, ex); + } + } + + /** + * This class is used to iterate over tokens between two positions + */ + class TokenIterator implements ListIterator { + + int start; + int end; + int ndx = 0; + + @SuppressWarnings("unchecked") + private TokenIterator(int start, int end) { + this.start = start; + this.end = end; + if (tokens != null && !tokens.isEmpty()) { + Token token = new Token(TokenType.COMMENT, start, end - start); + ndx = Collections.binarySearch((List) tokens, token); + // we will probably not find the exact token... + if (ndx < 0) { + // so, start from one before the token where we should be... + // -1 to get the location, and another -1 to go back.. + ndx = (-ndx - 1 - 1 < 0) ? 0 : (-ndx - 1 - 1); + Token t = tokens.get(ndx); + // if the prev token does not overlap, then advance one + if (t.end() <= start) { + ndx++; + } + + } + } + } + + @Override + public boolean hasNext() { + if (tokens == null) { + return false; + } + if (ndx >= tokens.size()) { + return false; + } + Token t = tokens.get(ndx); + return t.start < end; + } + + @Override + public Token next() { + return tokens.get(ndx++); + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + + @Override + public boolean hasPrevious() { + if (tokens == null) { + return false; + } + if (ndx <= 0) { + return false; + } + Token t = tokens.get(ndx); + return t.end() > start; + } + + @Override + public Token previous() { + return tokens.get(ndx--); + } + + @Override + public int nextIndex() { + return ndx + 1; + } + + @Override + public int previousIndex() { + return ndx - 1; + } + + @Override + public void set(Token e) { + throw new UnsupportedOperationException(); + } + + @Override + public void add(Token e) { + throw new UnsupportedOperationException(); + } + } + + /** + * Returns an iterator of tokens between p0 and p1. + * @param start start position for getting tokens + * @param end position for last token + * @return Iterator for tokens that overall with range from start to end + */ + public Iterator getTokens(int start, int end) { + return new TokenIterator(start, end); + } + + /** + * Finds the token at a given position. May return null if no token is + * found (whitespace skipped) or if the position is out of range: + */ + public Token getTokenAt(int pos) { + if (tokens == null || tokens.isEmpty() || pos > getLength()) { + return null; + } + Token tok = null; + Token tKey = new Token(TokenType.DEFAULT, pos, 1); + @SuppressWarnings("unchecked") + int ndx = Collections.binarySearch((List) tokens, tKey); + if (ndx < 0) { + // so, start from one before the token where we should be... + // -1 to get the location, and another -1 to go back.. + ndx = (-ndx - 1 - 1 < 0) ? 0 : (-ndx - 1 - 1); + Token t = tokens.get(ndx); + if ((t.start <= pos) && (pos <= t.end())) { + tok = t; + } + } else { + tok = tokens.get(ndx); + } + return tok; + } + + public Token getWordAt(int offs, Pattern p) { + Token word = null; + try { + Element line = getParagraphElement(offs); + if (line == null) { + return null; + } + int lineStart = line.getStartOffset(); + int lineEnd = Math.min(line.getEndOffset(), getLength()); + Segment seg = new Segment(); + getText(lineStart, lineEnd - lineStart, seg); + if (seg.count > 0) { + // we need to get the word using the words pattern p + Matcher m = p.matcher(seg); + int o = offs - lineStart; + while (m.find()) { + if (m.start() <= o && o <= m.end()) { + word = new Token(TokenType.DEFAULT, m.start() + lineStart, m.end() - m.start()); + break; + } + } + } + } catch (BadLocationException ex) { + Logger.getLogger(SyntaxDocument.class.getName()).log(Level.SEVERE, null, ex); + } + return word; + } + + /** + * Returns the token following the current token, or null + * This is an expensive operation, so do not use it to update the gui + */ + public Token getNextToken(Token tok) { + int n = tokens.indexOf(tok); + if ((n >= 0) && (n < (tokens.size() - 1))) { + return tokens.get(n + 1); + } else { + return null; + } + } + + /** + * Returns the token prior to the given token, or null + * This is an expensive operation, so do not use it to update the gui + */ + public Token getPrevToken(Token tok) { + int n = tokens.indexOf(tok); + if ((n > 0) && (!tokens.isEmpty())) { + return tokens.get(n - 1); + } else { + return null; + } + } + + /** + * This is used to return the other part of a paired token in the document. + * A paired part has token.pairValue <> 0, and the paired token will + * have the negative of t.pairValue. + * This method properly handles nestings of same pairValues, but overlaps + * are not checked. + * if the document does not contain a paired token, then null is returned. + * + * @return the other pair's token, or null if nothing is found. + */ + public Token getPairFor(Token t) { + if (t == null || t.pairValue == 0) { + return null; + } + Token p = null; + int ndx = tokens.indexOf(t); + // w will be similar to a stack. The openners weght is added to it + // and the closers are subtracted from it (closers are already negative) + int w = t.pairValue; + int direction = (t.pairValue > 0) ? 1 : -1; + boolean done = false; + int v = Math.abs(t.pairValue); + while (!done) { + ndx += direction; + if (ndx < 0 || ndx >= tokens.size()) { + break; + } + Token current = tokens.get(ndx); + if (Math.abs(current.pairValue) == v) { + w += current.pairValue; + if (w == 0) { + p = current; + done = true; + } + } + } + + return p; + } + + // public boolean isDirty() { return dirty; } + + public void setCanUndo(boolean value) { + if (canUndoState != value) { + // System.out.println("canUndo = " + value); + canUndoState = value; + propSupport.firePropertyChange(CAN_UNDO, !value, value); + } + } + + public void setCanRedo(boolean value) { + if (canRedoState != value) { + // System.out.println("canRedo = " + value); + canRedoState = value; + propSupport.firePropertyChange(CAN_REDO, !value, value); + } + } + + public void addPropertyChangeListener(String property, PropertyChangeListener listener) { + // System.out.println("ADD " + property + " " + listener.hashCode() + " / " + this.hashCode()); + propSupport.addPropertyChangeListener(property, listener); + } + + public void removePropertyChangeListener(String property, PropertyChangeListener listener) { + // System.out.println("REM " + property + " " + listener.hashCode() + " / " + this.hashCode()); + propSupport.removePropertyChangeListener(property, listener); + } + + /** + * Performs an undo action, if possible + */ + public void doUndo() { + if (undo.canUndo()) { + undo.undo(); + parse(); + } + } + + public boolean canUndo() { + return canUndoState; // undo.canUndo(); + } + + /** + * Performs a redo action, if possible. + */ + public void doRedo() { + if (undo.canRedo()) { + undo.redo(); + parse(); + } + } + + public boolean canRedo() { + return canRedoState; // undo.canRedo(); + } + + /** + * Discards all undoable edits + */ + public void clearUndos() { + undo.discardAllEdits(); + } + + /** + * Returns a matcher that matches the given pattern on the entire document + * + * @return matcher object + */ + public Matcher getMatcher(Pattern pattern) { + return getMatcher(pattern, 0, getLength()); + } + + /** + * Returns a matcher that matches the given pattern in the part of the + * document starting at offset start. Note that the matcher will have + * offset starting from start + * + * @return matcher that MUST be offset by start to get the proper + * location within the document + */ + public Matcher getMatcher(Pattern pattern, int start) { + return getMatcher(pattern, start, getLength() - start); + } + + /** + * Returns a matcher that matches the given pattern in the part of the + * document starting at offset start and ending at start + length. + * Note that the matcher will have + * offset starting from start + * + * @return matcher that MUST be offset by start to get the proper location within the document + */ + public Matcher getMatcher(Pattern pattern, int start, int length) { + Matcher matcher = null; + if (getLength() == 0) { + return null; + } + if (start >= getLength()) { + return null; + } + try { + if (start < 0) { + start = 0; + } + if (start + length > getLength()) { + length = getLength() - start; + } + Segment seg = new Segment(); + getText(start, length, seg); + matcher = pattern.matcher(seg); + } catch (BadLocationException ex) { + log.log(Level.SEVERE, "Requested offset: " + ex.offsetRequested(), ex); + } + return matcher; + } + + /** + * Gets the line at given position. The line returned will NOT include + * the line terminator '\n' + * @param pos Position (usually from text.getCaretPosition() + * @return the STring of text at given position + * @throws BadLocationException + */ + public String getLineAt(int pos) throws BadLocationException { + Element e = getParagraphElement(pos); + Segment seg = new Segment(); + getText(e.getStartOffset(), e.getEndOffset() - e.getStartOffset(), seg); + char last = seg.last(); + if (last == '\n' || last == '\r') { + seg.count--; + } + return seg.toString(); + } + + /** + * Deletes the line at given position + * + * @throws javax.swing.text.BadLocationException + */ + public void removeLineAt(int pos) + throws BadLocationException { + Element e = getParagraphElement(pos); + remove(e.getStartOffset(), getElementLength(e)); + } + + /** + * Replaces the line at given position with the given string, which can span + * multiple lines + * + * @throws javax.swing.text.BadLocationException + */ + public void replaceLineAt(int pos, String newLines) + throws BadLocationException { + Element e = getParagraphElement(pos); + replace(e.getStartOffset(), getElementLength(e), newLines, null); + } + + /* + * Helper method to get the length of an element and avoid getting + * a too long element at the end of the document + */ + private int getElementLength(Element e) { + int end = e.getEndOffset(); + if (end >= (getLength() - 1)) { + end--; + } + return end - e.getStartOffset(); + } + + /** + * Gets the text without the comments. For example for the string + * { // it's a comment this method will return "{ ". + * @param aStart start of the text. + * @param anEnd end of the text. + * @return String for the line without comments (if exists). + */ + public synchronized String getUncommentedText(int aStart, int anEnd) { + readLock(); + StringBuilder result = new StringBuilder(); + Iterator iter = getTokens(aStart, anEnd); + while (iter.hasNext()) { + Token t = iter.next(); + if (!TokenType.isComment(t)) { + result.append(t.getText(this)); + } + } + readUnlock(); + return result.toString(); + } + + /** + * Returns the starting position of the line at pos + * + * @return starting position of the line + */ + public int getLineStartOffset(int pos) { + return getParagraphElement(pos).getStartOffset(); + } + + /** + * Returns the end position of the line at pos. + * Does a bounds check to ensure the returned value does not exceed + * document length + */ + public int getLineEndOffset(int pos) { + int end = 0; + end = getParagraphElement(pos).getEndOffset(); + if (end >= getLength()) { + end = getLength(); + } + return end; + } + + /** + * Returns the number of lines in this document + */ + public int getLineCount() { + Element e = getDefaultRootElement(); + return e.getElementCount(); + } + + /** + * Returns the line number at given position. The line numbers are zero based + */ + public int getLineNumberAt(int pos) { + return getDefaultRootElement().getElementIndex(pos); + } + + @Override + public String toString() { + return "SyntaxDocument(" + lexer + ", " + ((tokens == null) ? 0 : tokens.size()) + " tokens)@" + + hashCode(); + } + + /** + * We override this here so that the replace is treated as one operation + * by the undomanager + * + * @throws BadLocationException + */ + @Override + public void replace(int offset, int length, String text, AttributeSet attrs) throws BadLocationException { + remove(offset, length); + undo.startCombine(); + insertString(offset, text, attrs); + } + + /** + * Appends the given string to the text of this document. + * + * @return this document + */ + public SyntaxDocument append(String str) { + try { + insertString(getLength(), str, null); + } catch (BadLocationException ex) { + log.log(Level.WARNING, "Error appending str", ex); + } + return this; + } + + // our logger instance... + private static final Logger log = Logger.getLogger(SyntaxDocument.class.getName()); +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/SyntaxStyle.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/SyntaxStyle.java new file mode 100644 index 0000000..c35cdce --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/SyntaxStyle.java @@ -0,0 +1,137 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane; + +import java.awt.Color; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import javax.swing.text.Segment; +import javax.swing.text.TabExpander; +import javax.swing.text.Utilities; + +/** + * This class represents the Style for a TokenType. This class is responsible + * for actually drawing a Token on the View. + * + * @author Ayman Al-Sairafi + */ +public final class SyntaxStyle { + + private Color color; + private int fontStyle; + + public SyntaxStyle() { + super(); + } + + public SyntaxStyle(Color color, boolean bold, boolean italic) { + super(); + this.color = color; + setBold(bold); + setItalic(italic); + } + + public SyntaxStyle(Color color, int fontStyle) { + super(); + this.color = color; + this.fontStyle = fontStyle; + } + + public SyntaxStyle(String str) { + String[] parts = str.split("\\s*,\\s*"); + if (parts.length != 2) { + throw new IllegalArgumentException("style not correct format: " + str); + } + this.color = new Color(Integer.decode(parts[0])); + this.fontStyle = Integer.decode(parts[1]); + } + + public boolean isBold() { + return (fontStyle & Font.BOLD) != 0; + } + + public void setBold(Boolean bold) { + if (bold) { + fontStyle |= Font.BOLD; + } else { + int mask = -1 ^ Font.BOLD; + fontStyle = (fontStyle & (mask)); + } + } + + public String getColorString() { + return String.format("0x%06x", color.getRGB() & 0x00ffffff); + } + + public void setColorString(String color) { + this.color = Color.decode(color); + } + + public Boolean isItalic() { + return (fontStyle & Font.ITALIC) != 0; + } + + public void setItalic(Boolean italic) { + if (italic) { + fontStyle |= Font.ITALIC; + } else { + fontStyle = (fontStyle & (-1 ^ Font.ITALIC)); + } + } + + public int getFontStyle() { + return fontStyle; + } + + public Color getColor() { + return color; + } + + /** + * Draw text. This can directly call the Utilities.drawTabbedText. + * Sub-classes can override this method to provide any other decorations. + * @param segment - the source of the text + * @param x - the X origin >= 0 + * @param y - the Y origin >= 0 + * @param graphics - the graphics context + * @param e - how to expand the tabs. If this value is null, tabs will be + * expanded as a space character. + * @param startOffset - starting offset of the text in the document >= 0 + * @return + */ + public int drawText(Segment segment, int x, int y, + Graphics graphics, TabExpander e, int startOffset) { + graphics.setFont(graphics.getFont().deriveFont(getFontStyle())); + FontMetrics fontMetrics = graphics.getFontMetrics(); + int a = fontMetrics.getAscent(); + int h = a + fontMetrics.getDescent(); + int w = Utilities.getTabbedTextWidth(segment, fontMetrics, 0, e, startOffset); + int rX = x - 1; + int rY = y - a; + int rW = w + 2; + int rH = h; + if ((getFontStyle() & 0x10) != 0) { + graphics.setColor(Color.decode("#EEEEEE")); + graphics.fillRect(rX, rY, rW, rH); + } + graphics.setColor(getColor()); + x = Utilities.drawTabbedText(segment, x, y, graphics, e, startOffset); + if ((getFontStyle() & 0x8) != 0) { + graphics.setColor(Color.RED); + graphics.drawRect(rX, rY, rW, rH); + } + return x; + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/SyntaxStyles.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/SyntaxStyles.java new file mode 100644 index 0000000..3c21de3 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/SyntaxStyles.java @@ -0,0 +1,130 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; +import java.util.logging.Logger; +import java.util.regex.Pattern; +import javax.swing.text.Segment; +import javax.swing.text.TabExpander; +import de.sciss.syntaxpane.util.Configuration; +import de.sciss.syntaxpane.util.JarServiceProvider; + +/** + * The Styles to use for each TokenType. The defaults are created here, and + * then the resource META-INF/services/syntaxstyles.properties is read and + * merged. You can also pass a properties instance and merge your prefered + * styles into the default styles. + * + * Text is drawn by forwarding the drawText request to the SyntaxStyle for the + * that matches the given TokenType + * + * @author Ayman Al-Sairafi + */ +public class SyntaxStyles { + + public static final Pattern STYLE_PATTERN = Pattern.compile("Style\\.(\\w+)"); + + /** + * You can call the mergeStyles method with a Properties file to customize + * the existing styles. Any existing styles will be overwritten by the + * styles you provide. + */ + public void mergeStyles(Properties styles) { + for (Map.Entry e : styles.entrySet()) { + String tokenType = e.getKey().toString(); + String style = e.getValue().toString(); + try { + TokenType tt = TokenType.valueOf(tokenType); + SyntaxStyle tokenStyle = new SyntaxStyle(style); + put(tt, tokenStyle); + } catch (IllegalArgumentException ex) { + LOG.warning("illegal token type or style for: " + tokenType); + } + } + } + Map styles; + private static SyntaxStyles instance = createInstance(); + private static final Logger LOG = Logger.getLogger(SyntaxStyles.class.getName()); + private static SyntaxStyle DEFAULT_STYLE = new SyntaxStyle(Color.BLACK, Font.PLAIN); + + private SyntaxStyles() {} + + /** + * Creates default styles + */ + private static SyntaxStyles createInstance() { + SyntaxStyles syntaxstyles = new SyntaxStyles(); + Properties styles = JarServiceProvider.readProperties(SyntaxStyles.class); + syntaxstyles.mergeStyles(styles); + return syntaxstyles; + } + + /** + * Returns the default singleton + */ + public static SyntaxStyles getInstance() { + return instance; + } + + public static SyntaxStyles read(Configuration config) { + SyntaxStyles ss = createInstance(); + // Configuration styleConf = config.subConfig(STYLE_PROPERTY_KEY); + + for (Configuration.StringKeyMatcher m : config.getKeys(STYLE_PATTERN)) { + String type = m.group1; + try { + ss.put(TokenType.valueOf(type), new SyntaxStyle(m.value)); + } catch (IllegalArgumentException e) { + Logger.getLogger(SyntaxStyles.class.getName()).warning( + String.format("Invalid Token Type [%s] for Style of ", type)); + } + } + return ss; + } + + public void put(TokenType type, SyntaxStyle style) { + if (styles == null) { + styles = new HashMap(); + } + styles.put(type, style); + } + + /** + * Returns the style for the given TokenType + */ + public SyntaxStyle getStyle(TokenType type) { + if (styles != null && styles.containsKey(type)) { + return styles.get(type); + } else { + return DEFAULT_STYLE; + } + } + + /** + * Draws the given Token. This will simply find the proper SyntaxStyle for + * the TokenType and then asks the proper Style to draw the text of the + * Token. + */ + public int drawText(Segment segment, int x, int y, + Graphics graphics, TabExpander e, Token token) { + SyntaxStyle s = getStyle(token.type); + return s.drawText(segment, x, y, graphics, e, token.start); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/SyntaxView.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/SyntaxView.java new file mode 100644 index 0000000..626aac4 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/SyntaxView.java @@ -0,0 +1,173 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane; + +import java.awt.Color; +import java.awt.Font; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.RenderingHints; +import java.awt.Shape; +import java.awt.Toolkit; +import java.util.Iterator; +import java.util.Map; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.text.BadLocationException; +import javax.swing.text.Element; +import javax.swing.text.PlainView; +import javax.swing.text.Segment; +import javax.swing.text.ViewFactory; +import de.sciss.syntaxpane.util.Configuration; + +public class SyntaxView extends PlainView { + + public static final String PROPERTY_RIGHT_MARGIN_COLOR = "RightMarginColor"; + public static final String PROPERTY_RIGHT_MARGIN_COLUMN = "RightMarginColumn"; + public static final String PROPERTY_SINGLE_COLOR_SELECT = "SingleColorSelect"; + private static final Logger log = Logger.getLogger(SyntaxView.class.getName()); + private SyntaxStyle DEFAULT_STYLE = SyntaxStyles.getInstance().getStyle(TokenType.DEFAULT); + private final boolean singleColorSelect; + private final int rightMarginColumn; + private final Color rightMarginColor; + private final SyntaxStyles styles; + + /** + * Construct a new view using the given configuration and prefix given + * + * @param element + * @param config + */ + public SyntaxView(Element element, Configuration config) { + super(element); + singleColorSelect = config.getBoolean(PROPERTY_SINGLE_COLOR_SELECT, false); + rightMarginColor = new Color(config.getInteger(PROPERTY_RIGHT_MARGIN_COLOR, + 0xFF7777)); + rightMarginColumn = config.getInteger(PROPERTY_RIGHT_MARGIN_COLUMN, + 0); + styles = SyntaxStyles.read(config); + } + + @Override + protected int drawUnselectedText(Graphics graphics, int x, int y, int p0, + int p1) { + setRenderingHits((Graphics2D) graphics); + Font saveFont = graphics.getFont(); + Color saveColor = graphics.getColor(); + SyntaxDocument doc = (SyntaxDocument) getDocument(); + Segment segment = getLineBuffer(); + // Draw the right margin first, if needed. This way the text overlays + // the margin + if (rightMarginColumn > 0) { + int m_x = rightMarginColumn * graphics.getFontMetrics().charWidth('m'); + int h = graphics.getFontMetrics().getHeight(); + graphics.setColor(rightMarginColor); + graphics.drawLine(m_x, y, m_x, y - h); + } + try { + // Colour the parts + Iterator i = doc.getTokens(p0, p1); + int start = p0; + while (i.hasNext()) { + Token t = i.next(); + // if there is a gap between the next token start and where we + // should be starting (spaces not returned in tokens), then draw + // it in the default type + if (start < t.start) { + doc.getText(start, t.start - start, segment); + x = DEFAULT_STYLE.drawText(segment, x, y, graphics, this, start); + } + // t and s are the actual start and length of what we should + // put on the screen. assume these are the whole token.... + int l = t.length; + int s = t.start; + // ... unless the token starts before p0: + if (s < p0) { + // token is before what is requested. adgust the length and s + l -= (p0 - s); + s = p0; + } + // if token end (s + l is still the token end pos) is greater + // than p1, then just put up to p1 + if (s + l > p1) { + l = p1 - s; + } + doc.getText(s, l, segment); + x = styles.drawText(segment, x, y, graphics, this, t); + start = t.end(); + } + // now for any remaining text not tokenized: + if (start < p1) { + doc.getText(start, p1 - start, segment); + x = DEFAULT_STYLE.drawText(segment, x, y, graphics, this, start); + } + } catch (BadLocationException ex) { + log.log(Level.SEVERE, "Requested: " + ex.offsetRequested(), ex); + } finally { + graphics.setFont(saveFont); + graphics.setColor(saveColor); + } + return x; + } + + @Override + protected int drawSelectedText(Graphics graphics, int x, int y, int p0, int p1) + throws BadLocationException { + if (singleColorSelect) { + if (rightMarginColumn > 0) { + int m_x = rightMarginColumn * graphics.getFontMetrics().charWidth('m'); + int h = graphics.getFontMetrics().getHeight(); + graphics.setColor(rightMarginColor); + graphics.drawLine(m_x, y, m_x, y - h); + } + return super.drawSelectedText(graphics, x, y, p0, p1); + } else { + return drawUnselectedText(graphics, x, y, p0, p1); + } + } + + /** + * Sets the Rendering Hints o nthe Graphics. This is used so that + * any painters can set the Rendering Hits to match the view. + * @param g2d + */ + public static void setRenderingHits(Graphics2D g2d) { + g2d.addRenderingHints(sysHints); + } + + @Override + protected void updateDamage(javax.swing.event.DocumentEvent changes, + Shape a, + ViewFactory f) { + super.updateDamage(changes, a, f); + java.awt.Component host = getContainer(); + host.repaint(); + } + /** + * The values for the string key for Text Anti-Aliasing + */ + private static RenderingHints sysHints; + + static { + sysHints = null; + try { + Toolkit toolkit = Toolkit.getDefaultToolkit(); + @SuppressWarnings("unchecked") + Map map = (Map) + toolkit.getDesktopProperty("awt.font.desktophints"); + sysHints = new RenderingHints(map); + } catch (Throwable t) { + } + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/Token.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/Token.java new file mode 100644 index 0000000..8946e57 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/Token.java @@ -0,0 +1,146 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane; + +import java.io.Serializable; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.text.BadLocationException; +import javax.swing.text.Document; +import javax.swing.text.Segment; + +/** + * A Token in a Document. Tokens do NOT store a reference to the + * underlying SyntaxDocument, and must generally be obtained from + * the SyntaxDocument methods. The reason for not storing the + * SyntaxDocument is simply for memory, as the number of Tokens + * per document can be large, you may end up with twice the memory + * in a SyntaxDocument with Tokens than a simple PlainDocument. + * + * @author Ayman Al-Sairafi + */ +public class Token implements Serializable, Comparable { + + public final TokenType type; + public final int start; + public final int length; + /** + * the pair value to use if this token is one of a pair: + * This is how it is used: + * The opening part will have a positive number X + * The closing part will have a negative number X + * X should be unique for a pair: + * e.g. for [ pairValue = +1 + * for ] pairValue = -1 + */ + public final byte pairValue; + /** + * The kind of the Document. This is only needed if proper Parsing + * of a document is needed and it makes certain operations faster. + * You can use any of the supplied Generic Values, or create your + * language specific uses by using USER_FIRST + x; + */ + public final short kind = 0; + + /** + * Constructs a new token + */ + public Token(TokenType type, int start, int length) { + this.type = type; + this.start = start; + this.length = length; + this.pairValue = 0; + } + + /** + * Construct a new part of pair token + */ + public Token(TokenType type, int start, int length, byte pairValue) { + this.type = type; + this.start = start; + this.length = length; + this.pairValue = pairValue; + } + + @Override + public boolean equals(Object obj) { + if (obj instanceof Object) { + Token token = (Token) obj; + return ((this.start == token.start) && + (this.length == token.length) && + (this.type.equals(token.type))); + } else { + return false; + } + } + + @Override + public int hashCode() { + return start; + } + + @Override + public String toString() { + if (pairValue == 0) { + return String.format("%s (%d, %d)", type, start, length); + } else { + return String.format("%s (%d, %d) (%d)", type, start, length, pairValue); + } + } + + @Override + public int compareTo(Object o) { + Token t = (Token) o; + if (this.start != t.start) { + return (this.start - t.start); + } else if (this.length != t.length) { + return (this.length - t.length); + } else { + return this.type.compareTo(t.type); + } + } + + /** + * return the end position of the token. + * @return start + length + */ + public int end() { + return start + length; + } + + /** + * Get the text of the token from this document + */ + public CharSequence getText(Document doc) { + Segment text = new Segment(); + try { + doc.getText(start, length, text); + } catch (BadLocationException ex) { + Logger.getLogger(Token.class.getName()).log(Level.SEVERE, null, ex); + } finally { + return text; + } + } + + public String getString(Document doc) { + String result = ""; + try { + result = doc.getText(start, length); + } catch (BadLocationException ex) { + Logger.getLogger(Token.class.getName()).log(Level.SEVERE, null, ex); + } finally { + return result; + } + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/TokenComparators.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/TokenComparators.java new file mode 100644 index 0000000..3f46fa7 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/TokenComparators.java @@ -0,0 +1,55 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane; + +import java.io.Serializable; +import java.util.Comparator; + +/** + * Two comparators to compare Tokens. + * @author Ayman Al-Sairafi + */ +public class TokenComparators { + + public static final Comparator LONGEST_FIRST = new LongestFirst(); + public static final Comparator SHORTEST_FIRST = new ShortestFirst(); + + private static class LongestFirst implements Comparator, Serializable { + + @Override + public int compare(Token t1, Token t2) { + if (t1.start != t2.start) { + return (t1.start - t2.start); + } else if (t1.length != t2.length) { + return (t2.length - t1.length); + } else { + return t1.type.compareTo(t2.type); + } + } + } + + private static class ShortestFirst implements Comparator, Serializable { + + @Override + public int compare(Token t1, Token t2) { + if (t1.start != t2.start) { + return (t1.start - t2.start); + } else if (t1.length != t2.length) { + return (t1.length - t2.length); + } else { + return t1.type.compareTo(t2.type); + } + } + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/TokenConstants.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/TokenConstants.java new file mode 100644 index 0000000..0ba1ec7 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/TokenConstants.java @@ -0,0 +1,124 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package de.sciss.syntaxpane; + +/** + * Constants used by Tokens. + * @author Ayman Al-Sairafi + */ +public class TokenConstants { + /** + * Token Kinds + */ + // Operators and separators - Suitable for Java Type Languages + public static final short EQ = 1; // = + public static final short GT = 2; // > + public static final short LT = 3; // < + public static final short NOT = 4; // ! + public static final short COMP = 5; // ~ + public static final short QUESTION = 6; // ? + public static final short COLON = 7; // : + public static final short EQEQ = 8; // == + public static final short LTEQ = 9; // <= + public static final short GTEQ = 10; // >= + public static final short NOTEQ = 11; // != + public static final short ANDAND = 12; // && + public static final short OROR = 13; // || + public static final short PLUSPLUS = 14; // ++ + public static final short MINUSMINUS = 15; // -- + public static final short PLUS = 16; // + + public static final short MINUS = 17; // - + public static final short MULT = 18; // * + public static final short DIV = 19; // / + public static final short AND = 20; // & + public static final short OR = 21; // | + public static final short XOR = 22; // ^ + public static final short MOD = 23; // % + public static final short LSHIFT = 24; // << + public static final short RSHIFT = 25; // >> + public static final short URSHIFT = 26; // >>> + public static final short PLUSEQ = 27; // += + public static final short MINUSEQ = 28; // -= + public static final short MULTEQ = 29; // *= + public static final short DIVEQ = 30; // /= + public static final short ANDEQ = 31; // &= + public static final short OREQ = 32; // |= + public static final short XOREQ = 33; // ^= + public static final short MODEQ = 34; // %= + public static final short LSHIFTEQ = 35; // <<= + public static final short RSHIFTEQ = 36; // >>= + public static final short URSHIFTEQ = 37; // >>>= + public static final short LPAREN = 38; // ( + public static final short RPAREN = 39; // ) + public static final short LBRACE = 40; // { + public static final short RBRACE = 41; // } + public static final short LBRACK = 42; // [ + public static final short RBRACK = 43; // ] + public static final short SEMICOLON = 44; // ; + public static final short COMMA = 46; // , + public static final short DOT = 47; // . + + // Keywords for Java Type Languages + public static final short KW_START = 255; + public static final short KW_abstract = KW_START + 0; + public static final short KW_assert = KW_START + 1; + public static final short KW_boolean = KW_START + 2; + public static final short KW_break = KW_START + 3; + public static final short KW_byte = KW_START + 4; + public static final short KW_case = KW_START + 5; + public static final short KW_catch = KW_START + 6; + public static final short KW_char = KW_START + 7; + public static final short KW_class = KW_START + 8; + public static final short KW_const = KW_START + 9; + public static final short KW_continue = KW_START + 10; + public static final short KW_do = KW_START + 11; + public static final short KW_double = KW_START + 12; + public static final short KW_else = KW_START + 13; + public static final short KW_extends = KW_START + 14; + public static final short KW_final = KW_START + 15; + public static final short KW_finally = KW_START + 16; + public static final short KW_float = KW_START + 17; + public static final short KW_for = KW_START + 18; + public static final short KW_default = KW_START + 19; + public static final short KW_implements = KW_START + 20; + public static final short KW_import = KW_START + 21; + public static final short KW_instanceof = KW_START + 22; + public static final short KW_int = KW_START + 23; + public static final short KW_interface = KW_START + 24; + public static final short KW_long = KW_START + 25; + public static final short KW_native = KW_START + 26; + public static final short KW_new = KW_START + 27; + public static final short KW_goto = KW_START + 28; + public static final short KW_if = KW_START + 29; + public static final short KW_public = KW_START + 30; + public static final short KW_short = KW_START + 31; + public static final short KW_super = KW_START + 32; + public static final short KW_switch = KW_START + 33; + public static final short KW_synchronized = KW_START + 34; + public static final short KW_package = KW_START + 35; + public static final short KW_private = KW_START + 36; + public static final short KW_protected = KW_START + 37; + public static final short KW_transient = KW_START + 38; + public static final short KW_return = KW_START + 39; + public static final short KW_void = KW_START + 40; + public static final short KW_static = KW_START + 41; + public static final short KW_while = KW_START + 42; + public static final short KW_this = KW_START + 43; + public static final short KW_throw = KW_START + 44; + public static final short KW_throws = KW_START + 45; + public static final short KW_try = KW_START + 46; + public static final short KW_volatile = KW_START + 47; + public static final short KW_strictfp = KW_START + 48; +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/TokenType.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/TokenType.java new file mode 100644 index 0000000..d9f00bd --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/TokenType.java @@ -0,0 +1,81 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane; + +/** + * These are the various token types supported by SyntaxPane. + * + * @author ayman + */ +public enum TokenType { + + OPERATOR, // Language operators + DELIMITER, // Delimiters. Constructs that are not necessarily operators for a language + KEYWORD, // language reserved keywords + KEYWORD2, // Other language reserved keywords, like C #defines + IDENTIFIER, // identifiers, variable names, class names + NUMBER, // numbers in various formats + STRING, // String + STRING2, // For highlighting meta chars within a String + COMMENT, // comments + COMMENT2, // special stuff within comments + REGEX, // regular expressions + REGEX2, // special chars within regular expressions + TYPE, // Types, usually not keywords, but supported by the language + TYPE2, // Types from standard libraries + TYPE3, // Types for users + DEFAULT, // any other text + WARNING, // Text that should be highlighted as a warning + ERROR; // Text that signals an error + + /** + * Tests if the given token is a Comment Token. + * @param t + * @return + */ + public static boolean isComment(Token t) { + if (t != null && (t.type == COMMENT || t.type == COMMENT2)) { + return true; + } else { + return false; + } + } + + /** + * Tests if the given token is a Keyword Token. + * @param t + * @return + */ + public static boolean isKeyword(Token t) { + if (t != null && (t.type == KEYWORD || t.type == KEYWORD2)) { + return true; + } else { + return false; + } + } + + + /** + * Tests if the given token is a String Token. + * @param t + * @return + */ + public static boolean isString(Token t) { + if (t != null && (t.type == STRING || t.type == STRING2)) { + return true; + } else { + return false; + } + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/AbstractUndoRedoAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/AbstractUndoRedoAction.java new file mode 100644 index 0000000..8e2f4f1 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/AbstractUndoRedoAction.java @@ -0,0 +1,88 @@ +package de.sciss.syntaxpane.actions; + +import de.sciss.syntaxpane.SyntaxDocument; +import de.sciss.syntaxpane.util.Configuration; + +import javax.swing.*; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; + +public abstract class AbstractUndoRedoAction extends DefaultSyntaxAction { + private JEditorPane editor; + protected SyntaxDocument doc; + + private final String property; + + protected AbstractUndoRedoAction(String property, String key) { + super(key); + this.property = property; + } + + private PropertyChangeListener propListener = new PropertyChangeListener() { + @Override + public void propertyChange(PropertyChangeEvent e) { + // System.out.println(property + " - " + e); + setEnabled(updateState()); + } + }; + + abstract protected boolean updateState(); + + private void removeDocument() { + if (doc != null) { + doc.removePropertyChangeListener(property, propListener); + doc = null; + } + } + + private void setDocument(SyntaxDocument newDoc) { + if (doc != null) throw new IllegalStateException(); + doc = newDoc; + doc.addPropertyChangeListener(property, propListener); + setEnabled(updateState()); + } + + private PropertyChangeListener docListener = new PropertyChangeListener() { + @Override + public void propertyChange(PropertyChangeEvent e) { + // if (e.getPropertyName().equals("document")) { + removeDocument(); + Object newDoc = e.getNewValue(); + if (newDoc instanceof SyntaxDocument) { + setDocument((SyntaxDocument) newDoc); + // editor.removePropertyChangeListener("document", docListener); + } +// } else { +// System.out.println(e.getPropertyName() + " " + e.getNewValue()); +// } + } + }; + + @Override + public void install(JEditorPane editor, Configuration config, String name) { + super.install(editor, config, name); + + if (this.editor != null) throw new IllegalStateException(); + + this.editor = editor; + editor.addPropertyChangeListener("document", docListener); + + // editor.addPropertyChangeListener("editorKit", docListener); + + // Document doc = editor.getDocument(); + // if (doc instanceof SyntaxDocument) { + // setDocument((SyntaxDocument) doc); + // } + } + + @Override + public void deinstall(JEditorPane editor) { + super.deinstall(editor); + + if (this.editor != editor) throw new IllegalStateException(); + + editor.removePropertyChangeListener("document", docListener); + removeDocument(); + this.editor = null; + } +} \ No newline at end of file diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ActionUtils.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ActionUtils.java new file mode 100644 index 0000000..10d7fbe --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ActionUtils.java @@ -0,0 +1,595 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.Component; +import java.awt.Frame; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Window; +import java.awt.event.KeyEvent; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.swing.Action; +import javax.swing.JComboBox; +import javax.swing.JEditorPane; +import javax.swing.MutableComboBoxModel; +import javax.swing.SwingUtilities; +import javax.swing.text.BadLocationException; +import javax.swing.text.Document; +import javax.swing.text.EditorKit; +import javax.swing.text.Element; +import javax.swing.text.JTextComponent; +import javax.swing.text.PlainDocument; +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.SyntaxDocument; +import de.sciss.syntaxpane.Token; + +/** + * Various utility methods to work on JEditorPane and its SyntaxDocument + * for use by Actions + * + * @author Ayman Al-Sairafi + */ +public class ActionUtils { + + private ActionUtils() { + } + + private static ActionUtils instance = null; + + /** + * Get the Singleton instance. Will be created lazily. + */ + public static synchronized ActionUtils getInstance() { + if(instance == null) { + instance = new ActionUtils(); + } + return instance; + } + + /** + * Get the indentation of a line of text. This is the subString from + * beginning of line to the first non-space char + * @param line the line of text + * @return indentation of line. + */ + public static String getIndent(String line) { + if (line == null || line.length() == 0) { + return ""; + } + int i = 0; + while (i < line.length() && line.charAt(i) == ' ') { + i++; + } + return line.substring(0, i); + } + + /** + * Return the lines that span the selection (split as an array of Strings) + * if there is no selection then current line is returned. + * + * Note that the strings returned will not contain the terminating line feeds + * If the document is empty, then an empty string array is returned. So + * you can always iterate over the returned array without a null check + * + * The text component will then have the full lines set as selection + * + * @return String[] of lines spanning selection / or line containing dot + */ + public static String[] getSelectedLines(JTextComponent target) { + String[] lines = null; + try { + PlainDocument pDoc = (PlainDocument) target.getDocument(); + int start = pDoc.getParagraphElement(target.getSelectionStart()).getStartOffset(); + int end; + if (target.getSelectionStart() == target.getSelectionEnd()) { + end = pDoc.getParagraphElement(target.getSelectionEnd()).getEndOffset(); + } else { + // if more than one line is selected, we need to subtract one from the end + // so that we do not select the line with the caret and no selection in it + end = pDoc.getParagraphElement(target.getSelectionEnd() - 1).getEndOffset(); + } + target.select(start, end); + lines = pDoc.getText(start, end - start).split("\n"); + target.select(start, end); + } catch (BadLocationException ex) { + Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, null, ex); + lines = EMPTY_STRING_ARRAY; + } + return lines; + } + + /** + * Return the line of text at the TextComponent's current position + */ + public static String getLine(JTextComponent target) { + return getLineAt(target, target.getCaretPosition()); + } + + /** + * Return the line of text at the given position. The returned value may + * be null. It will not contain the trailing new-line character. + * @param target the text component + * @param pos char position + */ + public static String getLineAt(JTextComponent target, int pos) { + String line = null; + Document doc = target.getDocument(); + if (doc instanceof PlainDocument) { + PlainDocument pDoc = (PlainDocument) doc; + int start = pDoc.getParagraphElement(pos).getStartOffset(); + int end = pDoc.getParagraphElement(pos).getEndOffset(); + try { + line = doc.getText(start, end - start); + if (line != null && line.endsWith("\n")) { + line = line.substring(0, line.length() - 1); + } + } catch (BadLocationException ex) { + Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, null, ex); + } + } + return line; + } + + /** + * Returns the Frame that contains this component or null if the component + * is not within a Window or the containing window is not a frame + */ + public static Frame getFrameFor(Component comp) { + Window w = SwingUtilities.getWindowAncestor(comp); + if (w != null && w instanceof Frame) { + return (Frame) w; + } + return null; + } + + /** + * Returns the the Token at pos as a String + */ + public static String getTokenStringAt( + SyntaxDocument doc, int pos) { + String word = ""; + Token t = doc.getTokenAt(pos); + if (t != null) { + try { + word = doc.getText(t.start, t.length); + } catch (BadLocationException ex) { + Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, null, ex); + } + } + return word; + } + + /** + * A helper function that will return the SyntaxDocument attached to the + * given text component. Return null if the document is not a + * SyntaxDocument, or if the text component is null + */ + public static SyntaxDocument getSyntaxDocument(JTextComponent component) { + if (component == null) { + return null; + } + Document doc = component.getDocument(); + if (doc instanceof SyntaxDocument) { + return (SyntaxDocument) doc; + } else { + return null; + } + } + + /** + * Gets the Line Number at the give position of the editor component. + * The first line number is ZERO + * + * @return line number + * @throws javax.swing.text.BadLocationException + */ + public static int getLineNumber(JTextComponent editor, int pos) + throws BadLocationException { + if (getSyntaxDocument(editor) != null) { + SyntaxDocument sdoc = getSyntaxDocument(editor); + return sdoc.getLineNumberAt(pos); + } else { + Document doc = editor.getDocument(); + return doc.getDefaultRootElement().getElementIndex(pos); + } + } + + /** + * Gets the column number at given position of editor. The first column is + * ZERO + * + * @return the 0 based column number + * @throws javax.swing.text.BadLocationException + */ + public static int getColumnNumber(JTextComponent editor, int pos) + throws BadLocationException { + // speedup if the pos is 0 + if(pos == 0) { + return 0; + } + Rectangle r = editor.modelToView(pos); + int start = editor.viewToModel(new Point(0, r.y)); + int column = pos - start; + return column; + } + + /** + * Get the closest position within the document of the component that + * has given line and column. + * + * @param line the first being 1 + * @param column the first being 1 + * @return the closest position for the text component at given line and + * column + */ + public static int getDocumentPosition(JTextComponent editor, int line, + int column) { + int lineHeight = editor.getFontMetrics(editor.getFont()).getHeight(); + int charWidth = editor.getFontMetrics(editor.getFont()).charWidth('m'); + int y = line * lineHeight; + int x = column * charWidth; + Point pt = new Point(x, y); + int pos = editor.viewToModel(pt); + return pos; + } + + public static int getLineCount(JTextComponent pane) { + SyntaxDocument sdoc = getSyntaxDocument(pane); + if (sdoc != null) { + return sdoc.getLineCount(); + } + int count = 0; + try { + int p = pane.getDocument().getLength() - 1; + if (p > 0) { + count = getLineNumber(pane, p); + } + } catch (BadLocationException ex) { + Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, null, ex); + } + return count; + } + + /** + * Insert the given item into the combo box, and set it as first selected + * item. If the item already exists, it is removed, so there are no + * duplicates. + * + * @param item the item to insert. if it's null, then nothing is inserted + */ + public static void insertIntoCombo(JComboBox combo, Object item) { + if(item == null) { + return; + } + MutableComboBoxModel model = (MutableComboBoxModel) combo.getModel(); + if (model.getSize() == 0) { + model.insertElementAt(item, 0); + return; + } + + Object o = model.getElementAt(0); + if (o.equals(item)) { + return; + } + model.removeElement(item); + model.insertElementAt(item, 0); + combo.setSelectedIndex(0); + } + + public static void insertMagicString(JTextComponent target, String result) { + try { + insertMagicString(target, target.getCaretPosition(), result); + } catch (BadLocationException ex) { + Logger.getLogger(ActionUtils.class.getName()).log(Level.SEVERE, null, ex); + } + } + + /** + * Repeat the string source repeat times. + * If repeats == 0 then empty String is returned + * if source is null, then empty string is returned + * + * @return source String repeated repeat times. + */ + public static String repeatString(String source, int repeat) { + if (repeat < 0) { + throw new IllegalArgumentException("Cannot repeat " + repeat + " times."); + } + if (repeat == 0 || source == null || source.length() == 0) { + return ""; + } + StringBuffer buffer = new StringBuffer(); + for (int i = 0; i < repeat; i++) { + buffer.append(source); + } + return buffer.toString(); + } + + /** + * Checks if the given string is null, empty or contains whitespace only + * + * @return true if string is null, empty or contains whitespace only, false + * otherwise. + */ + public static boolean isEmptyOrBlanks(String string) { + if (string == null || string.length() == 0) { + return true; + } + for (int i = 0; i < string.length(); i++) { + char c = string.charAt(i); + if (!Character.isWhitespace(c)) { + return false; + } + } + return true; + } + + /** + * Return the TabStop property for the given text component, or 0 if not + * used + */ + public static int getTabSize(JTextComponent text) { + Integer tabs = (Integer) text.getDocument().getProperty(PlainDocument.tabSizeAttribute); + return (null == tabs) ? 0 : tabs.intValue(); + } + + /** + * Insert the given String into the text component. If the string contains + * the | vertical BAr char, then it will not be inserted, and the cursor will + * be set to its location. + * If there are TWO vertical bars, then the text between them will be selected + * If the toInsert String is multiLine, then indentation of all following lines + * will be the same as the first line. TAB characters will be replaced by + * the number of spaces in the document's TAB property. + * + * @throws javax.swing.text.BadLocationException + */ + public static void insertMagicString(JTextComponent target, int dot, String toInsert) + throws BadLocationException { + Document doc = target.getDocument(); + String[] lines = toInsert.split("\n"); + if (lines.length > 1) { + // multi line strings will need to be indented + String tabToSpaces = getTab(target); + String currentLine = getLineAt(target, dot); + String currentIndent = getIndent(currentLine); + StringBuilder sb = new StringBuilder(toInsert.length()); + boolean firstLine = true; + for (String l : lines) { + if (!firstLine) { + sb.append(currentIndent); + } + firstLine = false; + // replace tabs with spaces. + sb.append(l.replace("\t", tabToSpaces)); + sb.append("\n"); + } + toInsert = sb.toString(); + } + if (toInsert.indexOf('|') >= 0) { + int ofst = toInsert.indexOf('|'); + int ofst2 = toInsert.indexOf('|', ofst + 1); + toInsert = toInsert.replace("|", ""); + doc.insertString(dot, toInsert, null); + dot = target.getCaretPosition(); + int strLength = toInsert.length(); + if (ofst2 > 0) { + // note that we already removed the first |, so end offset is now + // one less than what it was. + target.select(dot + ofst - strLength, dot + ofst2 - strLength - 1); + } else { + target.setCaretPosition(dot + ofst - strLength); + } + } else { + doc.insertString(dot, toInsert, null); + } + } + + /** + * Expand the string template and replaces the selection with the expansion + * of the template. The template String may contain any of the following + * special tags. + * + *
  • {@code #{selection}} replaced with the selection, if any. If there is + * no selection, then the {@code #{selection}} tag will be removed. + *
  • {@code #{p:any text}} will be replaced by {@code any text} and then + * set selection to {@code any text} + * + * This method properly handles indentation as follows: + * The indentation of the whole block will match the indentation of the caret + * line, or the line with the beginning of the selection, if the selection is + * in whole line, i.e.e one or more lines of selected text. {@see selectLines()} + * + * @param target JEditorCOmponent to be affected + * @param templateLines template split as a String array of lines. + */ + public static void insertLinesTemplate(JTextComponent target, String[] templateLines) { + // get some stuff we'll need: + String thisIndent = getIndent(getLineAt(target, target.getSelectionStart())); + String[] selLines = getSelectedLines(target); + int selStart = -1, selEnd = -1; + StringBuffer sb = new StringBuffer(); + for (String tLine : templateLines) { + int selNdx = tLine.indexOf("#{selection}"); + if (selNdx >= 0) { + // for each of the selected lines: + for (String selLine : selLines) { + sb.append(tLine.subSequence(0, selNdx)); + sb.append(selLine); + sb.append('\n'); + } + } else { + sb.append(thisIndent); + // now check for any ptags + Matcher pm = PTAGS_PATTERN.matcher(tLine); + int lineStart = sb.length(); + while (pm.find()) { + selStart = pm.start() + lineStart; + pm.appendReplacement(sb, pm.group(1)); + selEnd = sb.length(); + } + pm.appendTail(sb); + sb.append('\n'); + } + } + int ofst = target.getSelectionStart(); + target.replaceSelection(sb.toString()); + if (selStart >= 0) { + // target.setCaretPosition(selStart); + target.select(ofst + selStart, ofst + selEnd); + } + } + + /** + * Expand the string template and replaces the selection with the expansion + * of the template. The template String may contain any of the following + * special tags. + * + *
  • {@code #{selection}} replaced with the selection, if any. If there is + * no selection, then the {@code #{selection}} tag will be removed. + *
  • {@code #{p:AnyText}} will be replaced by {@code any text} and then + * set the text selection to {@code AnyText} + * + * This methood does NOT perform any indentation and the template should + * generally span one line only + */ + public static void insertSimpleTemplate(JTextComponent target, String template) { + String selected = target.getSelectedText(); + selected = (selected == null) ? "" : selected; + StringBuffer sb = new StringBuffer(template.length()); + Matcher pm = PTAGS_PATTERN.matcher(template.replace(TEMPLATE_SELECTION, selected)); + int selStart = -1, selEnd = -1; + int lineStart = 0; + while (pm.find()) { + selStart = pm.start() + lineStart; + pm.appendReplacement(sb, pm.group(1)); + selEnd = sb.length(); + } + pm.appendTail(sb); + // String expanded = template.replace(TEMPLATE_SELECTION, selected); + + if (selStart >= 0) { + selStart += target.getSelectionStart(); + selEnd += target.getSelectionStart(); + } + target.replaceSelection(sb.toString()); + if (selStart >= 0) { + // target.setCaretPosition(selStart); + target.select(selStart, selEnd); + } + } + + /** + * If the selection is multi lined, then the full lines are selected, + * otherwise, nothing is done. + * + * @return true if the selection is multi-line, or a whole line + */ + public static boolean selectLines(JTextComponent target) { + if (target.getSelectionStart() == target.getSelectionEnd()) { + return false; + } + PlainDocument pDoc = (PlainDocument) target.getDocument(); + Element es = pDoc.getParagraphElement(target.getSelectionStart()); + // if more than one line is selected, we need to subtract one from the end + // so that we do not select the line with the caret and no selection in it + Element ee = pDoc.getParagraphElement(target.getSelectionEnd() - 1); + if (es.equals(ee) && ee.getEndOffset() != target.getSelectionEnd()) { + return false; + } + int start = es.getStartOffset(); + int end = ee.getEndOffset(); + target.select(start, end - 1); + return true; + } + + /** + * Sets the caret position of the given target to the given line and column + * + * @param line the first being 1 + * @param column the first being 1 + */ + public static void setCaretPosition(JTextComponent target, int line, int column) { + int p = getDocumentPosition(target, line, column); + target.setCaretPosition(p); + } + + /** + * Return a string with number of spaces equal to the tab-stop of the TextComponent + */ + public static String getTab(JTextComponent target) { + return SPACES.substring(0, getTabSize(target)); + } + + /** + * Searches all actions of a JTextComponent for ab action of the given class and returns + * the first one that matches that class, or null if no Action is found + * + * @return Action object of that class or null + */ + public static T getAction(JTextComponent target, Class aClass) { + for (Object k : target.getActionMap().allKeys()) { + Action a = target.getActionMap().get(k); + if (aClass.isInstance(a)) { + @SuppressWarnings("unchecked") + T t = (T) a; + return t; + } + } + return null; + } + + /** + * Return the DefaultSyntaxKit of this target, or null if the target does not + * have a DefaultSyntaxKit + * + * @return kit or null + */ + public static DefaultSyntaxKit getSyntaxKit(JTextComponent target) { + DefaultSyntaxKit kit = null; + if (target instanceof JEditorPane) { + JEditorPane jEditorPane = (JEditorPane) target; + EditorKit k = jEditorPane.getEditorKit(); + if (k instanceof DefaultSyntaxKit) { + kit = (DefaultSyntaxKit) k; + } + } + return kit; + } + + /** + * Create and send a KeyPress KeyEvent to the component given + * @param target Editor to get the action + * @param v_key from KeyEvent.V_ constants + * @param modifiers from KeyEvent.*MASK constants + */ + public static void sendKeyPress(JTextComponent target, int v_key, int modifiers) { + KeyEvent ke = new KeyEvent(target, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), + modifiers, v_key, KeyEvent.CHAR_UNDEFINED); + target.dispatchEvent(ke); + } + // This is used internally to avoid NPE if we have no Strings + final static String[] EMPTY_STRING_ARRAY = new String[0]; + // This is used to quickly create Strings of at most 16 spaces (using substring) + final static String SPACES = " "; + /** + * The Pattern to use for PTags in insertSimpleTemplate + */ + public static final Pattern PTAGS_PATTERN = Pattern.compile("\\#\\{p:([^}]*)\\}"); + public static final String TEMPLATE_SELECTION = "#{selection}"; +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/CaretMonitor.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/CaretMonitor.java new file mode 100644 index 0000000..6f31813 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/CaretMonitor.java @@ -0,0 +1,119 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import javax.swing.JLabel; +import javax.swing.event.CaretEvent; +import javax.swing.event.CaretListener; +import javax.swing.text.BadLocationException; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; + +/** + * This class can be used to display the caret location in friendly manner for + * an EditorPane. + * + * @author Ayman Al-Sairafi + */ +public class CaretMonitor implements CaretListener { + + private JLabel label; + private JTextComponent text; + + /** + * The format string to use when there is no selected: + * the arguments are: + * 1 based line number + * 1 based column number + * 0 based position + */ + private String noSelectionFormat = "%d:%d (%d)"; + /** + * The format string to use when something is selected: + * the arguments are: + * 1 based line number for selection start + * 1 based column number for selection start + * 1 based line number for selection end + * 1 based column number for selection end + * length of selection + * 0 based start position + * 0 based end position + */ + private String selectionFormat = "%d:%d - %d:%d (%d)"; + + public CaretMonitor(JTextComponent text, JLabel label) { + this.label = label; + this.text = text; + text.addCaretListener(this); + updateLabel(text.getCaretPosition()); + } + + @Override + public void caretUpdate(CaretEvent evt) { + updateLabel(evt.getDot()); + } + + protected void updateLabel(int pos) { + if (text.getDocument() instanceof SyntaxDocument) { + try { + if (text.getSelectionStart() == text.getSelectionEnd()) { + String loc = String.format(noSelectionFormat, + ActionUtils.getLineNumber(text, pos) + 1, + ActionUtils.getColumnNumber(text, pos) + 1, + pos); + label.setText(loc); + } else { + int start = text.getSelectionStart(); + int end = text.getSelectionEnd(); + String loc = String.format(selectionFormat, + ActionUtils.getLineNumber(text, start) + 1, + ActionUtils.getColumnNumber(text, start) + 1, + ActionUtils.getLineNumber(text, end) + 1, + ActionUtils.getColumnNumber(text, end) + 1, + (end - start), + start, + end); + label.setText(loc); + } + } catch (BadLocationException ex) { + label.setText("Ex: " + ex.getMessage()); + } + } else { + label.setText(String.format(noSelectionFormat, 1, 1, 1)); + } + } + + @Override + protected void finalize() throws Throwable { + text.removeCaretListener(this); + super.finalize(); + } + + public String getNoSelectionFormat() { + return noSelectionFormat; + } + + public void setNoSelectionFormat(String noSelectionFormat) { + this.noSelectionFormat = noSelectionFormat; + } + + public String getSelectionFormat() { + return selectionFormat; + } + + public void setSelectionFormat(String selectionFormat) { + this.selectionFormat = selectionFormat; + } + +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ComboCompletionAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ComboCompletionAction.java new file mode 100644 index 0000000..23265bf --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ComboCompletionAction.java @@ -0,0 +1,80 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import java.util.List; +import java.util.Map; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.actions.gui.ComboCompletionDialog; +import de.sciss.syntaxpane.util.JarServiceProvider; + +/** + * ComboBox like Completion Action: + * This will display a list of items to choose from, it can be used similar to + * IntelliSense. The List is obtained from a plain text file, each line being + * an item in the list. + * + * @author Ayman Al-Sairafi + */ +public class ComboCompletionAction extends DefaultSyntaxAction { + + Map completions; + ComboCompletionDialog dlg; + private List items; + + public ComboCompletionAction() { + super("COMBO_COMPLETION"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sdoc, + int dot, ActionEvent e) { + if (sdoc == null) { + return; + } + Token token = sdoc.getTokenAt(dot); + String abbrev = ""; + if (token != null) { + abbrev = token.getString(sdoc); + target.select(token.start, token.end()); + } + if (dlg == null) { + dlg = new ComboCompletionDialog(target); + } + dlg.displayFor(abbrev, items); + } + + public void setItemsURL(String value) { + items = JarServiceProvider.readLines(value); + } + + /** + * Gets the items to display in the combo + * @return + */ + public List getItems() { + return items; + } + + /** + * Sets the items to display in the combo. + * @param items + */ + public void setItems(List items) { + this.items = items; + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/CompleteWordAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/CompleteWordAction.java new file mode 100644 index 0000000..97a2a8c --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/CompleteWordAction.java @@ -0,0 +1,102 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.actions.gui.ComboCompletionDialog; +import de.sciss.syntaxpane.util.StringUtils; + +/** + * This action will try to complete the word at the cursor by + * looking for a matching word in this document that starts with + * the same letters. + * + * This makes use of the SyntaxDocument.getWordAt, which requires + * a Regexp Pattern. The Pattern should match any word regardless of + * the Tokens. + * + * This Regexp is configurable with {@code ACTION_NAME.WordsRegexp}. + * The default Regexp is \w+ (any word char) + * + * @author Ayman Al-Sairafi + */ +public class CompleteWordAction extends DefaultSyntaxAction { + + public CompleteWordAction() { + super("COMPLETE_WORD"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sdoc, + int dot, ActionEvent e) { + Token current = sdoc.getWordAt(dot, wordsPattern); + if (current == null) { + return; + } + String cw = current.getString(sdoc); + target.select(current.start, current.end()); + + sdoc.readLock(); + List matches = new ArrayList(); + Matcher m = sdoc.getMatcher(wordsPattern, 0, current.start); + addWords(m, cw, matches); + m = sdoc.getMatcher(wordsPattern, current.end(), sdoc.getLength() - current.end()); + addWords(m, cw, matches); + sdoc.readUnlock(); + if (matches.size() == 0) { + return; + } + if (matches.size() == 1) { + target.replaceSelection(matches.get(0)); + return; + } + if (dlg == null) { + dlg = new ComboCompletionDialog(target); + } + dlg.displayFor(cw, matches); + } + + public void setWordsRegexp(String value) { + wordsPattern = Pattern.compile(value); + + } + + /** + * Add words from the matcher m that match the word abbr to matches + * List + * @param m matcher instance, could be null, to iterate through + * @param abbr abbriviated word + * @param matches List of matches + */ + private void addWords(Matcher m, String abbr, List matches) { + while (m != null && m.find()) { + String word = m.group(); + if (StringUtils.camelCaseMatch(word, abbr)) { + if (!matches.contains(word)) { + matches.add(word); + } + } + } + } + private ComboCompletionDialog dlg; + private Pattern wordsPattern = DEFAULT_WORDS_REGEXP; + private static final Pattern DEFAULT_WORDS_REGEXP = Pattern.compile("\\w+"); +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/DefaultSyntaxAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/DefaultSyntaxAction.java new file mode 100644 index 0000000..2d9fc55 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/DefaultSyntaxAction.java @@ -0,0 +1,139 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import java.net.URL; +import java.util.regex.Pattern; +import javax.swing.*; +import javax.swing.text.JTextComponent; +import javax.swing.text.TextAction; +import de.sciss.syntaxpane.SyntaxDocument; +import de.sciss.syntaxpane.util.Configuration; +import de.sciss.syntaxpane.util.ReflectUtils; + +/** + * The DefaultSyntaxAction. You can extend this class or implement the interface + * SyntaxAction to create your own actions. + * + * @author Ayman Al-Sairafi + */ +abstract public class DefaultSyntaxAction extends TextAction implements SyntaxAction { + + public DefaultSyntaxAction(String actionName) { + super(actionName); + putValue(NAME, actionName); + } + + @Override + public void install(JEditorPane editor, Configuration config, String name) { + // find setter methods for each property key: + String actionName = name.substring(ACTION_PREFIX.length()); + for (Configuration.StringKeyMatcher m : config.getKeys( + Pattern.compile(Pattern.quote(name) + "\\.((\\w|-)+)"))) { + if (!ReflectUtils.callSetter(this, m.group1, m.value)) { + putValue(m.group1, m.value); + } + } + // if we did not put a name, use the action name + if (getValue(NAME) == null) { + putValue(NAME, actionName); + } + // if we did not put an icon, try and find one using our name + if (getValue(SMALL_ICON) == null) { + setSmallIcon(actionName + ".png"); + } + } + + @Override + public void deinstall(JEditorPane editor) { + // nothing + } + + @Override + public void actionPerformed(ActionEvent e) { + JTextComponent text = getTextComponent(e); + SyntaxDocument sdoc = ActionUtils.getSyntaxDocument(text); + if (text != null) { + actionPerformed(text, sdoc, text.getCaretPosition(), e); + } + } + + /** + * Convenience method that will be called if the Action is performed on a + * JTextComponent. SyntaxActions should generally override this method. + * @param target (non-null JTextComponent from Action.getSource + * @param sDoc (SyntaxDOcument of the text component, could be null) + * @param dot (position of caret at text document) + * @param e actual ActionEvent passed to actionPerformed + */ + public void actionPerformed(JTextComponent target, SyntaxDocument sDoc, + int dot, ActionEvent e) { + throw new UnsupportedOperationException("Not yet implemented"); + } + + @Override + public String toString() { + return "Action " + getValue(NAME) + "of type " + this.getClass().getSimpleName(); + } + + /** + * Configure the MenuText for the Action + * @param text + */ + public final void setMenuText(String text) { + putValue(NAME, text); + // also set the SHORT_DESCRIPTIOn if it was not set, so we have + // at least some tooltip for toolbar buttons + if (getValue(SHORT_DESCRIPTION) == null) { + putValue(SHORT_DESCRIPTION, text); + } + } + + /** + * Configure the ToolTip for the Action + * @param text + */ + public final void setToolTip(String text) { + putValue(SHORT_DESCRIPTION, text); + } + + /** + * Sets the Large Icon for this action from given url + * + * @param url + */ + public final void setLargeIcon(String url) { + URL loc = this.getClass().getClassLoader().getResource(LARGE_ICONS_LOC_PREFIX + url); + if (loc != null) { + ImageIcon i = new ImageIcon(loc); + putValue(LARGE_ICON_KEY, i); + } + } + + /** + * Configure the SmallIcon for the Action + * @param url + */ + public final void setSmallIcon(String url) { + URL loc = this.getClass().getClassLoader().getResource(SMALL_ICONS_LOC_PREFIX + url); + if (loc != null) { + ImageIcon i = new ImageIcon(loc); + putValue(SMALL_ICON, i); + } + } + public static final String ACTION_PREFIX = "Action."; + public static final String SMALL_ICONS_LOC_PREFIX = "de/sciss/syntaxpane/images/small-icons/"; + public static final String LARGE_ICONS_LOC_PREFIX = "de/sciss/syntaxpane/images/large-icons/"; +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/DeleteLinesAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/DeleteLinesAction.java new file mode 100644 index 0000000..ddf0bb8 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/DeleteLinesAction.java @@ -0,0 +1,44 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.text.BadLocationException; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; + +/** + * This Action deletes the current line, or all the highlighted lines. + * @author Ayman Al-Sairafi + */ +public class DeleteLinesAction extends DefaultSyntaxAction { + + public DeleteLinesAction() { + super("DELETE_LINES"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sdoc, + int dot, ActionEvent e) { + try { + int st = sdoc.getLineStartOffset(target.getSelectionStart()); + int en = sdoc.getLineEndOffset(target.getSelectionEnd()); + sdoc.remove(st, en - st); + } catch (BadLocationException ex) { + Logger.getLogger(DeleteLinesAction.class.getName()).log(Level.SEVERE, null, ex); + } + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/DocumentSearchData.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/DocumentSearchData.java new file mode 100644 index 0000000..3bbc7cd --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/DocumentSearchData.java @@ -0,0 +1,267 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.Component; +import java.text.MessageFormat; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import javax.swing.text.BadLocationException; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; +import de.sciss.syntaxpane.actions.gui.QuickFindDialog; +import de.sciss.syntaxpane.actions.gui.ReplaceDialog; + +/** + * Data that is shared by Find / Replace and Find Next actions for a Document + * The data here will be added as a property of the Document using the key + * PROPERTY_KEY. Only through the getFtmEditor can you crate a new instance. + * + * The class is responsible for handling the doFind and doReplace all actions. + * + * The class is also responsible for displaying the Find / Replace dialog + * + * @author Ayman Al-Sairafi + */ +public class DocumentSearchData { + + private static final String PROPERTY_KEY = "SearchData"; + private Pattern pattern = null; + private boolean wrap = true; + private ReplaceDialog replaceDlg; + private QuickFindDialog quickFindDlg; + + /** + * This prevent creating a new instance. You must call the getFromEditor + * to crate a new instance attached to a Document + * + */ + private DocumentSearchData() { + } + + public Pattern getPattern() { + return pattern; + } + + /** + * Set the pattern to the given compiled pattern. + * @see this#setPattern(String, boolean, boolean) + * @param pattern + */ + public void setPattern(Pattern pattern) { + this.pattern = pattern; + } + + /** + * Sets the pattern from a string and flags + * @param pat String of pattern + * @param regex true if the pattern should be a regexp + * @param ignoreCase true to ignore case + * @throws java.util.regex.PatternSyntaxException + */ + public void setPattern(String pat, boolean regex, boolean ignoreCase) + throws PatternSyntaxException { + if (pat != null && pat.length() > 0) { + int flag = (regex) ? 0 : Pattern.LITERAL; + flag |= (ignoreCase) ? Pattern.CASE_INSENSITIVE : 0; + setPattern(Pattern.compile(pat, flag)); + } else { + setPattern(null); + } + } + + public boolean isWrap() { + return wrap; + } + + public void setWrap(boolean wrap) { + this.wrap = wrap; + } + + /** + * Get the Search data from a Document. If document does not have any + * search data, then a new instance is added, put and reurned. + * @param target JTextCOmponent we are attaching to + * @return + */ + public static DocumentSearchData getFromEditor(JTextComponent target) { + if (target == null) { + return null; + } + Object o = target.getDocument().getProperty(PROPERTY_KEY); + if (o instanceof DocumentSearchData) { + DocumentSearchData documentSearchData = (DocumentSearchData) o; + return documentSearchData; + } else { + DocumentSearchData newDSD = new DocumentSearchData(); + target.getDocument().putProperty(PROPERTY_KEY, newDSD); + return newDSD; + } + } + + /** + * Perform a replace all operation on the given component. + * Note that this create a new duplicate String big as the entire + * document and then assign it to the target text component + * @param target + * @param replacement + */ + public void doReplaceAll(JTextComponent target, String replacement) { + if (replacement == null) { + replacement = ""; + } + SyntaxDocument sDoc = ActionUtils.getSyntaxDocument(target); + if (sDoc == null) { + return; + } + if (getPattern() == null) { + return; + } + Matcher matcher = sDoc.getMatcher(getPattern()); + String newText = matcher.replaceAll(replacement); + try { + sDoc.replace(0, sDoc.getLength(), newText, null); + } catch (BadLocationException ex) { + Logger.getLogger(DocumentSearchData.class.getName()).log(Level.SEVERE, null, ex); + } + } + + /** + * Replace single occurrence of match with the replacement. + * @param target + * @param replacement + */ + public void doReplace(JTextComponent target, String replacement) { + if (target.getSelectedText() != null) { + target.replaceSelection(replacement == null ? "" : replacement); + doFindNext(target); + } + } + + /** + * FInd the previous match + * @param target + * @return + */ + public boolean doFindPrev(JTextComponent target) { + if (getPattern() == null) { + return false; + } + SyntaxDocument sDoc = ActionUtils.getSyntaxDocument(target); + if (sDoc == null) { + return false; + } + int dot = target.getSelectionStart(); + Matcher matcher = sDoc.getMatcher(getPattern()); + if (matcher == null) { + return false; + } + // we have no way of jumping to last match, so we need to + // go throw all matches, and stop when we reach current pos + int start = -1; + int end = -1; + while (matcher.find()) { + if (matcher.end() >= dot) { + break; + } + start = matcher.start(); + end = matcher.end(); + } + if (end > 0) { + target.select(start, end); + return true; + } else { + return false; + } + } + + /** + * Perform a FindNext operation on the given text component. Position + * the caret at the start of the next found pattern. + * @param target + * @return true if pattern is found, false otherwise + */ + public boolean doFindNext(JTextComponent target) { + if (getPattern() == null) { + return false; + } + SyntaxDocument sDoc = ActionUtils.getSyntaxDocument(target); + if (sDoc == null) { + return false; + } + int start = target.getSelectionEnd(); + if (target.getSelectionEnd() == target.getSelectionStart()) { + // we must advance the position by one, otherwise we will find + // the same text again + start++; + } + if (start >= sDoc.getLength()) { + start = sDoc.getLength(); + } + Matcher matcher = sDoc.getMatcher(getPattern(), start); + if (matcher != null && matcher.find()) { + // since we used an offset in the matcher, the matcher location + // MUST be offset by that location + target.select(matcher.start() + start, matcher.end() + start); + return true; + } else { + if (isWrap()) { + matcher = sDoc.getMatcher(getPattern()); + if (matcher != null && matcher.find()) { + target.select(matcher.start(), matcher.end()); + return true; + } else { + return false; + } + } else { + return false; + } + } + } + + /** + * Display an OptionPane dialog that the search string is not found + * @param target + */ + public void msgNotFound(Component target) { + JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(target), + MessageFormat.format(java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle") + .getString("DocumentSearchData.SearchStringNotFound"), getPattern()), + java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle") + .getString("DocumentSearchData.Find"), JOptionPane.INFORMATION_MESSAGE); + } + + /** + * Show the Find and Replace dialog for the given frame + * @param target + */ + public void showReplaceDialog(JTextComponent target) { + if (replaceDlg == null) { + replaceDlg = new ReplaceDialog(target, this); + } + replaceDlg.setVisible(true); + } + + public void showQuickFindDialog(JTextComponent target) { + if (quickFindDlg == null) { + quickFindDlg = new QuickFindDialog(target, this); + } + quickFindDlg.showFor(target); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/DuplicateLinesAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/DuplicateLinesAction.java new file mode 100644 index 0000000..6c3fd10 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/DuplicateLinesAction.java @@ -0,0 +1,45 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.text.BadLocationException; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; + +/** + * This Action duplicates the current line, or all the highlighted lines. + * @author Ayman Al-Sairafi + */ +public class DuplicateLinesAction extends DefaultSyntaxAction { + + public DuplicateLinesAction() { + super("DUPLICATE_LINES"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sdoc, + int dot, ActionEvent e) { + try { + int st = sdoc.getLineStartOffset(target.getSelectionStart()); + int en = sdoc.getLineEndOffset(target.getSelectionEnd()); + String dupLines = sdoc.getText(st, en - st); + sdoc.insertString(st, dupLines, null); + } catch (BadLocationException ex) { + Logger.getLogger(DuplicateLinesAction.class.getName()).log(Level.SEVERE, null, ex); + } + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/FindNextAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/FindNextAction.java new file mode 100644 index 0000000..2045a73 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/FindNextAction.java @@ -0,0 +1,26 @@ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; + +/** + * This class performs a Find Next operation by using the current pattern + */ +public class FindNextAction extends DefaultSyntaxAction { + + public FindNextAction() { + super("find-next"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sdoc, + int dot, ActionEvent e) { + DocumentSearchData dsd = DocumentSearchData.getFromEditor(target); + if (dsd != null) { + if(!dsd.doFindNext(target)) { + dsd.msgNotFound(target); + } + } + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/FindReplaceAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/FindReplaceAction.java new file mode 100644 index 0000000..168b285 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/FindReplaceAction.java @@ -0,0 +1,42 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; + +/** + * Finder class. This class contains the general Find, Find Next, + * Find Previous, and the Find Marker Actions. + * + * Note that all Actions are subclasses of this class because all actions + * require the find text to be shared among them. This is the best approach + * to have all Action classes share this same data. + * + * @author Ayman Al-Sairafi + */ +public class FindReplaceAction extends DefaultSyntaxAction { + + public FindReplaceAction() { + super("FIND_REPLACE"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sdoc, + int dot, ActionEvent e) { + DocumentSearchData dsd = DocumentSearchData.getFromEditor(target); + dsd.showReplaceDialog(target); + } +} \ No newline at end of file diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/GotoLineAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/GotoLineAction.java new file mode 100644 index 0000000..6c09a3d --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/GotoLineAction.java @@ -0,0 +1,35 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import de.sciss.syntaxpane.actions.gui.GotoLineDialog; +import java.awt.event.ActionEvent; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; + +/** + * This actions displays the GotoLine dialog + */ +public class GotoLineAction extends DefaultSyntaxAction { + + public GotoLineAction() { + super("GOTO_LINE"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sdoc, + int dot, ActionEvent e) { + GotoLineDialog.showForEditor(target); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/HTMLPreviewAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/HTMLPreviewAction.java new file mode 100644 index 0000000..14042ec --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/HTMLPreviewAction.java @@ -0,0 +1,47 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; +import de.sciss.syntaxpane.actions.gui.HTMLPreviewFrame; + +/** + * Show an HTML Preview window. + * This will automatically update on changes to the underlying document. + * + */ +public class HTMLPreviewAction extends DefaultSyntaxAction { + public static final String HTML_PREVIEW_WINDOW = "html-preview-window"; + + public HTMLPreviewAction() { + super("HTML_PREVIEW"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sDoc, + int dot, ActionEvent e) { + // have the document property + Object obj = sDoc.getProperty(HTML_PREVIEW_WINDOW); + if(obj == null) { + HTMLPreviewFrame dlg = new HTMLPreviewFrame(sDoc); + sDoc.putProperty( HTML_PREVIEW_WINDOW,dlg); + dlg.setVisible(true); + } else { + HTMLPreviewFrame dlg = (HTMLPreviewFrame) obj; + dlg.setVisible(enabled); + } + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/IndentAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/IndentAction.java new file mode 100644 index 0000000..da27ca1 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/IndentAction.java @@ -0,0 +1,96 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import java.util.Map; +import java.util.regex.Pattern; +import javax.swing.JEditorPane; +import javax.swing.text.EditorKit; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.SyntaxDocument; +import de.sciss.syntaxpane.Token; + +/** + * IndentAction is used to replace Tabs with spaces. If there is selected + * text, then the lines spanning the selection will be shifted + * right by one tab-width space character. + * + * Since this is also used as an abbreviation completion action, + * Abbreviiations are processed by this event. + * + * FIXME: Move the abbreviation expansion to an ActionUtils proc + * @author Ayman Al-Sairafi + * + */ +public class IndentAction extends DefaultSyntaxAction { + + public IndentAction() { + super("insert-tab"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sDoc, + int dot, ActionEvent e) { + String selected = target.getSelectedText(); + EditorKit kit = ((JEditorPane) target).getEditorKit(); + Map abbrvs = ((DefaultSyntaxKit) kit).getAbbreviations(); + if (selected == null) { + // Check for abbreviations: + Token abbrToken = sDoc.getWordAt(dot, wordsPattern); + Integer tabStop = ActionUtils.getTabSize(target); + int lineStart = sDoc.getParagraphElement(dot).getStartOffset(); + int column = dot - lineStart; + int needed = tabStop - (column % tabStop); + if (abbrvs == null || abbrToken == null) { + target.replaceSelection(ActionUtils.SPACES.substring(0, needed)); + } else { + String abbr = abbrToken.getString(sDoc); + if (abbrvs.containsKey(abbr)) { + target.select(abbrToken.start, abbrToken.end()); + abbr = abbrvs.get(abbr); + String[] abbrLines = abbr.split("\n"); + if (abbrLines.length > 1) { + ActionUtils.insertLinesTemplate(target, abbrLines); + } else { + ActionUtils.insertSimpleTemplate(target, abbr); + } + } else { + target.replaceSelection(ActionUtils.SPACES.substring(0, needed)); + } + } + } else { + String[] lines = ActionUtils.getSelectedLines(target); + int start = target.getSelectionStart(); + StringBuilder sb = new StringBuilder(); + for (String line : lines) { + sb.append(ActionUtils.getTab(target)); + sb.append(line); + sb.append('\n'); + } + target.replaceSelection(sb.toString()); + target.select(start, start + sb.length()); + } + } + private Pattern wordsPattern = Pattern.compile("\\w+"); + + public void setWordRegex(String regex) { + wordsPattern = Pattern.compile(regex); + } + + public Pattern getWordRegex() { + return wordsPattern; + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/JIndentAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/JIndentAction.java new file mode 100644 index 0000000..b9b9c3f --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/JIndentAction.java @@ -0,0 +1,81 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.text.BadLocationException; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +/** + * This class should be mapped to VK_ENTER. It performs proper indentation + * for Java Type languages and automatically inserts "*" in multi-line comments + * Initial Code contributed by ser... AT mail.ru + * + * @author Ayman Al-Sairafi + */ +public class JIndentAction extends DefaultSyntaxAction { + + public JIndentAction() { + super("JINDENT"); + } + + /** + * {@inheritDoc} + * @param e + */ + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sDoc, + int dot, ActionEvent e) { + int pos = target.getCaretPosition(); + int start = sDoc.getParagraphElement(pos).getStartOffset(); + String line = ActionUtils.getLine(target); + String lineToPos = line.substring(0, pos - start); + String prefix = ActionUtils.getIndent(line); + Token t = sDoc.getTokenAt(pos); + if (TokenType.isComment(t)) { + String trimmed = line.trim(); + if (trimmed.startsWith("/*") && trimmed.endsWith("*/")) { + // it's a single line comment, do not do anything special + } else if (trimmed.endsWith("*/")) { + try { + // the prefix should be the line where the comment started + String commentStartLine = sDoc.getLineAt(t.start); + prefix = ActionUtils.getIndent(commentStartLine); + } catch (BadLocationException ex) { + Logger.getLogger(JIndentAction.class.getName()).log(Level.SEVERE, null, ex); + } + } else if (trimmed.startsWith("*")) { + prefix += "* "; + } else if (trimmed.startsWith("/**")) { + prefix += " * "; + } else if (trimmed.startsWith("/*")) { + prefix += " "; + } + } else if (lineToPos.trim().endsWith("{")) { + prefix += ActionUtils.getTab(target); + } else { + String noComment = sDoc.getUncommentedText(start, pos); // skip EOL comments + + if (noComment.trim().endsWith("{")) { + prefix += ActionUtils.getTab(target); + } + } + target.replaceSelection("\n" + prefix); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/JUnindentAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/JUnindentAction.java new file mode 100644 index 0000000..42fffe9 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/JUnindentAction.java @@ -0,0 +1,57 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import javax.swing.text.BadLocationException; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; +import de.sciss.syntaxpane.Token; + +public class JUnindentAction extends DefaultSyntaxAction { + + /** + * creates new JUnindentAction. + * Initial Code contributed by ser... AT mail.ru + */ + public JUnindentAction() { + super("JUNINDENT"); + } + + /** + * {@inheritDoc} + */ + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sDoc, + int dot, ActionEvent e) { + int pos = target.getCaretPosition(); + int start = sDoc.getParagraphElement(pos).getStartOffset(); + String line = ActionUtils.getLine(target); + if (ActionUtils.isEmptyOrBlanks(line)) { + try { + sDoc.insertString(pos, "}", null); + Token t = sDoc.getPairFor(sDoc.getTokenAt(pos)); + if (null != t) { + String pairLine = ActionUtils.getLineAt(target, t.start); + String indent = ActionUtils.getIndent(pairLine); + sDoc.replace(start, line.length() + 1, indent + "}", null); + } + } catch (BadLocationException ble) { + target.replaceSelection("}"); + } + } else { + target.replaceSelection("}"); + } + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/JumpToPairAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/JumpToPairAction.java new file mode 100644 index 0000000..440bac4 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/JumpToPairAction.java @@ -0,0 +1,43 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; +import de.sciss.syntaxpane.Token; + +/** + * This actions Jumps to the pair of the token at the cursor. + */ +public class JumpToPairAction extends DefaultSyntaxAction { + + public JumpToPairAction() { + super("JUMP_TO_PAIR"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sdoc, + int dot, ActionEvent e) { + Token current = sdoc.getTokenAt(dot); + if (current == null) { + return; + } + + Token pair = sdoc.getPairFor(current); + if (pair != null) { + target.setCaretPosition(pair.start); + } + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/MapCompletionAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/MapCompletionAction.java new file mode 100644 index 0000000..6821712 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/MapCompletionAction.java @@ -0,0 +1,57 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import java.util.Map; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.util.JarServiceProvider; + +/** + * Completion Actions: + * All completions are based on a simple String to String Map. + */ +public class MapCompletionAction extends DefaultSyntaxAction { + + Map completions; + + public MapCompletionAction() { + super("MAP_COMPLETION"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sDoc, + int dot, ActionEvent e) { + Token token = sDoc.getTokenAt(dot); + if (token != null) { + String abbriv = ActionUtils.getTokenStringAt(sDoc, dot); + if (completions.containsKey(abbriv)) { + String completed = completions.get(abbriv); + if (completed.indexOf('|') >= 0) { + int ofst = completed.length() - completed.indexOf('|') - 1; + sDoc.replaceToken(token, completed.replace("|", "")); + target.setCaretPosition(target.getCaretPosition() - ofst); + } else { + sDoc.replaceToken(token, completed); + } + } + } + } + + public void setCompletionsFile(String value) { + completions = JarServiceProvider.readStringsMap(value); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/PairAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/PairAction.java new file mode 100644 index 0000000..34fa469 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/PairAction.java @@ -0,0 +1,56 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import java.util.HashMap; +import java.util.Map; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; + +/** + * A Pair action inserts a pair of characters (left and right) around the + * current selection, and then places the caret between them + * + * The pairs are hard-coded here. + */ +public class PairAction extends DefaultSyntaxAction { + + public PairAction() { + super("PAIR_ACTION"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sDoc, + int dot, ActionEvent e) { + String left = e.getActionCommand(); + String right = PAIRS.get(left); + String selected = target.getSelectedText(); + if (selected != null) { + target.replaceSelection(left + selected + right); + } else { + target.replaceSelection(left + right); + target.setCaretPosition(target.getCaretPosition() - right.length()); + } + } + private static Map PAIRS = new HashMap(4); + + + static { + PAIRS.put("(", ")"); + PAIRS.put("[", "]"); + PAIRS.put("\"", "\""); + PAIRS.put("'", "'"); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/PythonIndentAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/PythonIndentAction.java new file mode 100644 index 0000000..ef835ca --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/PythonIndentAction.java @@ -0,0 +1,57 @@ +/* + * Copyright 2009 Stefan Bechtold (stefan.bechtold@googlemail.com) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import javax.swing.text.JTextComponent; + +import de.sciss.syntaxpane.SyntaxDocument; + +public class PythonIndentAction extends DefaultSyntaxAction { + + /** + * creates new PythonIndentAction. + */ + public PythonIndentAction() { + super("PYTHONINDENT"); + } + + /** + * {@inheritDoc} + * @param e + */ + @Override + public void actionPerformed(ActionEvent e) { + JTextComponent target = getTextComponent(e); + if (target != null) { + SyntaxDocument sDoc = ActionUtils.getSyntaxDocument(target); + int pos = target.getCaretPosition(); + int start = sDoc.getParagraphElement(pos).getStartOffset(); + String line = ActionUtils.getLine(target); + String lineToPos = line.substring(0, pos - start); + String prefix = ActionUtils.getIndent(line); + int tabSize = ActionUtils.getTabSize(target); + if (lineToPos.trim().endsWith(":")) { + prefix += ActionUtils.SPACES.substring(0, tabSize); + } else { + String noComment = sDoc.getUncommentedText(start, pos); // skip EOL comments + + if (noComment.trim().endsWith(":")) { + prefix += ActionUtils.SPACES.substring(0, tabSize); + } + } + target.replaceSelection("\n" + prefix); + } + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/QuickFindAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/QuickFindAction.java new file mode 100644 index 0000000..673baa5 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/QuickFindAction.java @@ -0,0 +1,35 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; + +/** + * + * @author Ayman Al-Sairafi + */ +public class QuickFindAction extends DefaultSyntaxAction { + + public QuickFindAction() { + super("quick-find"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sDoc, + int dot, ActionEvent e) { + DocumentSearchData.getFromEditor(target).showQuickFindDialog(target); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/RedoAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/RedoAction.java new file mode 100644 index 0000000..405a649 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/RedoAction.java @@ -0,0 +1,39 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import javax.swing.text.JTextComponent; + +import de.sciss.syntaxpane.SyntaxDocument; + +/** + * Redo action + */ +public class RedoAction extends AbstractUndoRedoAction { + + public RedoAction() { + super(SyntaxDocument.CAN_REDO, "REDO"); + } + + @Override + protected boolean updateState() { + return doc.canRedo(); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sDoc, int dot, ActionEvent e) { + if (sDoc != null) sDoc.doRedo(); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ReflectCompletionAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ReflectCompletionAction.java new file mode 100644 index 0000000..ec4aeba --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ReflectCompletionAction.java @@ -0,0 +1,49 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import de.sciss.syntaxpane.actions.gui.ReflectCompletionDialog; +import java.awt.event.ActionEvent; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; +import de.sciss.syntaxpane.Token; + +/** + * ComboBox like Completion Action: + * This will display a list of items to choose from, its can be used similar to + * IntelliSense + * + * @author Ayman Al-Sairafi + */ +public class ReflectCompletionAction extends DefaultSyntaxAction { + + ReflectCompletionDialog dlg; + + public ReflectCompletionAction() { + super("REFLECT_COMPLETION"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sDoc, + int dot, ActionEvent e) { + Token t = sDoc.getTokenAt(dot); + if(t != null) { + target.select(t.start, t.end()); + } + if (dlg == null) { + dlg = new ReflectCompletionDialog(target); + } + dlg.displayFor(target); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ScriptAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ScriptAction.java new file mode 100644 index 0000000..ba3d290 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ScriptAction.java @@ -0,0 +1,113 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.util.regex.Pattern; +import javax.script.Invocable; +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; +import javax.script.ScriptException; +import javax.swing.*; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; +import de.sciss.syntaxpane.util.Configuration; +import de.sciss.syntaxpane.util.JarServiceProvider; + +/** + * This class executes a script every time it is called. + * Anything can be done using any script. + * + * @author Ayman Al-Sairafi + */ +public class ScriptAction extends DefaultSyntaxAction { + + public ScriptAction() { + super("scripted-action"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sDoc, + int dot, ActionEvent e) { + if (getValue(SCRIPT_FUNCTION) != null) { + String f = getValue(SCRIPT_FUNCTION).toString(); + try { + engine.put("TARGET", target); + engine.put("SDOC", sDoc); + engine.put("DOT", dot); + engine.put("EVENT", e); + engine.put("ACTION", this); + engine.put("AU", ActionUtils.getInstance()); + invocable.invokeFunction(f); + } catch (ScriptException ex) { + showScriptError(target, ex); + } catch (NoSuchMethodException ex) { + showScriptError(target, ex); + } + } else { + JOptionPane.showMessageDialog(target, java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle") + .getString("ScriptAction.NoScriptConfigured"), + java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle") + .getString("ScriptAction.ErrorInScript"), JOptionPane.WARNING_MESSAGE); + } + } + + public void setFunction(String name) { + putValue(SCRIPT_FUNCTION, name); + } + + @Override + public void install(JEditorPane editor, Configuration config, String name) { + super.install(editor, config, name); + // now read and store all of our scripts. + for (Configuration.StringKeyMatcher m : config.getKeys(Pattern.compile("Script\\.((\\w|-)+)\\.URL"))) { + getScriptFromURL(m.value); + } + } + + public void getScriptFromURL(String url) { + InputStream is = JarServiceProvider.findResource(url, this.getClass().getClassLoader()); + if (is != null) { + Reader reader = new InputStreamReader(is); + try { + engine.eval(reader); + } catch (ScriptException ex) { + showScriptError(null, ex); + } + } else { + JOptionPane.showMessageDialog(null, java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle").getString("ScriptAction.NoScriptFoundIn") + url, + java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle").getString("ScriptAction.ErrorInScript"), JOptionPane.WARNING_MESSAGE); + } + } + + private void showScriptError(JTextComponent target, Exception ex) { + JOptionPane.showMessageDialog(target, ex.getMessage(), + java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle").getString("ScriptAction.ErrorInScript"), JOptionPane.WARNING_MESSAGE); + } + /** + * The key used to store the Script Name for the this action + */ + static final String SCRIPT_FUNCTION = "SCRIPT_FUNCTION"; + static final ScriptEngine engine; + static final Invocable invocable; + + + static { + engine = new ScriptEngineManager().getEngineByExtension("js"); + invocable = (Invocable) engine; + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ScriptRunnerAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ScriptRunnerAction.java new file mode 100644 index 0000000..06b6302 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ScriptRunnerAction.java @@ -0,0 +1,90 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import java.text.MessageFormat; + +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; +import javax.script.ScriptException; +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; + +/** + * Executes the script in the component's text using a ScriptEngine + * The Configuration must contain the key [prefix.]ACTION_NAME.ScriptExtension + * and its value is the ScriptExtension that getEngineByExtension returns + * If no engine is found, then an option is given to the user to disable the action + * + * @author Ayman Al-Sairafi + */ +public class ScriptRunnerAction extends DefaultSyntaxAction { + + public ScriptRunnerAction() { + super("SCRIPT_EXECUTE"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sDoc, + int dot, ActionEvent e) { + try { + ScriptEngine eng = getEngine(target); + if (eng != null) { + getEngine(target).eval(target.getText()); + } + } catch (ScriptException ex) { + JOptionPane.showMessageDialog(SwingUtilities.getWindowAncestor(target), + java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle").getString("ScriptRunnerAction.ErrorExecutingScript") + ex.getMessage(), + java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle").getString("ScriptRunnerAction.ScriptError"), + JOptionPane.ERROR_MESSAGE); + ActionUtils.setCaretPosition(target, + ex.getLineNumber(), + ex.getColumnNumber()); + } + } + + private ScriptEngine getEngine(JTextComponent target) { + if (engine == null) { + if (sem == null) { + sem = new ScriptEngineManager(); + } + engine = sem.getEngineByExtension(scriptExtension); + } + if (engine == null) { + int result = JOptionPane.showOptionDialog(target, + MessageFormat.format(java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle").getString("ScriptRunnerAction.ScriptEngineNotFound"), scriptExtension), + "syntaxpane", + JOptionPane.YES_NO_OPTION, + JOptionPane.ERROR_MESSAGE, + null, + null, + null); + if (result == JOptionPane.YES_OPTION) { + setEnabled(false); + } + } + return engine; + } + + public void setScriptExtension(String value) { + scriptExtension = value; + } + + static ScriptEngineManager sem; + private ScriptEngine engine; + private String scriptExtension; +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ShowAbbsAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ShowAbbsAction.java new file mode 100644 index 0000000..af5c9bd --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ShowAbbsAction.java @@ -0,0 +1,52 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import java.util.Map; +import javax.swing.JEditorPane; +import javax.swing.JOptionPane; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.SyntaxDocument; +import de.sciss.syntaxpane.actions.gui.ShowAbbsDialog; + +/** + * Display all abbreviations for a JTextComponent., if it has any. + * Abbreviations are obtained from the IndentAction, so if the target does not + * have an instance of that actions, nothing is displayed. + * @author Ayman Al-Sairafi + */ +public class ShowAbbsAction extends DefaultSyntaxAction { + + public ShowAbbsAction() { + super("show-abbreviations"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sDoc, + int dot, ActionEvent e) { + // find the abbreviations actions: + DefaultSyntaxKit kit = ActionUtils.getSyntaxKit(target); + if (kit != null) { + Map abbs = kit.getAbbreviations(); + if (abbs == null || abbs.isEmpty()) { + JOptionPane.showMessageDialog(target, + java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle").getString("ShowAbbsAction.NoAbbsForType")); + } else { + new ShowAbbsDialog((JEditorPane) target, abbs); + } + } + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/SmartHomeAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/SmartHomeAction.java new file mode 100644 index 0000000..f567c86 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/SmartHomeAction.java @@ -0,0 +1,74 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import java.text.CharacterIterator; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.text.BadLocationException; +import javax.swing.text.Element; +import javax.swing.text.JTextComponent; +import javax.swing.text.Segment; +import de.sciss.syntaxpane.SyntaxDocument; + +/** + * + * @author Ayman Al-Sairafi + */ +public class SmartHomeAction extends DefaultSyntaxAction { + + public SmartHomeAction() { + super("smart-home"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sDoc, + int dot, ActionEvent e) { + try { + target.setCaretPosition(getSmartHomeOffset(target, sDoc, dot)); + } catch (BadLocationException ex) { + Logger.getLogger(SmartHomeAction.class.getName()).log(Level.SEVERE, null, ex); + } + } + + static int getSmartHomeOffset(JTextComponent target, SyntaxDocument sDoc, + int dot) throws BadLocationException { + Element el = sDoc.getParagraphElement(dot); + Segment seg = new Segment(); + sDoc.getText(el.getStartOffset(), + el.getEndOffset() - el.getStartOffset() - 1, seg); + int homeOffset = 0; + int dotLineOffset = dot - el.getStartOffset(); + boolean inText = false; + // see the location of first non-space offset + for (int i = 0; i < dotLineOffset; i++) { + if (!Character.isWhitespace(seg.charAt(i))) { + inText = true; + break; + } + } + // if we are at first char in line, or we are past the non space + // chars in the line, then we move to non-space char + // otherwise, we move to first char of line + if (dotLineOffset == 0 || inText) { + for (char ch = seg.first(); + ch != CharacterIterator.DONE && Character.isWhitespace(ch); + ch = seg.next()) { + homeOffset++; + } + } + return el.getStartOffset() + homeOffset; + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/SmartHomeSelectAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/SmartHomeSelectAction.java new file mode 100644 index 0000000..e62fe5c --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/SmartHomeSelectAction.java @@ -0,0 +1,42 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.text.BadLocationException; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; + +/** + * + * @author Ayman Al-Sairafi + */ +public class SmartHomeSelectAction extends DefaultSyntaxAction { + + public SmartHomeSelectAction() { + super("smart-home-select"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sDoc, + int dot, ActionEvent e) { + try { + target.moveCaretPosition(SmartHomeAction.getSmartHomeOffset(target, sDoc, dot)); + } catch (BadLocationException ex) { + Logger.getLogger(SmartHomeSelectAction.class.getName()).log(Level.SEVERE, null, ex); + } + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/SyntaxAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/SyntaxAction.java new file mode 100644 index 0000000..7e7d678 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/SyntaxAction.java @@ -0,0 +1,45 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import javax.swing.*; + +import de.sciss.syntaxpane.util.Configuration; + +/** + * All SyntaxPane Keyboard related actions implement this class. These + * classes are created dynamically, and then registered to the SyntaxKit. + * + * A class may have multiple TextActions that may be related. Each EditorKit + * that is installed will have only one instance of each class, even if more + * than one action is specified. + * + * The key value pairs in the Configuration are of the form: + * + * [EditorKit.]Action.NAME = class, keyboard key + * + * @author Ayman Al-Sairafi + */ +public interface SyntaxAction extends Action { + + /** + * Configure the actions in this class + * @param config the properties from which the action was constructed + * @param name name of the action, (prefixed by Action.) will be obtained from the property Key as the + * text following the Action. + */ + public void install(JEditorPane editor, Configuration config, String name); + + public void deinstall(JEditorPane editor); +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/TemplateAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/TemplateAction.java new file mode 100644 index 0000000..2dc37f0 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/TemplateAction.java @@ -0,0 +1,71 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; + +/** + * This action replaces the selection with the configured template in + * the config ACTION-NAME.Template + * + * There are two kinds of templates: + *
  • Simple Templates are replaced as is
  • + *
  • Whole Line Templates will ensure a whole line is selected. + * Each line in the selection will be prefixed, and postfixed with whatever appears + * on the line in the template
  • + * + */ +public class TemplateAction extends DefaultSyntaxAction { + + private String template; + private String[] tlines = null; + private boolean wholeLines; + private boolean mustHaveSelection; + + public TemplateAction() { + super("template"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sdoc, + int dot, ActionEvent e) { + if (mustHaveSelection) { + if (target.getSelectionEnd() == target.getSelectionStart()) { + return; + } + } + if (wholeLines) { + if(tlines == null) { + tlines = template.split("\n"); + } + ActionUtils.insertLinesTemplate(target, tlines); + } else { + ActionUtils.insertSimpleTemplate(target, template); + } + } + + public void setWholeLines(String value) { + wholeLines = Boolean.parseBoolean(value); + } + + public void setTemplate(String t) { + template = t; + } + + public void setMustHaveSelection(String value) { + mustHaveSelection = Boolean.parseBoolean(value); + } +} \ No newline at end of file diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ToggleCommentsAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ToggleCommentsAction.java new file mode 100644 index 0000000..f78ac45 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ToggleCommentsAction.java @@ -0,0 +1,82 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * Copyright 2013-2014 Hanns Holger Rutz. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; + +/** + * This action will toggle comments on or off on selected whole lines. + * + * @author Ayman Al-Sairafi, Hanns Holger Rutz + */ +public class ToggleCommentsAction extends DefaultSyntaxAction { + + protected String lineCommentStart = "//"; + protected Pattern lineCommentPattern = null; + + /** + * creates new JIndentAction. + * Initial Code contributed by ser... AT mail.ru + */ + public ToggleCommentsAction() { + super("toggle-comment"); + } + + /** + * {@inheritDoc} + */ + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sDoc, + int dot, ActionEvent e) { + if (lineCommentPattern == null) { + lineCommentPattern = Pattern.compile("(^\\s*)(" + lineCommentStart + "\\s?)(.*)"); + } + String[] lines = ActionUtils.getSelectedLines(target); + int start = target.getSelectionStart(); + StringBuilder toggled = new StringBuilder(); + boolean allComments = true; + for (int i = 0; i < lines.length; i++) { + Matcher m1 = lineCommentPattern.matcher(lines[i]); + if (!m1.find()) { + allComments = false; + break; + } + } + for (int i = 0; i < lines.length; i++) { + if (allComments) { + Matcher m1 = lineCommentPattern.matcher(lines[i]); + m1.find(); + toggled.append(m1.replaceFirst("$1$3")); + } else { + toggled.append(lineCommentStart); + toggled.append(' '); + toggled.append(lines[i]); + } + toggled.append('\n'); + } + target.replaceSelection(toggled.toString()); + target.select(start, start + toggled.length()); + } + + public void setLineComments(String value) { + String v1 = value.replace("\"", ""); + lineCommentStart = v1.charAt(v1.length() - 1) == ' ' ? v1.substring(0, v1.length() - 1) : v1; + lineCommentPattern = null; + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ToggleComponentAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ToggleComponentAction.java new file mode 100644 index 0000000..b81b293 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/ToggleComponentAction.java @@ -0,0 +1,57 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import javax.swing.JEditorPane; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.DefaultSyntaxKit; + +/** + * This Action will Toggle any SyntaxComponents on the EditorPane + * You need the configuration Key prefix.ACTION_NAME.Component = componentclassname + * Where: + * ACTION_NAME is the name given to the action (prefix.Action.ACTION_NAME) + * componentclassname is the fully qualified class name of the component + * @author Ayman Al-Sairafi + */ +public class ToggleComponentAction extends DefaultSyntaxAction { + + private String componentName; + + public ToggleComponentAction() { + super("toggle-component"); + putValue(SELECTED_KEY, Boolean.TRUE); + } + + public void setComponent(String name) { + componentName = name; + } + + @Override + public String toString() { + return super.toString() + "(" + componentName + ")"; + } + + @Override + public void actionPerformed(ActionEvent e) { + JTextComponent target = getTextComponent(e); + if (target instanceof JEditorPane) { + JEditorPane jEditorPane = (JEditorPane) target; + DefaultSyntaxKit kit = (DefaultSyntaxKit) jEditorPane.getEditorKit(); + boolean status = kit.toggleComponent(jEditorPane, componentName); + putValue(SELECTED_KEY, status); + } + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/UndoAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/UndoAction.java new file mode 100644 index 0000000..10b1778 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/UndoAction.java @@ -0,0 +1,38 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import de.sciss.syntaxpane.SyntaxDocument; + +import javax.swing.text.JTextComponent; +import java.awt.event.ActionEvent; + +/** + * Undo action + */ +public class UndoAction extends AbstractUndoRedoAction { + public UndoAction() { + super(SyntaxDocument.CAN_UNDO, "UNDO"); + } + + @Override + protected boolean updateState() { + return doc.canUndo(); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sDoc, int dot, ActionEvent e) { + if (sDoc != null) sDoc.doUndo(); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/UnindentAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/UnindentAction.java new file mode 100644 index 0000000..5eca4ac --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/UnindentAction.java @@ -0,0 +1,51 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; + +/** + * This is usually mapped to Shift-TAB to unindent the selection. The + * current line, or the selected lines are un-indented by the tabstop of the + * document. + */ +public class UnindentAction extends DefaultSyntaxAction { + + public UnindentAction() { + super("UNINDENT"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sDoc, + int dot, ActionEvent e) { + String indent = ActionUtils.getTab(target); + String[] lines = ActionUtils.getSelectedLines(target); + int start = target.getSelectionStart(); + StringBuilder sb = new StringBuilder(); + for (String line : lines) { + if (line.startsWith(indent)) { + sb.append(line.substring(indent.length())); + } else if (line.startsWith("\t")) { + sb.append(line.substring(1)); + } else { + sb.append(line); + } + sb.append('\n'); + } + target.replaceSelection(sb.toString()); + target.select(start, start + sb.length()); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/XmlPrettifyAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/XmlPrettifyAction.java new file mode 100644 index 0000000..32fb7ba --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/XmlPrettifyAction.java @@ -0,0 +1,140 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.Component; +import java.awt.event.ActionEvent; +import java.io.IOException; +import java.io.StringReader; +import java.io.StringWriter; +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import javax.swing.text.JTextComponent; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.OutputKeys; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerConfigurationException; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; +import de.sciss.syntaxpane.SyntaxDocument; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.SAXParseException; + +/** + * Attempt to prettify an XML document. + * @author Ayman Al-Sairafi + */ +public class XmlPrettifyAction extends DefaultSyntaxAction { + + public XmlPrettifyAction() { + super("XML_PRETTIFY"); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (transformer == null) { + return; + } + JTextComponent target = getTextComponent(e); + try { + SyntaxDocument sdoc = ActionUtils.getSyntaxDocument(target); + StringWriter out = new StringWriter(sdoc.getLength()); + StringReader reader = new StringReader(target.getText()); + InputSource src = new InputSource(reader); + Document doc = getDocBuilder().parse(src); + //Setup indenting to "pretty print" + getTransformer().transform(new DOMSource(doc), new StreamResult(out)); + target.setText(out.toString()); + } catch (SAXParseException ex) { + showErrorMessage(target, + String.format("XML error: %s\nat(%d, %d)", + ex.getMessage(), ex.getLineNumber(), ex.getColumnNumber())); + ActionUtils.setCaretPosition(target, ex.getLineNumber(), ex.getColumnNumber() - 1); + } catch (TransformerException ex) { + showErrorMessage(target, ex.getMessageAndLocation()); + } catch (SAXException ex) { + showErrorMessage(target, ex.getLocalizedMessage()); + } catch (IOException ex) { + showErrorMessage(target, ex.getLocalizedMessage()); + } + } + static Transformer transformer; + static DocumentBuilderFactory docBuilderFactory; + static DocumentBuilder docBuilder; + + private static void showErrorMessage(JTextComponent text, String msg) { + Component parent = SwingUtilities.getWindowAncestor(text); + JOptionPane.showMessageDialog(parent, msg, "SyntaxPane XML", JOptionPane.ERROR_MESSAGE); + } + + public static Transformer getTransformer() { + if (transformer == null) { + TransformerFactory tfactory = TransformerFactory.newInstance(); + try { + transformer = tfactory.newTransformer(); + } catch (TransformerConfigurationException ex) { + throw new IllegalArgumentException("Unable to create transformer. ", ex); + } + } + return transformer; + } + + public void setIndent(String text) { + getTransformer().setOutputProperty(OutputKeys.INDENT, text); + } + + public void setStandAlone(String text) { + getTransformer().setOutputProperty(OutputKeys.STANDALONE, text); + } + + public void setSOmitDeclaration(String text) { + getTransformer().setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, text); + } + + public void setIndentAmount(String text) { + getTransformer().setOutputProperty("{http://xml.apache.org/xslt}indent-amount", text); + } + + public void setIgnoreComments(String ic) { + getDocBuilderFactory().setIgnoringComments(Boolean.parseBoolean(ic)); + } + + public void setIgnoreWhiteSpace(String value) { + getDocBuilderFactory().setIgnoringElementContentWhitespace(Boolean.parseBoolean(value)); + } + + public static DocumentBuilderFactory getDocBuilderFactory() { + if (docBuilderFactory == null) { + docBuilderFactory = DocumentBuilderFactory.newInstance(); + } + return docBuilderFactory; + } + + public DocumentBuilder getDocBuilder() { + if (docBuilder == null) { + try { + docBuilder = getDocBuilderFactory().newDocumentBuilder(); + } catch (ParserConfigurationException ex) { + throw new IllegalArgumentException("Unable to create document builder", ex); + } + } + return docBuilder; + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/XmlTagCompleteAction.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/XmlTagCompleteAction.java new file mode 100644 index 0000000..880cb4a --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/XmlTagCompleteAction.java @@ -0,0 +1,48 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions; + +import java.awt.event.ActionEvent; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +/** + * Completes an the Tag. + * @author Ayman Al-Sairafi + */ +public class XmlTagCompleteAction extends DefaultSyntaxAction { + + public XmlTagCompleteAction() { + super("XML_TAG_COMPLETE"); + } + + @Override + public void actionPerformed(JTextComponent target, SyntaxDocument sDoc, + int dot, ActionEvent e) { + Token tok = sDoc.getTokenAt(dot); + while (tok != null && tok.type != TokenType.TYPE) { + tok = sDoc.getPrevToken(tok); + } + if (tok == null) { + target.replaceSelection(">"); + } else { + CharSequence tag = tok.getText(sDoc); + int savepos = target.getSelectionStart(); + target.replaceSelection(">"); + target.setCaretPosition(savepos + 1); + } + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ComboCompletionDialog.form b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ComboCompletionDialog.form new file mode 100644 index 0000000..85abeb6 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ComboCompletionDialog.form @@ -0,0 +1,71 @@ + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ComboCompletionDialog.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ComboCompletionDialog.java new file mode 100644 index 0000000..9d33b54 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ComboCompletionDialog.java @@ -0,0 +1,247 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions.gui; + +import java.awt.Font; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Window; +import java.awt.event.KeyEvent; +import java.util.List; +import java.util.Vector; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.SwingUtilities; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.text.BadLocationException; +import javax.swing.text.JTextComponent; + +import de.sciss.syntaxpane.util.StringUtils; +import de.sciss.syntaxpane.util.SwingUtils; + +/** + * + * @author Ayman Al-Sairafi + */ +public class ComboCompletionDialog + extends javax.swing.JDialog implements EscapeListener { + + /** + * The result returned to the caller + */ + private String result = null; + /** + * Our target component + */ + private JTextComponent target; + public String escapeChars = ";(= \t\n\r"; + public List items; + + /** + * Creates new form ComboCompletionDialog + * @param target + */ + public ComboCompletionDialog(JTextComponent target) { + super(SwingUtilities.getWindowAncestor(target), ModalityType.APPLICATION_MODAL); + initComponents(); + jTxtItem.getDocument().addDocumentListener(new DocumentListener() { + + @Override + public void insertUpdate(DocumentEvent e) { + refilterList(); + } + + @Override + public void removeUpdate(DocumentEvent e) { + refilterList(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + refilterList(); + } + }); + // This will allow the textfield to receive TAB keys + jTxtItem.setFocusTraversalKeysEnabled(false); + this.target = target; + SwingUtils.addEscapeListener(this); + } + + /** + * Display the Completion Dialog with initial abbrev and using the given items + * The dialog is responsible for showing itself and for updating the target + * with the text, depending on user actions. + * + * The dialog will be aligned to the selectionStart of the target component + * and when a selection is made, replaceSelection will be called on dialog + * + * @param abbrev + * @param items + */ + public void displayFor(String abbrev, List items) { + this.items = items; + try { + Window window = SwingUtilities.getWindowAncestor(target); + Rectangle rt = target.modelToView(target.getSelectionStart()); + Point loc = new Point(rt.x, rt.y); + setLocationRelativeTo(window); + // convert the location from Text Componet coordinates to + // Frame coordinates... + loc = SwingUtilities.convertPoint(target, loc, window); + // and then to Screen coordinates + SwingUtilities.convertPointToScreen(loc, window); + setLocation(loc); + } catch (BadLocationException ex) { + Logger.getLogger(ComboCompletionDialog.class.getName()).log(Level.SEVERE, null, ex); + } finally { + Font font = target.getFont(); + jTxtItem.setFont(font); + jLstItems.setFont(font); + doLayout(); + jTxtItem.setText(abbrev); + refilterList(); + setVisible(true); + } + } + + private void refilterList() { + String prefix = jTxtItem.getText(); + Vector filtered = new Vector(); + Object selected = jLstItems.getSelectedValue(); + for (String s : items) { + if (StringUtils.camelCaseMatch(s, prefix)) { + filtered.add(s); + } + } + jLstItems.setListData(filtered); + if (selected != null && filtered.contains(selected)) { + jLstItems.setSelectedValue(selected, true); + } else { + jLstItems.setSelectedIndex(0); + } + } + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jTxtItem = new javax.swing.JTextField(); + jScrollPane1 = new javax.swing.JScrollPane(); + jLstItems = new javax.swing.JList(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + setResizable(false); + setUndecorated(true); + + jTxtItem.setBorder(null); + jTxtItem.addKeyListener(new java.awt.event.KeyAdapter() { + public void keyPressed(java.awt.event.KeyEvent evt) { + jTxtItemKeyPressed(evt); + } + }); + + jLstItems.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); + jLstItems.setFocusable(false); + jLstItems.addMouseListener(new java.awt.event.MouseAdapter() { + public void mouseClicked(java.awt.event.MouseEvent evt) { + jLstItemsMouseClicked(evt); + } + }); + jScrollPane1.setViewportView(jLstItems); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jTxtItem, javax.swing.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE) + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addComponent(jTxtItem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(0, 0, 0) + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)) + ); + + pack(); + }// //GEN-END:initComponents + + private void jTxtItemKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTxtItemKeyPressed + + int i = jLstItems.getSelectedIndex(); + switch (evt.getKeyCode()) { + case KeyEvent.VK_ESCAPE: + result = jTxtItem.getText(); + target.replaceSelection(result); + setVisible(false); + return; + case KeyEvent.VK_DOWN: + if (i < jLstItems.getModel().getSize() - 1) { + i++; + } + jLstItems.setSelectedIndex(i); + jLstItems.ensureIndexIsVisible(i); + break; + case KeyEvent.VK_UP: + if (i > 0) { + i--; + } + jLstItems.setSelectedIndex(i); + jLstItems.ensureIndexIsVisible(i); + break; + } + + if (escapeChars.indexOf(evt.getKeyChar()) >= 0) { + if (jLstItems.getSelectedIndex() >= 0) { + result = jLstItems.getSelectedValue().toString(); + } else { + result = jTxtItem.getText(); + } + char pressed = evt.getKeyChar(); + // we need to just accept ENTER, and replace the tab with a single + // space + if (pressed != '\n') { + result += (pressed == '\t') ? ' ' : pressed; + } + target.replaceSelection(result); + setVisible(false); + } + }//GEN-LAST:event_jTxtItemKeyPressed + + private void jLstItemsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLstItemsMouseClicked + if(evt.getClickCount() == 2) { + String selected = jLstItems.getSelectedValue().toString(); + target.replaceSelection(selected); + setVisible(false); + } + }//GEN-LAST:event_jLstItemsMouseClicked + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JList jLstItems; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JTextField jTxtItem; + // End of variables declaration//GEN-END:variables + + @Override + public void escapePressed() { + setVisible(false); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/EscapeListener.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/EscapeListener.java new file mode 100644 index 0000000..ee9bcb8 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/EscapeListener.java @@ -0,0 +1,31 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package de.sciss.syntaxpane.actions.gui; + +import javax.swing.RootPaneContainer; + +/** + * This interface is used by dialogs that will need to listen to ESC key. + * When the ESC key is pressed, escapePressed is called. + * @author Ayman Al-Sairafi + */ +public interface EscapeListener extends RootPaneContainer { + + /** + * This method will be called when ESC key is pressed. + */ + public void escapePressed(); + +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/GotoLineDialog.form b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/GotoLineDialog.form new file mode 100644 index 0000000..794638e --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/GotoLineDialog.form @@ -0,0 +1,78 @@ + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/GotoLineDialog.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/GotoLineDialog.java new file mode 100644 index 0000000..f49cf2a --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/GotoLineDialog.java @@ -0,0 +1,154 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions.gui; + +import java.lang.ref.WeakReference; +import de.sciss.syntaxpane.actions.*; +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.util.SwingUtils; + +/** + * A simple dialog to prompt for a line number and go to it + * @author Ayman Al-Sairafi + */ +public class GotoLineDialog + extends javax.swing.JDialog implements EscapeListener { + + private static final String PROPERTY_KEY = "GOTOLINE_DIALOG"; + private WeakReference text; + + /** + * Creates new form GotoLineDialog + * @param text + */ + private GotoLineDialog(JTextComponent text) { + super(SwingUtilities.getWindowAncestor(text), ModalityType.APPLICATION_MODAL); + initComponents(); + this.text = new WeakReference(text); + setLocationRelativeTo(text.getRootPane()); + getRootPane().setDefaultButton(jBtnOk); + text.getDocument().putProperty(PROPERTY_KEY, this); + SwingUtils.addEscapeListener(this); + } + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jCmbLineNumbers = new javax.swing.JComboBox(); + jBtnOk = new javax.swing.JButton(); + + java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle"); // NOI18N + setTitle(bundle.getString("GotoLineDialog.title")); // NOI18N + setModal(true); + setName(""); // NOI18N + setResizable(false); + + jCmbLineNumbers.setEditable(true); + jCmbLineNumbers.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jCmbLineNumbersActionPerformed(evt); + } + }); + + jBtnOk.setAction(jCmbLineNumbers.getAction()); + jBtnOk.setText(bundle.getString("GotoLineDialog.jBtnOk.text")); // NOI18N + jBtnOk.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jBtnOkActionPerformed(evt); + } + }); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jCmbLineNumbers, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jBtnOk, javax.swing.GroupLayout.DEFAULT_SIZE, 47, Short.MAX_VALUE) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jCmbLineNumbers, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jBtnOk, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + pack(); + }// //GEN-END:initComponents + + private void setTextPos() { + Object line = jCmbLineNumbers.getSelectedItem(); + if (line != null) { + try { + int lineNr = Integer.parseInt(line.toString()); + ActionUtils.insertIntoCombo(jCmbLineNumbers, line); + ActionUtils.setCaretPosition(text.get(), lineNr, 0); + setVisible(false); + } catch (NumberFormatException ex) { + JOptionPane.showMessageDialog(this, "Invalid Number: " + line, + "Number Error", JOptionPane.ERROR_MESSAGE); + } + } + } + + private void jCmbLineNumbersActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCmbLineNumbersActionPerformed + if (evt.getActionCommand().equals("comboBoxEdited")) { + setTextPos(); + } + }//GEN-LAST:event_jCmbLineNumbersActionPerformed + + private void jBtnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnOkActionPerformed + setTextPos(); + }//GEN-LAST:event_jBtnOkActionPerformed + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton jBtnOk; + private javax.swing.JComboBox jCmbLineNumbers; + // End of variables declaration//GEN-END:variables + + /** + * Create or return the GotoLine dialog for a given ext component + * @param text + */ + public static void showForEditor(JTextComponent text) { + GotoLineDialog dlg = null; + if (text.getDocument().getProperty(PROPERTY_KEY) == null) { + dlg = new GotoLineDialog(text); + } else { + dlg = (GotoLineDialog) text.getDocument().getProperty(PROPERTY_KEY); + } + dlg.jCmbLineNumbers.requestFocusInWindow(); + dlg.setVisible(true); + + } + + @Override + public void escapePressed() { + setVisible(false); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/HTMLPreviewFrame.form b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/HTMLPreviewFrame.form new file mode 100644 index 0000000..904d7e6 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/HTMLPreviewFrame.form @@ -0,0 +1,59 @@ + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/HTMLPreviewFrame.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/HTMLPreviewFrame.java new file mode 100644 index 0000000..f818170 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/HTMLPreviewFrame.java @@ -0,0 +1,115 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions.gui; + +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.text.BadLocationException; +import javax.swing.text.Document; +import de.sciss.syntaxpane.actions.HTMLPreviewAction; + +/** + * + * @author Ayman Al-Sairafi + */ +public class HTMLPreviewFrame extends javax.swing.JFrame implements DocumentListener { + + Document doc; + /** + * Creates new form HTMLPreviewFrame + * @param doc + */ + public HTMLPreviewFrame(Document doc) { + initComponents(); + this.doc = doc; + doc.addDocumentListener(this); + updateHTML(); + } + + private void updateHTML() { + try { + jEdtHtml.setText(doc.getText(0, doc.getLength())); + } catch (BadLocationException ex) { + Logger.getLogger(HTMLPreviewFrame.class.getName()).log(Level.SEVERE, null, ex); + } + } + + /** + * This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jScrollPane1 = new javax.swing.JScrollPane(); + jEdtHtml = new javax.swing.JEditorPane(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle"); // NOI18N + setTitle(bundle.getString("HTMLPreviewFrame.title")); // NOI18N + addWindowListener(new java.awt.event.WindowAdapter() { + public void windowClosed(java.awt.event.WindowEvent evt) { + onWindowClosed(evt); + } + }); + + jEdtHtml.setContentType(bundle.getString("HTMLPreviewFrame.jEdtHtml.contentType")); // NOI18N + jEdtHtml.setEditable(false); + jScrollPane1.setViewportView(jEdtHtml); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 688, Short.MAX_VALUE) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 449, Short.MAX_VALUE) + ); + + pack(); + }// //GEN-END:initComponents + + private void onWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_onWindowClosed + doc.removeDocumentListener(this); + doc.putProperty(HTMLPreviewAction.HTML_PREVIEW_WINDOW, null); + doc = null; + }//GEN-LAST:event_onWindowClosed + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JEditorPane jEdtHtml; + private javax.swing.JScrollPane jScrollPane1; + // End of variables declaration//GEN-END:variables + + @Override + public void insertUpdate(DocumentEvent e) { + updateHTML(); + } + + @Override + public void removeUpdate(DocumentEvent e) { + updateHTML(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + updateHTML(); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/MemberCell.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/MemberCell.java new file mode 100644 index 0000000..7cfae6f --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/MemberCell.java @@ -0,0 +1,257 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions.gui; + +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Image; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.net.URL; +import java.util.HashMap; +import java.util.Map; +import javax.swing.*; + +import de.sciss.syntaxpane.SyntaxView; +import de.sciss.syntaxpane.actions.ActionUtils; +import de.sciss.syntaxpane.util.ReflectUtils; + +/** + * This class will render a Member. There are Method, Field and Constructor subclasses + * @author Ayman Al-Sairafi + */ +abstract class MemberCell extends JPanel { + + private final JList list; + private final boolean isSelected; + private final Color backColor; + private final Member member; + private final Class theClass; + + public MemberCell(JList list, boolean isSelected, Color backColor, Member member, Class clazz) { + super(); + this.list = list; + this.isSelected = isSelected; + this.backColor = backColor; + this.member = member; + this.theClass = clazz; + } + + @Override + public void paintComponent(Graphics g) { + SyntaxView.setRenderingHits((Graphics2D) g); + g.setFont(list.getFont()); + super.paintComponent(g); + FontMetrics fm = g.getFontMetrics(); + g.setColor(isSelected ? list.getSelectionBackground() : backColor); + g.fillRect(0, 0, getWidth(), getHeight()); + g.setColor(isSelected ? list.getSelectionForeground() : list.getForeground()); + Image icn = getIcon(); + g.drawImage(icn, 2, 0, null); + int x = 6 + (icn == null ? 0 : icn.getWidth(this)); + int y = fm.getHeight(); + if (member.getDeclaringClass().equals(theClass)) { + Font bold = list.getFont().deriveFont(Font.BOLD); + g.setFont(bold); + } + x = drawString(getMemberName(), x, y, g); + g.setFont(list.getFont()); + x = drawString(getArguments(), x, y, g); + String right = getReturnType(); + int rw = fm.stringWidth(right); + g.drawString(right, getWidth() - rw - 4, fm.getAscent()); + } + + @Override + public Dimension getPreferredSize() { + Font font = list.getFont(); + Graphics g = getGraphics(); + FontMetrics fm = g.getFontMetrics(font); + // total text for this component: + String total = getMemberName() + getArguments() + getReturnType() + " "; + return new Dimension(fm.stringWidth(total) + 20, Math.max(fm.getHeight(), 16)); + } + + private int drawString(String string, int x, int y, Graphics g) { + if(ActionUtils.isEmptyOrBlanks(string)) { + return x; + } + int w = g.getFontMetrics().stringWidth(string); + g.drawString(string, x, y); + return x + w; + } + + /** + * Read all relevant icons and returns the Map. The loc should contain the + * fully qualified URL for the icons. The icon names read will have the words + * _private, protected, _static, _static_private and _static_protected and the + * extension ".png" appended. + * @param loc root for icon locations + * @return Map (can be used directly with getModifiers & 0xf) + */ + Map readIcons(String loc) { + Map icons = new HashMap(); + icons.put(Modifier.PUBLIC, readImage(loc, "")); + icons.put(Modifier.PRIVATE, readImage(loc, "_private")); + icons.put(Modifier.PROTECTED, readImage(loc, "_protected")); + icons.put(Modifier.STATIC | Modifier.PUBLIC, readImage(loc, "_static")); + icons.put(Modifier.STATIC | Modifier.PRIVATE, readImage(loc, "_static_private")); + icons.put(Modifier.STATIC | Modifier.PROTECTED, readImage(loc, "_static_protected")); + return icons; + } + + private Image readImage(String iconLoc, String kind) { + String fullPath = iconLoc + kind + ".png"; + URL loc = this.getClass().getClassLoader().getResource(fullPath); + if (loc == null) { + return null; + } else { + return new ImageIcon(loc).getImage(); + } + } + + protected String getMemberName() { + return member.getName(); + } + + abstract protected String getArguments(); + + abstract protected String getReturnType(); + + abstract protected Image getIcon(); +} + +/** + * Renders a Method + * @author Ayman Al-Sairafi + */ +class MethodCell extends MemberCell { + + private final Method method; + + public MethodCell(JList list, boolean isSelected, Color backColor, Method method, Class clazz) { + super(list, isSelected, backColor, method, clazz); + this.method = method; + } + + @Override + protected String getArguments() { + return ReflectUtils.getParamsString(method.getParameterTypes()); + } + + @Override + protected String getReturnType() { + return method.getReturnType().getSimpleName(); + } + + @Override + protected Image getIcon() { + int type = method.getModifiers() & 0xf; // only get public/private/protected/static + if (icons == null) { + icons = readIcons(METHOD_ICON_LOC); + } + return icons.get(type); + } + private static Map icons = null; + public static final String METHOD_ICON_LOC = "de/sciss/syntaxpane/images/completions/method"; +} + +/** + * Renders a Field + * @author Ayman Al-Sairafi + */ +class FieldCell extends MemberCell { + + private final Field field; + + public FieldCell(JList list, boolean isSelected, Color backColor, Field field, Class clazz) { + super(list, isSelected, backColor, field, clazz); + this.field = field; + } + + @Override + protected String getArguments() { + return ""; + } + + @Override + protected String getReturnType() { + return field.getType().getSimpleName(); + } + + @Override + protected Image getIcon() { + int type = field.getModifiers() & 0xf; // only get public/private/protected/static + if (icons == null) { + icons = readIcons(FIELD_ICON_LOC); + } + if (icons.get(type) == null) { + System.err.println("Unable to get icon for type: " + field.getModifiers()); + } + return icons.get(type); + } + private static Map icons = null; + public static final String FIELD_ICON_LOC = "de/sciss/syntaxpane/images/completions/field"; +} + +/** + * Renders a Field + * @author Ayman Al-Sairafi + */ +class ConstructorCell extends MemberCell { + + private final Constructor cons; + + public ConstructorCell(JList list, boolean isSelected, Color backColor, Constructor cons, Class clazz) { + super(list, isSelected, backColor, cons, clazz); + this.cons = cons; + } + + @Override + protected String getMemberName() { + return cons.getDeclaringClass().getSimpleName(); + } + + @Override + protected String getArguments() { + return ReflectUtils.getParamsString(cons.getParameterTypes()); + } + + @Override + protected String getReturnType() { + return cons.getDeclaringClass().getSimpleName(); + } + + @Override + protected Image getIcon() { + int type = cons.getModifiers() & 0x7; // only get public/private/protected, mask out static + if (icons == null) { + icons = readIcons(FIELD_ICON_LOC); + } + if (icons.get(type) == null) { + System.out.println("Unable to get icon for type: " + cons.getModifiers()); + } + return icons.get(type); + } + + private static Map icons = null; + public static final String FIELD_ICON_LOC = "de/sciss/syntaxpane/images/completions/constructor"; +} \ No newline at end of file diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/MembersListRenderer.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/MembersListRenderer.java new file mode 100644 index 0000000..135d266 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/MembersListRenderer.java @@ -0,0 +1,52 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions.gui; + +import java.awt.Color; +import java.awt.Component; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import javax.swing.DefaultListCellRenderer; +import javax.swing.JList; + +class MembersListRenderer extends DefaultListCellRenderer { + + static final Color evensColor = new Color(0xeeffee); + private ReflectCompletionDialog dlg; + + public MembersListRenderer(ReflectCompletionDialog dlg) { + this.dlg = dlg; + } + + @Override + public Component getListCellRendererComponent(final JList list, Object value, final int index, + final boolean isSelected, boolean cellHasFocus) { + Color back = (index % 2 == 1) ? list.getBackground() : evensColor; + if (value instanceof Method) { + final Method method = (Method) value; + return new MethodCell(list, isSelected, back, method, dlg.getTheClass()); + } else if (value instanceof Field) { + Field field = (Field) value; + return new FieldCell(list, isSelected, back, field, dlg.getTheClass()); + } else if (value instanceof Constructor) { + Constructor cons = (Constructor) value; + return new ConstructorCell(list, isSelected, back, cons, dlg.getTheClass()); + } else { + Component comp = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + comp.setBackground(back); + return comp; + } + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/QuickFindDialog.form b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/QuickFindDialog.form new file mode 100644 index 0000000..4e9843d --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/QuickFindDialog.form @@ -0,0 +1,176 @@ + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/QuickFindDialog.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/QuickFindDialog.java new file mode 100644 index 0000000..b74637c --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/QuickFindDialog.java @@ -0,0 +1,320 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions.gui; + +import java.awt.Color; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.lang.ref.WeakReference; +import java.net.URL; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; +import javax.swing.*; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.text.BadLocationException; +import javax.swing.text.JTextComponent; + +import de.sciss.syntaxpane.actions.DefaultSyntaxAction; +import de.sciss.syntaxpane.actions.DocumentSearchData; +import de.sciss.syntaxpane.components.Markers; +import de.sciss.syntaxpane.components.Markers.SimpleMarker; +import de.sciss.syntaxpane.util.SwingUtils; + +/** + * QuickFind Dialog. Firefox like dialog shown at bottom of editor. + * @author Ayman Al-Sairafi + */ +public class QuickFindDialog extends javax.swing.JDialog + implements DocumentListener, ActionListener, EscapeListener { + + private SimpleMarker marker = new SimpleMarker(Color.PINK); + private WeakReference target; + private WeakReference dsd; + private int oldCaretPosition; + /** + * This will be set to true if ESC key is used to quit the form. + * In that case, the caret will be restored to its old pos, otherwise + * it will remain where the user probably clicked. + */ + private boolean escaped = false; + + /** + * Creates new form QuickFindDialog + * + * @param target + * @param data search data + */ + public QuickFindDialog(final JTextComponent target, DocumentSearchData data) { + super(SwingUtilities.getWindowAncestor(target), ModalityType.MODELESS.MODELESS); + initComponents(); + SwingUtils.addEscapeListener(this); + dsd = new WeakReference(data); + } + + public void showFor(final JTextComponent target) { + oldCaretPosition = target.getCaretPosition(); + Container view = target.getParent(); + Dimension wd = getSize(); + wd.width = target.getVisibleRect().width; + Point loc = new Point(0, view.getHeight()); + setSize(wd); + setLocationRelativeTo(view); + SwingUtilities.convertPointToScreen(loc, view); + setLocation(loc); + jTxtFind.setFont(target.getFont()); + jTxtFind.getDocument().addDocumentListener(this); + WindowAdapter closeListener = new WindowAdapter() { + + @Override + public void windowDeactivated(WindowEvent e) { + target.getDocument().removeDocumentListener(QuickFindDialog.this); + Markers.removeMarkers(target, marker); + if (escaped) { + Rectangle aRect; + try { + aRect = target.modelToView(oldCaretPosition); + target.setCaretPosition(oldCaretPosition); + target.scrollRectToVisible(aRect); + } catch (BadLocationException ex) { + } + } + dispose(); + } + }; + addWindowListener(closeListener); + this.target = new WeakReference(target); + Pattern p = dsd.get().getPattern(); + if (p != null) { + jTxtFind.setText(p.pattern()); + } + jChkWrap.setSelected(dsd.get().isWrap()); + setVisible(true); + } + + private void setIcon(AbstractButton b, String name) { + URL res = getClass().getClassLoader().getResource(DefaultSyntaxAction.SMALL_ICONS_LOC_PREFIX + name); + if (res != null) b.setIcon(new javax.swing.ImageIcon(res)); + } + + /** + * This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jToolBar1 = new javax.swing.JToolBar(); + jSeparator1 = new javax.swing.JToolBar.Separator(); + jLabel1 = new javax.swing.JLabel(); + jSeparator2 = new javax.swing.JToolBar.Separator(); + jTxtFind = new javax.swing.JTextField(); + jSeparator3 = new javax.swing.JToolBar.Separator(); + jBtnPrev = new javax.swing.JButton(); + jBtnNext = new javax.swing.JButton(); + jChkIgnoreCase = new javax.swing.JCheckBox(); + jChkRegExp = new javax.swing.JCheckBox(); + jChkWrap = new javax.swing.JCheckBox(); + jSeparator4 = new javax.swing.JToolBar.Separator(); + jLblStatus = new javax.swing.JLabel(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + setBackground(java.awt.Color.darkGray); + setName("QuickFindDialog"); // NOI18N + setResizable(false); + setUndecorated(true); + + jToolBar1.setBorder(javax.swing.BorderFactory.createEtchedBorder()); + jToolBar1.setFloatable(false); + jToolBar1.setRollover(true); + jToolBar1.add(jSeparator1); + + jLabel1.setLabelFor(jTxtFind); + java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle"); // NOI18N + jLabel1.setText(bundle.getString("QuickFindDialog.jLabel1.text")); // NOI18N + jToolBar1.add(jLabel1); + jToolBar1.add(jSeparator2); + + jTxtFind.setColumns(30); + jTxtFind.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); + jTxtFind.setMaximumSize(new java.awt.Dimension(200, 24)); + jTxtFind.setMinimumSize(new java.awt.Dimension(60, 24)); + jToolBar1.add(jTxtFind); + jToolBar1.add(jSeparator3); + + setIcon(jBtnPrev, "go-up.png"); + jBtnPrev.setFocusable(false); + jBtnPrev.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + jBtnPrev.setOpaque(false); + jBtnPrev.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); + jBtnPrev.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jBtnPrevActionPerformed(evt); + } + }); + jToolBar1.add(jBtnPrev); + + setIcon(jBtnNext, "go-down.png"); + jBtnNext.setFocusable(false); + jBtnNext.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); + jBtnNext.setMargin(new java.awt.Insets(2, 2, 2, 2)); + jBtnNext.setOpaque(false); + jBtnNext.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); + jBtnNext.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jBtnNextActionPerformed(evt); + } + }); + jToolBar1.add(jBtnNext); + + jChkIgnoreCase.setMnemonic('C'); + jChkIgnoreCase.setText(bundle.getString("QuickFindDialog.jChkIgnoreCase.text")); // NOI18N + jChkIgnoreCase.setFocusable(false); + jChkIgnoreCase.setOpaque(false); + jChkIgnoreCase.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); + jToolBar1.add(jChkIgnoreCase); + jChkIgnoreCase.addActionListener(this); + + jChkRegExp.setMnemonic('R'); + jChkRegExp.setText(bundle.getString("QuickFindDialog.jChkRegExp.text")); // NOI18N + jChkRegExp.setFocusable(false); + jChkRegExp.setOpaque(false); + jChkRegExp.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); + jToolBar1.add(jChkRegExp); + jChkRegExp.addActionListener(this); + + jChkWrap.setMnemonic('W'); + jChkWrap.setText(bundle.getString("QuickFindDialog.jChkWrap.text")); // NOI18N + jChkWrap.setFocusable(false); + jChkWrap.setOpaque(false); + jChkWrap.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM); + jToolBar1.add(jChkWrap); + jChkWrap.addActionListener(this); + + jToolBar1.add(jSeparator4); + + jLblStatus.setFont(jLblStatus.getFont().deriveFont(jLblStatus.getFont().getStyle() | java.awt.Font.BOLD, jLblStatus.getFont().getSize()-2)); + jLblStatus.setForeground(java.awt.Color.red); + jToolBar1.add(jLblStatus); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 684, Short.MAX_VALUE) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + ); + + pack(); + }// //GEN-END:initComponents + + private void jBtnNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnNextActionPerformed + if (dsd.get().doFindNext(target.get())) { + jLblStatus.setText(null); + } else { + jLblStatus.setText(java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle").getString("QuickFindDialog.NotFound")); + } +}//GEN-LAST:event_jBtnNextActionPerformed + + private void jBtnPrevActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnPrevActionPerformed + if (dsd.get().doFindPrev(target.get())) { + jLblStatus.setText(null); + } else { + jLblStatus.setText(java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle").getString("QuickFindDialog.NotFound")); + } +}//GEN-LAST:event_jBtnPrevActionPerformed + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton jBtnNext; + private javax.swing.JButton jBtnPrev; + private javax.swing.JCheckBox jChkIgnoreCase; + private javax.swing.JCheckBox jChkRegExp; + private javax.swing.JCheckBox jChkWrap; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLblStatus; + private javax.swing.JToolBar.Separator jSeparator1; + private javax.swing.JToolBar.Separator jSeparator2; + private javax.swing.JToolBar.Separator jSeparator3; + private javax.swing.JToolBar.Separator jSeparator4; + private javax.swing.JToolBar jToolBar1; + private javax.swing.JTextField jTxtFind; + // End of variables declaration//GEN-END:variables + + @Override + public void insertUpdate(DocumentEvent e) { + updateFind(); + } + + @Override + public void removeUpdate(DocumentEvent e) { + updateFind(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + updateFind(); + } + + private void updateFind() { + JTextComponent t = target.get(); + DocumentSearchData d = dsd.get(); + String toFind = jTxtFind.getText(); + if (toFind == null || toFind.isEmpty()) { + jLblStatus.setText(null); + return; + } + try { + d.setWrap(jChkWrap.isSelected()); + d.setPattern(toFind, + jChkRegExp.isSelected(), + jChkIgnoreCase.isSelected()); + // The dsd doFindNext will always find from current pos, + // so we need to relocate to our saved pos before we call doFindNext + jLblStatus.setText(null); + t.setCaretPosition(oldCaretPosition); + if (!d.doFindNext(t)) { + jLblStatus.setText(java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle").getString("QuickFindDialog.NotFound")); + } else { + jLblStatus.setText(null); + } + } catch (PatternSyntaxException e) { + jLblStatus.setText(e.getDescription()); + } + } + + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() instanceof JCheckBox) { + updateFind(); + } + } + + @Override + public void escapePressed() { + escaped = true; + setVisible(false); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ReflectCompletionDialog.form b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ReflectCompletionDialog.form new file mode 100644 index 0000000..70b623c --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ReflectCompletionDialog.form @@ -0,0 +1,95 @@ + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ReflectCompletionDialog.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ReflectCompletionDialog.java new file mode 100644 index 0000000..e4d0961 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ReflectCompletionDialog.java @@ -0,0 +1,342 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions.gui; + +import java.awt.Font; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Window; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.ItemEvent; +import java.awt.event.KeyEvent; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Vector; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.SwingUtilities; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.text.BadLocationException; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.actions.ActionUtils; +import de.sciss.syntaxpane.util.ReflectUtils; +import de.sciss.syntaxpane.util.StringUtils; +import de.sciss.syntaxpane.util.SwingUtils; + +/** + * + * @author Ayman Al-Sairafi + */ +public class ReflectCompletionDialog + extends javax.swing.JDialog implements EscapeListener { + + /** + * The class we are displaying its members: + */ + private Class theClass; + /** + * The current filter, to avoid refiltering the items + */ + public String escapeChars = ";(= \t\n"; + public List items; + private final JTextComponent target; + + /** + * Creates new form ReflectCompletionDialog + * @param target Text component for this dialog + */ + public ReflectCompletionDialog(JTextComponent target) { + super(SwingUtilities.getWindowAncestor(target), ModalityType.APPLICATION_MODAL); + initComponents(); + this.target = target; + jTxtItem.getDocument().addDocumentListener(new DocumentListener() { + + @Override + public void insertUpdate(DocumentEvent e) { + refilterList(); + } + + @Override + public void removeUpdate(DocumentEvent e) { + refilterList(); + } + + @Override + public void changedUpdate(DocumentEvent e) { + refilterList(); + } + }); + // This will allow the textfield to receive TAB keys + jTxtItem.setFocusTraversalKeysEnabled(false); + // Add action so we automatically filter on comboBox Enter Key + jCmbClassName.getEditor().addActionListener(new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + updateItems(); + } + }); + SwingUtils.addEscapeListener(this); + } + + public void setFonts(Font font) { + jTxtItem.setFont(font); + jLstItems.setFont(font); + doLayout(); + } + + private String getSelection() { + String result; + if (jLstItems.getSelectedIndex() >= 0) { + Object selected = jLstItems.getSelectedValue(); + if (selected instanceof Method) { + result = ReflectUtils.getJavaCallString((Method) selected); + } else if (selected instanceof Constructor) { + result = ReflectUtils.getJavaCallString((Constructor) selected); + } else if (selected instanceof Field) { + result = ((Field) selected).getName(); + } else { + result = selected.toString(); + } + } else { + result = jTxtItem.getText(); + } + return result; + } + + private void refilterList() { + String prefix = jTxtItem.getText(); + Vector filtered = new Vector(); + Object selected = jLstItems.getSelectedValue(); + for (Member m : items) { + if (StringUtils.camelCaseMatch(m.getName(), prefix)) { + filtered.add(m); + } + } + jLstItems.setListData(filtered); + if (selected != null && filtered.contains(selected)) { + jLstItems.setSelectedValue(selected, true); + } else { + jLstItems.setSelectedIndex(0); + } + } + + /** This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jTxtItem = new javax.swing.JTextField(); + jScrollPane1 = new javax.swing.JScrollPane(); + jLstItems = new javax.swing.JList(); + jCmbClassName = new javax.swing.JComboBox(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + setName("CompletionDialog"); // NOI18N + setResizable(false); + setUndecorated(true); + + jTxtItem.setBorder(null); + jTxtItem.addKeyListener(new java.awt.event.KeyAdapter() { + public void keyPressed(java.awt.event.KeyEvent evt) { + jTxtItemKeyPressed(evt); + } + }); + + jLstItems.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); + jLstItems.setCellRenderer(new de.sciss.syntaxpane.actions.gui.MembersListRenderer(this)); + jLstItems.setFocusable(false); + jLstItems.addMouseListener(new java.awt.event.MouseAdapter() { + public void mouseClicked(java.awt.event.MouseEvent evt) { + jLstItemsMouseClicked(evt); + } + }); + jScrollPane1.setViewportView(jLstItems); + + jCmbClassName.setEditable(true); + jCmbClassName.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Object", "String" })); + jCmbClassName.addItemListener(new java.awt.event.ItemListener() { + public void itemStateChanged(java.awt.event.ItemEvent evt) { + jCmbClassNameItemStateChanged(evt); + } + }); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jTxtItem, javax.swing.GroupLayout.DEFAULT_SIZE, 437, Short.MAX_VALUE) + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 437, Short.MAX_VALUE) + .addComponent(jCmbClassName, 0, 437, Short.MAX_VALUE) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addComponent(jTxtItem, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(0, 0, 0) + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 156, Short.MAX_VALUE) + .addGap(0, 0, 0) + .addComponent(jCmbClassName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + ); + + pack(); + }// //GEN-END:initComponents + + private void jTxtItemKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTxtItemKeyPressed + + int i = jLstItems.getSelectedIndex(); + switch (evt.getKeyCode()) { + case KeyEvent.VK_ESCAPE: + target.setCaretPosition(target.getSelectionEnd()); + setVisible(false); + return; + case KeyEvent.VK_DOWN: + i++; + break; + case KeyEvent.VK_UP: + i--; + break; + case KeyEvent.VK_HOME: + i = 0; + break; + case KeyEvent.VK_END: + i = jLstItems.getModel().getSize() - 1; + break; + case KeyEvent.VK_PAGE_DOWN: + i += jLstItems.getVisibleRowCount(); + break; + case KeyEvent.VK_PAGE_UP: + i -= jLstItems.getVisibleRowCount(); + break; + } + + if (escapeChars.indexOf(evt.getKeyChar()) >= 0) { + String result = getSelection(); + char pressed = evt.getKeyChar(); + // we need to just accept ENTER, and replace the tab with a single + // space + if (pressed != '\n') { + result += (pressed == '\t') ? ' ' : pressed; + } + target.replaceSelection(result); + setVisible(false); + } else { + // perform bounds checks for i + if (i >= jLstItems.getModel().getSize()) { + i = jLstItems.getModel().getSize() - 1; + } + if (i < 0) { + i = 0; + } + jLstItems.setSelectedIndex(i); + jLstItems.ensureIndexIsVisible(i); + } + }//GEN-LAST:event_jTxtItemKeyPressed + + private void jCmbClassNameItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jCmbClassNameItemStateChanged + if (evt.getStateChange() == ItemEvent.SELECTED) { + updateItems(); + } + }//GEN-LAST:event_jCmbClassNameItemStateChanged + + private void jLstItemsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLstItemsMouseClicked + if (evt.getClickCount() == 2) { + String selected = getSelection(); + target.replaceSelection(selected); + setVisible(false); + } + }//GEN-LAST:event_jLstItemsMouseClicked + + private void updateItems() { + String className = jCmbClassName.getEditor().getItem().toString(); + if (items == null) { + items = new ArrayList(); + } else { + items.clear(); + } + // we must have the class in the Combo: + Class aClass = ReflectUtils.findClass(className, ReflectUtils.DEFAULT_PACKAGES); + if (aClass != null) { + // for now, add everything: + theClass = aClass; + ReflectUtils.addConstrcutors(aClass, items); + ReflectUtils.addMethods(aClass, items); + ReflectUtils.addFields(aClass, items); + ActionUtils.insertIntoCombo(jCmbClassName, className); + jTxtItem.requestFocusInWindow(); + } + refilterList(); + } + + public Class getTheClass() { + return theClass; + } + + /** + * Set the items to display + * @param items + */ + public void setItems(List items) { + this.items = items; + } + + /** + * Display the dialog. + * @param target text component (its Window will be the parent) + */ + public void displayFor(JTextComponent target) { + try { + int dot = target.getSelectionStart(); + Window window = SwingUtilities.getWindowAncestor(target); + Rectangle rt = target.modelToView(dot); + Point loc = new Point(rt.x, rt.y); + // convert the location from Text Componet coordinates to + // Frame coordinates... + loc = SwingUtilities.convertPoint(target, loc, window); + // and then to Screen coordinates + SwingUtilities.convertPointToScreen(loc, window); + setLocationRelativeTo(window); + setLocation(loc); + } catch (BadLocationException ex) { + Logger.getLogger(ReflectCompletionDialog.class.getName()).log(Level.SEVERE, null, ex); + } finally { + setFonts(target.getFont()); + updateItems(); + jTxtItem.setText(target.getSelectedText()); + setVisible(true); + } + } + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JComboBox jCmbClassName; + private javax.swing.JList jLstItems; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JTextField jTxtItem; + // End of variables declaration//GEN-END:variables + + @Override + public void escapePressed() { + target.setCaretPosition(target.getSelectionEnd()); + setVisible(false); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ReplaceDialog.form b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ReplaceDialog.form new file mode 100644 index 0000000..7c86d28 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ReplaceDialog.form @@ -0,0 +1,225 @@ + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ReplaceDialog.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ReplaceDialog.java new file mode 100644 index 0000000..aac86d0 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ReplaceDialog.java @@ -0,0 +1,316 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.actions.gui; + +import de.sciss.syntaxpane.actions.*; +import de.sciss.syntaxpane.components.Markers; +import java.awt.Color; +import java.awt.HeadlessException; +import java.net.URL; +import java.util.regex.Matcher; +import java.util.regex.PatternSyntaxException; +import javax.swing.*; +import javax.swing.event.CaretEvent; +import javax.swing.event.CaretListener; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.util.SwingUtils; + +/** + * A Find and Replace Dialog. The dialog will also act as a listener to + * Document changes so that all highlights are updated if the document is + * changed. + * + * @author Ayman Al-Sairafi + */ +public class ReplaceDialog extends javax.swing.JDialog + implements CaretListener, EscapeListener { + + private JTextComponent textComponent; + private DocumentSearchData dsd; + private static Markers.SimpleMarker SEARCH_MARKER = new Markers.SimpleMarker(Color.YELLOW); + + /** + * Creates new form FindDialog + * @param text + * @param dsd DocumentSerachData + */ + public ReplaceDialog(JTextComponent text, + DocumentSearchData dsd) { + super(SwingUtilities.getWindowAncestor(text), ModalityType.MODELESS.MODELESS); + initComponents(); + textComponent = text; + this.dsd = dsd; + textComponent.addCaretListener(this); + setLocationRelativeTo(text.getRootPane()); + getRootPane().setDefaultButton(jBtnNext); + SwingUtils.addEscapeListener(this); + jBtnReplaceAll.setEnabled(text.isEditable() && text.isEnabled()); + } + + /** + * updates the highlights in the document when it is updated. + * This is called by the DocumentListener methods + */ + public void updateHighlights() { + Markers.removeMarkers(textComponent, SEARCH_MARKER); + if (jTglHighlight.isSelected()) { + Markers.markAll(textComponent, dsd.getPattern(), SEARCH_MARKER); + } + } + + private void showRegexpError(PatternSyntaxException ex) throws HeadlessException { + JOptionPane.showMessageDialog(this, "Regexp error: " + ex.getMessage(), + "Regular Expression Error", JOptionPane.ERROR_MESSAGE); + jCmbFind.requestFocus(); + } + + /** + * update the finder object with data from our UI + */ + private void updateFinder() { + String regex = (String) jCmbFind.getSelectedItem(); + try { + dsd.setPattern(regex, + jChkRegex.isSelected(), + jChkIgnoreCase.isSelected()); + ActionUtils.insertIntoCombo(jCmbFind, regex); + } catch (PatternSyntaxException e) { + showRegexpError(e); + } + } + + private void setIcon(AbstractButton b, String name) { + URL res = getClass().getClassLoader().getResource(DefaultSyntaxAction.SMALL_ICONS_LOC_PREFIX + name); + if (res != null) b.setIcon(new javax.swing.ImageIcon(res)); + } + + /** + * This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jLblFind = new javax.swing.JLabel(); + jBtnNext = new javax.swing.JButton(); + jBtnPrev = new javax.swing.JButton(); + jBtnReplaceAll = new javax.swing.JButton(); + jChkWrap = new javax.swing.JCheckBox(); + jChkRegex = new javax.swing.JCheckBox(); + jChkIgnoreCase = new javax.swing.JCheckBox(); + jLblReplace = new javax.swing.JLabel(); + jTglHighlight = new javax.swing.JToggleButton(); + jCmbReplace = new javax.swing.JComboBox(); + jCmbFind = new javax.swing.JComboBox(); + jBtnReplace = new javax.swing.JButton(); + + java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle"); // NOI18N + setTitle(bundle.getString("ReplaceDialog.title")); // NOI18N + setName(""); // NOI18N + setResizable(false); + + jLblFind.setDisplayedMnemonic('F'); + jLblFind.setLabelFor(jCmbFind); + jLblFind.setText(bundle.getString("ReplaceDialog.jLblFind.text")); // NOI18N + + setIcon(jBtnNext, "go-next.png"); + jBtnNext.setMnemonic('N'); + jBtnNext.setText(bundle.getString("ReplaceDialog.jBtnNext.text")); // NOI18N + jBtnNext.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jBtnNextActionPerformed(evt); + } + }); + + setIcon(jBtnPrev, "go-previous.png"); + jBtnPrev.setMnemonic('N'); + jBtnPrev.setText(bundle.getString("ReplaceDialog.jBtnPrev.text")); // NOI18N + jBtnPrev.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jBtnPrevActionPerformed(evt); + } + }); + + setIcon(jBtnReplaceAll, "edit-find-replace-all.png"); + jBtnReplaceAll.setMnemonic('H'); + jBtnReplaceAll.setText(bundle.getString("ReplaceDialog.jBtnReplaceAll.text")); // NOI18N + jBtnReplaceAll.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jBtnReplaceAllActionPerformed(evt); + } + }); + + jChkWrap.setMnemonic('W'); + jChkWrap.setText(bundle.getString("ReplaceDialog.jChkWrap.text")); // NOI18N + jChkWrap.setToolTipText(bundle.getString("ReplaceDialog.jChkWrap.toolTipText")); // NOI18N + + jChkRegex.setMnemonic('R'); + jChkRegex.setText(bundle.getString("ReplaceDialog.jChkRegex.text")); // NOI18N + + jChkIgnoreCase.setMnemonic('I'); + jChkIgnoreCase.setText(bundle.getString("ReplaceDialog.jChkIgnoreCase.text")); // NOI18N + + jLblReplace.setDisplayedMnemonic('R'); + jLblReplace.setLabelFor(jCmbReplace); + jLblReplace.setText(bundle.getString("ReplaceDialog.jLblReplace.text")); // NOI18N + + setIcon(jTglHighlight, "highlight.png"); + jTglHighlight.setText(bundle.getString("ReplaceDialog.jTglHighlight.text")); // NOI18N + jTglHighlight.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jTglHighlightActionPerformed(evt); + } + }); + + jCmbReplace.setEditable(true); + + jCmbFind.setEditable(true); + + setIcon(jBtnReplace, "edit-find-replace.png"); + jBtnReplace.setText(bundle.getString("ReplaceDialog.jBtnReplace.text")); // NOI18N + jBtnReplace.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jBtnReplaceActionPerformed(evt); + } + }); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(jLblFind) + .addComponent(jLblReplace)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jCmbFind, 0, 289, Short.MAX_VALUE) + .addComponent(jCmbReplace, javax.swing.GroupLayout.Alignment.TRAILING, 0, 289, Short.MAX_VALUE) + .addComponent(jChkRegex, javax.swing.GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE) + .addComponent(jChkWrap, javax.swing.GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE) + .addComponent(jChkIgnoreCase, javax.swing.GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jBtnReplace, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE) + .addComponent(jBtnNext, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE) + .addComponent(jBtnPrev, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE) + .addComponent(jTglHighlight, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE) + .addComponent(jBtnReplaceAll, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 107, Short.MAX_VALUE)) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLblFind) + .addComponent(jCmbFind, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jBtnNext)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jBtnPrev) + .addComponent(jCmbReplace, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLblReplace)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jBtnReplace) + .addComponent(jChkWrap, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addGap(3, 3, 3) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jChkRegex) + .addComponent(jBtnReplaceAll)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jChkIgnoreCase) + .addComponent(jTglHighlight)) + .addContainerGap()) + ); + + pack(); + }// //GEN-END:initComponents + + private void jBtnNextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnNextActionPerformed + try { + updateFinder(); + if (!dsd.doFindNext(textComponent)) { + dsd.msgNotFound(textComponent); + } + textComponent.requestFocusInWindow(); + } catch (PatternSyntaxException ex) { + showRegexpError(ex); + } + }//GEN-LAST:event_jBtnNextActionPerformed + + private void jBtnReplaceAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnReplaceAllActionPerformed + try { + updateFinder(); + String replacement = (String) jCmbReplace.getSelectedItem(); + if (replacement == null) return; + if(!jChkRegex.isSelected()) { + replacement = Matcher.quoteReplacement(replacement); + } + ActionUtils.insertIntoCombo(jCmbReplace, replacement); + jTglHighlight.setSelected(false); + dsd.doReplaceAll(textComponent, replacement); + textComponent.requestFocusInWindow(); + } catch (PatternSyntaxException ex) { + showRegexpError(ex); + } +}//GEN-LAST:event_jBtnReplaceAllActionPerformed + + private void jTglHighlightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTglHighlightActionPerformed + updateFinder(); + updateHighlights(); + }//GEN-LAST:event_jTglHighlightActionPerformed + + private void jBtnPrevActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnPrevActionPerformed + updateFinder(); + dsd.doFindPrev(textComponent); +}//GEN-LAST:event_jBtnPrevActionPerformed + + private void jBtnReplaceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnReplaceActionPerformed + jTglHighlight.setSelected(false); + String replacement = jCmbReplace.getSelectedItem() == null ? + "" : jCmbReplace.getSelectedItem().toString(); + dsd.doReplace(textComponent, replacement); + }//GEN-LAST:event_jBtnReplaceActionPerformed + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton jBtnNext; + private javax.swing.JButton jBtnPrev; + private javax.swing.JButton jBtnReplace; + private javax.swing.JButton jBtnReplaceAll; + private javax.swing.JCheckBox jChkIgnoreCase; + private javax.swing.JCheckBox jChkRegex; + private javax.swing.JCheckBox jChkWrap; + private javax.swing.JComboBox jCmbFind; + private javax.swing.JComboBox jCmbReplace; + private javax.swing.JLabel jLblFind; + private javax.swing.JLabel jLblReplace; + private javax.swing.JToggleButton jTglHighlight; + // End of variables declaration//GEN-END:variables + + @Override + public void caretUpdate(CaretEvent e) { + updateHighlights(); + } + + @Override + public void escapePressed() { + setVisible(false); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ShowAbbsDialog.form b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ShowAbbsDialog.form new file mode 100644 index 0000000..ce71e9d --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ShowAbbsDialog.form @@ -0,0 +1,115 @@ + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ShowAbbsDialog.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ShowAbbsDialog.java new file mode 100644 index 0000000..edc7cd4 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/actions/gui/ShowAbbsDialog.java @@ -0,0 +1,136 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package de.sciss.syntaxpane.actions.gui; + +import java.util.Arrays; +import java.util.Map; +import javax.swing.JEditorPane; +import javax.swing.SwingUtilities; +import de.sciss.syntaxpane.util.SwingUtils; + +/** + * Show abbreviations for a JEditorPane. + * + * @author Ayman Al-Sairafi + */ +public class ShowAbbsDialog + extends javax.swing.JDialog implements EscapeListener { + + /** + * Creates new form ShowAbbsDialog + * @param parent + * @param abbs + */ + public ShowAbbsDialog(JEditorPane parent, Map abbs) { + super(SwingUtilities.getWindowAncestor(parent), ModalityType.APPLICATION_MODAL); + initComponents(); + Object[] abbsList = abbs.keySet().toArray(); + Arrays.sort(abbsList); + jLstAbbs.setListData(abbsList); + this.abbs = abbs; + jEdtAbbr.setEditorKit(parent.getEditorKit()); + jLstAbbs.setSelectedIndex(0); + SwingUtils.addEscapeListener(this); + setVisible(true); + } + + /** + * This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jSplitPane1 = new javax.swing.JSplitPane(); + jScrollPane1 = new javax.swing.JScrollPane(); + jLstAbbs = new javax.swing.JList(); + jScrollPane2 = new javax.swing.JScrollPane(); + jEdtAbbr = new javax.swing.JEditorPane(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle"); // NOI18N + setTitle(bundle.getString("ShowAbbsDialog.title")); // NOI18N + setLocationByPlatform(true); + setMinimumSize(new java.awt.Dimension(600, 300)); + setModal(true); + setName("dlgShowAbbs"); // NOI18N + + jSplitPane1.setDividerLocation(150); + jSplitPane1.setDividerSize(3); + + jScrollPane1.setPreferredSize(new java.awt.Dimension(258, 400)); + + jLstAbbs.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); + jLstAbbs.addListSelectionListener(new javax.swing.event.ListSelectionListener() { + public void valueChanged(javax.swing.event.ListSelectionEvent evt) { + jLstAbbsValueChanged(evt); + } + }); + jScrollPane1.setViewportView(jLstAbbs); + + jSplitPane1.setLeftComponent(jScrollPane1); + + jEdtAbbr.setEditable(false); + jEdtAbbr.setMinimumSize(new java.awt.Dimension(106, 400)); + jScrollPane2.setViewportView(jEdtAbbr); + + jSplitPane1.setRightComponent(jScrollPane2); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 580, Short.MAX_VALUE) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 337, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + pack(); + }// //GEN-END:initComponents + + private void jLstAbbsValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jLstAbbsValueChanged + if (evt.getValueIsAdjusting() == false) { + Object selected = jLstAbbs.getSelectedValue(); + if (selected != null) { + jEdtAbbr.setText(abbs.get(selected.toString())); + } + } + }//GEN-LAST:event_jLstAbbsValueChanged + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JEditorPane jEdtAbbr; + private javax.swing.JList jLstAbbs; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JScrollPane jScrollPane2; + private javax.swing.JSplitPane jSplitPane1; + // End of variables declaration//GEN-END:variables + Map abbs; + + @Override + public void escapePressed() { + setVisible(false); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/components/LineNumbersRuler.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/components/LineNumbersRuler.java new file mode 100644 index 0000000..88368a5 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/components/LineNumbersRuler.java @@ -0,0 +1,323 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * Copyright 2013-2014 Hanns Holger Rutz. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.components; + +import java.awt.*; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import javax.swing.BorderFactory; +import javax.swing.JEditorPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.SwingUtilities; +import javax.swing.event.CaretEvent; +import javax.swing.event.CaretListener; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.text.BadLocationException; +import javax.swing.text.Element; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; +import de.sciss.syntaxpane.SyntaxView; +import de.sciss.syntaxpane.actions.ActionUtils; +import de.sciss.syntaxpane.actions.gui.GotoLineDialog; +import de.sciss.syntaxpane.util.Configuration; + +/** + * This class will display line numbers for a related text component. The text + * component must use the same line height for each line. + * + * This class was designed to be used as a component added to the row header + * of a JScrollPane. + * + * Original code from http://tips4java.wordpress.com/2009/05/23/text-component-line-number/ + * + * @author Rob Camick + * + * Revised for de.sciss.syntaxpane + * + * @author Ayman Al-Sairafi, Hanns Holger Rutz + */ +public class LineNumbersRuler extends JPanel + implements CaretListener, DocumentListener, PropertyChangeListener, SyntaxComponent { + + public static final String PROPERTY_BACKGROUND = "LineNumbers.Background"; + public static final String PROPERTY_FOREGROUND = "LineNumbers.Foreground"; + public static final String PROPERTY_CURRENT_BACK = "LineNumbers.CurrentBack"; + public static final String PROPERTY_LEFT_MARGIN = "LineNumbers.LeftMargin"; + public static final String PROPERTY_RIGHT_MARGIN = "LineNumbers.RightMargin"; + public static final String PROPERTY_Y_OFFSET = "LineNumbers.YOFFset"; + public static final int DEFAULT_R_MARGIN = 5; + public static final int DEFAULT_L_MARGIN = 5; + private Status status; + private final static int MAX_HEIGHT = Integer.MAX_VALUE - 1000000; + // Text component this TextTextLineNumber component is in sync with + private JEditorPane editor; + private int minimumDisplayDigits = 2; + // Keep history information to reduce the number of times the component + // needs to be repainted + private int lastDigits; + private int lastHeight; + private int lastLine; + private MouseListener mouseListener = null; + // The formatting to use for displaying numbers. Use in String.format(numbersFormat, line) + private String numbersFormat = "%3d"; + + private Color currentLineColor; + + /** + * Returns the JScrollPane that contains this EditorPane, or null if no + * JScrollPane is the parent of this editor + */ + public JScrollPane getScrollPane(JTextComponent editorPane) { + Container p = editorPane.getParent(); + while (p != null) { + if (p instanceof JScrollPane) { + return (JScrollPane) p; + } + p = p.getParent(); + } + return null; + } + + @Override + public void config(Configuration config) { + int right = config.getInteger(PROPERTY_RIGHT_MARGIN, DEFAULT_R_MARGIN); + int left = config.getInteger(PROPERTY_LEFT_MARGIN , DEFAULT_L_MARGIN); + Color foreground = config.getColor(PROPERTY_FOREGROUND, Color.BLACK); + setForeground(foreground); + Color back = config.getColor(PROPERTY_BACKGROUND, Color.WHITE); + setBackground(back); + setBorder(BorderFactory.createEmptyBorder(0, left, 0, right)); + currentLineColor = config.getColor(PROPERTY_CURRENT_BACK, back); + } + + @Override + public void install(final JEditorPane editor) { + this.editor = editor; + + setFont(editor.getFont()); + + // setMinimumDisplayDigits(3); + Insets ein = editor.getInsets(); + if (ein.top != 0 || ein.bottom != 0) { + Insets curr = getInsets(); + setBorder(BorderFactory.createEmptyBorder(ein.top, curr.left, ein.bottom, curr.right)); + } + + editor.getDocument().addDocumentListener(this); + editor.addCaretListener(this); + editor.addPropertyChangeListener(this); + JScrollPane sp = getScrollPane(editor); + if (sp != null) sp.setRowHeaderView(this); + mouseListener = new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + GotoLineDialog.showForEditor(editor); + } + }; + addMouseListener(mouseListener); + setPreferredWidth(false); // required for toggle-lines to correctly repaint + status = Status.INSTALLING; + } + + @Override + public void deinstall(JEditorPane editor) { + removeMouseListener(mouseListener); + status = Status.DEINSTALLING; + editor.getDocument().removeDocumentListener(this); + editor.removeCaretListener(this); + editor.removePropertyChangeListener(this); + JScrollPane sp = getScrollPane(editor); + if (sp != null) { + sp.setRowHeaderView(null); + } + } + + /** + * Gets the minimum display digits + * + * @return the minimum display digits + */ + public int getMinimumDisplayDigits() { + return minimumDisplayDigits; + } + + /** + * Specify the minimum number of digits used to calculate the preferred + * width of the component. Default is 3. + * + * @param minimumDisplayDigits the number digits used in the preferred + * width calculation + */ + public void setMinimumDisplayDigits(int minimumDisplayDigits) { + this.minimumDisplayDigits = minimumDisplayDigits; + setPreferredWidth(false); + } + + /** + * Calculate the width needed to display the maximum line number + */ + private void setPreferredWidth(boolean force) { + int lines = ActionUtils.getLineCount(editor); + int digits = Math.max(String.valueOf(lines).length(), minimumDisplayDigits); + + // Update sizes when number of digits in the line number changes + + if (force || lastDigits != digits) { + lastDigits = digits; + numbersFormat = "%" + digits + "d"; + FontMetrics fontMetrics = getFontMetrics(getFont()); + int width = fontMetrics.charWidth('0') * digits; + Insets insets = getInsets(); + int preferredWidth = insets.left + insets.right + width; + + Dimension d = getPreferredSize(); + d.setSize(preferredWidth, MAX_HEIGHT); + setPreferredSize(d); + setSize(d); + } + } + + /** + * Draw the line numbers + */ + @Override + public void paintComponent(Graphics g) { + super.paintComponent(g); + + FontMetrics fontMetrics = getFontMetrics(getFont()); + Insets insets = getInsets(); + int currentLine = -1; + try { + currentLine = ActionUtils.getLineNumber(editor, editor.getCaretPosition()); + } catch (BadLocationException ex) { + // this won't happen, even if it does, we can ignore it and we will not have + // a current line to worry about... + } + + int lh = fontMetrics.getHeight(); + int maxLines = ActionUtils.getLineCount(editor); + SyntaxView.setRenderingHits((Graphics2D) g); + + Rectangle clip = g.getClip().getBounds(); + int topLine = (int) (clip.getY() / lh); + int bottomLine = Math.min(maxLines, (int) (clip.getHeight() + lh - 1) / lh + topLine + 1); + + for (int line = topLine; line < bottomLine; line++) { + String lineNumber = String.format(numbersFormat, line + 1); + int y = line * lh + insets.top; + int yt = y + fontMetrics.getAscent(); + if (line == currentLine) { + g.setColor(currentLineColor); + g.fillRect(0, y /* - lh + fontMetrics.getDescent() - 1 */, getWidth(), lh); + g.setColor(getForeground()); + g.drawString(lineNumber, insets.left, yt); + } else { + g.drawString(lineNumber, insets.left, yt); + } + } + } + +// +// Implement CaretListener interface +// + @Override + public void caretUpdate(CaretEvent e) { + // Get the line the caret is positioned on + + int caretPosition = editor.getCaretPosition(); + Element root = editor.getDocument().getDefaultRootElement(); + int currentLine = root.getElementIndex(caretPosition); + + // Need to repaint so the correct line number can be highlighted + + if (lastLine != currentLine) { + repaint(); + lastLine = currentLine; + } + } + +// +// Implement DocumentListener interface +// + @Override + public void changedUpdate(DocumentEvent e) { + documentChanged(); + } + + @Override + public void insertUpdate(DocumentEvent e) { + documentChanged(); + } + + @Override + public void removeUpdate(DocumentEvent e) { + documentChanged(); + } + + /* + * A document change may affect the number of displayed lines of text. + * Therefore the lines numbers will also change. + */ + private void documentChanged() { + // Preferred size of the component has not been updated at the time + // the DocumentEvent is fired + + SwingUtilities.invokeLater(new Runnable() { + + @Override + public void run() { + int preferredHeight = editor.getPreferredSize().height; + + // Document change has caused a change in the number of lines. + // Repaint to reflect the new line numbers + + if (lastHeight != preferredHeight) { + setPreferredWidth(false); + repaint(); + lastHeight = preferredHeight; + } + } + }); + } + + /** + * Implement PropertyChangeListener interface + */ + @Override + public void propertyChange(PropertyChangeEvent evt) { + String prop = evt.getPropertyName(); + if (prop.equals("document")) { + if (evt.getOldValue() instanceof SyntaxDocument) { + SyntaxDocument syntaxDocument = (SyntaxDocument) evt.getOldValue(); + syntaxDocument.removeDocumentListener(this); + } + if (evt.getNewValue() instanceof SyntaxDocument && status.equals(Status.INSTALLING)) { + SyntaxDocument syntaxDocument = (SyntaxDocument) evt.getNewValue(); + syntaxDocument.addDocumentListener(this); + setPreferredWidth(false); + repaint(); + } + } else if (prop.equals("font") && evt.getNewValue() instanceof Font) { + setFont((Font) evt.getNewValue()); + setPreferredWidth(true); + } + // TODO - theoretically also track "insets" + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/components/Markers.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/components/Markers.java new file mode 100644 index 0000000..d565a8d --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/components/Markers.java @@ -0,0 +1,131 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.components; + +import de.sciss.syntaxpane.actions.*; +import java.awt.Color; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultHighlighter; +import javax.swing.text.Highlighter; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; +import de.sciss.syntaxpane.Token; + +/** + * This class contains static utility methods to make highlighting in text + * components easier. + * + * @author Ayman Al-Sairafi, Hanns Holger Rutz + */ +public class Markers { + + // This subclass is used in our highlighting code + public static class SimpleMarker extends DefaultHighlighter.DefaultHighlightPainter { + + public SimpleMarker(Color color) { + super(color); + } + } + + /** + * Removes only our private highlights + * This is public so that we can remove the highlights when the editorKit + * is unregistered. SimpleMarker can be null, in which case all instances of + * our Markers are removed. + * @param component the text component whose markers are to be removed + * @param marker the SimpleMarker to remove + */ + public static void removeMarkers(JTextComponent component, SimpleMarker marker) { + Highlighter hilite = component.getHighlighter(); + Highlighter.Highlight[] hilites = hilite.getHighlights(); + + for (int i = 0; i < hilites.length; i++) { + if (hilites[i].getPainter() instanceof SimpleMarker) { + SimpleMarker hMarker = (SimpleMarker) hilites[i].getPainter(); + if (marker == null || hMarker.equals(marker)) { + hilite.removeHighlight(hilites[i]); + } + } + } + } + + /** + * Removes all the markers from an JEditorPane + */ + public static void removeMarkers(JTextComponent editorPane) { + removeMarkers(editorPane, null); + } + + /** + * Adds highlights for the given Token on the given pane + */ + public static void markToken(JTextComponent pane, Token token, SimpleMarker marker) { + markText(pane, token.start, token.end(), marker); + } + + /** + * Adds highlights for the given region on the given pane + */ + public static void markText(JTextComponent pane, int start, int end, SimpleMarker marker) { + try { + Highlighter hiliter = pane.getHighlighter(); + int selStart = pane.getSelectionStart(); + int selEnd = pane.getSelectionEnd(); + // if there is no selection or selection does not overlap + if(selStart == selEnd || end < selStart || start > selStart) { + hiliter.addHighlight(start, end, marker); + return; + } + // selection starts within the highlight, highlight before selection + if(selStart > start && selStart < end ) { + hiliter.addHighlight(start, selStart, marker); + } + // selection ends within the highlight, highlight remaining + if(selEnd > start && selEnd < end ) { + hiliter.addHighlight(selEnd, end, marker); + } + + } catch (BadLocationException ex) { + // nothing we can do if the request is out of bound + LOG.log(Level.SEVERE, null, ex); + } + } + + /** + * Marks all text in the document that matches the given pattern + * @param pane control to use + * @param pattern pattern to match + * @param marker marker to use for highlighting + */ + public static void markAll(JTextComponent pane, Pattern pattern, SimpleMarker marker) { + SyntaxDocument sDoc = ActionUtils.getSyntaxDocument(pane); + if(sDoc == null || pattern == null) { + return; + } + Matcher matcher = sDoc.getMatcher(pattern); + // we may not have any matcher (due to undo or something, so don't do anything. + if(matcher==null) { + return; + } + while(matcher.find()) { + markText(pane, matcher.start(), matcher.end(), marker); + } + } + + private static final Logger LOG = Logger.getLogger(Markers.class.getName()); +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/components/PairsMarker.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/components/PairsMarker.java new file mode 100644 index 0000000..3d5a994 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/components/PairsMarker.java @@ -0,0 +1,97 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.components; + +import java.awt.Color; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import de.sciss.syntaxpane.actions.*; +import javax.swing.JEditorPane; +import javax.swing.event.CaretEvent; +import javax.swing.event.CaretListener; +import javax.swing.text.JTextComponent; +import de.sciss.syntaxpane.SyntaxDocument; +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.util.Configuration; + +/** + * This class highlights any pairs of the given language. Pairs are defined + * with the Token.pairValue. + * + * @author Ayman Al-Sairafi + */ +public class PairsMarker implements CaretListener, SyntaxComponent, PropertyChangeListener { + + public static final String PROPERTY_COLOR = "PairMarker.Color"; + private JTextComponent pane; + private Markers.SimpleMarker marker; + private Status status; + + public PairsMarker() { + } + + @Override + public void caretUpdate(CaretEvent e) { + removeMarkers(); + int pos = e.getDot(); + SyntaxDocument doc = ActionUtils.getSyntaxDocument(pane); + Token token = doc.getTokenAt(pos); + if (token != null && token.pairValue != 0) { + Markers.markToken(pane, token, marker); + Token other = doc.getPairFor(token); + if (other != null) { + Markers.markToken(pane, other, marker); + } + } + } + + /** + * Remove all the highlights from the editor pane. This should be called + * when the editor-kit is removed. + */ + public void removeMarkers() { + Markers.removeMarkers(pane, marker); + } + + @Override + public void config(Configuration config) { + Color markerColor = config.getColor(PROPERTY_COLOR, new Color(0xeeee33)); + this.marker = new Markers.SimpleMarker(markerColor); + } + + @Override + public void install(JEditorPane editor) { + pane = editor; + pane.addCaretListener(this); + status = Status.INSTALLING; + } + + @Override + public void deinstall(JEditorPane editor) { + status = Status.DEINSTALLING; + pane.removeCaretListener(this); + removeMarkers(); + } + + @Override + public void propertyChange(PropertyChangeEvent evt) { + if (evt.getPropertyName().equals("document")) { + pane.removeCaretListener(this); + if (status.equals(Status.INSTALLING)) { + pane.addCaretListener(this); + removeMarkers(); + } + } + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/components/SyntaxComponent.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/components/SyntaxComponent.java new file mode 100644 index 0000000..8174afd --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/components/SyntaxComponent.java @@ -0,0 +1,52 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.components; + +import javax.swing.JEditorPane; +import de.sciss.syntaxpane.util.Configuration; + +/** + * A Component that is installed to the EditorKit to perform GUI operations + * on the Editor. + * + * @author Ayman Al-Sairafi + */ +public interface SyntaxComponent { + + /** + * Configure the component using the given properties. The keys + * needed for configuration will be prefixed by the given prefix + * @param config configuration data + */ + public void config(Configuration config); + + /** + * Called to install the component on an editor + */ + public void install(JEditorPane editor); + + /** + * Called when the component is to be removed from the editor + */ + public void deinstall(JEditorPane editor); + + /** + * The status is used to have proper propertyChange support. We need to know if we are INSTALLING + * the component or DE-INSTALLING it + */ + static enum Status { + INSTALLING, + DEINSTALLING + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/components/TokenMarker.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/components/TokenMarker.java new file mode 100644 index 0000000..92098bf --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/components/TokenMarker.java @@ -0,0 +1,146 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.components; + +import java.beans.PropertyChangeEvent; +import de.sciss.syntaxpane.actions.*; +import java.awt.Color; +import java.beans.PropertyChangeListener; +import java.util.HashSet; +import java.util.Iterator; +import java.util.Set; +import java.util.logging.Logger; +import javax.swing.JEditorPane; +import javax.swing.event.CaretEvent; +import javax.swing.event.CaretListener; +import de.sciss.syntaxpane.SyntaxDocument; +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; +import de.sciss.syntaxpane.util.Configuration; + +/** + * This class highlights Tokens within a document whenever the caret is moved + * to a TokenType provided in the config file. + * + * @author Ayman Al-Sairafi + */ +public class TokenMarker implements SyntaxComponent, CaretListener, PropertyChangeListener { + + public static final String DEFAULT_TOKENTYPES = "IDENTIFIER, TYPE, TYPE2, TYPE3"; + public static final String PROPERTY_COLOR = "TokenMarker.Color"; + public static final String PROPERTY_TOKENTYPES = "TokenMarker.TokenTypes"; + private static final Color DEFAULT_COLOR = new Color(0xFFEE66); + private JEditorPane pane; + private Set tokenTypes = new HashSet(); + private Markers.SimpleMarker marker; + private Status status; + + /** + * Constructs a new Token highlighter + */ + public TokenMarker() { + } + + @Override + public void caretUpdate(CaretEvent e) { + markTokenAt(e.getDot()); + } + + public void markTokenAt(int pos) { + SyntaxDocument doc = ActionUtils.getSyntaxDocument(pane); + if (doc != null) { + Token token = doc.getTokenAt(pos); + removeMarkers(); + if (token != null && tokenTypes.contains(token.type)) { + addMarkers(token); + } + } + } + + /** + * removes all markers from the pane. + */ + public void removeMarkers() { + Markers.removeMarkers(pane, marker); + } + + /** + * add highlights for the given pattern + * @param pattern + */ + void addMarkers(Token tok) { + SyntaxDocument sDoc = (SyntaxDocument) pane.getDocument(); + sDoc.readLock(); + // we need to create a STring, because the CharSequence does not have an + // equals method and Object.equals is called. It will not match + String text = tok.getText(sDoc).toString(); + Iterator it = sDoc.getTokens(0, sDoc.getLength()); + while (it.hasNext()) { + Token nextToken = it.next(); + String nextText = nextToken.getText(sDoc).toString(); + if (text.equals(nextText)) { + Markers.markToken(pane, nextToken, marker); + } + + } + sDoc.readUnlock(); + } + + @Override + public void config(Configuration config) { + Color markerColor = config.getColor( + PROPERTY_COLOR, DEFAULT_COLOR); + this.marker = new Markers.SimpleMarker(markerColor); + String types = config.getString( + PROPERTY_TOKENTYPES, DEFAULT_TOKENTYPES); + + for (String type : types.split("\\s*,\\s*")) { + try { + TokenType tt = TokenType.valueOf(type); + tokenTypes.add(tt); + } catch (IllegalArgumentException e) { + LOG.warning("Error in setting up TokenMarker " + + " - Invalid TokenType: " + type); + } + + } + } + + @Override + public void install(JEditorPane editor) { + this.pane = editor; + pane.addCaretListener(this); + markTokenAt(editor.getCaretPosition()); + status = Status.INSTALLING; + } + + @Override + public void deinstall(JEditorPane editor) { + status = Status.DEINSTALLING; + removeMarkers(); + pane.removeCaretListener(this); + } + private static final Logger LOG = Logger.getLogger(TokenMarker.class.getName()); + + @Override + public void propertyChange(PropertyChangeEvent evt) { + if (evt.getPropertyName().equals("document")) { + pane.removeCaretListener(this); + if (status.equals(Status.INSTALLING)) { + pane.addCaretListener(this); + removeMarkers(); + } + } + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/lexers/DefaultJFlexLexer.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/lexers/DefaultJFlexLexer.java new file mode 100644 index 0000000..edcbb2a --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/lexers/DefaultJFlexLexer.java @@ -0,0 +1,138 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.lexers; + +import java.io.CharArrayReader; +import de.sciss.syntaxpane.*; +import java.io.IOException; +import java.io.Reader; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.text.Segment; + +/** + * This is a default, and abstract implementation of a Lexer using JFLex + * with some utility methods that Lexers can implement. + * + * @author Ayman Al-Sairafi + */ +public abstract class DefaultJFlexLexer implements Lexer { + + protected int tokenStart; + protected int tokenLength; + protected int offset; + + /** + * Helper method to create and return a new Token from of TokenType + * tokenStart and tokenLength will be modified to the newStart and + * newLength params + */ + protected Token token(TokenType type, int tStart, int tLength, + int newStart, int newLength) { + tokenStart = newStart; + tokenLength = newLength; + return new Token(type, tStart + offset, tLength); + } + + /** + * Create and return a Token of given type from start with length + * offset is added to start + */ + protected Token token(TokenType type, int start, int length) { + return new Token(type, start + offset, length); + } + + /** + * Create and return a Token of given type. start is obtained from {@link DefaultJFlexLexer#yychar()} + * and length from {@link DefaultJFlexLexer#yylength()} + * offset is added to start + */ + protected Token token(TokenType type) { + return new Token(type, yychar() + offset, yylength()); + } + + /** + * Create and return a Token of given type and pairValue. + * start is obtained from {@link DefaultJFlexLexer#yychar()} + * and length from {@link DefaultJFlexLexer#yylength()} + * offset is added to start + */ + protected Token token(TokenType type, int pairValue) { + return new Token(type, yychar() + offset, yylength(), (byte) pairValue); + } + + /** + * The DefaultJFlexLexer simply calls the yylex method of a JFlex compatible + * Lexer and adds the tokens obtained to an ArrayList. + */ + @Override + public void parse(Segment segment, int ofst, List tokens) { + try { + CharArrayReader reader = new CharArrayReader(segment.array, segment.offset, segment.count); + yyreset(reader); + this.offset = ofst; + for (Token t = yylex(); t != null; t = yylex()) { + tokens.add(t); + } + } catch (IOException ex) { + Logger.getLogger(DefaultJFlexLexer.class.getName()).log(Level.SEVERE, null, ex); + } + } + + /** + * This will be called to reset the the lexer. + * This is created automatically by JFlex. + */ + public abstract void yyreset(Reader reader); + + /** + * This is called to return the next Token from the Input Reader + * @return next token, or null if no more tokens. + * @throws java.io.IOException + */ + public abstract Token yylex() throws java.io.IOException; + + /** + * Returns the character at position pos from the + * matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. + * A value from 0 to yylength()-1. + * + * @return the character at position pos + */ + public abstract char yycharat(int pos); + + /** + * Returns the length of the matched text region. + * This method is automatically implemented by JFlex lexers + */ + public abstract int yylength(); + + /** + * Returns the text matched by the current regular expression. + * This method is automatically implemented by JFlex lexers + */ + public abstract String yytext(); + + /** + * Return the char number from beginning of input stream. + * This is NOT implemented by JFlex, so the code must be + * added to create this and return the private yychar field + */ + public abstract int yychar(); +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/lexers/EmptyLexer.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/lexers/EmptyLexer.java new file mode 100644 index 0000000..f6f7371 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/lexers/EmptyLexer.java @@ -0,0 +1,30 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package de.sciss.syntaxpane.lexers; + +import de.sciss.syntaxpane.*; +import java.util.List; +import javax.swing.text.Segment; + +/** + * A lexer that does nothing. Used for plain document editing. + * @author Ayman Al-Sairafi + */ +public class EmptyLexer implements Lexer { + + @Override + public void parse(Segment segment, int ofst, List tokens) { + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/lexers/SimpleRegexLexer.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/lexers/SimpleRegexLexer.java new file mode 100644 index 0000000..4c28212 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/lexers/SimpleRegexLexer.java @@ -0,0 +1,99 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.lexers; + +import java.io.FileReader; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.TreeSet; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.swing.text.Segment; +import de.sciss.syntaxpane.Lexer; +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenComparators; +import de.sciss.syntaxpane.TokenType; + +/** + * This is a "dynamic" Lexer that will use Regex patterns to parse any document, + * It is NOT as fast as other JFlex generated lexers. + * + * The current implementation is about 20x slower than a JFlex lexer + * (5000 lines in 100ms, vs 5ms for JFlex lexer) + * + * This is still usable for a few 100 lines. 500 lines parse in about 10ms. + * + * It also depends on how complex the Regexp and how many of them will actually + * provide a match. + * + * Since KEYWORD TokenType is by order less than IDENTIFIER, the higher + * precedence of KEYWORD token will be used, even if the same regex matches + * an IDENTIFIER. This is a neat side-effect of the ordering of the TokenTypes. + * We now just need to add any non-overlapping matches. And since longer matches + * are found first, we will properly match the longer identifiers which start with + * a keyword. + * + * This behaviour can easily be modified by overriding the {@link compareTo} method + * + * @author Ayman Al-Sairafi + */ +public class SimpleRegexLexer implements Lexer { + + public SimpleRegexLexer(Map props) { + putPatterns(props); + } + + public SimpleRegexLexer(String propsLocation) throws IOException { + Properties props = new Properties(); + props.load(new FileReader(propsLocation)); + putPatterns(props); + } + + @Override + public void parse(Segment segment, int ofst, List tokens) { + TreeSet allMatches = new TreeSet(TokenComparators.LONGEST_FIRST); + // add to ourset all the matches by all our regexes + for (Map.Entry e : patterns.entrySet()) { + Matcher m = e.getValue().matcher(segment); + while (m.find()) { + Token t = new Token(e.getKey(), m.start() + ofst, m.end() - m.start()); + allMatches.add(t); + } + } + int end = -1; + for (Token t : allMatches) { + if (t.start > end) { + tokens.add(t); + end = t.end(); + } + } + } + Map patterns = new HashMap(); + + public SimpleRegexLexer putPattern(TokenType type, String regex) { + patterns.put(type, Pattern.compile(regex)); + return this; + } + + public SimpleRegexLexer putPatterns(Map props) { + for (Object key : props.keySet()) { + TokenType t = TokenType.valueOf(key.toString()); + patterns.put(t, Pattern.compile(props.get(key).toString())); + } + return this; + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/BashSyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/BashSyntaxKit.java new file mode 100644 index 0000000..7aa389c --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/BashSyntaxKit.java @@ -0,0 +1,28 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.syntaxkits; + +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.lexers.BashLexer; + +/** + * + * @author Ayman Al-Sairafi + */ +public class BashSyntaxKit extends DefaultSyntaxKit { + + public BashSyntaxKit() { + super(new BashLexer()); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/CSyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/CSyntaxKit.java new file mode 100644 index 0000000..c260b5e --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/CSyntaxKit.java @@ -0,0 +1,38 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.syntaxkits; + +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.Lexer; +import de.sciss.syntaxpane.lexers.CLexer; + +/** + * + * @author Ayman Al-Sairafi + */ +public class CSyntaxKit extends DefaultSyntaxKit { + + public CSyntaxKit() { + super(new CLexer()); + } + + /** + * Construct a JavaSyntaxKit user the supplied lexer. This is protected so + * only subclasses may extend this with a new lexer. + * @param lexer + */ + CSyntaxKit(Lexer lexer) { + super(lexer); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/ClojureSyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/ClojureSyntaxKit.java new file mode 100644 index 0000000..afbdcf4 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/ClojureSyntaxKit.java @@ -0,0 +1,33 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.syntaxkits; + +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.Lexer; +import de.sciss.syntaxpane.lexers.ClojureLexer; + +/** + * + * @author Ayman Al-Sairafi + */ +public class ClojureSyntaxKit extends DefaultSyntaxKit { + + public ClojureSyntaxKit() { + super(new ClojureLexer()); + } + + public ClojureSyntaxKit(Lexer lexer) { + super(lexer); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/CppSyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/CppSyntaxKit.java new file mode 100644 index 0000000..b869b37 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/CppSyntaxKit.java @@ -0,0 +1,27 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.syntaxkits; + +import de.sciss.syntaxpane.lexers.CppLexer; + +/** + * + * @author Ayman Al-Sairafi + */ +public class CppSyntaxKit extends CSyntaxKit { + + public CppSyntaxKit() { + super(new CppLexer()); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/DOSBatchSyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/DOSBatchSyntaxKit.java new file mode 100644 index 0000000..2f7ec86 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/DOSBatchSyntaxKit.java @@ -0,0 +1,28 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.syntaxkits; + +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.lexers.DOSBatchLexer; + +/** + * + * @author Ayman Al-Sairafi + */ +public class DOSBatchSyntaxKit extends DefaultSyntaxKit { + + public DOSBatchSyntaxKit() { + super(new DOSBatchLexer()); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/GroovySyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/GroovySyntaxKit.java new file mode 100644 index 0000000..5eb080c --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/GroovySyntaxKit.java @@ -0,0 +1,27 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.syntaxkits; + +import de.sciss.syntaxpane.lexers.GroovyLexer; + +/** + * + * @author Ayman Al-Sairafi + */ +public class GroovySyntaxKit extends JavaSyntaxKit { + + public GroovySyntaxKit() { + super(new GroovyLexer()); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/JFlexSyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/JFlexSyntaxKit.java new file mode 100644 index 0000000..3dc9773 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/JFlexSyntaxKit.java @@ -0,0 +1,27 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.syntaxkits; + +import de.sciss.syntaxpane.lexers.JFlexLexer; + +/** + * JFlex lexer + * @author Ayman Al-Sairafi + */ +public class JFlexSyntaxKit extends JavaSyntaxKit { + + public JFlexSyntaxKit() { + super(new JFlexLexer()); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/JavaScriptSyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/JavaScriptSyntaxKit.java new file mode 100644 index 0000000..982d83d --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/JavaScriptSyntaxKit.java @@ -0,0 +1,28 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.syntaxkits; + +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.lexers.JavaScriptLexer; + +/** + * + * @author Ayman Al-Sairafi + */ +public class JavaScriptSyntaxKit extends DefaultSyntaxKit { + + public JavaScriptSyntaxKit() { + super(new JavaScriptLexer()); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/JavaSyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/JavaSyntaxKit.java new file mode 100644 index 0000000..d845863 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/JavaSyntaxKit.java @@ -0,0 +1,33 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.syntaxkits; + +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.Lexer; +import de.sciss.syntaxpane.lexers.JavaLexer; + +/** + * + * @author Ayman Al-Sairafi + */ +public class JavaSyntaxKit extends DefaultSyntaxKit { + + public JavaSyntaxKit() { + super(new JavaLexer()); + } + + JavaSyntaxKit(Lexer lexer) { + super(lexer); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/LuaSyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/LuaSyntaxKit.java new file mode 100644 index 0000000..d7ccca5 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/LuaSyntaxKit.java @@ -0,0 +1,28 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.syntaxkits; + +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.lexers.LuaLexer; + +/** + * + * @author Michael Leung + */ +public class LuaSyntaxKit extends DefaultSyntaxKit { + + public LuaSyntaxKit() { + super(new LuaLexer()); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/PlainSyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/PlainSyntaxKit.java new file mode 100644 index 0000000..042c92c --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/PlainSyntaxKit.java @@ -0,0 +1,28 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.syntaxkits; + +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.lexers.EmptyLexer; + +/** + * + * @author Ayman Al-Sairafi + */ +public class PlainSyntaxKit extends DefaultSyntaxKit { + + public PlainSyntaxKit() { + super(new EmptyLexer()); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/PropertiesSyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/PropertiesSyntaxKit.java new file mode 100644 index 0000000..3a1c358 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/PropertiesSyntaxKit.java @@ -0,0 +1,28 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.syntaxkits; + +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.lexers.PropertiesLexer; + +/** + * + * @author Ayman Al-Sairafi + */ +public class PropertiesSyntaxKit extends DefaultSyntaxKit { + + public PropertiesSyntaxKit() { + super(new PropertiesLexer()); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/PythonSyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/PythonSyntaxKit.java new file mode 100644 index 0000000..e04baf6 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/PythonSyntaxKit.java @@ -0,0 +1,29 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.syntaxkits; + +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.lexers.PythonLexer; + +/** + * + * @author Ayman Al-Sairafi + */ +public class PythonSyntaxKit extends DefaultSyntaxKit { + + public PythonSyntaxKit() { + super(new PythonLexer()); + } + +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/RubySyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/RubySyntaxKit.java new file mode 100644 index 0000000..9b25ceb --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/RubySyntaxKit.java @@ -0,0 +1,28 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.syntaxkits; + +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.lexers.RubyLexer; + +/** + * + * @author Ayman Al-Sairafi + */ +public class RubySyntaxKit extends DefaultSyntaxKit { + + public RubySyntaxKit() { + super(new RubyLexer()); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/ScalaSyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/ScalaSyntaxKit.java new file mode 100644 index 0000000..5606640 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/ScalaSyntaxKit.java @@ -0,0 +1,33 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.syntaxkits; + +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.Lexer; +import de.sciss.syntaxpane.lexers.ScalaLexer; + +/** + * + * @author Ayman Al-Sairafi + */ +public class ScalaSyntaxKit extends DefaultSyntaxKit { + + public ScalaSyntaxKit() { + super(new ScalaLexer()); + } + + public ScalaSyntaxKit(Lexer lexer) { + super(lexer); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/SqlSyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/SqlSyntaxKit.java new file mode 100644 index 0000000..c881e3b --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/SqlSyntaxKit.java @@ -0,0 +1,28 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.syntaxkits; + +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.lexers.SqlLexer; + +/** + * + * @author Ayman Al-Sairafi + */ +public class SqlSyntaxKit extends DefaultSyntaxKit { + + public SqlSyntaxKit() { + super(new SqlLexer()); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/TALSyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/TALSyntaxKit.java new file mode 100644 index 0000000..f1ae602 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/TALSyntaxKit.java @@ -0,0 +1,28 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.syntaxkits; + +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.lexers.TALLexer; + +/** + * + * @author Ayman Al-Sairafi + */ +public class TALSyntaxKit extends DefaultSyntaxKit { + + public TALSyntaxKit() { + super(new TALLexer()); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/XHTMLSyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/XHTMLSyntaxKit.java new file mode 100644 index 0000000..43ff3b5 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/XHTMLSyntaxKit.java @@ -0,0 +1,28 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.syntaxkits; + +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.lexers.XHTMLLexer; + +/** + * + * @author Ayman Al-Sairafi + */ +public class XHTMLSyntaxKit extends DefaultSyntaxKit { + + public XHTMLSyntaxKit() { + super(new XHTMLLexer()); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/XPathSyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/XPathSyntaxKit.java new file mode 100644 index 0000000..473162d --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/XPathSyntaxKit.java @@ -0,0 +1,28 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.syntaxkits; + +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.lexers.XPathLexer; + +/** + * + * @author Ayman Al-Sairafi + */ +public class XPathSyntaxKit extends DefaultSyntaxKit { + + public XPathSyntaxKit() { + super(new XPathLexer()); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/XmlSyntaxKit.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/XmlSyntaxKit.java new file mode 100644 index 0000000..02f816d --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/syntaxkits/XmlSyntaxKit.java @@ -0,0 +1,29 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.syntaxkits; + +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.lexers.XmlLexer; + +/** + * + * @author Ayman Al-Sairafi + */ +public class XmlSyntaxKit extends DefaultSyntaxKit { + + public XmlSyntaxKit() { + super(new XmlLexer()); + } + +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/util/Configuration.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/util/Configuration.java new file mode 100644 index 0000000..c461fae --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/util/Configuration.java @@ -0,0 +1,378 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.util; + +import java.awt.Color; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +/** + * Wrapper around the Properties class with supprt for Heirarchical confogurations + * and more functionality. + * + * Except for the getXXXX methods, all other Map Interface methods operate on the + * current (non-parent) collection and do NOT touch the parent. + * + * @author Ayman Al-Sairafi + */ +public class Configuration implements Map { + + /** + * Our parent + */ + Configuration parent; + /** + * Our Class for the configuration + */ + Class clazz; + /** + * The properties we have, excluding the parents defaults + */ + Map props; + + /** + * Creates a new COnfiguration that uses parent as its parent + * Configuration. + * + * @param theClass + * @param parent + */ + public Configuration(Class theClass, Configuration parent) { + this(theClass); + this.parent = parent; + } + + /** + * Creates an empty Configuration + * @param theClass + */ + public Configuration(Class theClass) { + super(); + this.clazz = theClass; + } + + /** + * Get a string from this object or one of its parents. If nothing + * is found, null is returned. + * If the Regex ${key} is found, then it is replaced by the value of that + * key within this (or parent's) map. + * Special COnstructs in ${}: + *
  • class_path will be replaced by the name of the + * Configuration (usually ClassName) with "." replaced by "/", and then + * converted to all lowercase
  • + *
  • class_simpleName
  • is replaced by class.SimpleName + * @param key + * @return + */ + public String getString(String key) { + String value = null; + if (props != null) { + value = props.get(key); + } + for (Configuration p = parent; value == null && p != null; p = p.parent) { + value = p.get(key); + } + // if we have a parent, then perform ${} replacements + if (value != null) { + Matcher m = PARENT_KEY.matcher(value); + StringBuffer sb = new StringBuffer(); + while (m.find()) { + String p_key = m.group(1); + String p_value = getString(p_key); + if (p_key.equals("class_path")) { + p_value = clazz.getName().replace(".", "/").toLowerCase(); + } else if (p_key.equals("class_simpleName")) { + p_value = clazz.getSimpleName(); + } else { + p_value = getString(p_key); + if (p_value == null) { + Logger.getLogger(this.getClass().getName()).warning( + "no value for ${" + p_key + + "} is defined"); + } + } + m.appendReplacement(sb, p_value); + } + m.appendTail(sb); + value = sb.toString(); + } + return value; + } + + /** + * Returns a non-null value either by traversing the current + * and parent(s) map, or returning the defaultValue + * @param key + * @param defaultValue + * @throws NullPointerException if defaultValue is null + * @return + */ + public String getString(String key, String defaultValue) { + if (defaultValue == null) { + throw new NullPointerException("defaultValue cannot be null"); + } + String value = getString(key); + return (value == null) ? defaultValue : value; + } + + /** + * Gets an integer from the properties. If number cannot be found + * or if it cannot be decoded, the default is returned + * The integer is decoded using {@link Integer.decode(String)} + * @param key + * @param Default + * @return + */ + public int getInteger(String key, int Default) { + String v = getString(key); + if (v == null) { + return Default; + } + try { + int i = Integer.decode(v); + return i; + } catch (NumberFormatException e) { + LOG.log(Level.WARNING, null, e); + return Default; + } + } + + /** + * Returns a String[] of the comma separated items in the value. + * + * Does NOT return null. If the key is not found, + * then an empty string array is returned. So the return of this method + * can always be used directly in a foreach loop + * @param key + * @return non-null String[] + */ + public String[] getPropertyList(String key) { + String v = getString(key); + if (v == null) { + return EMPTY_LIST; + } else { + return COMMA_SEPARATOR.split(v); + } + } + + /** + * Returns a boolean from the configuration + * @param key + * @param Default + * @return + */ + public boolean getBoolean(String key, boolean Default) { + String b = getString(key); + if (b == null) { + return Default; + } + return Boolean.parseBoolean(b.trim()); + } + + /** + * return the Color that has the given key or the Default + * @param key + * @param Default + * @return + */ + public Color getColor(String key, Color Default) { + String c = getString(key); + if (c == null) { + return Default; + } else { + try { + return Color.decode(c); + } catch (NumberFormatException e) { + return Default; + } + } + } + + @SuppressWarnings("unchecked") + @Override + public void putAll(Map config) { + if (props == null) { + props = new HashMap(); + } + props.putAll(config); + } + + /** + * Returns ALL property names from this Configuration's parents and + * this Configuration. As usual, parents are added first so they + * are overriden by children. + * + * @return Set of all String keys in this and parents + */ + public Set stringPropertyNames() { + Set propNames = new HashSet(); + if (parent != null) { + propNames.addAll(parent.stringPropertyNames()); + } + if (props != null) { + for (Object k : props.keySet()) { + propNames.add(k.toString()); + } + } + return propNames; + } + + @Override + public String put(String key, String value) { + if (props == null) { + props = new HashMap(); + } + Object old = props.put(key, value); + return (old == null) ? null : old.toString(); + } + + @Override + public int size() { + return (props == null) ? 0 : props.size(); + } + + @Override + public boolean isEmpty() { + return (props == null) ? true : props.isEmpty(); + } + + @Override + public boolean containsKey(Object key) { + return (props == null) ? false : props.containsKey(key); + } + + @Override + public boolean containsValue(Object value) { + return (props == null) ? false : props.containsValue(value); + } + + @Override + public String get(Object key) { + return (props == null) ? null : props.get(key); + } + + @Override + public String remove(Object key) { + if (props == null) { + return null; + } + Object old = props.remove(key); + return (old == null) ? null : old.toString(); + } + + @Override + public void clear() { + if (props != null) { + props.clear(); + } + } + + @Override + @SuppressWarnings("unchecked") + public Set keySet() { + if (props == null) { + return Collections.EMPTY_SET; + } else { + return props.keySet(); + } + } + + @Override + @SuppressWarnings("unchecked") + public Collection values() { + if (props == null) { + return Collections.EMPTY_SET; + } else { + return props.values(); + } + } + + @Override + @SuppressWarnings("unchecked") + public Set> entrySet() { + if (props == null) { + return Collections.EMPTY_SET; + } else { + return props.entrySet(); + } + } + + @Override + public String toString() { + return "Configuration " + clazz + " for " + parent; + } + + /** + * Utility class to hold data for {@link getKeys} method. + */ + public static class StringKeyMatcher { + + private StringKeyMatcher(String key, Matcher matcher, String group1, String value) { + this.key = key; + this.matcher = matcher; + this.group1 = group1; + this.value = value; + } + /** + * The full key matched + */ + public final String key; + /** + * matcher instance for the key + */ + public final Matcher matcher; + /** + * Matched group 1. Could be null if no Group 1 is found + */ + public final String group1; + /** + * Value for key matched + */ + public final String value; + } + + /** + * Obtain a set of all keys (and parent's keys) that match the given pattern. + * If no keys match, then an empty set is returned. + * Use this instead of the {@link stringPropertyNames} + * @param pattern + * @return + */ + public Set getKeys(Pattern pattern) { + Set matched = new HashSet(); + Set all = stringPropertyNames(); + for (String k : all) { + Matcher m = pattern.matcher(k); + if (m.matches()) { + StringKeyMatcher skm = new StringKeyMatcher(k, m, + (m.groupCount() >= 1) ? m.group(1) : null, + getString(k)); + matched.add(skm); + } + } + return matched; + } + public static final String[] EMPTY_LIST = new String[0]; + public static final Pattern COMMA_SEPARATOR = Pattern.compile("\\s*,\\s*"); + private static Pattern PARENT_KEY = Pattern.compile("\\$\\{(\\w+)\\}"); + private static final Logger LOG = Logger.getLogger(Configuration.class.getName()); +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/util/JarServiceProvider.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/util/JarServiceProvider.java new file mode 100644 index 0000000..3e4f200 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/util/JarServiceProvider.java @@ -0,0 +1,287 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.util; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Properties; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * @author subwiz + * @author Ayman Al-Sairafi + */ +public class JarServiceProvider { + + public static final String SERVICES_ROOT = "META-INF/services/"; + private static final Logger LOG = Logger.getLogger(JarServiceProvider.class.getName()); + + /** + * Prevents anyone from instantiating this class. + * Just use the static method + */ + private JarServiceProvider() {} + + private static ClassLoader getClassLoader() { + ClassLoader cl = JarServiceProvider.class.getClassLoader(); + return cl == null ? ClassLoader.getSystemClassLoader() : cl; + } + + /** + * Returns an Object array from the file in META-INF/resources/{classname} + * + * @throws java.io.IOException + */ + public static List getServiceProviders(Class cls) throws IOException { + ArrayList l = new ArrayList(); + ClassLoader cl = getClassLoader(); + String serviceFile = SERVICES_ROOT + cls.getName(); + Enumeration e = cl.getResources(serviceFile); + while (e.hasMoreElements()) { + URL u = e.nextElement(); + InputStream is = u.openStream(); + BufferedReader br = null; + try { + br = new BufferedReader( + new InputStreamReader(is, Charset.forName("UTF-8"))); + String str = null; + while ((str = br.readLine()) != null) { + int commentStartIdx = str.indexOf("#"); + if (commentStartIdx != -1) { + str = str.substring(0, commentStartIdx); + } + str = str.trim(); + if (str.length() == 0) { + continue; + } + try { + Object obj = cl.loadClass(str).newInstance(); + l.add(obj); + } catch (Exception ex) { + LOG.warning("Could not load: " + str); + LOG.warning(ex.getMessage()); + } + } + } finally { + if (br != null) { + br.close(); + } + } + } + return l; + } + + /** + * Reads a file in the META-INF/services location. File name will be + * fully qualified classname, in all lower-case, appended with ".properties" + * If no file is found, then a an empty Property instance will be returned + * + * @return Property file read. + */ + public static Properties readProperties(Class clazz) { + return readProperties(clazz.getName()); + } + + /** + * Reads a file in the META-INF/services named name appended with + * ".properties" + * + * If no file is found, then a an empty Property instance will be returned + * + * @param name name of file (use dots to separate subfolders). + * @return Property file read. + */ + public static Properties readProperties(String name) { + Properties props = new Properties(); + String serviceFile = name.toLowerCase(); + if (!serviceFile.endsWith(".properties")) { + serviceFile += ".properties"; + } + InputStream is = findResource(serviceFile); + if (is != null) { + try { + props.load(new InputStreamReader(is, "UTF-8")); + } catch (IOException ex) { + Logger.getLogger(JarServiceProvider.class.getName()).log(Level.SEVERE, null, ex); + } + } + return props; + } + + /** + * Reads language specific files in the META-INF/services named name appended + * with ".properties". The contents of the files are merged as follows: + *
      + *
    • First the default language file (<name>.properties) is read
    • + *
    • Then the general language variant of the file + * (<name>_<lang>.properties) is read and its + * entries are added to/overwrite the entries of the default life
    • + *
    • Last the country specific language variant of the file + * (<name>_<lang>_<country>.properties) is read and its + * entries are added to/overwrite the existing entries
    • + *
    + * Example: You have three files: + *
      + *
    • config.properties which contains the complete configuration + * (most likely with English menus, tooltips)
    • + *
    • config_de.properties which only contains menu names and tooltips + * in German language
    • + *
    • config_de_CH which might just contain entries for specific + * Swiss spelling variant of some words in a tooltip
    • + *
        + * + * If no filesis found, then a an empty Property instance will be returned + * + * @param name name of file (use dots to separate subfolders). + * @param locale The locale for which to read the files + * @return Property file read. + */ + public static Properties readProperties(String name, Locale locale) { + // If name already ends in ".properties", then cut this off + name = name.toLowerCase(); + int idx = name.lastIndexOf(".properties"); + if (idx > 0) { + name = name.substring(0, idx); + } + // 1. Read properties of default langauge + Properties props = readProperties(name); + // 2. Read properties of general language variant + if (locale != null && locale.getLanguage() != null) { + name += "_"+locale.getLanguage(); + Properties langProps = readProperties(name); + props.putAll(langProps); + } + // 3. Read properties of country specific language variant + if (locale != null && locale.getCountry() != null) { + name += "_"+locale.getCountry(); + Properties countryProps = readProperties(name); + props.putAll(countryProps); + } + return props; + } + /** + * Read a file in the META-INF/services named name appended with + * ".properties", and returns it as a Map + * If no file is found, then a an empty Property instance will be returned + * @param name name of file (use dots to separate subfolders). + * @return Map of keys and values + */ + public static Map readStringsMap(String name) { + Properties props = readProperties(name); + HashMap map = new HashMap(); + if (props != null) { + for (Map.Entry e : props.entrySet()) { + map.put(e.getKey().toString(), e.getValue().toString()); + } + } + return map; + } + + /** + * Read the given URL and returns a List of Strings for each input line + * Each line will not have the line terminator. + * + * The resource is searched in /META-INF/services/url, then in + * url, then the url is treated as a location in the current classpath + * and an attempt to read it from that location is done. + * + * @param url location of file to read + * @return List of Strings for each line read. or EMPTY_LIST if URL is not found + */ + @SuppressWarnings("unchecked") + public static List readLines(String url) { + InputStream is = findResource(url); + if (is == null) { + return Collections.EMPTY_LIST; + } + List lines = new ArrayList(); + try { + BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); + for (String line = br.readLine(); line != null; line = br.readLine()) { + // Trim and unescape some control chars + line = line.trim().replace("\\n", "\n").replace("\\t", "\t"); + lines.add(line); + } + } catch (IOException ex) { + LOG.log(Level.SEVERE, null, ex); + } finally { + try { + is.close(); + } catch (IOException ex) { + LOG.log(Level.SEVERE, null, ex); + } + return lines; + } + + } + + /** + * Attempts to find a location url. The following locations are searched in + * sequence: + * url, + * SERVICES_ROOT/url + * all classpath/url + * + * @return InputStream at that location, or null if not found + * @see JarServiceProvider#findResource(java.lang.String) + */ + public static InputStream findResource(String url, ClassLoader cl) { + InputStream is = null; + + URL loc = cl.getResource(url); + // if (loc == null) { + // loc = cl.getResource(url); + // } + if (loc == null) { + loc = cl.getResource(SERVICES_ROOT + url); + } + if (loc == null) { + is = ClassLoader.getSystemResourceAsStream(url); + } else { + try { + is = loc.openStream(); + } catch (IOException ex) { + Logger.getLogger(JarServiceProvider.class.getName()).log(Level.SEVERE, null, ex); + } + } + return is; + } + + /** + * Attempts to find a location url. The following locations are searched in + * sequence: + * url, + * SERVICES_ROOT/url + * all classpath/url + * The System ClassLoader is used. + * + * @return InputSTream at that location, or null if not found + * @see JarServiceProvider#findResource(java.lang.String, java.lang.ClassLoader) + */ + public static InputStream findResource(String url) { + return findResource(url, getClassLoader()); + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/util/ReflectUtils.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/util/ReflectUtils.java new file mode 100644 index 0000000..30f166b --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/util/ReflectUtils.java @@ -0,0 +1,362 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.util; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Constructor; +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Member; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Reflection Utility methods + * @author Ayman Al-Sairafi + */ +public class ReflectUtils { + + /** + * Adds all methods (from Class.getMethodCalls) to the list + * @param aClass + * @param list + * @return number of methods added + */ + public static int addMethods(Class aClass, List list) { + Method[] methods = aClass.getMethods(); + for (Method m : methods) { + list.add(m); + } + return methods.length; + } + + /** + * Adds all static methods (from Class.getMethodCalls) to the list + * @param aClass + * @param list + * @return number of methods added + */ + public static int addStaticMethods(Class aClass, List list) { + Method[] methods = aClass.getMethods(); + for (Method m : methods) { + if (Modifier.isStatic(m.getModifiers())) { + list.add(m); + } + } + return methods.length; + } + + /** + * Adds all static Fields (from Class.getFields) to the list + * @param aClass + * @param list + * @return number of fields added + */ + public static int addStaticFields(Class aClass, List list) { + Field[] fields = aClass.getFields(); + for (Field f : fields) { + if (Modifier.isStatic(f.getModifiers())) { + list.add(f); + } + } + return fields.length; + } + + /** + * Adds all Fields (from Class.getFields) to the list + * @param aClass + * @param list + * @return number of fields added + */ + public static int addFields(Class aClass, List list) { + Field[] fields = aClass.getFields(); + for (Field f : fields) { + list.add(f); + } + return fields.length; + } + + /** + * Adds all Constructor (from Class.getConstructorCalls) to the list + * @param aClass + * @param list + * @return number of constructors added + */ + public static int addConstrcutors(Class aClass, List list) { + Constructor[] constructors = aClass.getConstructors(); + for (Constructor c : constructors) { + list.add(c); + } + return constructors.length; + } + + /** + * Convert the constructor to a Java Code String + * (arguments are replaced by the simple types) + * @param c Constructor + * @return + */ + public static String getJavaCallString(Constructor c) { + StringBuilder call = new StringBuilder(); + call.append(c.getDeclaringClass().getSimpleName()); + addParamsString(call, c.getParameterTypes()); + return call.toString(); + } + + /** + * Convert the Method to a Java Code String + * (arguments are replaced by the simple types) + * @param method Method + * @return + */ + public static String getJavaCallString(Method method) { + StringBuilder call = new StringBuilder(); + call.append(method.getName()); + addParamsString(call, method.getParameterTypes()); + return call.toString(); + } + + /** + * Adds the class SimpleNames, comma sepearated and surrounded by paranthesis to the + * call StringBuffer + * @param call + * @param params + * @return + */ + public static StringBuilder addParamsString(StringBuilder call, Class[] params) { + call.append("("); + boolean firstArg = true; + for (Class arg : params) { + if (firstArg) { + firstArg = false; + } else { + call.append(", "); + } + call.append(arg.getSimpleName()); + } + call.append(")"); + return call; + } + + /** + * Gets a String array of all method calls for the given class + * @param aClass + * @return + */ + public static String[] getMethodCalls(Class aClass) { + String[] methods = new String[aClass.getMethods().length]; + int i = 0; + for (Method method : aClass.getMethods()) { + methods[i++] = getJavaCallString(method); + } + return methods; + } + + /** + * Gets an array of all Constructor calls for the given class + * @param aClass + * @return + */ + public static String[] getConstructorCalls(Class aClass) { + Constructor[] constructors = aClass.getConstructors(); + String[] cons = new String[constructors.length]; + int i = 0; + for (Constructor c : constructors) { + cons[i++] = getJavaCallString(c); + } + return cons; + } + + /** + * Return a paranthesis enclosed, comma sepearated String of all + * SimpleClass names in params. + * @param params + * @return + */ + public static String getParamsString(Class[] params) { + StringBuilder sb = new StringBuilder(); + addParamsString(sb, params); + return sb.toString(); + } + + /** + * Scans all classes accessible from the context class loader which belong to the given package and subpackages. + * + * @param packageName The base package + * @return The classes + * @throws ClassNotFoundException + * @throws IOException + */ + private static Class[] getClasses(String packageName) + throws ClassNotFoundException, IOException { +// ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); + ClassLoader classLoader = ClassLoader.getSystemClassLoader(); + assert classLoader != null; + String path = packageName.replace('.', '/'); + Enumeration resources = classLoader.getResources(path); + List dirs = new ArrayList(); + while (resources.hasMoreElements()) { + URL resource = resources.nextElement(); + dirs.add(new File(resource.getFile())); + } + ArrayList classes = new ArrayList(); + for (File directory : dirs) { + classes.addAll(findClasses(directory, packageName)); + } + return classes.toArray(new Class[classes.size()]); + } + + /** + * Recursive method used to find all classes in a given directory and subdirs. + * + * @param directory The base directory + * @param packageName The package name for classes found inside the base directory + * @return The classes + * @throws ClassNotFoundException + */ + private static List findClasses(File directory, String packageName) throws ClassNotFoundException { + List classes = new ArrayList(); + if (!directory.exists()) { + return classes; + } + File[] files = directory.listFiles(); + for (File file : files) { + if (file.isDirectory()) { + assert !file.getName().contains("."); + classes.addAll(findClasses(file, packageName + "." + file.getName())); + } else if (file.getName().endsWith(".class")) { + classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6))); + } + } + return classes; + } + + /** + * Attempt to find the given className within any of the packages. + * If the class is not found, then null is returned + * @param className Fully or partially qualified classname within any of the packages + * @param packages List of packages for search + * @return CLass object or null if not found. + */ + public static Class findClass(String className, List packages) { + try { + return Class.forName(className); + } catch (ClassNotFoundException ex) { + } catch (NoClassDefFoundError ex) { + } + for (String pack : packages) { + try { + return Class.forName(pack + "." + className); + } catch (ClassNotFoundException ex) { + } catch (NoClassDefFoundError ex) { + } + } + return null; + } + + /** + * Find a setter method for the give object's property and try to call it. + * No exceptions are thrown. You typically call this method because either + * you are sure no exceptions will be thrown, or to silently ignore + * any that may be thrown. + * This will also find a setter that accepts an interface that the value + * implements. + * This is still not very effcient and should only be called if + * performance is not of an issue. + * You can check the return value to see if the call was seuccessful or + * not. + * @param obj Object to receive the call + * @param property property name (without set. First letter will be + * capitalized) + * @param value Value of the property. + * @return + */ + public static boolean callSetter(Object obj, String property, Object value) { + String key = String.format("%s.%s(%s)", obj.getClass().getName(), + property, value.getClass().getName()); + Method m = null; + boolean result = false; + if(!SETTERS_MAP.containsKey(key)) { + m = findMethod(obj, property, value); + SETTERS_MAP.put(key, m); + } else { + m = SETTERS_MAP.get(key); + } + if(m != null) { + try { + m.invoke(obj, value); + result = true; + } catch (IllegalAccessException ex) { + Logger.getLogger(ReflectUtils.class.getName()).log(Level.SEVERE, null, ex); + } catch (IllegalArgumentException ex) { + Logger.getLogger(ReflectUtils.class.getName()).log(Level.SEVERE, null, ex); + } catch (InvocationTargetException ex) { + Logger.getLogger(ReflectUtils.class.getName()).log(Level.SEVERE, null, ex); + } + } + return result; + } + + private static synchronized Method findMethod(Object obj, + String property, Object value) { + Method m = null; + Class theClass = obj.getClass(); + String setter = String.format("set%C%s", + property.charAt(0), property.substring(1)); + Class paramType = value.getClass(); + while (paramType != null) { + try { + m = theClass.getMethod(setter, paramType); + return m; + } catch (NoSuchMethodException ex) { + // try on the interfaces of this class + for (Class iface : paramType.getInterfaces()) { + try { + m = theClass.getMethod(setter, iface); + return m; + } catch (NoSuchMethodException ex1) { + } + } + paramType = paramType.getSuperclass(); + } + } + return m; + } + public static final List DEFAULT_PACKAGES = new ArrayList(3); + + static { + DEFAULT_PACKAGES.add("java.lang"); + DEFAULT_PACKAGES.add("java.util"); + DEFAULT_PACKAGES.add("syntaxpane"); + } + /** + * To speed up find setter methods, this map will be used. + * The Key String will be of the format objectClass.property(valueclass) + * Where: + * objectClass = obj.getClass().getName + * property = property (as passed in to callSetter), before set is appended + * valueCLass = value.getClass().getName() + * The Method will be either the method, or null if a search was not and no + * method is found. + */ + private static HashMap SETTERS_MAP = new HashMap(); +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/util/StringUtils.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/util/StringUtils.java new file mode 100644 index 0000000..1159bb5 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/util/StringUtils.java @@ -0,0 +1,60 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.util; + +import java.io.Serializable; +import java.util.Comparator; + +/** + * Don't we all need one of those? + * + * @author Ayman Al-Sairafi + */ +public class StringUtils { + + /** + * Perfrom a String startsWith match with support for CamelCase. + * @param word full word + * @param abbr abbriviated word + * @return true if the word startsWith abbr, or if any uppercase char in abbr + * matches the next uppercase char in word + * + * FIXME: not so effecient as it creates a StringBuilder, but works + * FIXME: add {@code Comparator} + */ + public static boolean camelCaseMatch(String word, String abbr) { + StringBuilder sb = new StringBuilder(); + sb.append(word.charAt(0)); + for (int i = 1; i < word.length(); i++) { + char c = word.charAt(i); + if (Character.isUpperCase(c)) { + sb.append(c); + } + } + String cc = sb.toString(); + if (cc.startsWith(abbr)) { + return true; + } else { + return word.startsWith(abbr); + } + } + + static class CamelCaseCompare implements Comparator, Serializable { + + @Override + public int compare(String o1, String o2) { + throw new UnsupportedOperationException("Not supported yet."); + } + } +} diff --git a/SyntaxPane/src/main/java/de/sciss/syntaxpane/util/SwingUtils.java b/SyntaxPane/src/main/java/de/sciss/syntaxpane/util/SwingUtils.java new file mode 100644 index 0000000..a951fd2 --- /dev/null +++ b/SyntaxPane/src/main/java/de/sciss/syntaxpane/util/SwingUtils.java @@ -0,0 +1,49 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.util; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.KeyEvent; +import javax.swing.JComponent; +import javax.swing.KeyStroke; +import de.sciss.syntaxpane.actions.gui.EscapeListener; + +/** + * As always, some general purpose handy Swing Utility methods + * @author Ayman Al-Sairafi + */ +public class SwingUtils { + + /** + * FIXME: These two addEscapeListener can be called on a new interface + * that implements RootPainCOntainer (Swing) and a new method that + * is called + * @param dialog + */ + public static void addEscapeListener(final EscapeListener dialog) { + ActionListener escListener = new ActionListener() { + + @Override + public void actionPerformed(ActionEvent e) { + dialog.escapePressed(); + } + }; + + dialog.getRootPane().registerKeyboardAction(escListener, + KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), + JComponent.WHEN_IN_FOCUSED_WINDOW); + + } +} diff --git a/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/bash.flex b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/bash.flex new file mode 100644 index 0000000..97c3cbb --- /dev/null +++ b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/bash.flex @@ -0,0 +1,365 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package de.sciss.syntaxpane.lexers; + + +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +%% + +%public +%class BashLexer +%extends DefaultJFlexLexer +%final +%unicode +%char +%type Token + +%{ + /** + * Create an empty lexer, yyrset will be called later to reset and assign + * the reader + */ + public BashLexer() { + super(); + } + + private static final byte PARAN = 1; + private static final byte BRACKET = 2; + private static final byte CURLY = 3; + private static final byte DO = 4; + private static final byte CASE = 5; + private static final byte IF = 5; + private static final byte INT_EXPR = 6; + + @Override + public int yychar() { + return yychar; + } + +%} + +LineTerminator = \r|\n|\r\n +InputCharacter = [^\r\n] + +Identifier = [a-zA-Z][a-zA-Z0-9_]* + +Comment = "#" {InputCharacter}* {LineTerminator}? +Shebang = "#!" {InputCharacter}* {LineTerminator}? + +StringCharacter = [^\r\n\"\\] +SingleCharacter = [^\r\n\'\\] +BackQuoteChars = [^\r\n\`\\] + + +%% + + +{ + /* Bash keywords */ + "if" { return token(TokenType.KEYWORD, IF); } + "fi" { return token(TokenType.KEYWORD, -IF); } + "do" { return token(TokenType.KEYWORD, DO); } + "done" { return token(TokenType.KEYWORD, -DO); } + "case" { return token(TokenType.KEYWORD, CASE); } + "esac" { return token(TokenType.KEYWORD, -CASE); } + "$((" { return token(TokenType.KEYWORD, INT_EXPR); } + "))" { return token(TokenType.KEYWORD, -INT_EXPR); } + + "(" { return token(TokenType.OPERATOR, PARAN); } + ")" { return token(TokenType.OPERATOR, -PARAN); } + "{" { return token(TokenType.OPERATOR, CURLY); } + "}" { return token(TokenType.OPERATOR, -CURLY); } + "[" { return token(TokenType.OPERATOR, BRACKET); } + "]" { return token(TokenType.OPERATOR, -BRACKET); } + + "-eq" | + "-ne" | + "-lt" | + "-gt" | + "-ge" | + "-le" | + ">=" | + "<=" | + "==" | + "!=" | + "-z" | + "-n" | + "=~" | + + "$" | + "#" | + "&" | + "." | + ";" | + "+" | + "-" | + "=" | + "/" | + "++" | + "@" { return token(TokenType.OPERATOR); } + + "then" | + "else" | + "elif" | + "for" | + "in" | + "until" | + "while" | + "break" | + "local" | + "continue" { return token(TokenType.KEYWORD); } + + /* string literal */ + \"{StringCharacter}+\" | + + \'{SingleCharacter}+\ { return token(TokenType.STRING); } + + \`{BackQuoteChars}+\` { return token(TokenType.STRING2); } + + + /* Other commands */ + "alias" | + "apropos" | + "apt" | + "aspell" | + "awk" | + "bash" | + "basename" | + "bc" | + "bg" | + "builtin" | + "bzip2" | + "cal" | + "cat" | + "cd" | + "cfdisk" | + "chgrp" | + "chmod" | + "chown" | + "chroot" | + "chkconfig" | + "cksum" | + "clear" | + "cmp" | + "comm" | + "command" | + "continue" | + "cp" | + "cron" | + "crontab" | + "csplit" | + "cut" | + "date" | + "dc" | + "dd" | + "ddrescue" | + "declare" | + "df" | + "diff" | + "diff3" | + "dig" | + "dir" | + "dircolors" | + "dirname" | + "dirs" | + "dmesg" | + "du" | + "echo" | + "egrep" | + "eject" | + "enable" | + "env" | + "ethtool" | + "eval" | + "exec" | + "exit" | + "expect" | + "expand" | + "export" | + "expr" | + "false" | + "fdformat" | + "fdisk" | + "fg" | + "fgrep" | + "file" | + "find" | + "fmt" | + "fold" | + "format" | + "free" | + "fsck" | + "ftp" | + "function" | + "gawk" | + "getopts" | + "grep" | + "groups" | + "gzip" | + "hash" | + "head" | + "history" | + "hostname" | + "id" | + "ifconfig" | + "ifdown" | + "ifup" | + "import" | + "install" | + "join" | + "kill" | + "killall" | + "less" | + "let" | + "ln" | + "locate" | + "logname" | + "logout" | + "look" | + "lpc" | + "lpr" | + "lprint" | + "lprintd" | + "lprintq" | + "lprm" | + "ls" | + "lsof" | + "man" | + "mkdir" | + "mkfifo" | + "mkisofs" | + "mknod" | + "more" | + "mount" | + "mtools" | + "mv" | + "mmv" | + "netstat" | + "nice" | + "nl" | + "nohup" | + "nslookup" | + "open" | + "op" | + "passwd" | + "paste" | + "pathchk" | + "ping" | + "popd" | + "pr" | + "printcap" | + "printenv" | + "printf" | + "ps" | + "pushd" | + "pwd" | + "quota" | + "quotacheck" | + "quotactl" | + "ram" | + "rcp" | + "read" | + "readonly" | + "reboot" | + "renice" | + "remsync" | + "return" | + "rev" | + "rm" | + "rmdir" | + "rsync" | + "screen" | + "scp" | + "sdiff" | + "sed" | + "select" | + "seq" | + "set" | + "sftp" | + "shift" | + "shopt" | + "shutdown" | + "sleep" | + "slocate" | + "sort" | + "source" | + "split" | + "ssh" | + "strace" | + "su" | + "sudo" | + "sum" | + "symlink" | + "sync" | + "tail" | + "tar" | + "tee" | + "test" | + "time" | + "times" | + "touch" | + "top" | + "traceroute" | + "trap" | + "tr" | + "true" | + "tsort" | + "tty" | + "type" | + "ulimit" | + "umask" | + "umount" | + "unalias" | + "uname" | + "unexpand" | + "uniq" | + "units" | + "unset" | + "unshar" | + "useradd" | + "usermod" | + "users" | + "uuencode" | + "uudecode" | + "v" | + "vdir" | + "vi" | + "vmstat" | + "watch" | + "wc" | + "whereis" | + "which" | + "who" | + "whoami" | + "Wget" | + "write" | + "xargs" | + "yes" { return token(TokenType.KEYWORD); } + + {Identifier} { return token(TokenType.IDENTIFIER); } + + /* labels */ + ":" [a-zA-Z][a-zA-Z0-9_]* { return token(TokenType.TYPE); } + + /* comments */ + {Shebang} { return token(TokenType.COMMENT2); } + {Comment} { return token(TokenType.COMMENT); } + . | {LineTerminator} { /* skip */ } + +} + +<> { return null; } \ No newline at end of file diff --git a/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/c.flex b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/c.flex new file mode 100644 index 0000000..7e229ed --- /dev/null +++ b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/c.flex @@ -0,0 +1,241 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * Copyright 2006 Arnout Engelen . + * Copyright 2000-2006 Omnicore Software, Hans Kratz & Dennis Strein GbR, + * Geert Bevin . + * Distributed under the terms of either: + * - the common development and distribution license (CDDL), v1.0; or + * - the GNU Lesser General Public License, v2.1 or later + */ +package de.sciss.syntaxpane.lexers; + + +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +%% + +%public +%class CLexer +%extends DefaultJFlexLexer +%final +%unicode +%char +%type Token + + +%{ + + public CLexer() { + super(); + } + + private static final byte PARAN = 1; + private static final byte BRACKET = 2; + private static final byte CURLY = 3; + + @Override + public int yychar() { + return yychar; + } +%} + +/* main character classes */ +LineTerminator = \r|\n|\r\n +InputCharacter = [^\r\n] + +WhiteSpace = {LineTerminator} | [ \t\f]+ + +/* comments */ +Comment = {TraditionalComment} | {EndOfLineComment} + +TraditionalComment = "/*" [^*] ~"*/" | "/*" "*"+ "/" +EndOfLineComment = "//" {InputCharacter}* {LineTerminator}? + +/* identifiers */ + +ConstantIdentifier = {SimpleConstantIdentifier} +SimpleConstantIdentifier = [#A-Z0-9_]+ + +Identifier = [:jletter:][:jletterdigit:]* + +TypeIdentifier = {SimpleTypeIdentifier} +SimpleTypeIdentifier = [A-Z][:jletterdigit:]* + +/* int literals */ + +DecLiteral = 0 | [1-9][0-9]* {IntegerSuffix} + +HexLiteral = 0 [xX] 0* {HexDigit}* {IntegerSuffix} +HexDigit = [0-9a-fA-F] + +OctLiteral = 0+ {OctDigit}* {IntegerSuffix} +OctDigit = [0-7] + +IntegerSuffix = [uU]? [lL]? [uU]? + +/* float literals */ + +FloatLiteral = ({FLit1}|{FLit2}|{FLit3}|{FLit4}) ([fF]|[dD])? + +FLit1 = [0-9]+ \. [0-9]* {Exponent}? +FLit2 = \. [0-9]+ {Exponent}? +FLit3 = [0-9]+ {Exponent} +FLit4 = [0-9]+ {Exponent}? + +Exponent = [eE] [+\-]? [0-9]+ + +%% + + { + + /* keywords */ + "break" | + "case" | + "catch" | + "continue" | + "default" | + "do" | + "else" | + "for" | + "goto" | + "enum" | + "if" | + "inline" | + "mutable" | + "noinline" | + "return" | + "safecast" | + "sealed" | + "selectany" | + "sizeof" | + "static_cast" | + "switch" | + "template" | + "this" | + "thread" | + "throw" | + "try" | + "typedef" | + "typeid" | + "typename" | + "using" | + "uuid" | + "value" | + "virtual" | + "while" + { return token(TokenType.KEYWORD); } + + "static" | + "struct" | + "union" | + "volatile" | + "register" | + "extern" | + "const" | + "signed" | + "unsigned" | + "bool" | + "char" | + "double" | + "int" | + "long" | + "float" | + "short" | + "void" { return token(TokenType.TYPE); } + + /* literals */ + + + (\" ( [^\"\n\\] | \\[^\n] )* (\n | \\\n | \")) | + (\' ( [^\'\n\\] | \\[^\n] )* (\n | \\\n | \')) + { return token(TokenType.STRING); } + + "true" | + "false" | + {DecLiteral} | + {OctLiteral} | + {HexLiteral} | + + {FloatLiteral} + { return token(TokenType.NUMBER); } + + /* preprocessor symbols */ + "#define" | + "#elif" | + "#else" | + "#endif" | + "#error" | + "#ifdef" | + "#ifndef" | + "#if" | + "#import" | + "#include" | + "#line" | + "#pragma" | + "#undef" | + "#using" + { return token(TokenType.KEYWORD2); } + + + /* separators */ + "(" { return token(TokenType.OPERATOR, PARAN); } + ")" { return token(TokenType.OPERATOR, -PARAN); } + "{" { return token(TokenType.OPERATOR, CURLY); } + "}" { return token(TokenType.OPERATOR, -CURLY); } + "[" { return token(TokenType.OPERATOR, BRACKET); } + "]" { return token(TokenType.OPERATOR, -BRACKET); } + + /* operators */ + "=" | + ";" | + "," | + "." | + ">" | + "<" | + "!" | + "~" | + "?" | + ":" | + "+" | + "-" | + "*" | + "/" | + "&" | + "|" | + "^" | + ">>" | + "<<" | + "%" { return token(TokenType.OPERATOR); } + + {ConstantIdentifier} { return token(TokenType.IDENTIFIER); } + + {TypeIdentifier} { return token(TokenType.IDENTIFIER); } + + \n | + {Identifier} | + {WhiteSpace} { return token(TokenType.IDENTIFIER); } + + + + {Comment} { return token(TokenType.COMMENT); } + +} + + + +/* error fallback */ +.|\n { } +<> { return null; } diff --git a/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/clojure.flex b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/clojure.flex new file mode 100644 index 0000000..b280d59 --- /dev/null +++ b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/clojure.flex @@ -0,0 +1,496 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package de.sciss.syntaxpane.lexers; + + +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +%% + +%public +%class ClojureLexer +%extends DefaultJFlexLexer +%final +%unicode +%char +%type Token + + +%{ + /** + * Create an empty lexer, yyrset will be called later to reset and assign + * the reader + */ + public ClojureLexer() { + super(); + } + + @Override + public int yychar() { + return yychar; + } + + private static final byte PARAN = 1; + private static final byte BRACKET = 2; + private static final byte CURLY = 3; + +%} + +/* main character classes */ +LineTerminator = \r|\n|\r\n +InputCharacter = [^\r\n] + +WhiteSpace = {LineTerminator} | [ \t\f]+ + +/* comments */ +Comment = {EndOfLineComment} + +EndOfLineComment = ";" {InputCharacter}* {LineTerminator}? + +/* identifiers */ +Identifier = [:jletter:][:jletterdigit:]* + +/* integer literals */ +DecIntegerLiteral = 0 | [1-9][0-9]* +DecLongLiteral = {DecIntegerLiteral} [lL] + +HexIntegerLiteral = 0 [xX] 0* {HexDigit} {1,8} +HexLongLiteral = 0 [xX] 0* {HexDigit} {1,16} [lL] +HexDigit = [0-9a-fA-F] + +OctIntegerLiteral = 0+ [1-3]? {OctDigit} {1,15} +OctLongLiteral = 0+ 1? {OctDigit} {1,21} [lL] +OctDigit = [0-7] + +/* floating point literals */ +FloatLiteral = ({FLit1}|{FLit2}|{FLit3}) {Exponent}? [fF] +DoubleLiteral = ({FLit1}|{FLit2}|{FLit3}) {Exponent}? + +FLit1 = [0-9]+ \. [0-9]* +FLit2 = \. [0-9]+ +FLit3 = [0-9]+ +Exponent = [eE] [+-]? [0-9]+ + +/* string and character literals */ +StringCharacter = [^\r\n\"\\] +SingleCharacter = [^\r\n\'\\] + +%state STRING, CHARLITERAL + +%% + + { + + /* keywords */ + "fn" | + "fn*" | + "if" | + "def" | + "let" | + "let*" | + "loop*" | + "new" | + "nil" | + "recur" | + "loop" | + "do" | + "quote" | + "the-var" | + "identical?" | + "throw" | + "set!" | + "monitor-enter" | + "monitor-exit" | + "try" | + "catch" | + "finally" | + "in-ns" { return token(TokenType.KEYWORD); } + + /* Built-ins */ + "*agent*" | + "*command-line-args*" | + "*in*" | + "*macro-meta*" | + "*ns*" | + "*out*" | + "*print-meta*" | + "*print-readably*" | + "*proxy-classes*" | + "*warn-on-reflection*" | + "+" | + "-" | + "->" | + ".." | + "/" | + "<" | + "<=" | + "=" | + "==" | + ">" | + ">=" | + "accessor" | + "agent" | + "agent-errors" | + "aget" | + "alength" | + "all-ns" | + "alter" | + "and" | + "apply" | + "array-map" | + "aset" | + "aset-boolean" | + "aset-byte" | + "aset-char" | + "aset-double" | + "aset-float" | + "aset-int" | + "aset-long" | + "aset-short" | + "assert" | + "assoc" | + "await" | + "await-for" | + "bean" | + "binding" | + "bit-and" | + "bit-not" | + "bit-or" | + "bit-shift-left" | + "bit-shift-right" | + "bit-xor" | + "boolean" | + "butlast" | + "byte" | + "cast" | + "char" | + "class" | + "clear-agent-errors" | + "comment" | + "commute" | + "comp" | + "comparator" | + "complement" | + "concat" | + "cond" | + "conj" | + "cons" | + "constantly" | + "construct-proxy" | + "contains?" | + "count" | + "create-ns" | + "create-struct" | + "cycle" | + "dec" | + "defmacro" | + "defmethod" | + "defmulti" | + "defn" | + "defn-" | + "defstruct" | + "deref" | + "destructure" | + "disj" | + "dissoc" | + "distinct" | + "doall" | + "doc" | + "dorun" | + "doseq" | + "dosync" | + "dotimes" | + "doto" | + "double" | + "drop" | + "drop-while" | + "ensure" | + "eval" | + "every?" | + "false?" | + "ffirst" | + "file-seq" | + "filter" | + "find" | + "find-doc" | + "find-ns" | + "find-var" | + "first" | + "float" | + "flush" | + "fnseq" | + "for" | + "frest" | + "gensym" | + "gen-class" | + "gen-interface" | + "get" | + "get-proxy-class" | + "hash-map" | + "hash-set" | + "identity" | + "if-let" | + "import" | + "inc" | + "instance?" | + "int" | + "interleave" | + "into" | + "into-array" | + "iterate" | + "key" | + "keys" | + "keyword" | + "keyword?" | + "last" | + "lazy-cat" | + "lazy-cons" | + "line-seq" | + "list" | + "list*" | + "load" | + "load-file" | + "locking" | + "long" | + "macroexpand" | + "macroexpand-1" | + "make-array" | + "map" | + "map?" | + "mapcat" | + "max" | + "max-key" | + "memfn" | + "merge" | + "merge-with" | + "meta" | + "min" | + "min-key" | + "name" | + "namespace" | + "neg?" | + "newline" | + "nil?" | + "not" | + "not-any?" | + "not-every?" | + "not=" | + "ns-imports" | + "ns-interns" | + "ns-map" | + "ns-name" | + "ns-publics" | + "ns-refers" | + "ns-resolve" | + "ns-unmap" | + "nth" | + "nthrest" | + "or" | + "partial" | + "peek" | + "pmap" | + "pop" | + "pos?" | + "pr" | + "pr-str" | + "print" | + "print-doc" | + "print-str" | + "println" | + "println-str" | + "prn" | + "prn-str" | + "proxy" | + "proxy-mappings" | + "quot" | + "rand" | + "rand-int" | + "range" | + "re-find" | + "re-groups" | + "re-matcher" | + "re-matches" | + "re-pattern" | + "re-seq" | + "read" | + "read-line" | + "reduce" | + "ref" | + "ref-set" | + "refer" | + "rem" | + "remove-method" | + "remove-ns" | + "repeat" | + "replace" | + "replicate" | + "require" | + "resolve" | + "rest" | + "resultset-seq" | + "reverse" | + "rfirst" | + "rrest" | + "rseq" | + "scan" | + "second" | + "select-keys" | + "send" | + "send-off" | + "seq" | + "seq?" | + "set" | + "short" | + "slurp" | + "some" | + "sort" | + "sort-by" | + "sorted-map" | + "sorted-map-by" | + "sorted-set" | + "special-symbol?" | + "split-at" | + "split-with" | + "str" | + "string?" | + "struct" | + "struct-map" | + "subs" | + "subvec" | + "symbol" | + "symbol?" | + "sync" | + "take" | + "take-nth" | + "take-while" | + "test" | + "time" | + "to-array" | + "to-array-2d" | + "touch" | + "tree-seq" | + "true?" | + "update-proxy" | + "val" | + "vals" | + "var-get" | + "var-set" | + "var?" | + "vector" | + "vector?" | + "when" | + "when-first" | + "when-let" | + "when-not" | + "while" | + "with-local-vars" | + "with-meta" | + "with-open" | + "with-out-str" | + "xml-seq" | + "zero?" | + "zipmap" | + "repeatedly" | + "add-classpath" | + "vec" | + "hash" { return token(TokenType.KEYWORD2); } + + + /* operators */ + + "(" { return token(TokenType.OPERATOR, PARAN); } + ")" { return token(TokenType.OPERATOR, -PARAN); } + "{" { return token(TokenType.OPERATOR, CURLY); } + "}" { return token(TokenType.OPERATOR, -CURLY); } + "[" { return token(TokenType.OPERATOR, BRACKET); } + "]" { return token(TokenType.OPERATOR, -BRACKET); } + + /* string literal */ + \" { + yybegin(STRING); + tokenStart = yychar; + tokenLength = 1; + } + + /* character literal */ + \' { + yybegin(CHARLITERAL); + tokenStart = yychar; + tokenLength = 1; + } + + /* numeric literals */ + + {DecIntegerLiteral} | + {DecLongLiteral} | + + {HexIntegerLiteral} | + {HexLongLiteral} | + + {OctIntegerLiteral} | + {OctLongLiteral} | + + {FloatLiteral} | + {DoubleLiteral} | + {DoubleLiteral}[dD] { return token(TokenType.NUMBER); } + + /* comments */ + {Comment} { return token(TokenType.COMMENT); } + + /* whitespace */ + {WhiteSpace} { } + + /* identifiers */ + {Identifier} { return token(TokenType.IDENTIFIER); } +} + + + { + \" { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } + + {StringCharacter}+ { tokenLength += yylength(); } + + \\[0-3]?{OctDigit}?{OctDigit} { tokenLength += yylength(); } + + /* escape sequences */ + + \\. { tokenLength += 2; } + {LineTerminator} { yybegin(YYINITIAL); } +} + + { + \' { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } + + {SingleCharacter}+ { tokenLength += yylength(); } + + /* escape sequences */ + + \\. { tokenLength += 2; } + {LineTerminator} { yybegin(YYINITIAL); } +} + +/* error fallback */ +.|\n { } +<> { return null; } + diff --git a/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/cpp.flex b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/cpp.flex new file mode 100644 index 0000000..610e84e --- /dev/null +++ b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/cpp.flex @@ -0,0 +1,274 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * Copyright 2006 Arnout Engelen . + * Copyright 2000-2006 Omnicore Software, Hans Kratz & Dennis Strein GbR, + * Geert Bevin . + * Distributed under the terms of either: + * - the common development and distribution license (CDDL), v1.0; or + * - the GNU Lesser General Public License, v2.1 or later + */ +package de.sciss.syntaxpane.lexers; + + +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +%% + +%public +%class CppLexer +%extends DefaultJFlexLexer +%final +%unicode +%char +%type Token + + +%{ + + public CppLexer() { + super(); + } + + @Override + public int yychar() { + return yychar; + } + + private static final byte PARAN = 1; + private static final byte BRACKET = 2; + private static final byte CURLY = 3; + +%} + +/* main character classes */ +LineTerminator = \r|\n|\r\n +InputCharacter = [^\r\n] + +/* comments */ +Comment = {TraditionalComment} | {EndOfLineComment} + +TraditionalComment = "/*" [^*] ~"*/" | "/*" "*"+ "/" +EndOfLineComment = "//" {InputCharacter}* {LineTerminator}? + +/* identifiers */ + +ConstantIdentifier = {SimpleConstantIdentifier} +SimpleConstantIdentifier = [#A-Z0-9_]+ + +Identifier = [:jletter:][:jletterdigit:]* + +/* int literals */ + +DecLiteral = 0 | [1-9][0-9]* {IntegerSuffix} + +HexLiteral = 0 [xX] 0* {HexDigit}* {IntegerSuffix} +HexDigit = [0-9a-fA-F] + +OctLiteral = 0+ {OctDigit}* {IntegerSuffix} +OctDigit = [0-7] + +IntegerSuffix = [uU]? [lL]? [uU]? + +/* float literals */ + +FloatLiteral = ({FLit1}|{FLit2}|{FLit3}|{FLit4}) ([fF]|[dD])? + +FLit1 = [0-9]+ \. [0-9]* {Exponent}? +FLit2 = \. [0-9]+ {Exponent}? +FLit3 = [0-9]+ {Exponent} +FLit4 = [0-9]+ {Exponent}? + +Exponent = [eE] [+\-]? [0-9]+ + +%% + + { + + /* keywords */ + "break" | + "case" | + "catch" | + "continue" | + "default" | + "do" | + "else" | + "for" | + "goto" | + "enum" | + "if" | + "inline" | + "mutable" | + "noinline" | + "return" | + "safecast" | + "sealed" | + "selectany" | + "sizeof" | + "static_cast" | + "switch" | + "template" | + "this" | + "thread" | + "throw" | + "try" | + "typedef" | + "typeid" | + "typename" | + "using" | + "uuid" | + "value" | + "virtual" | + "while" | + /* C++ Keywords */ + "new" | + "delete" | + "this" | + "friend" | + "using" | + "throw" | + "try" | + "catch" | + "class" | + "typename" | + "template" | + "namespace" + { return token(TokenType.KEYWORD); } + + "static" | + "struct" | + "union" | + "volatile" | + "register" | + "extern" | + "const" | + "signed" | + "unsigned" | + "bool" | + "char" | + "double" | + "int" | + "long" | + "float" | + "short" | + "void" | + + "public" | + "protected" | + "private" | + "virtual" | + "inline" | + "virtual" | + "explicit" | + "export" | + "bool" | + "wchar_t" + { return token(TokenType.TYPE); } + + /* literals */ + + + (\" ( [^\"\n\\] | \\[^\n] )* (\n | \\\n | \")) | + (\' ( [^\'\n\\] | \\[^\n] )* (\n | \\\n | \')) + { return token(TokenType.STRING); } + + "true" | + "false" | + {DecLiteral} | + {OctLiteral} | + {HexLiteral} | + + {FloatLiteral} + { return token(TokenType.NUMBER); } + + /* preprocessor symbols */ + "#define" | + "#elif" | + "#else" | + "#endif" | + "#error" | + "#ifdef" | + "#ifndef" | + "#if" | + "#import" | + "#include" | + "#line" | + "#pragma" | + "#undef" | + "#using" + { return token(TokenType.KEYWORD2); } + + + /* separators */ + "(" { return token(TokenType.OPERATOR, PARAN); } + ")" { return token(TokenType.OPERATOR, -PARAN); } + "{" { return token(TokenType.OPERATOR, CURLY); } + "}" { return token(TokenType.OPERATOR, -CURLY); } + "[" { return token(TokenType.OPERATOR, BRACKET); } + "]" { return token(TokenType.OPERATOR, -BRACKET); } + + /* operators */ + "=" | + ";" | + "," | + "." | + ">" | + "<" | + "!" | + "~" | + "?" | + ":" | + "+" | + "-" | + "*" | + "/" | + "&" | + "|" | + "^" | + "%" | + ">>" | + "<<" | + "operator" | + "typeid" | + "and" | + "bitor" | + "or" | + "xor" | + "compl" | + "bitand" | + "and_eq" | + "or_eq" | + "xor_eq" | + "not" | + "not_eq" + { return token(TokenType.OPERATOR); } + + /** C++ standard and built-in objects */ + "cin" | + "cout" + { return token(TokenType.TYPE2); } + + {ConstantIdentifier} { return token(TokenType.TYPE); } + + {Identifier} { return token(TokenType.IDENTIFIER); } + + {Comment} { return token(TokenType.COMMENT); } +} + + + +/* error fallback */ +.|\n { } +<> { return null; } diff --git a/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/dosbatch.flex b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/dosbatch.flex new file mode 100644 index 0000000..088803d --- /dev/null +++ b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/dosbatch.flex @@ -0,0 +1,170 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package de.sciss.syntaxpane.lexers; + + +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +%% + +%public +%class DOSBatchLexer +%extends DefaultJFlexLexer +%final +%unicode +%char +%type Token +%ignorecase +%state ECHO_TEXT + +%{ + /** + * Create an empty lexer, yyrset will be called later to reset and assign + * the reader + */ + public DOSBatchLexer() { + super(); + } + + @Override + public int yychar() { + return yychar; + } +%} + +StartComment = "rem" +LineTerminator = \r|\n|\r\n +InputCharacter = [^\r\n] + +Comment = {StartComment} {InputCharacter}* {LineTerminator}? + +%% + + { + /* DOS keywords */ + "@" | + "goto" | + "call" | + "exit" | + "if" | + "else" | + "for" | + "copy" | + "set" | + "dir" | + "cd" | + "set" | + "errorlevel" { return token(TokenType.KEYWORD); } + + "%" [:jletter:] [:jletterdigit:]* "%" { return token(TokenType.STRING2); } + + "%" [:digit:]+ { return token(TokenType.KEYWORD2); } + + "echo" { + yybegin(ECHO_TEXT); + return token(TokenType.KEYWORD); + } + + /* DOS commands */ + "append" | + "assoc" | + "at" | + "attrib" | + "break" | + "cacls" | + "cd" | + "chcp" | + "chdir" | + "chkdsk" | + "chkntfs" | + "cls" | + "cmd" | + "color" | + "comp" | + "compact" | + "convert" | + "copy" | + "date" | + "del" | + "dir" | + "diskcomp" | + "diskcopy" | + "doskey" | + "exist" | + "endlocal" | + "erase" | + "fc" | + "find" | + "findstr" | + "format" | + "ftype" | + "graftabl" | + "help" | + "keyb" | + "label" | + "md" | + "mkdir" | + "mode" | + "more" | + "move" | + "path" | + "pause" | + "popd" | + "print" | + "prompt" | + "pushd" | + "rd" | + "recover" | + "rem" | + "ren" | + "rename" | + "replace" | + "restore" | + "rmdir" | + "set" | + "setlocal" | + "shift" | + "sort" | + "start" | + "subst" | + "time" | + "title" | + "tree" | + "type" | + "ver" | + "verify" | + "vol" | + "xcopy" { return token(TokenType.KEYWORD); } + + [:jletterdigit:]+ { return token(TokenType.IDENTIFIER); } + + /* labels */ + ":" [a-zA-Z][a-zA-Z0-9_]* { return token(TokenType.TYPE3); } + + /* comments */ + {Comment} { return token(TokenType.COMMENT); } + . | {LineTerminator} { /* skip */ } +} + + { + "%" [:jletter:] [:jletterdigit:]* "%" { return token(TokenType.STRING2); } + + "%" [:digit:]+ { return token(TokenType.KEYWORD2); } + + . * { return token(TokenType.STRING); } + {LineTerminator} { yybegin(YYINITIAL) ; } +} +<> { return null; } \ No newline at end of file diff --git a/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/groovy.flex b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/groovy.flex new file mode 100644 index 0000000..27c396d --- /dev/null +++ b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/groovy.flex @@ -0,0 +1,491 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package de.sciss.syntaxpane.lexers; + + +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +%% + +%public +%class GroovyLexer +%extends DefaultJFlexLexer +%final +%unicode +%char +%type Token + + +%{ + /** + * Default constructor is needed as we will always call the yyreset + */ + public GroovyLexer() { + super(); + } + + @Override + public int yychar() { + return yychar; + } + + private static final byte PARAN = 1; + private static final byte BRACKET = 2; + private static final byte CURLY = 3; +%} + +/* main character classes */ +LineTerminator = \r|\n|\r\n +InputCharacter = [^\r\n] + +WhiteSpace = {LineTerminator} | [ \t\f] + +/* comments */ +Comment = {TraditionalComment} | {EndOfLineComment} + +TraditionalComment = "/*" [^*] ~"*/" | "/*" "*"+ "/" +EndOfLineComment = "//" {InputCharacter}* {LineTerminator}? + +/* identifiers */ +Identifier = [:jletter:][:jletterdigit:]* + +/* Groovy and generally Java types have first UpperCase Letter */ +// Type = [:uppercase:][:jletterdigit:]* + +/* integer literals */ +DecIntegerLiteral = 0 | [1-9][0-9]* +DecLongLiteral = {DecIntegerLiteral} [lL] + +HexIntegerLiteral = 0 [xX] 0* {HexDigit} {1,8} +HexLongLiteral = 0 [xX] 0* {HexDigit} {1,16} [lL] +HexDigit = [0-9a-fA-F] + +OctIntegerLiteral = 0+ [1-3]? {OctDigit} {1,15} +OctLongLiteral = 0+ 1? {OctDigit} {1,21} [lL] +OctDigit = [0-7] + +/* floating point literals */ +FloatLiteral = ({FLit1}|{FLit2}|{FLit3}) {Exponent}? [fF] +DoubleLiteral = ({FLit1}|{FLit2}|{FLit3}) {Exponent}? + +FLit1 = [0-9]+ \. [0-9]* +FLit2 = \. [0-9]+ +FLit3 = [0-9]+ +Exponent = [eE] [+-]? [0-9]+ + +/* string and character literals */ +StringCharacter = [^\r\n\"\\\$] +SingleCharacter = [^\r\n\'\\] +RegexCharacter = [^\r\n\/] + +%state STRING, CHARLITERAL, REGEX, GSTRING_EXPR, CHARLITERAL, JDOC, JDOC_TAG +%state ML_STRING, ML_STRING_EXPR + +%% + + { + + /* keywords */ + "abstract" | + "boolean" | + "break" | + "byte" | + "case" | + "catch" | + "char" | + "class" | + "const" | + "continue" | + "do" | + "double" | + "enum" | + "else" | + "extends" | + "final" | + "finally" | + "float" | + "for" | + "default" | + "implements" | + "import" | + "instanceof" | + "int" | + "interface" | + "long" | + "native" | + "new" | + "goto" | + "if" | + "public" | + "short" | + "super" | + "switch" | + "synchronized" | + "package" | + "private" | + "protected" | + "transient" | + "return" | + "void" | + "static" | + "while" | + "this" | + "throw" | + "throws" | + "try" | + "volatile" | + "strictfp" | + + /* Groovy reserved words not in Java */ + "as" | + "asssert" | + "def" | + "in" | + "threadsafe" | + + /* Booleans and null */ + "true" | + "false" | + "null" { return token(TokenType.KEYWORD); } + + + /* Builtin Types and Object Wrappers */ + "Boolean" | + "Byte" | + "Character" | + "Double" | + "Float" | + "Integer" | + "Object" | + "Short" | + "String" | + "Void" | + "Class" | + "Number" | + "Package" | + "StringBuffer" | + "StringBuilder" | + "CharSequence" | + "Thread" | + "Regex" { return token(TokenType.TYPE); } + + /* Some Java standard Library Types */ + "Throwable" | + "Cloneable" | + "Comparable" | + "Serializable" | + "Runnable" { return token(TokenType.TYPE); } + + /* Groovy commonly used methods */ + "print" | + "println" { return token(TokenType.KEYWORD); } + + /* Frequently used Standard Exceptions */ + "ArithmeticException" | + "ArrayIndexOutOfBoundsException" | + "ClassCastException" | + "ClassNotFoundException" | + "CloneNotSupportedException" | + "Exception" | + "IllegalAccessException" | + "IllegalArgumentException" | + "IllegalStateException" | + "IllegalThreadStateException" | + "IndexOutOfBoundsException" | + "InstantiationException" | + "InterruptedException" | + "NegativeArraySizeException" | + "NoSuchFieldException" | + "NoSuchMethodException" | + "NullPointerException" | + "NumberFormatException" | + "RuntimeException" | + "SecurityException" | + "StringIndexOutOfBoundsException" | + "UnsupportedOperationException" { return token(TokenType.TYPE2); } + + /* operators */ + "(" { return token(TokenType.OPERATOR, PARAN); } + ")" { return token(TokenType.OPERATOR, -PARAN); } + "{" { return token(TokenType.OPERATOR, CURLY); } + "}" { return token(TokenType.OPERATOR, -CURLY); } + "[" { return token(TokenType.OPERATOR, BRACKET); } + "]" { return token(TokenType.OPERATOR, -BRACKET); } + + ";" | + "," | + "." | + "@" | + "=" | + ">" | + "<" | + "!" | + "~" | + "?" | + ":" | + "==" | + "<=" | + ">=" | + "!=" | + "&&" | + "||" | + "++" | + "--" | + "+" | + "-" | + "*" | + "/" | + "&" | + "|" | + "^" | + "%" | + "<<" | + ">>" | + ">>>" | + "+=" | + "-=" | + "*=" | + "/=" | + "&=" | + "|=" | + "^=" | + "%=" | + "<<=" | + ">>=" | + ">>>=" { return token(TokenType.OPERATOR); } + + "~=" | + "?." { return token(TokenType.OPERATOR); } + + /* string literal */ + \"{3} { + yybegin(ML_STRING); + tokenStart = yychar; + tokenLength = 3; + } + + /* string literal */ + \" { + yybegin(STRING); + tokenStart = yychar; + tokenLength = 1; + } + + /* character literal */ + \' { + yybegin(CHARLITERAL); + tokenStart = yychar; + tokenLength = 1; + } + + /* numeric literals */ + + {DecIntegerLiteral} | + {DecLongLiteral} | + + {HexIntegerLiteral} | + {HexLongLiteral} | + + {OctIntegerLiteral} | + {OctLongLiteral} | + + {FloatLiteral} | + {DoubleLiteral} | + {DoubleLiteral}[dD] { return token(TokenType.NUMBER); } + + // JavaDoc comments need a state so that we can highlight the @ controls + "/**" { + yybegin(JDOC); + tokenStart = yychar; + tokenLength = 3; + } + + /* comments */ + {Comment} { return token(TokenType.COMMENT); } + + /* whitespace */ + {WhiteSpace}+ { /* skip */ } + + /* identifiers */ + {Identifier} { return token(TokenType.IDENTIFIER); } + + /* + Groovy Regex -- state cannot be easily used here due to / by itself being + a valid operator. So if we flip into the REGEX state, we cannot distinguish + a regular / + */ + "/" [^*] {RegexCharacter}+ "/" { return token(TokenType.REGEX); } + +} + + + { + + \" { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } + + "${" { + yybegin(GSTRING_EXPR); + // length also includes the trailing quote + int s = tokenStart; + int l = tokenLength; + tokenStart = yychar; + tokenLength = 2; + return token(TokenType.STRING, s, l); + } + + {StringCharacter}+ { tokenLength += yylength(); } + + \\[0-3]?{OctDigit}?{OctDigit} { tokenLength += yylength(); } + + /* escape sequences */ + + + \\. { tokenLength += 2; } + {LineTerminator} { yybegin(YYINITIAL); } + +} + + { + "}" { + yybegin(STRING); + // length also includes the trailing quote + int s = tokenStart; + int l = tokenLength + 1; + tokenStart = yychar + 1; + tokenLength = 0; + return token(TokenType.STRING2, s, l); + } + + {StringCharacter} { tokenLength ++; } +} + + { + + \"{3} { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 3); + } + + "${" { + yybegin(ML_STRING_EXPR); + // length also includes the trailing quote + int s = tokenStart; + int l = tokenLength; + tokenStart = yychar; + tokenLength = 2; + return token(TokenType.STRING, s, l); + } + + \\[0-3]?{OctDigit}?{OctDigit} { tokenLength += yylength(); } + + /* escape sequences */ + + \\. { tokenLength += 2; } + .|{LineTerminator} { tokenLength += yylength(); } + +} + + { + "}" { + yybegin(ML_STRING); + // length also includes the trailing quote + int s = tokenStart; + int l = tokenLength + 1; + tokenStart = yychar + 1; + tokenLength = 0; + return token(TokenType.STRING2, s, l); + } + + .|\n|\r { tokenLength ++; } +} + + { + \' { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } + + {SingleCharacter}+ { tokenLength += yylength(); } + + /* escape sequences */ + + \\. { tokenLength += 2; } + {LineTerminator} { yybegin(YYINITIAL); } +} + + { + "*/" { + yybegin(YYINITIAL); + return token(TokenType.COMMENT, tokenStart, tokenLength + 2); + } + + "@" { + yybegin(JDOC_TAG); + int start = tokenStart; + tokenStart = yychar; + int len = tokenLength; + tokenLength = 1; + return token(TokenType.COMMENT, start, len); + } + + .|\n { tokenLength ++; } + +} + + { + ([:letter:])+ ":"? { tokenLength += yylength(); } + + "*/" { + yybegin(YYINITIAL); + return token(TokenType.COMMENT, tokenStart, tokenLength + 2); + } + + .|\n { + yybegin(JDOC); + // length also includes the trailing quote + int start = tokenStart; + tokenStart = yychar; + int len = tokenLength; + tokenLength = 1; + return token(TokenType.COMMENT2, start, len); + } +} + + { + "/" { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.REGEX, tokenStart, tokenLength + 1); + } + + {RegexCharacter}+ { tokenLength += yylength(); } + + /* escape sequences */ + + \\. { tokenLength += 2; } + {LineTerminator} { yybegin(YYINITIAL); } +} + +/* error fallback */ +.|\n { } +<> { return null; } + diff --git a/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/java.flex b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/java.flex new file mode 100644 index 0000000..054860e --- /dev/null +++ b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/java.flex @@ -0,0 +1,376 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package de.sciss.syntaxpane.lexers; + + +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +%% + +%public +%class JavaLexer +%extends DefaultJFlexLexer +%final +%unicode +%char +%type Token + + +%{ + /** + * Create an empty lexer, yyrset will be called later to reset and assign + * the reader + */ + public JavaLexer() { + super(); + } + + @Override + public int yychar() { + return yychar; + } + + private static final byte PARAN = 1; + private static final byte BRACKET = 2; + private static final byte CURLY = 3; + +%} + +/* main character classes */ +LineTerminator = \r|\n|\r\n +InputCharacter = [^\r\n] + +WhiteSpace = {LineTerminator} | [ \t\f]+ + +/* comments */ +Comment = {TraditionalComment} | {EndOfLineComment} + +TraditionalComment = "/*" [^*] ~"*/" | "/*" "*"+ "/" +EndOfLineComment = "//" {InputCharacter}* {LineTerminator}? + +/* identifiers */ +Identifier = [:jletter:][:jletterdigit:]* + +/* integer literals */ +DecIntegerLiteral = 0 | [1-9][0-9]* +DecLongLiteral = {DecIntegerLiteral} [lL] + +HexIntegerLiteral = 0 [xX] 0* {HexDigit} {1,8} +HexLongLiteral = 0 [xX] 0* {HexDigit} {1,16} [lL] +HexDigit = [0-9a-fA-F] + +OctIntegerLiteral = 0+ [1-3]? {OctDigit} {1,15} +OctLongLiteral = 0+ 1? {OctDigit} {1,21} [lL] +OctDigit = [0-7] + +/* floating point literals */ +FloatLiteral = ({FLit1}|{FLit2}|{FLit3}) {Exponent}? [fF] +DoubleLiteral = ({FLit1}|{FLit2}|{FLit3}) {Exponent}? + +FLit1 = [0-9]+ \. [0-9]* +FLit2 = \. [0-9]+ +FLit3 = [0-9]+ +Exponent = [eE] [+-]? [0-9]+ + +/* string and character literals */ +StringCharacter = [^\r\n\"\\] +SingleCharacter = [^\r\n\'\\] + +%state STRING, CHARLITERAL, JDOC, JDOC_TAG + +%% + + { + + /* keywords */ + "abstract" | + "boolean" | + "break" | + "byte" | + "case" | + "catch" | + "char" | + "class" | + "const" | + "continue" | + "do" | + "double" | + "enum" | + "else" | + "extends" | + "final" | + "finally" | + "float" | + "for" | + "default" | + "implements" | + "import" | + "instanceof" | + "int" | + "interface" | + "long" | + "native" | + "new" | + "goto" | + "if" | + "public" | + "short" | + "super" | + "switch" | + "synchronized" | + "package" | + "private" | + "protected" | + "transient" | + "return" | + "void" | + "static" | + "while" | + "this" | + "throw" | + "throws" | + "try" | + "volatile" | + "strictfp" | + + "true" | + "false" | + "null" { return token(TokenType.KEYWORD); } + + /* Java Built in types and wrappers */ + "Boolean" | + "Byte" | + "Character" | + "Double" | + "Float" | + "Integer" | + "Object" | + "Short" | + "Void" | + "Class" | + "Number" | + "Package" | + "StringBuffer" | + "StringBuilder" | + "CharSequence" | + "Thread" | + "String" { return token(TokenType.TYPE); } + + /* Some Java standard Library Types */ + "Throwable" | + "Cloneable" | + "Comparable" | + "Serializable" | + "Runnable" { return token(TokenType.TYPE); } + + "WARNING" { return token(TokenType.WARNING); } + "ERROR" { return token(TokenType.ERROR); } + + /* Frequently used Standard Exceptions */ + "ArithmeticException" | + "ArrayIndexOutOfBoundsException" | + "ClassCastException" | + "ClassNotFoundException" | + "CloneNotSupportedException" | + "Exception" | + "IllegalAccessException" | + "IllegalArgumentException" | + "IllegalStateException" | + "IllegalThreadStateException" | + "IndexOutOfBoundsException" | + "InstantiationException" | + "InterruptedException" | + "NegativeArraySizeException" | + "NoSuchFieldException" | + "NoSuchMethodException" | + "NullPointerException" | + "NumberFormatException" | + "RuntimeException" | + "SecurityException" | + "StringIndexOutOfBoundsException" | + "UnsupportedOperationException" { return token(TokenType.TYPE2); } + + /* operators */ + + "(" { return token(TokenType.OPERATOR, PARAN); } + ")" { return token(TokenType.OPERATOR, -PARAN); } + "{" { return token(TokenType.OPERATOR, CURLY); } + "}" { return token(TokenType.OPERATOR, -CURLY); } + "[" { return token(TokenType.OPERATOR, BRACKET); } + "]" { return token(TokenType.OPERATOR, -BRACKET); } + ";" | + "," | + "." | + "=" | + ">" | + "<" | + "!" | + "~" | + "?" | + ":" | + "==" | + "<=" | + ">=" | + "!=" | + "&&" | + "||" | + "++" | + "--" | + "+" | + "-" | + "*" | + "/" | + "&" | + "|" | + "^" | + "%" | + "<<" | + ">>" | + ">>>" | + "+=" | + "-=" | + "*=" | + "/=" | + "&=" | + "|=" | + "^=" | + "%=" | + "<<=" | + ">>=" | + ">>>=" { return token(TokenType.OPERATOR); } + + /* string literal */ + \" { + yybegin(STRING); + tokenStart = yychar; + tokenLength = 1; + } + + /* character literal */ + \' { + yybegin(CHARLITERAL); + tokenStart = yychar; + tokenLength = 1; + } + + /* numeric literals */ + + {DecIntegerLiteral} | + {DecLongLiteral} | + + {HexIntegerLiteral} | + {HexLongLiteral} | + + {OctIntegerLiteral} | + {OctLongLiteral} | + + {FloatLiteral} | + {DoubleLiteral} | + {DoubleLiteral}[dD] { return token(TokenType.NUMBER); } + + // JavaDoc comments need a state so that we can highlight the @ controls + "/**" { + yybegin(JDOC); + tokenStart = yychar; + tokenLength = 3; + } + + /* comments */ + {Comment} { return token(TokenType.COMMENT); } + + /* whitespace */ + {WhiteSpace} { } + + /* identifiers */ + {Identifier} { return token(TokenType.IDENTIFIER); } +} + + + { + \" { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } + + {StringCharacter}+ { tokenLength += yylength(); } + + \\[0-3]?{OctDigit}?{OctDigit} { tokenLength += yylength(); } + + /* escape sequences */ + + \\. { tokenLength += 2; } + {LineTerminator} { yybegin(YYINITIAL); } +} + + { + \' { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } + + {SingleCharacter}+ { tokenLength += yylength(); } + + /* escape sequences */ + + \\. { tokenLength += 2; } + {LineTerminator} { yybegin(YYINITIAL); } +} + + { + "*/" { + yybegin(YYINITIAL); + return token(TokenType.COMMENT, tokenStart, tokenLength + 2); + } + + "@" { + yybegin(JDOC_TAG); + int start = tokenStart; + tokenStart = yychar; + int len = tokenLength; + tokenLength = 1; + return token(TokenType.COMMENT, start, len); + } + + .|\n { tokenLength ++; } + +} + + { + ([:letter:])+ ":"? { tokenLength += yylength(); } + + "*/" { + yybegin(YYINITIAL); + return token(TokenType.COMMENT, tokenStart, tokenLength + 2); + } + + .|\n { + yybegin(JDOC); + // length also includes the trailing quote + int start = tokenStart; + tokenStart = yychar; + int len = tokenLength; + tokenLength = 1; + return token(TokenType.COMMENT2, start, len); + } +} + + +/* error fallback */ +.|\n { } +<> { return null; } + diff --git a/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/javascript.flex b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/javascript.flex new file mode 100644 index 0000000..ab844d7 --- /dev/null +++ b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/javascript.flex @@ -0,0 +1,279 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package de.sciss.syntaxpane.lexers; + + +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +%% + +%public +%class JavaScriptLexer +%extends DefaultJFlexLexer +%final +%unicode +%char +%type Token + + +%{ + /** + * Create an empty lexer, yyrset will be called later to reset and assign + * the reader + */ + public JavaScriptLexer() { + super(); + } + + @Override + public int yychar() { + return yychar; + } + + private static final byte PARAN = 1; + private static final byte BRACKET = 2; + private static final byte CURLY = 3; + +%} + +/* main character classes */ +LineTerminator = \r|\n|\r\n +InputCharacter = [^\r\n] + +WhiteSpace = {LineTerminator} | [ \t\f]+ + +/* comments */ +Comment = {TraditionalComment} | {EndOfLineComment} + +TraditionalComment = "/*" [^*] ~"*/" | "/*" "*"+ "/" +EndOfLineComment = "//" {InputCharacter}* {LineTerminator}? + +/* identifiers */ +Identifier = [:jletter:][:jletterdigit:]* + +/* integer literals */ +DecIntegerLiteral = 0 | [1-9][0-9]* +DecLongLiteral = {DecIntegerLiteral} [lL] + +HexIntegerLiteral = 0 [xX] 0* {HexDigit} {1,8} +HexLongLiteral = 0 [xX] 0* {HexDigit} {1,16} [lL] +HexDigit = [0-9a-fA-F] + +OctIntegerLiteral = 0+ [1-3]? {OctDigit} {1,15} +OctLongLiteral = 0+ 1? {OctDigit} {1,21} [lL] +OctDigit = [0-7] + +/* floating point literals */ +FloatLiteral = ({FLit1}|{FLit2}|{FLit3}) {Exponent}? [fF] +DoubleLiteral = ({FLit1}|{FLit2}|{FLit3}) {Exponent}? + +FLit1 = [0-9]+ \. [0-9]* +FLit2 = \. [0-9]+ +FLit3 = [0-9]+ +Exponent = [eE] [+-]? [0-9]+ + +/* string and character literals */ +StringCharacter = [^\r\n\"\\] +SStringCharacter = [^\r\n\'\\] + +%state STRING SSTRING + +%% + + { + + /* keywords */ + "break" | + "case" | + "catch" | + "continue" | + "do" | + "else" | + "finally" | + "for" | + "default" | + "delete" | + "new" | + "goto" | + "if" | + "switch" | + "return" | + "while" | + "this" | + "try" | + "var" | + "function" | + "with" | + "in" | + + /* boolean literals */ + "true" | + "false" | + + /* null literal */ + "null" { return token(TokenType.KEYWORD); } + + /* standard / builtin functions */ + "Infinity" | + "NaN" | + "undefined" | + "decodeURI" | + "encodeURIComponent" | + "escape" | + "eval" | + "isFinite" | + "isNaN" | + "parseFloat" | + "parseInt" | + "unescape" { return token(TokenType.KEYWORD2); } + + /* Built-in Types*/ + "Array" | + "Boolean" | + "Date" | + "Math" | + "Number" | + "Object" | + "RegExp" | + "String" | + {Identifier} ":" { return token(TokenType.TYPE); } + + + /* operators */ + + "(" { return token(TokenType.OPERATOR, PARAN); } + ")" { return token(TokenType.OPERATOR, -PARAN); } + "{" { return token(TokenType.OPERATOR, CURLY); } + "}" { return token(TokenType.OPERATOR, -CURLY); } + "[" { return token(TokenType.OPERATOR, BRACKET); } + "]" { return token(TokenType.OPERATOR, -BRACKET); } + ";" | + "," | + "." | + "=" | + ">" | + "<" | + "!" | + "~" | + "?" | + ":" | + "==" | + "<=" | + ">=" | + "!=" | + "&&" | + "||" | + "++" | + "--" | + "+" | + "-" | + "*" | + "/" | + "&" | + "|" | + "^" | + "%" | + "<<" | + ">>" | + ">>>" | + "+=" | + "-=" | + "*=" | + "/=" | + "&=" | + "|=" | + "^=" | + "%=" | + "<<=" | + ">>=" | + ">>>=" { return token(TokenType.OPERATOR); } + + /* string literal */ + \" { + yybegin(STRING); + tokenStart = yychar; + tokenLength = 1; + } + + \' { + yybegin(SSTRING); + tokenStart = yychar; + tokenLength = 1; + } + + /* numeric literals */ + + {DecIntegerLiteral} | + {DecLongLiteral} | + + {HexIntegerLiteral} | + {HexLongLiteral} | + + {OctIntegerLiteral} | + {OctLongLiteral} | + + {FloatLiteral} | + {DoubleLiteral} | + {DoubleLiteral}[dD] { return token(TokenType.NUMBER); } + + /* comments */ + {Comment} { return token(TokenType.COMMENT); } + + /* whitespace */ + {WhiteSpace} { } + + /* identifiers */ + {Identifier} { return token(TokenType.IDENTIFIER); } +} + + { + \" { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } + + {StringCharacter}+ { tokenLength += yylength(); } + + \\[0-3]?{OctDigit}?{OctDigit} { tokenLength += yylength(); } + + /* escape sequences */ + + \\. { tokenLength += 2; } + {LineTerminator} { yybegin(YYINITIAL); } +} + + { + \' { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } + + {SStringCharacter}+ { tokenLength += yylength(); } + + \\[0-3]?{OctDigit}?{OctDigit} { tokenLength += yylength(); } + + /* escape sequences */ + + \\. { tokenLength += 2; } + {LineTerminator} { yybegin(YYINITIAL); } +} + +/* error fallback */ +.|\n { } +<> { return null; } + diff --git a/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/jflex.flex b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/jflex.flex new file mode 100644 index 0000000..6e69fef --- /dev/null +++ b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/jflex.flex @@ -0,0 +1,400 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package de.sciss.syntaxpane.lexers; + + +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +%% + +%public +%class JFlexLexer +%extends DefaultJFlexLexer +%final +%unicode +%char +%type Token + + +%{ + /** + * Create an empty lexer, yyrset will be called later to reset and assign + * the reader + */ + public JFlexLexer() { + super(); + } + + @Override + public int yychar() { + return yychar; + } +%} + +/* main character classes */ +LineTerminator = \r|\n|\r\n +InputCharacter = [^\r\n] + +WhiteSpace = {LineTerminator} | [ \t\f]+ + +/* comments */ +Comment = {TraditionalComment} | {EndOfLineComment} + +TraditionalComment = "/*" [^*] ~"*/" | "/*" "*"+ "/" +EndOfLineComment = "//" {InputCharacter}* {LineTerminator}? + +/* identifiers */ +Identifier = [:jletter:][:jletterdigit:]* + +/* integer literals */ +DecIntegerLiteral = 0 | [1-9][0-9]* +DecLongLiteral = {DecIntegerLiteral} [lL] + +HexIntegerLiteral = 0 [xX] 0* {HexDigit} {1,8} +HexLongLiteral = 0 [xX] 0* {HexDigit} {1,16} [lL] +HexDigit = [0-9a-fA-F] + +OctIntegerLiteral = 0+ [1-3]? {OctDigit} {1,15} +OctLongLiteral = 0+ 1? {OctDigit} {1,21} [lL] +OctDigit = [0-7] + +/* floating point literals */ +FloatLiteral = ({FLit1}|{FLit2}|{FLit3}) {Exponent}? [fF] +DoubleLiteral = ({FLit1}|{FLit2}|{FLit3}) {Exponent}? + +FLit1 = [0-9]+ \. [0-9]* +FLit2 = \. [0-9]+ +FLit3 = [0-9]+ +Exponent = [eE] [+-]? [0-9]+ + +/* string and character literals */ +StringCharacter = [^\r\n\"\\] +SingleCharacter = [^\r\n\'\\] + +%state STRING, CHARLITERAL, JDOC, JDOC_TAG + +%% + + { + + /* keywords */ + "abstract" | + "boolean" | + "break" | + "byte" | + "case" | + "catch" | + "char" | + "class" | + "const" | + "continue" | + "do" | + "double" | + "enum" | + "else" | + "extends" | + "final" | + "finally" | + "float" | + "for" | + "default" | + "implements" | + "import" | + "instanceof" | + "int" | + "interface" | + "long" | + "native" | + "new" | + "goto" | + "if" | + "public" | + "short" | + "super" | + "switch" | + "synchronized" | + "package" | + "private" | + "protected" | + "transient" | + "return" | + "void" | + "static" | + "while" | + "this" | + "throw" | + "throws" | + "try" | + "volatile" | + "strictfp" | + "true" | + "false" | + "null" { return token(TokenType.KEYWORD); } + + /* JFlex special types */ + "<>" | + "[:jletter:]" | + "[:jletterdigit:]" | + "[:letter:]" | + "[:digit:]" | + "[:uppercase:]" | + "[:lowercase:]" | + "<" [a-zA-Z][a-zA-Z0-9_]* ">" { return token(TokenType.TYPE2); } + + /* JFlex Specials */ + "%%" | + "%{" | + "%}" | + "%class" | + "%implements" | + "%extends" | + "%public" | + "%final" | + "%abstract" | + "%apiprivate" | + "%init{" | + "%init}" | + "%initthrow{" | + "%initthrow}" | + "%initthrow" | + "%ctorarg" | + "%scanerror" | + "%buffer" | + "%include" | + "%function" | + "%integer" | + "%int" | + "%intwrap" | + "%yylexthrow{" | + "%yylexthrow}" | + "%yylexthrow" | + "%eofval{" | + "%eofval}" | + "%eof{" | + "%eof}" | + "%eofthrow{" | + "%eofthrow}" | + "%eofthrow" | + "%eofclose" | + "%debug" | + "%standalone" | + "%cup" | + "%cupsym" | + "%cupdebug" | + "%byacc" | + "%switch" | + "%table" | + "%pack" | + "%7bit" | + "%8bit" | + "%full" | + "%unicode" | + "%16bit" | + "%caseless" | + "%ignorecase" | + "%char" | + "%line" | + "%column" | + "%notunix" | + "%yyeof" | + "%s" | + "%state" | + "%x" | + "%xstate" | + "%type" { return token(TokenType.KEYWORD2); } + + + /* Java Built in types and wrappers */ + "Boolean" | + "Byte" | + "Double" | + "Float" | + "Integer" | + "Object" | + "Short" | + "String" { return token(TokenType.TYPE); } + + /* operators */ + + "(" | + ")" | + "{" | + "}" | + "[" | + "]" | + ";" | + "," | + "." | + "=" | + ">" | + "<" | + "!" | + "~" | + "?" | + ":" | + "==" | + "<=" | + ">=" | + "!=" | + "&&" | + "||" | + "++" | + "--" | + "+" | + "-" | + "*" | + "/" | + "&" | + "|" | + "^" | + "%" | + "<<" | + ">>" | + ">>>" | + "+=" | + "-=" | + "*=" | + "/=" | + "&=" | + "|=" | + "^=" | + "%=" | + "<<=" | + ">>=" | + ">>>=" { return token(TokenType.OPERATOR); } + + /* string literal */ + \" { + yybegin(STRING); + tokenStart = yychar; + tokenLength = 1; + } + + /* character literal */ + \' { + yybegin(CHARLITERAL); + tokenStart = yychar; + tokenLength = 1; + } + + /* numeric literals */ + + {DecIntegerLiteral} | + {DecLongLiteral} | + + {HexIntegerLiteral} | + {HexLongLiteral} | + + {OctIntegerLiteral} | + {OctLongLiteral} | + + {FloatLiteral} | + {DoubleLiteral} | + {DoubleLiteral}[dD] { return token(TokenType.NUMBER); } + + // JavaDoc comments need a state so that we can highlight the @ controls + "/**" { + yybegin(JDOC); + tokenStart = yychar; + tokenLength = 3; + } + + /* comments */ + {Comment} { return token(TokenType.COMMENT); } + + /* whitespace */ + {WhiteSpace} { } + + /* identifiers */ + {Identifier} { return token(TokenType.IDENTIFIER); } +} + + + { + \" { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } + + {StringCharacter}+ { tokenLength += yylength(); } + + \\[0-3]?{OctDigit}?{OctDigit} { tokenLength += yylength(); } + + /* escape sequences */ + + \\. { tokenLength += 2; } + {LineTerminator} { yybegin(YYINITIAL); } +} + + { + \' { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } + + {SingleCharacter}+ { tokenLength += yylength(); } + + /* escape sequences */ + + \\. { tokenLength += 2; } + {LineTerminator} { yybegin(YYINITIAL); } +} + + { + "*/" { + yybegin(YYINITIAL); + return token(TokenType.COMMENT, tokenStart, tokenLength + 2); + } + + "@" { + yybegin(JDOC_TAG); + int start = tokenStart; + tokenStart = yychar; + int len = tokenLength; + tokenLength = 1; + return token(TokenType.COMMENT, start, len); + } + + .|\n { tokenLength ++; } + +} + + { + ([:letter:])+ ":"? { tokenLength += yylength(); } + + "*/" { + yybegin(YYINITIAL); + return token(TokenType.COMMENT, tokenStart, tokenLength + 2); + } + + .|\n { + yybegin(JDOC); + // length also includes the trailing quote + int start = tokenStart; + tokenStart = yychar; + int len = tokenLength; + tokenLength = 1; + return token(TokenType.COMMENT2, start, len); + } +} + + +/* error fallback */ +.|\n { } +<> { return null; } + diff --git a/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/lua.flex b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/lua.flex new file mode 100644 index 0000000..7989a79 --- /dev/null +++ b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/lua.flex @@ -0,0 +1,298 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package de.sciss.syntaxpane.lexers; + + +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +%% + +%public +%class LuaLexer +%extends DefaultJFlexLexer +%final +%unicode +%char +%type Token + + +%{ + /** + * Create an empty lexer, yyrset will be called later to reset and assign + * the reader + */ + public LuaLexer() { + super(); + } + + @Override + public int yychar() { + return yychar; + } + + private static final byte PARAN = 1; + private static final byte BRACKET = 2; + private static final byte CURLY = 3; + private static final byte ENDBLOCK = 4; + private static final byte REPEATBLOCK = 5; + + TokenType longType; + int longLen; +%} + +/* main character classes */ +LineTerminator = \r|\n|\r\n + +WhiteSpace = {LineTerminator} | [ \t\f]+ + +LongStart = \[=*\[ +LongEnd = \]=*\] + +/* identifiers */ +Identifier = [:jletter:][:jletterdigit:]* + +/* integer literals */ +DecIntegerLiteral = [0-9]+ +HexDigit = [0-9a-fA-F] + +HexIntegerLiteral = 0x{HexDigit}+ + +/* floating point literals */ +DoubleLiteral = ({FLit1}|{FLit2}) {Exponent}? + +FLit1 = [0-9]+(\.[0-9]*)? +FLit2 = \.[0-9]+ +Exponent = [eE] [+-]? [0-9]+ + +/* string and character literals */ +StringCharacter1 = [^\r\n\"\\] +StringCharacter2 = [^\r\n\'\\] + +%state STRING1 +%state STRING2 +%state LONGSTRING + +%state COMMENT +%state LINECOMMENT + +%% + + { + + /* keywords */ + "and" | + "break" | + "for" | + "if" | + "in" | + "local" | + "not" | + "or" | + "return" | + "while" | + + /* boolean literals */ + "true" | + "false" | + + /* nil literal */ + "nil" { return token(TokenType.KEYWORD); } + + "repeat" { return token(TokenType.KEYWORD, REPEATBLOCK); } + "until" { return token(TokenType.KEYWORD, -REPEATBLOCK); } + + "function" { return token(TokenType.KEYWORD, ENDBLOCK); } + "then" { return token(TokenType.KEYWORD, ENDBLOCK); } + "do" { return token(TokenType.KEYWORD, ENDBLOCK); } + + "else" { return token(TokenType.KEYWORD); } + "elseif" { return token(TokenType.KEYWORD); } + + "end" { return token(TokenType.KEYWORD, -ENDBLOCK); } + + /* operators */ + + "+" | + "-" | + "*" | + "/" | + "%" | + "^" | + "#" | + "==" | + "~=" | + "<=" | + ">=" | + "<" | + ">" | + "=" | + ";" | + ":" | + "," | + "." | + ".." | + "..." { return token(TokenType.OPERATOR); } + + "(" { return token(TokenType.OPERATOR, PARAN); } + ")" { return token(TokenType.OPERATOR, -PARAN); } + "{" { return token(TokenType.OPERATOR, CURLY); } + "}" { return token(TokenType.OPERATOR, -CURLY); } + "[" { return token(TokenType.OPERATOR, BRACKET); } + "]" { return token(TokenType.OPERATOR, -BRACKET); } + + + {LongStart} { + longType = TokenType.STRING; + yybegin(LONGSTRING); + tokenStart = yychar; + tokenLength = yylength(); + longLen = tokenLength; + } + + "--" { + yybegin(COMMENT); + tokenStart = yychar; + tokenLength = yylength(); + } + + + /* string literal */ + \" { + yybegin(STRING1); + tokenStart = yychar; + tokenLength = 1; + } + \' { + yybegin(STRING2); + tokenStart = yychar; + tokenLength = 1; + } + + /* numeric literals */ + + {DecIntegerLiteral} | + + {HexIntegerLiteral} | + + {DoubleLiteral} { return token(TokenType.NUMBER); } + + /* whitespace */ + {WhiteSpace} { } + + /* identifiers */ + {Identifier} { return token(TokenType.IDENTIFIER); } +} + + { + {LongEnd} { + if (longLen == yylength()) { + tokenLength += yylength(); + yybegin(YYINITIAL); + return token(longType, tokenStart, tokenLength); + } else { + tokenLength++; + yypushback(yylength() - 1); + } + + } + {LineTerminator} { tokenLength += yylength(); } + . { tokenLength++; } + <> { + yybegin(YYINITIAL); + return token(longType, tokenStart, tokenLength); + } +} + + { + {LongStart} { + longType = TokenType.COMMENT; + yybegin(LONGSTRING); + tokenLength += yylength(); + longLen = yylength(); + } + + {LineTerminator} { + yybegin(YYINITIAL); + return token(TokenType.COMMENT, tokenStart, tokenLength); + } + + . { + yybegin(LINECOMMENT); + tokenLength += yylength(); + } + <> { + yybegin(YYINITIAL); + return token(TokenType.COMMENT, tokenStart, tokenLength); + } + +} + + { + {LineTerminator} { + yybegin(YYINITIAL); + tokenLength += yylength(); + return token(TokenType.COMMENT, tokenStart, tokenLength); + } + {LineTerminator} { tokenLength += yylength(); } + . { tokenLength++; } + <> { + yybegin(YYINITIAL); + return token(TokenType.COMMENT, tokenStart, tokenLength); + } +} + + { + \" { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } + + {StringCharacter1}+ { tokenLength += yylength(); } + + /* escape sequences */ + + \\. { tokenLength += 2; } + {LineTerminator} { yybegin(YYINITIAL); } + <> { + yybegin(YYINITIAL); + return token(TokenType.STRING, tokenStart, tokenLength); + } +} + + { + \' { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } + + {StringCharacter2}+ { tokenLength += yylength(); } + + /* escape sequences */ + + \\. { tokenLength += 2; } + {LineTerminator} { yybegin(YYINITIAL); } + <> { + yybegin(YYINITIAL); + return token(TokenType.STRING, tokenStart, tokenLength); + } +} + +/* error fallback */ +.|\n { } +<> { return null; } + diff --git a/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/properties.flex b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/properties.flex new file mode 100644 index 0000000..ae384f2 --- /dev/null +++ b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/properties.flex @@ -0,0 +1,63 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package de.sciss.syntaxpane.lexers; + + +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +%% + +%public +%class PropertiesLexer +%extends DefaultJFlexLexer +%final +%unicode +%char +%type Token + + +%{ + /** + * Create an empty lexer, yyrset will be called later to reset and assign + * the reader + */ + public PropertiesLexer() { + super(); + } + + @Override + public int yychar() { + return yychar; + } +%} + +StartComment = # +WhiteSpace = [ \t] +LineTerminator = \r|\n|\r\n +InputCharacter = [^\r\n] +KeyCharacter = [a-zA-Z0-9._ ] + +%% + + +{ + {KeyCharacter}+{WhiteSpace}*= { return token(TokenType.KEYWORD); } + {StartComment} {InputCharacter}* {LineTerminator}? + { return token(TokenType.COMMENT); } + . | {LineTerminator} { /* skip */ } +} + +<> { return null; } \ No newline at end of file diff --git a/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/python.flex b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/python.flex new file mode 100644 index 0000000..a668863 --- /dev/null +++ b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/python.flex @@ -0,0 +1,386 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package de.sciss.syntaxpane.lexers; + + +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +%% + +%public +%class PythonLexer +%extends DefaultJFlexLexer +%final +%unicode +%char +%type Token + + +%{ + /** + * Create an empty lexer, yyrset will be called later to reset and assign + * the reader + */ + public PythonLexer() { + super(); + } + + @Override + public int yychar() { + return yychar; + } + + private static final byte PARAN = 1; + private static final byte BRACKET = 2; + private static final byte CURLY = 3; + +%} + +/* main character classes */ +LineTerminator = \r|\n|\r\n +InputCharacter = [^\r\n] + +WhiteSpace = {LineTerminator} | [ \t\f]+ + +/* comments */ +Comment = "#" {InputCharacter}* {LineTerminator}? + +/* identifiers */ +Identifier = [a-zA-Z][a-zA-Z0-9_]* + +/* integer literals */ +DecIntegerLiteral = 0 | [1-9][0-9]* +DecLongLiteral = {DecIntegerLiteral} [lL] + +HexIntegerLiteral = 0 [xX] 0* {HexDigit} {1,8} +HexLongLiteral = 0 [xX] 0* {HexDigit} {1,16} [lL] +HexDigit = [0-9a-fA-F] + +OctIntegerLiteral = 0+ [1-3]? {OctDigit} {1,15} +OctLongLiteral = 0+ 1? {OctDigit} {1,21} [lL] +OctDigit = [0-7] + +/* floating point literals */ +FloatLiteral = ({FLit1}|{FLit2}|{FLit3}) {Exponent}? [fF] +DoubleLiteral = ({FLit1}|{FLit2}|{FLit3}) {Exponent}? + +FLit1 = [0-9]+ \. [0-9]* +FLit2 = \. [0-9]+ +FLit3 = [0-9]+ +Exponent = [eE] [+-]? [0-9]+ + +/* string and character literals */ +StringCharacter = [^\r\n\"\\] +SQStringCharacter = [^\r\n\'\\] + +%state STRING, ML_STRING, SQSTRING, SQML_STRING + +%% + + { + + /* keywords */ + "and" | + "as" | + "assert" | + "break" | + "class" | + "continue" | + "def" | + "del" | + "elif" | + "else" | + "except" | + "exec" | + "finally" | + "for" | + "from" | + "global" | + "if" | + "import" | + "in" | + "is" | + "lambda" | + "not" | + "or" | + "pass" | + "print" | + "self" | /* not exactly keyword, but almost */ + "raise" | + "return" | + "try" | + "while" | + "with" | + "yield" { return token(TokenType.KEYWORD); } + + /* Built-in Types*/ + "yield" | + "Ellipsis" | + "False" | + "None" | + "NotImplemented" | + "True" | + "__import__" | + "__name__" | + "abs" | + "apply" | + "bool" | + "buffer" | + "callable" | + "chr" | + "classmethod" | + "cmp" | + "coerce" | + "compile" | + "complex" | + "delattr" | + "dict" | + "dir" | + "divmod" | + "enumerate" | + "eval" | + "execfile" | + "file" | + "filter" | + "float" | + "frozenset" | + "getattr" | + "globals" | + "hasattr" | + "hash" | + "help" | + "hex" | + "id" | + "input" | + "int" | + "intern" | + "isinstance" | + "issubclass" | + "iter" | + "len" | + "list" | + "locals" | + "long" | + "map" | + "max" | + "min" | + "object" | + "oct" | + "open" | + "ord" | + "pow" | + "property" | + "range" | + "raw_input" | + "reduce" | + "reload" | + "repr" | + "reversed" | + "round" | + "set" | + "setattr" | + "slice" | + "sorted" | + "staticmethod" | + "str" | + "sum" | + "super" | + "tuple" | + "type" | + "unichr" | + "unicode" | + "vars" | + "xrange" | + "zip" { return token(TokenType.TYPE); } + + + + /* operators */ + + "(" { return token(TokenType.OPERATOR, PARAN); } + ")" { return token(TokenType.OPERATOR, -PARAN); } + "{" { return token(TokenType.OPERATOR, CURLY); } + "}" { return token(TokenType.OPERATOR, -CURLY); } + "[" { return token(TokenType.OPERATOR, BRACKET); } + "]" { return token(TokenType.OPERATOR, -BRACKET); } + "+" | + "-" | + "*" | + "**" | + "/" | + "//" | + "%" | + "<<" | + ">>" | + "&" | + "|" | + "^" | + "~" | + "<" | + ">" | + "<=" | + ">=" | + "==" | + "!=" | + "<>" | + "@" | + "," | + ":" | + "." | + "`" | + "=" | + ";" | + "+=" | + "-=" | + "*=" | + "/=" | + "//=" | + "%=" | + "&=" | + "|=" | + "^=" | + ">>=" | + "<<=" | + "**=" { return token(TokenType.OPERATOR); } + + /* string literal */ + \"{3} { + yybegin(ML_STRING); + tokenStart = yychar; + tokenLength = 3; + } + + \" { + yybegin(STRING); + tokenStart = yychar; + tokenLength = 1; + } + + \'{3} { + yybegin(SQML_STRING); + tokenStart = yychar; + tokenLength = 3; + } + + \' { + yybegin(SQSTRING); + tokenStart = yychar; + tokenLength = 1; + } + + /* numeric literals */ + + {DecIntegerLiteral} | + {DecLongLiteral} | + + {HexIntegerLiteral} | + {HexLongLiteral} | + + {OctIntegerLiteral} | + {OctLongLiteral} | + + {FloatLiteral} | + {DoubleLiteral} | + {FloatLiteral}[jJ] { return token(TokenType.NUMBER); } + + /* comments */ + {Comment} { return token(TokenType.COMMENT); } + + /* whitespace */ + {WhiteSpace} { } + + /* identifiers */ + {Identifier} { return token(TokenType.IDENTIFIER); } + + "$" | "?" { return token(TokenType.ERROR); } +} + + { + \" { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } + + {StringCharacter}+ { tokenLength += yylength(); } + + \\[0-3]?{OctDigit}?{OctDigit} { tokenLength += yylength(); } + + /* escape sequences */ + + \\. { tokenLength += 2; } + {LineTerminator} { yybegin(YYINITIAL); } +} + + { + \"{3} { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 3); + } + + {StringCharacter}+ { tokenLength += yylength(); } + + \\[0-3]?{OctDigit}?{OctDigit} { tokenLength += yylength(); } + + \" { tokenLength ++; } + + /* escape sequences */ + + \\. { tokenLength += 2; } + {LineTerminator} { tokenLength ++; } +} + + { + "'" { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } + + {SQStringCharacter}+ { tokenLength += yylength(); } + + \\[0-3]?{OctDigit}?{OctDigit} { tokenLength += yylength(); } + + /* escape sequences */ + + \\. { tokenLength += 2; } + {LineTerminator} { yybegin(YYINITIAL); } +} + + { + \'{3} { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 3); + } + + {SQStringCharacter}+ { tokenLength += yylength(); } + + \\[0-3]?{OctDigit}?{OctDigit} { tokenLength += yylength(); } + + \' { tokenLength ++; } + + /* escape sequences */ + + \\. { tokenLength += 2; } + {LineTerminator} { tokenLength ++; } +} + +/* error fallback */ +.|\n { } +<> { return null; } + diff --git a/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/ruby.flex b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/ruby.flex new file mode 100644 index 0000000..22f6862 --- /dev/null +++ b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/ruby.flex @@ -0,0 +1,276 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package de.sciss.syntaxpane.lexers; + + +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +%% + +%public +%class RubyLexer +%extends DefaultJFlexLexer +%final +%unicode +%char +%type Token + + +%{ + /** + * Create an empty lexer, yyrset will be called later to reset and assign + * the reader + */ + public RubyLexer() { + super(); + } + + @Override + public int yychar() { + return yychar; + } + + private static final byte PARAN = 1; + private static final byte BRACKET = 2; + private static final byte CURLY = 3; + private static final byte WORD = 4; + +%} + +/* main character classes */ +LineTerminator = \r|\n|\r\n +InputCharacter = [^\r\n] + +WhiteSpace = {LineTerminator} | [ \t\f]+ + +/* comments */ +Comment = "#" {InputCharacter}* {LineTerminator}? + +/* identifiers */ +Identifier = [a-zA-Z][a-zA-Z0-9_]* + +/* integer literals */ +DecIntegerLiteral = 0 | [1-9][0-9]* +DecLongLiteral = {DecIntegerLiteral} [lL] + +HexIntegerLiteral = 0 [xX] 0* {HexDigit} {1,8} +HexLongLiteral = 0 [xX] 0* {HexDigit} {1,16} [lL] +HexDigit = [0-9a-fA-F] + +OctIntegerLiteral = 0+ [1-3]? {OctDigit} {1,15} +OctLongLiteral = 0+ 1? {OctDigit} {1,21} [lL] +OctDigit = [0-7] + +/* floating point literals */ +FloatLiteral = ({FLit1}|{FLit2}|{FLit3}) {Exponent}? [fF] +DoubleLiteral = ({FLit1}|{FLit2}|{FLit3}) {Exponent}? + +FLit1 = [0-9]+ \. [0-9]* +FLit2 = \. [0-9]+ +FLit3 = [0-9]+ +Exponent = [eE] [+-]? [0-9]+ + +/* string and character literals */ +StringCharacter = [^\r\n\"\\] + +%state STRING, ML_STRING + +%% + + { + + /* keywords */ + "BEGIN" | + "ensure" | + "assert" | + "nil" | + "self" | + "when" | + "END" | + "false" | + "not" | + "super" | + "alias" | + "defined" | + "or" | + "then" | + "yield" | + "and" | + "redo" | + "true" | + "else" | + "in" | + "rescue" | + "undef" | + "break" | + "elsif" | + "module" | + "retry" | + "unless" | + "next" | + "return" { return token(TokenType.KEYWORD); } + + "begin" | + "case" | + "class" | + "def" | + "for" | + "while" | + "until" | + "do" | + "if" { return token(TokenType.KEYWORD, WORD); } + + "end" { return token(TokenType.KEYWORD, -WORD); } + + + /* Built-in Types*/ + "self" | + "nil" | + "true" | + "false" | + "__FILE__" | + "__LINE__" { return token(TokenType.TYPE); } + + + + /* operators */ + + "(" { return token(TokenType.OPERATOR, PARAN); } + ")" { return token(TokenType.OPERATOR, -PARAN); } + "{" { return token(TokenType.OPERATOR, CURLY); } + "}" { return token(TokenType.OPERATOR, -CURLY); } + "[" { return token(TokenType.OPERATOR, BRACKET); } + "]" { return token(TokenType.OPERATOR, -BRACKET); } + "+" | + "-" | + "*" | + "**" | + "/" | + "//" | + "%" | + "<<" | + ">>" | + "&" | + "|" | + "^" | + "~" | + "<" | + ">" | + "<=" | + ">=" | + "==" | + "!=" | + "<>" | + "@" | + "," | + ":" | + "." | + ".." | + "`" | + "=" | + ";" | + "+=" | + "-=" | + "*=" | + "/=" | + "//=" | + "%=" | + "&=" | + "|=" | + "^=" | + ">>=" | + "<<=" | + "**=" { return token(TokenType.OPERATOR); } + + /* string literal */ + \"{3} { + yybegin(ML_STRING); + tokenStart = yychar; + tokenLength = 3; + } + + \" { + yybegin(STRING); + tokenStart = yychar; + tokenLength = 1; + } + + + /* numeric literals */ + + {DecIntegerLiteral} | + {DecLongLiteral} | + + {HexIntegerLiteral} | + {HexLongLiteral} | + + {OctIntegerLiteral} | + {OctLongLiteral} | + + {FloatLiteral} | + {DoubleLiteral} | + {FloatLiteral}[jJ] { return token(TokenType.NUMBER); } + + /* comments */ + {Comment} { return token(TokenType.COMMENT); } + + /* whitespace */ + {WhiteSpace} { } + + /* identifiers */ + {Identifier}"?" { return token(TokenType.TYPE2); } + {Identifier} { return token(TokenType.IDENTIFIER); } +} + + { + \" { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } + + {StringCharacter}+ { tokenLength += yylength(); } + + \\[0-3]?{OctDigit}?{OctDigit} { tokenLength += yylength(); } + + /* escape sequences */ + + \\. { tokenLength += 2; } + {LineTerminator} { yybegin(YYINITIAL); } +} + + { + \"{3} { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 3); + } + + {StringCharacter}+ { tokenLength += yylength(); } + + \\[0-3]?{OctDigit}?{OctDigit} { tokenLength += yylength(); } + + /* escape sequences */ + + \\. { tokenLength += 2; } + {LineTerminator} { tokenLength ++; } +} + + +/* error fallback */ +.|\n { } +<> { return null; } + diff --git a/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/scala.flex b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/scala.flex new file mode 100644 index 0000000..fb30028 --- /dev/null +++ b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/scala.flex @@ -0,0 +1,347 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * -- + * + * The original .flex file is full of errors. With my inexisting JFlex + * knowledge, I try to fix the problems based on the Scala Language + * Specification (SLS) v2.9 (published draft May 24, 2011). (H. H. Rutz) + */ + +package de.sciss.syntaxpane.lexers; + +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +%% + +%public +%class ScalaLexer +%extends DefaultJFlexLexer +%final +%unicode +%char +%type Token + + +%{ + /** + * Create an empty lexer, yyrset will be called later to reset and assign + * the reader + */ + public ScalaLexer() { + super(); + } + + @Override + public int yychar() { + return yychar; + } + + private static final byte PARAN = 1; + private static final byte BRACKET = 2; + private static final byte CURLY = 3; + +%} + +/* main character classes */ +LineTerminator = \r|\n|\r\n +InputCharacter = [^\r\n] + +WhiteSpace = {LineTerminator} | [ \t\f]+ + +/* comments */ +Comment = {TraditionalComment} | {EndOfLineComment} + +/* plain comment added by HHR as a quick work-around for embedding non-highlighted text portions */ +PlainComment = "/*---" [^*] ~"*/" +TraditionalComment = "/*" [^*] ~"*/" | "/*" "*"+ "/" +EndOfLineComment = "//" {InputCharacter}* {LineTerminator}? + +/* identifiers */ +Identifier = [:jletter:][:jletterdigit:]* + +/* integer literals */ +DecIntegerLiteral = 0 | [1-9][0-9]* +DecLongLiteral = {DecIntegerLiteral} [lL] + +HexIntegerLiteral = 0 [xX] 0* {HexDigit} {1,8} +HexLongLiteral = 0 [xX] 0* {HexDigit} {1,16} [lL] +HexDigit = [0-9a-fA-F] + +OctIntegerLiteral = 0+ [1-3]? {OctDigit} {1,15} +OctLongLiteral = 0+ 1? {OctDigit} {1,21} [lL] +OctDigit = [0-7] + +/* floating point literals */ +FloatLiteral = ({FLit1}|{FLit2}|{FLit3}) {Exponent}? [fF] +DoubleLiteral = ({FLit1}|{FLit2}|{FLit3}) {Exponent}? + +FLit1 = [0-9]+ \. [0-9]* +FLit2 = \. [0-9]+ +FLit3 = [0-9]+ +Exponent = [eE] [+-]? [0-9]+ + +/* string and character literals */ +StringCharacter = [^\r\n\"\\] +SingleCharacter = [^\r\n\'\\] + +%state STRING, CHARLITERAL, JDOC, JDOC_TAG + +%% + + { + + /* keywords, SLS 1.1 */ + "abstract" | + "case" | + "catch" | + "class" | + "def" | + "do" | + "else" | + "extends" | + "false" | + "final" | + "finally" | + "for" | + "forSome" | + "if" | + "implicit" | + "import" | + "lazy" | + "macro" | + "match" | + "new" | + "null" | + "object" | + "override" | + "package" | + "private" | + "protected" | + "return" | + "sealed" | + "super" | + "this" | + "throw" | + "trait" | + "try" | + "true" | + "type" | + "val" | + "var" | + "while" | + "with" | + "yield" { return token(TokenType.KEYWORD); } + +/* "_" ":" "=" "=>" "<-" "<:" "<%" ">:" "#" "@" */ + + /* Java Built in types and wrappers XXX Wrong -- doesn't make sense to add a list */ + "Unit" | + "Boolean" | + "Byte" | + "Char" | + "Short" | + "Int" | + "Long" | + "Float" | + "Double" | + "Any" | + "AnyRef" | + "String" { return token(TokenType.TYPE); } + + /* Some Scala predefines */ +/* "println" { return token(TokenType.KEYWORD2); } */ + + /* Some Java standard Library Types */ +/* "Throwable" | + "Cloneable" | + "Comparable" | + "Serializable" | + "Runnable" { return token(TokenType.TYPE); } +*/ + "WARNING" { return token(TokenType.WARNING); } + "ERROR" { return token(TokenType.ERROR); } + + /* operators */ + + "(" { return token(TokenType.OPERATOR, PARAN); } + ")" { return token(TokenType.OPERATOR, -PARAN); } + "{" { return token(TokenType.OPERATOR, CURLY); } + "}" { return token(TokenType.OPERATOR, -CURLY); } + "[" { return token(TokenType.OPERATOR, BRACKET); } + "]" { return token(TokenType.OPERATOR, -BRACKET); } + ";" | + "," | + "." | + "=" | + ">" | + "<" | + "!" | + "~" | + "?" | + ":" | + "==" | + "<=" | + ">=" | + "!=" | + "&&" | + "||" | + "++" | + "--" | + "+" | + "-" | + "*" | + "/" | + "&" | + "|" | + "^" | + "%" | + "<<" | + ">>" | + ">>>" | + "+=" | + "-=" | + "*=" | + "/=" | + "&=" | + "|=" | + "^=" | + "%=" | + "<<=" | + ">>=" | + ">>>=" { return token(TokenType.OPERATOR); } + + /* string literal */ + \" { + yybegin(STRING); + tokenStart = yychar; + tokenLength = 1; + } + + /* character literal */ + \' { + yybegin(CHARLITERAL); + tokenStart = yychar; + tokenLength = 1; + } + + /* numeric literals */ + + {DecIntegerLiteral} | + {DecLongLiteral} | + + {HexIntegerLiteral} | + {HexLongLiteral} | + + {OctIntegerLiteral} | + {OctLongLiteral} | + + {FloatLiteral} | + {DoubleLiteral} | + {DoubleLiteral}[dD] { return token(TokenType.NUMBER); } + + // JavaDoc comments need a state so that we can highlight the @ controls + "/**" { + yybegin(JDOC); + tokenStart = yychar; + tokenLength = 3; + } + + /* comments */ + {PlainComment} { return token(TokenType.DEFAULT); } + {Comment} { return token(TokenType.COMMENT); } + + /* whitespace */ + {WhiteSpace} { } + + /* identifiers */ + {Identifier} { return token(TokenType.IDENTIFIER); } +} + + + { + \" { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } + + {StringCharacter}+ { tokenLength += yylength(); } + + \\[0-3]?{OctDigit}?{OctDigit} { tokenLength += yylength(); } + + /* escape sequences */ + + \\. { tokenLength += 2; } + {LineTerminator} { yybegin(YYINITIAL); } +} + + { + \' { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } + + {SingleCharacter}+ { tokenLength += yylength(); } + + /* escape sequences */ + + \\. { tokenLength += 2; } + {LineTerminator} { yybegin(YYINITIAL); } +} + + { + "*/" { + yybegin(YYINITIAL); + return token(TokenType.COMMENT, tokenStart, tokenLength + 2); + } + + "@" { + yybegin(JDOC_TAG); + int start = tokenStart; + tokenStart = yychar; + int len = tokenLength; + tokenLength = 1; + return token(TokenType.COMMENT, start, len); + } + + .|\n { tokenLength ++; } + +} + + { + ([:letter:])+ ":"? { tokenLength += yylength(); } + + "*/" { + yybegin(YYINITIAL); + return token(TokenType.COMMENT, tokenStart, tokenLength + 2); + } + + .|\n { + yybegin(JDOC); + // length also includes the trailing quote + int start = tokenStart; + tokenStart = yychar; + int len = tokenLength; + tokenLength = 1; + return token(TokenType.COMMENT2, start, len); + } +} + + +/* error fallback */ +.|\n { } +<> { return null; } + diff --git a/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/sql.flex b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/sql.flex new file mode 100644 index 0000000..2c6360b --- /dev/null +++ b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/sql.flex @@ -0,0 +1,383 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.lexers; + + +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +%% + +%public +%class SqlLexer +%extends DefaultJFlexLexer +%final +%unicode +%char +%type Token +%caseless + + +%{ + /** + * Default constructor is needed as we will always call the yyreset + */ + public SqlLexer() { + super(); + } + + @Override + public int yychar() { + return yychar; + } + +%} + +/* main character classes */ +LineTerminator = \r|\n|\r\n +InputCharacter = [^\r\n] + +WhiteSpace = {LineTerminator} | [ \t\f] + +/* comments */ +Comment = {TraditionalComment} | {EndOfLineComment} | {DocumentationComment} + +TraditionalComment = "/*" [^*] ~"*/" | "/*" "*"+ "/" +DocumentationComment = "/**" {CommentContent} "*"+ "/" +CommentContent = ( [^*] | \*+ [^/*] )* +EndOfLineComment = "--" {InputCharacter}* {LineTerminator}? + +/* identifiers */ +Identifier = [:jletter:][:jletterdigit:]* + +/* integer literals */ +DecIntegerLiteral = 0 | [1-9][0-9]* + +/* floating point literals */ +FloatLiteral = ({FLit1}|{FLit2}|{FLit3}) {Exponent}? [fF] + +FLit1 = [0-9]+ \. [0-9]* +FLit2 = \. [0-9]+ +FLit3 = [0-9]+ +Exponent = [eE] [+-]? [0-9]+ + +/* string and character literals */ +StringCharacter = [^\r\n\"\\] +SingleCharacter = [^\r\n\'\\] + +// Create states for Double Quoted and Single Quoted Strings +%state DQ_STRING, SQ_STRING + +Reserved = + "ADD" | + "ALL" | + "ALLOW REVERSE SCANS" | + "ALTER" | + "ANALYZE" | + "AND" | + "AS" | + "ASC" | + "AUTOMATIC" | + "BEGIN" | + "BEFORE" | + "BETWEEN" | + "BIGINT" | + "BINARY" | + "BLOB" | + "BOTH" | + "BUFFERPOOL" | + "BY" | + "CACHE" | + "CALL" | + "CASCADE" | + "CASE" | + "CHANGE" | + "CHAR" | + "CHARACTER" | + "CHECK" | + "COLLATE" | + "COLUMN" | + "COMMIT" | + "CONDITION" | + "CONSTANT" | + "CONSTRAINT" | + "CONTINUE" | + "CONVERT" | + "CREATE" | + "CROSS" | + "CURSOR" | + "DATE" | + "DATABASE" | + "DATABASES" | + "DEC" | + "DECIMAL" | + "DECODE" | + "DECLARE" | + "DEFAULT" | + "DELAYED" | + "DELETE" | + "DESC" | + "DESCRIBE" | + "DETERMINISTIC" | + "DISTINCT" | + "DISTINCTROW" | + "DIV" | + "DOUBLE" | + "DROP" | + "DUAL" | + "EACH" | + "ELSE" | + "ELSEIF" | + "ENCLOSED" | + "END" | + "ESCAPED" | + "EXCEPTION" | + "EXISTS" | + "EXIT" | + "EXPLAIN" | + "FALSE" | + "FETCH" | + "FLOAT" | + "FLOAT4" | + "FLOAT8" | + "FOR" | + "FORCE" | + "FOREIGN" | + "FROM" | + "FUNCTION" | + "FULLTEXT" | + "GLOBAL TEMPORARY" | + "GRANT" | + "GROUP" | + "HAVING" | + "IF" | + "IGNORE" | + "IN" | + "INDEX" | + "INFILE" | + "INNER" | + "INOUT" | + "INSENSITIVE" | + "INSERT" | + "INT" | + "INTEGER" | + "INTERVAL" | + "INTO" | + "IS" | + "IS REF CURSOR" | + "ITERATE" | + "JOIN" | + "KEY" | + "KEYS" | + "KILL" | + "LEADING" | + "LEAVE" | + "LEFT" | + "LIKE" | + "LIMIT" | + "LINES" | + "LOAD" | + "LOCK" | + "LONG" | + "LOOP" | + "MATCH" | + "MERGE" | + "MINVALUE" | + "MAXVALUE" | + "MOD" | + "MODIFIES" | + "NATURAL" | + "NOCYCLE" | + "NOORDER" | + "NOT" | + "NULL" | + "NUMERIC" | + "NUMBER" | + "ON" | + "OPEN" | + "OPTIMIZE" | + "OPTION" | + "OPTIONALLY" | + "OR" | + "ORDER" | + "OTHERS" | + "OUT" | + "OUTER" | + "OUTFILE" | + "PACKAGE" | + "PACKAGE BODY" | + "PAGESIZE" | + "PLS_INTEGER" | + "PRAGMA" | + "PRECISION" | + "PRIMARY" | + "PROCEDURE" | + "PURGE" | + "RAISE" | + "READ" | + "READS" | + "REAL" | + "REFERENCES" | + "REGEXP" | + "RELEASE" | + "RENAME" | + "REPEAT" | + "REPLACE" | + "REQUIRE" | + "RESTRICT" | + "RETURN" | + "REVOKE" | + "RIGHT" | + "RLIKE" | + "ROLLBACK" | + "ROWCOUNT" | + "ROWTYPE" | + "SIZE" | + "SCHEMA" | + "SCHEMAS" | + "SELECT" | + "SENSITIVE" | + "SEPARATOR" | + "SEQUENCE" | + "SET" | + "SHOW" | + "SMALLINT" | + "SONAME" | + "SPATIAL" | + "SPECIFIC" | + "SQL" | + "SQLEXCEPTION" | + "SQLSTATE" | + "SQLWARNING" | + "STARTING" | + "SYSDATE" | + "TABLE" | + "TABLESPACE" | + "TERMINATED" | + "THEN" | + "TO" | + "TO_CHAR" | + "TO_DATE" | + "TRAILING" | + "TRIGGER" | + "TRUE" | + "TRUNCATE" | + "TYPE" | + "UNDO" | + "UNION" | + "UNIQUE" | + "UNLOCK" | + "UNSIGNED" | + "UPDATE" | + "USAGE" | + "USE" | + "USER" | + "USING" | + "VALUES" | + "VARBINARY" | + "VARCHAR" | + "VARCHAR2" | + "VARCHARACTER" | + "VARYING" | + "WHEN" | + "WHERE" | + "WHILE" | + "WITH" | + "WRITE" | + "XOR" | + "ZEROFILL" +%% + + { + + /* keywords */ + {Reserved} { return token(TokenType.KEYWORD); } + + /* operators */ + + "(" | + ")" | + "{" | + "}" | + "[" | + "]" | + ";" | + "," | + "." | + "@" | + "=" | + ">" | + "<" | + "!" | + "~" | + "?" | + ":" { return token(TokenType.OPERATOR); } + + /* string literal */ + \" { + yybegin(DQ_STRING); + tokenStart = yychar; + tokenLength = 1; + } + \' { + yybegin(SQ_STRING); + tokenStart = yychar; + tokenLength = 1; + } + + /* numeric literals */ + + {DecIntegerLiteral} | + + {FloatLiteral} { return token(TokenType.NUMBER); } + + /* comments */ + {Comment} { return token(TokenType.COMMENT); } + + /* whitespace */ + {WhiteSpace}+ { /* skip */ } + + /* identifiers */ + {Identifier} { return token(TokenType.IDENTIFIER); } + +} + + { + {StringCharacter}+ { tokenLength += yylength(); } + \"\" { tokenLength += 2; } + \\. { tokenLength += 2; } + {LineTerminator} { yybegin(YYINITIAL); } + \" { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } +} + + { + {SingleCharacter}+ { tokenLength += yylength(); } + \'\' { tokenLength += 2; } + \\. { tokenLength += 2; } + {LineTerminator} { yybegin(YYINITIAL); } + \' { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } +} + +/* error fallback */ +.|\n { } +<> { return null; } + diff --git a/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/tal.flex b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/tal.flex new file mode 100644 index 0000000..9346b6d --- /dev/null +++ b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/tal.flex @@ -0,0 +1,166 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane.lexers; + + +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +%% + +%public +%class TALLexer +%extends DefaultJFlexLexer +%final +%unicode +%char +%type Token +%caseless + + +%{ + /** + * Create an empty lexer, yyrset will be called later to reset and assign + * the reader + */ + public TALLexer() { + super(); + } + + @Override + public int yychar() { + return yychar; + } +%} + +/* main character classes */ +LineTerminator = \r|\n|\r\n +InputCharacter = [^\r\n] + +WhiteSpace = {LineTerminator} | [ \t\f]+ + +/* comments */ +Comment = {TraditionalComment} | {EndOfLineComment} + +TraditionalComment = "!" [^\r\n!]* ( "!" | {LineTerminator} ) +EndOfLineComment = "--" {InputCharacter}* {LineTerminator}? + +/* identifiers */ +Identifier = [A-Za-z_][A-Za-z0-9\^_]* + +/* integer literals */ +DecIntegerLiteral = 0 | [1-9][0-9]* + +HexIntegerLiteral = 0 [xX] 0* {HexDigit} {1,8} +HexLongLiteral = 0 [xX] 0* {HexDigit} {1,16} [lL] +HexDigit = [0-9a-fA-F] + +OctIntegerLiteral = "%" [1-3]? {OctDigit} {1,15} +OctLongLiteral = 0+ 1? {OctDigit} {1,21} [lL] +OctDigit = [0-7] + +FixedLiteral = DecIntegerLiteral [fF] +DoubleLiteral = DecIntegerLiteral [dD] + +/* string and character literals */ +StringCharacter = [^\r\n\"\\] +SingleCharacter = [^\r\n\'\\] + +%% + + { + + /* keywords */ + "begin" | + "end" | + "struct" | + "fieldalign" | + "shared" | + "shared2" | + "literal" | + "for" | + "do" | + "while" | + "?page" | + "?section" { return token(TokenType.KEYWORD); } + + "int" | + "string" | + "int(32)" | + "fixed" | + "byte" | + "float" | + "filler" { return token(TokenType.TYPE); } + + + "(" | + ")" | + "{" | + "}" | + "[" | + "]" | + ";" | + "," | + "." | + "=" | + ">" | + "<" | + "!" | + "?" | + ":" | + ":=" | + "':='" | + "'=:'" | + "<>" | + "+" | + "-" | + "*" | + "/" | + "<<" | + ">>" { return token(TokenType.OPERATOR); } + + /* string literal */ + \"{StringCharacter}+\" { return token(TokenType.STRING); } + + /* character literal */ + \'{SingleCharacter}\' { return token(TokenType.STRING); } + + /* numeric literals */ + + {DecIntegerLiteral} | + + {HexIntegerLiteral} | + {HexLongLiteral} | + + {OctIntegerLiteral} | + {OctLongLiteral} | + + {FixedLiteral} | + {DoubleLiteral} { return token(TokenType.NUMBER); } + + /* comments */ + {Comment} { return token(TokenType.COMMENT); } + + /* whitespace */ + {WhiteSpace} { } + + /* identifiers */ + {Identifier} { return token(TokenType.IDENTIFIER); } +} + + +/* error fallback */ +.|\n { } +<> { return null; } + diff --git a/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/xhtml.flex b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/xhtml.flex new file mode 100644 index 0000000..8f63b52 --- /dev/null +++ b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/xhtml.flex @@ -0,0 +1,371 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package de.sciss.syntaxpane.lexers; + + +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +%% + +%public +%class XHTMLLexer +%extends DefaultJFlexLexer +%final +%unicode +%char +%type Token +%ignorecase + +%{ + /** + * Create an empty lexer, yyrset will be called later to reset and assign + * the reader + */ + public XHTMLLexer() { + super(); + } + + @Override + public int yychar() { + return yychar; + } + + private static final byte TAG_OPEN = 1; + private static final byte TAG_CLOSE = -1; + + private static final byte INSTR_OPEN = 2; + private static final byte INSTR_CLOSE = -2; + + private static final byte CDATA_OPEN = 3; + private static final byte CDATA_CLOSE = -3; + + private static final byte COMMENT_OPEN = 4; + private static final byte COMMENT_CLOSE = -4; +%} + +%xstate COMMENT, CDATA, TAG, INSTR, DOCTYPE + +/* main character classes */ + +/* white space */ +S = (\u0020 | \u0009 | \u000D | \u000A)+ + +/* characters */ +// Char = \u0009 | \u000A | \u000D | [\u0020-\uD7FF] | [\uE000-\uFFFD] | [\u10000-\u10FFFF] + +/* comments */ +CommentStart = "" + +NameStartChar = ":" | [A-Z] | "_" | [a-z] +NameChar = {NameStartChar} | "-" | "." | [0-9] | \u00B7 +Name = {NameStartChar} {NameChar}* + +/* XML Processing Instructions */ +InstrStart = "" + +DocTypeStart = "" + +/* Tags */ +OpenTagStart = "<" {Name} +OpenTagClose = "/>" +OpenTagEnd = ">" +CloseTag = "" + +/* attribute */ +Attribute = {Name} "=" + +/* HTML specifics */ +HTMLTagName = + "address" | + "applet" | + "area" | + "a" | + "b" | + "base" | + "basefont" | + "big" | + "blockquote" | + "body" | + "br" | + "caption" | + "center" | + "cite" | + "code" | + "dd" | + "dfn" | + "dir" | + "div" | + "dl" | + "dt" | + "font" | + "form" | + "h"[1-6] | + "head" | + "hr" | + "html" | + "img" | + "input" | + "isindex" | + "kbd" | + "li" | + "link" | + "LINK" | + "map" | + "META" | + "menu" | + "meta" | + "ol" | + "option" | + "param" | + "pre" | + "p" | + "samp" | + "span" | + "select" | + "small" | + "strike" | + "sub" | + "sup" | + "table" | + "td" | + "textarea" | + "th" | + "title" | + "tr" | + "tt" | + "ul" | + "var" | + "xmp" | + "script" | + "noscript" | + "style" + +HTMLAttrName = + "action" | + "align" | + "alink" | + "alt" | + "archive" | + "background" | + "bgcolor" | + "border" | + "bordercolor" | + "cellpadding" | + "cellspacing" | + "checked" | + "class" | + "clear" | + "code" | + "codebase" | + "color" | + "cols" | + "colspan" | + "content" | + "coords" | + "enctype" | + "face" | + "gutter" | + "height" | + "hspace" | + "href" | + "id" | + "link" | + "lowsrc" | + "marginheight" | + "marginwidth" | + "maxlength" | + "method" | + "name" | + "prompt" | + "rel" | + "rev" | + "rows" | + "rowspan" | + "scrolling" | + "selected" | + "shape" | + "size" | + "src" | + "start" | + "target" | + "text" | + "type" | + "url" | + "usemap" | + "ismap" | + "valign" | + "value" | + "vlink" | + "vspace" | + "width" | + "wrap" | + "abbr" | + "accept" | + "accesskey" | + "axis" | + "char" | + "charoff" | + "charset" | + "cite" | + "classid" | + "codetype" | + "compact" | + "data" | + "datetime" | + "declare" | + "defer" | + "dir" | + "disabled" | + "for" | + "frame" | + "headers" | + "hreflang" | + "lang" | + "language" | + "longdesc" | + "multiple" | + "nohref" | + "nowrap" | + "object" | + "profile" | + "readonly" | + "rules" | + "scheme" | + "scope" | + "span" | + "standby" | + "style" | + "summary" | + "tabindex" | + "valuetype" | + "version" + +HTMLOpenTagStart = "<" {HTMLTagName} +HTMLCloseTag = "" +HTMLAttribute = {HTMLAttrName} "=" + +/* string and character literals */ +DQuoteStringChar = [^\r\n\"] +SQuoteStringChar = [^\r\n\'] + +%% + + { + + "&" [a-z]+ ";" | + "&#" [:digit:]+ ";" { return token(TokenType.KEYWORD2); } + + {InstrStart} { + yybegin(INSTR); + return token(TokenType.TYPE2, INSTR_OPEN); + } + {DocTypeStart} { + yybegin(DOCTYPE); + return token(TokenType.TYPE2, INSTR_OPEN); + } + {HTMLOpenTagStart} { + yybegin(TAG); + return token(TokenType.KEYWORD2, TAG_OPEN); + } + {HTMLCloseTag} { return token(TokenType.KEYWORD2, TAG_CLOSE); } + {OpenTagStart} { + yybegin(TAG); + return token(TokenType.KEYWORD, TAG_OPEN); + } + {CloseTag} { return token(TokenType.KEYWORD, TAG_CLOSE); } + {CommentStart} { + yybegin(COMMENT); + return token(TokenType.COMMENT2, COMMENT_OPEN); + } + {CDataStart} { + yybegin(CDATA); + return token(TokenType.COMMENT2, CDATA_OPEN); + } +} + + { + {Attribute} { return token(TokenType.IDENTIFIER); } + + \"{DQuoteStringChar}*\" | + \'{SQuoteStringChar}*\' { return token(TokenType.STRING); } + + {InstrEnd} { + yybegin(YYINITIAL); + return token(TokenType.TYPE2, INSTR_CLOSE); + } +} + + { + [^>]* { } + + {OpenTagEnd} { + yybegin(YYINITIAL); + return token(TokenType.TYPE2, INSTR_CLOSE); + } +} + + { + {HTMLAttribute} { return token(TokenType.KEYWORD2); } + {Attribute} { return token(TokenType.IDENTIFIER); } + + \"{DQuoteStringChar}*\" | + \'{SQuoteStringChar}*\' { return token(TokenType.STRING); } + + + {OpenTagClose} { + yybegin(YYINITIAL); + return token(TokenType.KEYWORD, TAG_CLOSE); +} + + {OpenTagEnd} { + yybegin(YYINITIAL); + return token(TokenType.KEYWORD); + } +} + + { + {CommentEnd} { + yybegin(YYINITIAL); + return token(TokenType.COMMENT2, COMMENT_CLOSE); + } + ~{CommentEnd} { + yypushback(3); + return token(TokenType.COMMENT); + } +} + + { + {CDataEnd} { + yybegin(YYINITIAL); + return token(TokenType.COMMENT2, CDATA_CLOSE); + } + ~{CDataEnd} { + yypushback(3); + return token(TokenType.COMMENT); + } +} + + { +/* error fallback */ + .|\n { } + <> { return null; } +} diff --git a/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/xml.flex b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/xml.flex new file mode 100644 index 0000000..86a0a9e --- /dev/null +++ b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/xml.flex @@ -0,0 +1,196 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package de.sciss.syntaxpane.lexers; + + +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +%% + +%public +%class XmlLexer +%extends DefaultJFlexLexer +%final +%unicode +%char +%type Token + +%{ + /** + * Create an empty lexer, yyrset will be called later to reset and assign + * the reader + */ + public XmlLexer() { + super(); + } + + @Override + public int yychar() { + return yychar; + } + + private static final byte TAG_OPEN = 1; + private static final byte TAG_CLOSE = -1; + + private static final byte INSTR_OPEN = 2; + private static final byte INSTR_CLOSE = -2; + + private static final byte CDATA_OPEN = 3; + private static final byte CDATA_CLOSE = -3; + + private static final byte COMMENT_OPEN = 4; + private static final byte COMMENT_CLOSE = -4; +%} + +%xstate COMMENT, CDATA, TAG, INSTR + +/* main character classes */ + +/* white space */ +S = (\u0020 | \u0009 | \u000D | \u000A)+ + +/* characters */ + +Char = \u0009 | \u000A | \u000D | [\u0020-\uD7FF] | [\uE000-\uFFFD] | [\u10000-\u10FFFF] + +/* comments */ +CommentStart = "" + +NameStartChar = ":" | [A-Z] | "_" | [a-z] +NameStartCharUnicode = [\u00C0-\u00D6] | + [\u00D8-\u00F6] | + [\u00F8-\u02FF] | + [\u0370-\u037D] | + [\u037F-\u1FFF] | + [\u200C-\u200D] | + [\u2070-\u218F] | + [\u2C00-\u2FEF] | + [\u3001-\uD7FF] | + [\uF900-\uFDCF] | + [\uFDF0-\uFFFD] | + [\u10000-\uEFFFF] + +NameChar = {NameStartChar} | "-" | "." | [0-9] | \u00B7 +NameCharUnicode = [\u0300-\u036F] | [\u0203F-\u2040] +Name = {NameStartChar} {NameChar}* +NameUnicode = ({NameStartChar}|{NameStartCharUnicode}) ({NameChar}|{NameCharUnicode})* + +/* XML Processing Instructions */ +InstrStart = "" + +/* CDATA */ +CDataStart = "" + +/* Tags */ +OpenTagStart = "<" {Name} +OpenTagClose = "/>" +OpenTagEnd = ">" + +CloseTag = "" + +/* attribute */ +Attribute = {Name} "=" + +/* string and character literals */ +DQuoteStringChar = [^\r\n\"] +SQuoteStringChar = [^\r\n\'] + +%% + + { + + "&" [a-z]+ ";" | + "&#" [:digit:]+ ";" { return token(TokenType.KEYWORD2); } + + {InstrStart} { + yybegin(INSTR); + return token(TokenType.TYPE2, INSTR_OPEN); + } + {OpenTagStart} { + yybegin(TAG); + return token(TokenType.TYPE, TAG_OPEN); + } + {CloseTag} { return token(TokenType.TYPE, TAG_CLOSE); } + {CommentStart} { + yybegin(COMMENT); + return token(TokenType.COMMENT2, COMMENT_OPEN); + } + {CDataStart} { + yybegin(CDATA); + return token(TokenType.COMMENT2, CDATA_OPEN); + } +} + + { + {Attribute} { return token(TokenType.IDENTIFIER); } + + \"{DQuoteStringChar}*\" | + \'{SQuoteStringChar}*\' { return token(TokenType.STRING); } + + {InstrEnd} { + yybegin(YYINITIAL); + return token(TokenType.TYPE2, INSTR_CLOSE); + } + } + + { + {Attribute} { return token(TokenType.IDENTIFIER); } + + \"{DQuoteStringChar}*\" | + \'{SQuoteStringChar}*\' { return token(TokenType.STRING); } + + + {OpenTagClose} { + yybegin(YYINITIAL); + return token(TokenType.TYPE, TAG_CLOSE); +} + + {OpenTagEnd} { + yybegin(YYINITIAL); + return token(TokenType.TYPE); + } +} + + { + {CommentEnd} { + yybegin(YYINITIAL); + return token(TokenType.COMMENT2, COMMENT_CLOSE); + } + ~{CommentEnd} { + yypushback(3); + return token(TokenType.COMMENT); + } +} + + { + {CDataEnd} { + yybegin(YYINITIAL); + return token(TokenType.COMMENT2, CDATA_CLOSE); + } + ~{CDataEnd} { + yypushback(3); + return token(TokenType.COMMENT); + } +} + + { +/* error fallback */ + .|\n { } + <> { return null; } +} diff --git a/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/xpath.flex b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/xpath.flex new file mode 100644 index 0000000..246ea2c --- /dev/null +++ b/SyntaxPane/src/main/jflex/de/sciss/syntaxpane/lexers/xpath.flex @@ -0,0 +1,266 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * This flex file originally donated to the project by HeyChinaski + * + */ + +package de.sciss.syntaxpane.lexers; + +import de.sciss.syntaxpane.Token; +import de.sciss.syntaxpane.TokenType; + +%% + +%public +%class XPathLexer +%extends DefaultJFlexLexer +%final +%unicode +%char +%type Token + + +%{ + /** + * Create an empty lexer, yyrset will be called later to reset and assign + * the reader + */ + public XPathLexer() { + super(); + } + + @Override + public int yychar() { + return yychar; + } + + private static final byte PARAN = 1; + private static final byte BRACKET = 2; + private static final byte CURLY = 3; + +%} + +Digits = [0-9]+ +Letter = {BaseChar} | {Ideographic} +BaseChar = [\u0041-\u005A] | [\u0061-\u007A] | [\u00C0-\u00D6] | [\u00D8-\u00F6] | [\u00F8-\u00FF] | [\u0100-\u0131] | [\u0134-\u013E] | [\u0141-\u0148] | [\u014A-\u017E] | [\u0180-\u01C3] | [\u01CD-\u01F0] | [\u01F4-\u01F5] | [\u01FA-\u0217] | [\u0250-\u02A8] | [\u02BB-\u02C1] | \u0386 | [\u0388-\u038A] | \u038C | [\u038E-\u03A1] | [\u03A3-\u03CE] | [\u03D0-\u03D6] | \u03DA | \u03DC | \u03DE | \u03E0 | [\u03E2-\u03F3] | [\u0401-\u040C] | [\u040E-\u044F] | [\u0451-\u045C] | [\u045E-\u0481] | [\u0490-\u04C4] | [\u04C7-\u04C8] | [\u04CB-\u04CC] | [\u04D0-\u04EB] | [\u04EE-\u04F5] | [\u04F8-\u04F9] | [\u0531-\u0556] | \u0559 | [\u0561-\u0586] | [\u05D0-\u05EA] | [\u05F0-\u05F2] | [\u0621-\u063A] | [\u0641-\u064A] | [\u0671-\u06B7] | [\u06BA-\u06BE] | [\u06C0-\u06CE] | [\u06D0-\u06D3] | \u06D5 | [\u06E5-\u06E6] | [\u0905-\u0939] | \u093D | [\u0958-\u0961] | [\u0985-\u098C] | [\u098F-\u0990] | [\u0993-\u09A8] | [\u09AA-\u09B0] | \u09B2 | [\u09B6-\u09B9] | [\u09DC-\u09DD] | [\u09DF-\u09E1] | [\u09F0-\u09F1] | [\u0A05-\u0A0A] | [\u0A0F-\u0A10] | [\u0A13-\u0A28] | [\u0A2A-\u0A30] | [\u0A32-\u0A33] | [\u0A35-\u0A36] | [\u0A38-\u0A39] | [\u0A59-\u0A5C] | \u0A5E | [\u0A72-\u0A74] | [\u0A85-\u0A8B] | \u0A8D | [\u0A8F-\u0A91] | [\u0A93-\u0AA8] | [\u0AAA-\u0AB0] | [\u0AB2-\u0AB3] | [\u0AB5-\u0AB9] | \u0ABD | \u0AE0 | [\u0B05-\u0B0C] | [\u0B0F-\u0B10] | [\u0B13-\u0B28] | [\u0B2A-\u0B30] | [\u0B32-\u0B33] | [\u0B36-\u0B39] | \u0B3D | [\u0B5C-\u0B5D] | [\u0B5F-\u0B61] | [\u0B85-\u0B8A] | [\u0B8E-\u0B90] | [\u0B92-\u0B95] | [\u0B99-\u0B9A] | \u0B9C | [\u0B9E-\u0B9F] | [\u0BA3-\u0BA4] | [\u0BA8-\u0BAA] | [\u0BAE-\u0BB5] | [\u0BB7-\u0BB9] | [\u0C05-\u0C0C] | [\u0C0E-\u0C10] | [\u0C12-\u0C28] | [\u0C2A-\u0C33] | [\u0C35-\u0C39] | [\u0C60-\u0C61] | [\u0C85-\u0C8C] | [\u0C8E-\u0C90] | [\u0C92-\u0CA8] | [\u0CAA-\u0CB3] | [\u0CB5-\u0CB9] | \u0CDE | [\u0CE0-\u0CE1] | [\u0D05-\u0D0C] | [\u0D0E-\u0D10] | [\u0D12-\u0D28] | [\u0D2A-\u0D39] | [\u0D60-\u0D61] | [\u0E01-\u0E2E] | \u0E30 | [\u0E32-\u0E33] | [\u0E40-\u0E45] | [\u0E81-\u0E82] | \u0E84 | [\u0E87-\u0E88] | \u0E8A | \u0E8D | [\u0E94-\u0E97] | [\u0E99-\u0E9F] | [\u0EA1-\u0EA3] | \u0EA5 | \u0EA7 | [\u0EAA-\u0EAB] | [\u0EAD-\u0EAE] | \u0EB0 | [\u0EB2-\u0EB3] | \u0EBD | [\u0EC0-\u0EC4] | [\u0F40-\u0F47] | [\u0F49-\u0F69] | [\u10A0-\u10C5] | [\u10D0-\u10F6] | \u1100 | [\u1102-\u1103] | [\u1105-\u1107] | \u1109 | [\u110B-\u110C] | [\u110E-\u1112] | \u113C | \u113E | \u1140 | \u114C | \u114E | \u1150 | [\u1154-\u1155] | \u1159 | [\u115F-\u1161] | \u1163 | \u1165 | \u1167 | \u1169 | [\u116D-\u116E] | [\u1172-\u1173] | \u1175 | \u119E | \u11A8 | \u11AB | [\u11AE-\u11AF] | [\u11B7-\u11B8] | \u11BA | [\u11BC-\u11C2] | \u11EB | \u11F0 | \u11F9 | [\u1E00-\u1E9B] | [\u1EA0-\u1EF9] | [\u1F00-\u1F15] | [\u1F18-\u1F1D] | [\u1F20-\u1F45] | [\u1F48-\u1F4D] | [\u1F50-\u1F57] | \u1F59 | \u1F5B | \u1F5D | [\u1F5F-\u1F7D] | [\u1F80-\u1FB4] | [\u1FB6-\u1FBC] | \u1FBE | [\u1FC2-\u1FC4] | [\u1FC6-\u1FCC] | [\u1FD0-\u1FD3] | [\u1FD6-\u1FDB] | [\u1FE0-\u1FEC] | [\u1FF2-\u1FF4] | [\u1FF6-\u1FFC] | \u2126 | [\u212A-\u212B] | \u212E | [\u2180-\u2182] | [\u3041-\u3094] | [\u30A1-\u30FA] | [\u3105-\u312C] | [\uAC00-\uD7A3] +Ideographic = [\u4E00-\u9FA5] | \u3007 | [\u3021-\u3029] +NCNameStartChar = {Letter} | "_" +NameStartCharMinusColon = [A-Z] | "_" | [a-z] | [\uC0-\uD6] | [\uD8-\uF6] | [\uF8-\u2FF] | [\u370-\u37D] | [\u37F-\u1FFF] | [\u200C-\u200D] | [\u2070-\u218F] | [\u2C00-\u2FEF] | [\u3001-\uD7FF] | [\uF900-\uFDCF] | [\uFDF0-\uFFFD] +NCNameChar = {NameStartCharMinusColon} | "-" | "." | [0-9] | \uB7 | [\u0300-\u036F] | [\u203F-\u2040] +NCName = {NCNameStartChar} {NCNameChar}* +LocalPart = {NCName} +UnprefixedName = {LocalPart} +Prefix = {NCName} +PrefixedName = {Prefix} ":" {LocalPart} +QName = {PrefixedName} | {UnprefixedName} +NameTest = "*" | {NCName} ":" "*" | {QName} +VariableReference = "$" {QName} +LineTerminator = \r|\n|\r\n + +NodeType = "comment" + | "text" + | "processing-instruction" + | "node" + +OperatorName = "and" | "or" | "mod" | "div" + +Operator = {OperatorName} | "*" | "/" | "//" | "|" | "+" | "-" | "=" | "!=" | "<" | "<=" | ">" | ">=" + +FunctionName = {QName} + +XPathFunction = "default" + | "node-name" + | "nilled" + | "data" + | "base-uri" + | "document-uri" + | "error" + | "trace" + | "number" + | "abs" + | "ceiling" + | "floor" + | "round" + | "round-half-to-even" + | "string" + | "codepoints-to-string" + | "string-to-codepoints" + | "codepoint-equal" + | "compare" + | "concat" + | "string-join" + | "substring" + | "string-length" + | "normalize-space" + | "normalize-unicode" + | "upper-case" + | "lower-case" + | "translate" + | "escape-uri" + | "contains" + | "starts-with" + | "ends-with" + | "substring-before" + | "substring-after" + | "matches" + | "replace" + | "tokenize" + | "resolve-uri" + | "boolean" + | "not" + | "true" + | "false" + | "dateTime" + | "years-from-duration" + | "months-from-duration" + | "days-from-duration" + | "hours-from-duration" + | "minutes-from-duration" + | "seconds-from-duration" + | "year-from-dateTime" + | "month-from-dateTime" + | "day-from-dateTime" + | "hours-from-dateTime" + | "minutes-from-dateTime" + | "seconds-from-dateTime" + | "timezone-from-dateTime" + | "year-from-date" + | "month-from-date" + | "day-from-date" + | "timezone-from-date" + | "hours-from-time" + | "minutes-from-time" + | "seconds-from-time" + | "timezone-from-time" + | "adjust-dateTime-to-timezone" + | "adjust-date-to-timezone" + | "adjust-time-to-timezone" + | "QName" + | "local-name-from-QName" + | "namespace-uri-from-QName" + | "namespace-uri-for-prefix" + | "in-scope-prefixes" + | "resolve-QName" + | "name" + | "local-name" + | "namespace-uri" + | "lang" + | "root" + | "index-of" + | "remove" + | "empty" + | "exists" + | "distinct-values" + | "insert-before" + | "reverse" + | "subsequence" + | "unordered" + | "zero-or-one" + | "one-or-more" + | "exactly-one" + | "deep-equal" + | "count" + | "avg" + | "max" + | "min" + | "sum" + | "id" + | "idref" + | "doc" + | "doc-available" + | "collection" + | "position" + | "last" + | "current-dateTime" + | "current-date" + | "current-time" + | "implicit-timezone" + | "default-collation" + | "static-base-uri" + +AxisName = "ancestor" + | "ancestor-or-self" + | "attribute" + | "child" + | "descendant" + | "descendant-or-self" + | "following" + | "following-sibling" + | "namespace" + | "parent" + | "preceding" + | "preceding-sibling" + | "self" + +Number = {Digits} | {Digits} "." {Digits} + +S = [\u20] | [\u9] | [\uD] | [\uA] + +%state STRING_DOUBLE, STRING_SINGLE + +%% + + { + {VariableReference} { return token(TokenType.IDENTIFIER); } + {Number} { return token(TokenType.NUMBER); } + {AxisName} { return token(TokenType.TYPE); } + "(" { return token(TokenType.OPERATOR, PARAN); } + ")" { return token(TokenType.OPERATOR, -PARAN); } + "{" { return token(TokenType.OPERATOR, CURLY); } + "}" { return token(TokenType.OPERATOR, -CURLY); } + "[" { return token(TokenType.OPERATOR, BRACKET); } + "]" { return token(TokenType.OPERATOR, -BRACKET); } + "." | ".." | "@" | "," | "::" { return token(TokenType.OPERATOR); } + {Operator} { return token(TokenType.OPERATOR); } + {NodeType} { return token(TokenType.KEYWORD); } + {XPathFunction} { return token(TokenType.KEYWORD2); } + {FunctionName} { return token(TokenType.IDENTIFIER); } + {NameTest} { return token(TokenType.IDENTIFIER); } + + /* string literal */ + \" { + yybegin(STRING_DOUBLE); + tokenStart = yychar; + tokenLength = 1; + } + + /* string literal */ + \' { + yybegin(STRING_SINGLE); + tokenStart = yychar; + tokenLength = 1; + } + ":" | {S} | "\"" {} + . | {LineTerminator} { /* skip */ } +} + + { + \" { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } + + [^\"] { tokenLength += yylength(); } +} + + { + \' { + yybegin(YYINITIAL); + // length also includes the trailing quote + return token(TokenType.STRING, tokenStart, tokenLength + 1); + } + + [^\'] { tokenLength += yylength(); } +} diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/Bundle.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/Bundle.properties new file mode 100644 index 0000000..c8ae153 --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/Bundle.properties @@ -0,0 +1,44 @@ +# To change this template, choose Tools | Templates +# and open the template in the editor. + +SyntaxTester.title=SyntaxPane Tester +SyntaxTester.lblCaretPos.text=Caret Position +SyntaxTester.lblToken.text=Token under cursor +SyntaxTester.jEdtTest.contentType= +NO_TOKEN_AT_CURSOR=NO Token at cursor + +HTMLPreviewFrame.title=HTML Preview +HTMLPreviewFrame.jEdtHtml.contentType=text/html +QuickFindDialog.jChkWrap.text=Wrap +QuickFindDialog.jChkRegExp.text=Express\u00e3o regular +QuickFindDialog.jChkIgnoreCase.text=Ignorar mai\u00fasculas e min\u00fasculas +QuickFindDialog.jLabel1.text=Pesquisa R\u00e1pida +QuickFindDialog.NotFound=N\u00e3o encontrado +ReplaceDialog.jChkRegex.text=Express\u00e3o regular +ReplaceDialog.jChkIgnoreCase.text=Ignorar mai\u00fasculas e min\u00fasculas +ReplaceDialog.jLblReplace.text=Substituir +ReplaceDialog.jTglHighlight.text=Highlight +ReplaceDialog.jBtnReplaceAll.text=Substituir tudo +ReplaceDialog.jBtnPrev.text=Anterior +ReplaceDialog.jChkWrap.toolTipText=Wrap to beginning when end is reached +ReplaceDialog.jChkWrap.text=Wrap +ReplaceDialog.title=Encontrar e substituir +ReplaceDialog.jBtnNext.text=Pr\u00f3ximo +ReplaceDialog.jLblFind.text=Encontrar +ReplaceDialog.jBtnReplace.text=Substituir +ShowAbbsDialog.title=Abbreviations +# To change this template, choose Tools | Templates +# and open the template in the editor. +GotoLineDialog.title=Ir para a linha +GotoLineDialog.jBtnOk.text=IR + +DocumentSearchData.SearchStringNotFound=Search String {0} not found +DocumentSearchData.Find=Find +ScriptAction.NoScriptConfigured=Action does not have script function configured +ScriptAction.ErrorInScript=Error in Script +ScriptAction.NoScriptFoundIn=No script is found in: +ScriptRunnerAction.ErrorExecutingScript=Error executing script:\\n +ScriptRunnerAction.ScriptError=Script Error +ScriptRunnerAction.ScriptEngineNotFound=Script Engine for [{0}] not found. Disable this Action? +ShowAbbsAction.NoAbbsForType=No Abbreviations exist for this content type + diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/Bundle_de.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/Bundle_de.properties new file mode 100644 index 0000000..c60bf43 --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/Bundle_de.properties @@ -0,0 +1,40 @@ +# To change this template, choose Tools | Templates +# and open the template in the editor. + +SyntaxTester.title=SyntaxPane Tester +SyntaxTester.lblCaretPos.text=Caret-Position +SyntaxTester.lblToken.text=Token unter dem Cursor +SyntaxTester.jEdtTest.contentType= +NO_TOKEN_AT_CURSOR=Kein Token am Cursor + +GotoLineDialog.title=Gehe zu Zeile +GotoLineDialog.jBtnOk.text=Ok +HTMLPreviewFrame.title=HTML-Vorschau +HTMLPreviewFrame.jEdtHtml.contentType=text/html +QuickFindDialog.jChkWrap.text=Ganzes Dokument +QuickFindDialog.jChkRegExp.text=Regex +QuickFindDialog.jChkIgnoreCase.text=Gro/Klein ignorieren +QuickFindDialog.jLabel1.text=Schnellsuche +QuickFindDialog.NotFound=nicht gefunden +ReplaceDialog.jChkRegex.text=Regulrer Ausdruck +ReplaceDialog.jChkIgnoreCase.text=Gro/Klein ignorieren +ReplaceDialog.jLblReplace.text=Ersetzen +ReplaceDialog.jTglHighlight.text=Hervorheben +ReplaceDialog.jBtnReplaceAll.text=Alle Ersetzen +ReplaceDialog.jBtnPrev.text=Zurck +ReplaceDialog.jChkWrap.toolTipText=Von vorne weitersuchen wenn das Ende erreicht ist +ReplaceDialog.jChkWrap.text=Ganzes Dokument +ReplaceDialog.title=Suchen und Ersetzen +ReplaceDialog.jBtnNext.text=Weiter +ReplaceDialog.jLblFind.text=Suchen +ReplaceDialog.jBtnReplace.text=Ersetzen + +DocumentSearchData.SearchStringNotFound=Suchbegriff {0} nicht gefunden +DocumentSearchData.Find=Suchen +ScriptAction.NoScriptConfigured=Aktion hat kein Skript zugeordnet +ScriptAction.ErrorInScript=Fehler im Skript +ScriptAction.NoScriptFoundIn=Kein Skript gefunden in: +ScriptRunnerAction.ErrorExecutingScript=Fehler bei Skriptausfhrung:\\n +ScriptRunnerAction.ScriptError=Skript-Fehler +ScriptRunnerAction.ScriptEngineNotFound=Skript-Engine fr [{0}] nicht gefunden. Aktion deaktivieren? +ShowAbbsAction.NoAbbsForType=Es gibt keine Abkrzungen fr diesen Content-Type diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/defaultsyntaxkit/config.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/defaultsyntaxkit/config.properties new file mode 100644 index 0000000..d99b5a2 --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/defaultsyntaxkit/config.properties @@ -0,0 +1,155 @@ +# +# Main Configuration of SyntaxPane +# +# ----------------------------------------------------------------------------- +# +# These will be used by all kits, unless the same key is used for a specific +# kit, in which case the specific will be used: +# +# These are the componets that will be installed be default for any kit, +# unless specified otherwise +Components = de.sciss.syntaxpane.components.PairsMarker, \ + de.sciss.syntaxpane.components.LineNumbersRuler +# This is the color to highlight tokens whenever the cursor is on them +TokenMarker.Color = 0xffeeaa +# Colors for PairMarkers +PairMarker.Color = 0xffbb77 +# +# Right Margin for LineNumbers border in pixels, Default = 5 +LineNumbers.RightMargin = 7 +# Foreground for line numbers, Default = Black +LineNumbers.Foreground = 0x333300 +# Background for line numbers, Default = White +LineNumbers.Background = 0xeeeeff +# Color to use for highlighting current line background +LineNumbers.CurrentBack = 0xccccee +# Default color for the Caret, Black +CaretColor = 0x000000 +# +# Actions: +# The key is of the format: +# Actions.NAME = class [, key]* +# where NAME is the name to be given to the Action. Any String [alpha or -] is valid. +# class is the fully qualified class name of the SyntaxAction class. +# Starting from 0.9.5, each Action will instantiate a new class. If you need +# to share some data between the Actions, then add a Property to the Document +# Key is the keyboard key to map it to as specified by +# KeyStroke.getKeyStroge(String key). You may have zero or more key bindings +# to an Action. The last Key bound will be shown in the popup menu if enabled. +# You can also specify the "menu" modifier, and it will be mapped to the proper menu +# key depending on the running platform (CTRL on Windows and ALT on Mac) +# +# Each fully qualified key can also be used as a prefix for configuring the Action +# Action.NAME.MenuText = The description to use in menus (This sets the Action NAME property) +# Action.NAME.SmallIcon = the smallicon to use. The default is to look for an icon +# with the same name as the action + ".png". This sets the Actions SMALL_ICON property +# Action.NAME.Tooltip = Tooltip displayed for menu. This sets the +# Actions SHORT_DESCRIPTION property +Action.quick-find = de.sciss.syntaxpane.actions.QuickFindAction, menu F +Action.find = de.sciss.syntaxpane.actions.FindReplaceAction, control H +Action.find.MenuText = Find +Action.find.ToolTip= Display Find And Replace Dialog +Action.find-next = de.sciss.syntaxpane.actions.FindNextAction, F3 +Action.find-next.MenuText = Find Next +Action.find-next.ToolTip = Repeat Last Find +Action.goto-line = de.sciss.syntaxpane.actions.GotoLineAction, menu G +Action.goto-line.MenuText = Goto Line Number +Action.goto-line.ToolTip = Goto Line Number +Action.indent = de.sciss.syntaxpane.actions.IndentAction, TAB +Action.indent.MenuText = Indent +Action.indent.Abbreviations = ${class_path}/abbreviations.properties +Action.unindent = de.sciss.syntaxpane.actions.UnindentAction, shift TAB +Action.unindent.MenuText = Un-Indent +Action.jindent = de.sciss.syntaxpane.actions.JIndentAction, ENTER +Action.undo = de.sciss.syntaxpane.actions.UndoAction, menu Z +Action.undo.MenuText = Undo +Action.redo = de.sciss.syntaxpane.actions.RedoAction, menu Y +Action.redo.LinuxKey = control shift Z +Action.redo.MacKey = meta shift Z +Action.redo.MenuText = Redo +Action.delete-lines = de.sciss.syntaxpane.actions.DeleteLinesAction, control E +Action.delete-lines.MenuText = Delete Line(s) +Action.dup-lines-up = de.sciss.syntaxpane.actions.DuplicateLinesAction, shift control UP +Action.dup-lines-up.MenuText = Duplicate Lines Above +Action.dup-lines-down = de.sciss.syntaxpane.actions.DuplicateLinesAction, shift control DOWN +Action.dup-lines-down.MenuText = Duplicate Lines Below +Action.toggle-lines = de.sciss.syntaxpane.actions.ToggleComponentAction, control F2 +Action.toggle-lines.Component = de.sciss.syntaxpane.components.LineNumbersRuler +Action.toggle-lines.MenuText = Toggle Line Numbers +Action.toggle-comments = de.sciss.syntaxpane.actions.ToggleCommentsAction, menu SLASH +Action.toggle-comments.MenuText = Toggle Comments +Action.toggle-comments.SmallIcon = comment.png +Action.jump-to-pair = de.sciss.syntaxpane.actions.JumpToPairAction, control OPEN_BRACKET +Action.jump-to-pair.MenuText = Jump to Pair +Action.complete-word = de.sciss.syntaxpane.actions.CompleteWordAction, control K +Action.complete-word.MenuText = Complete Word +Action.smart-home = de.sciss.syntaxpane.actions.SmartHomeAction, HOME +Action.smart-home-select = de.sciss.syntaxpane.actions.SmartHomeSelectAction, shift HOME +Action.show-abbs = de.sciss.syntaxpane.actions.ShowAbbsAction, F8 +Action.show-abbs.MenuText = Show abbreviations +Action.show-abbs.ToolTip = Show abbreviations +# +# These configure the Default Actions provided by DefaultEditorKit for popup menus +DefaultAction.copy-to-clipboard.MenuText = Copy +DefaultAction.cut-to-clipboard.MenuText = Cut +DefaultAction.paste-from-clipboard.MenuText = Paste +DefaultAction.select-all.MenuText = Select All +# +# View configuration: +# This controls how text is anti-aliased on the editor control: +# see the RenderingHints.VALUE_TEXT_ANTIALIAS.... for details +# DEFAULT: use the JRE default (default value) +# ON: set to on, let the JRE determine best method for the display +# OFF: no AA +# GASP: used on GTK +# HBGR: +# HRGB: +# VBGR: +# VRGM +TextAA = ON +DEFAULT_EDIT_MENU= \ + cut-to-clipboard , \ + copy-to-clipboard , \ + paste-from-clipboard , \ + - , \ + select-all , \ + - , \ + undo , \ + redo , \ + - , \ + find , \ + find-next , \ + goto-line , \ + jump-to-pair , \ + - , \ + complete-word , \ + show-abbs + +# Default Popup Menu +PopupMenu = \ + ${DEFAULT_EDIT_MENU} , \ + - , \ + goto-line , \ + toggle-comments +# +# These are the various Attributes for each TokenType. +# The keys of this map are the TokenType Strings, and the values are: +# color (hex, or integer), Font.Style attribute +# Style is one of: 0 = plain, 1=bold, 2=italic, 3=bold/italic +Style.OPERATOR = 0x000000, 0 +Style.DELIMITER = 0x000000, 1 +Style.KEYWORD = 0x3333ee, 0 +Style.KEYWORD2 = 0x3333ee, 3 +Style.TYPE = 0x000000, 2 +Style.TYPE2 = 0x000000, 1 +Style.TYPE3 = 0x000000, 3 +Style.STRING = 0xcc6600, 0 +Style.STRING2 = 0xcc6600, 1 +Style.NUMBER = 0x999933, 1 +Style.REGEX = 0xcc6600, 0 +Style.IDENTIFIER = 0x000000, 0 +Style.COMMENT = 0x339933, 2 +Style.COMMENT2 = 0x339933, 3 +Style.DEFAULT = 0x000000, 0 +Style.WARNING = 0xCC0000, 0 +Style.ERROR = 0xCC0000, 3 \ No newline at end of file diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/defaultsyntaxkit/config_de.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/defaultsyntaxkit/config_de.properties new file mode 100644 index 0000000..2f20071 --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/defaultsyntaxkit/config_de.properties @@ -0,0 +1,30 @@ +# +# German localization ovverrides for +# Main Configuration of SyntaxPane +# +# Actions: +Action.find.MenuText = Suchen +Action.find.ToolTip= Suchen und Ersetzen Dialog anzeigen +Action.find-next.MenuText = Weitersuchen +Action.find-next.ToolTip = Letzte Suche erneut ausführen +Action.goto-line.MenuText = Gehe zu Zeilennummer +Action.goto-line.ToolTip = Gehe zu Zeilennummer +Action.indent.MenuText = Einrücken +Action.unindent.MenuText = Ausrücken +Action.undo.MenuText = Rückgängig +Action.redo.MenuText = Wiederherstellen +Action.delete-lines.MenuText = Zeile(n) löschen +Action.dup-lines-up.MenuText = Zeilen oben verdoppeln +Action.dup-lines-down.MenuText = Zeilen unten verdoppeln +Action.toggle-lines.MenuText = Zeilennummern an-/abschalten +Action.toggle-comments.MenuText = Kommentare umschalten +Action.jump-to-pair.MenuText = Zum Paar springen +Action.complete-word.MenuText = Wort vervollständigen +Action.show-abbs.MenuText = Abkürzungen anzeigen +Action.show-abbs.ToolTip = Abkürzungen anzeigen +# +# These configure the Default Actions provided by DefaultEditorKit for popup menus +DefaultAction.copy-to-clipboard.MenuText = Kopieren +DefaultAction.cut-to-clipboard.MenuText = Ausschneiden +DefaultAction.paste-from-clipboard.MenuText = Einfügen +DefaultAction.select-all.MenuText = Alles auswählen diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/annotation_type.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/annotation_type.png new file mode 100644 index 0000000..52ff9d6 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/annotation_type.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/class.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/class.png new file mode 100644 index 0000000..220e6f3 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/class.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/constructor.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/constructor.png new file mode 100644 index 0000000..fd95f9d Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/constructor.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/constructor_private.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/constructor_private.png new file mode 100644 index 0000000..eb58f0a Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/constructor_private.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/constructor_protected.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/constructor_protected.png new file mode 100644 index 0000000..006e905 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/constructor_protected.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/field.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/field.png new file mode 100644 index 0000000..06a86fb Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/field.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/field_private.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/field_private.png new file mode 100644 index 0000000..1d0ee3e Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/field_private.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/field_protected.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/field_protected.png new file mode 100644 index 0000000..589610c Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/field_protected.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/field_static.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/field_static.png new file mode 100644 index 0000000..3239478 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/field_static.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/field_static_private.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/field_static_private.png new file mode 100644 index 0000000..3b1c00a Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/field_static_private.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/field_static_protected.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/field_static_protected.png new file mode 100644 index 0000000..09cb7fb Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/field_static_protected.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/method.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/method.png new file mode 100644 index 0000000..7be8a37 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/method.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/method_private.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/method_private.png new file mode 100644 index 0000000..5bbdd17 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/method_private.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/method_protected.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/method_protected.png new file mode 100644 index 0000000..325ed18 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/method_protected.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/method_static.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/method_static.png new file mode 100644 index 0000000..414e584 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/method_static.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/method_static_private.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/method_static_private.png new file mode 100644 index 0000000..0a5e4b1 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/method_static_private.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/method_static_protected.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/method_static_protected.png new file mode 100644 index 0000000..e5f9c9b Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/completions/method_static_protected.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/Thumbs.db b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/Thumbs.db new file mode 100644 index 0000000..1b208f7 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/Thumbs.db differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/comment.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/comment.png new file mode 100644 index 0000000..fb1aa5c Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/comment.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/complete-word.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/complete-word.png new file mode 100644 index 0000000..32943e9 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/complete-word.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/completions.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/completions.png new file mode 100644 index 0000000..8851b99 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/completions.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/copy-to-clipboard.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/copy-to-clipboard.png new file mode 100644 index 0000000..8dd48c4 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/copy-to-clipboard.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/cut-to-clipboard.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/cut-to-clipboard.png new file mode 100644 index 0000000..dc9eb9a Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/cut-to-clipboard.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/edit-find-replace-all.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/edit-find-replace-all.png new file mode 100644 index 0000000..8bf48cb Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/edit-find-replace-all.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/edit-find-replace.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/edit-find-replace.png new file mode 100644 index 0000000..6edbef6 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/edit-find-replace.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/find-next.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/find-next.png new file mode 100644 index 0000000..4d6b125 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/find-next.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/find.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/find.png new file mode 100644 index 0000000..d072d3c Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/find.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/go-down.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/go-down.png new file mode 100644 index 0000000..3dd7fcc Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/go-down.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/go-next.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/go-next.png new file mode 100644 index 0000000..6ef8de7 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/go-next.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/go-previous.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/go-previous.png new file mode 100644 index 0000000..659cd90 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/go-previous.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/go-up.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/go-up.png new file mode 100644 index 0000000..fa9a7d7 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/go-up.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/goto-line.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/goto-line.png new file mode 100644 index 0000000..684c247 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/goto-line.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/highlight.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/highlight.png new file mode 100644 index 0000000..fd9e6ec Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/highlight.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/html-preview.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/html-preview.png new file mode 100644 index 0000000..ac5957a Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/html-preview.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/indent.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/indent.png new file mode 100644 index 0000000..6bad6bb Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/indent.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/jump-to-pair.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/jump-to-pair.png new file mode 100644 index 0000000..ddf0ee3 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/jump-to-pair.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/paste-from-clipboard.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/paste-from-clipboard.png new file mode 100644 index 0000000..24588a3 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/paste-from-clipboard.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/play.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/play.png new file mode 100644 index 0000000..a7de0fe Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/play.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/redo.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/redo.png new file mode 100644 index 0000000..c3b0df0 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/redo.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/reflect.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/reflect.png new file mode 100644 index 0000000..01cfa6e Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/reflect.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/select-all.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/select-all.png new file mode 100644 index 0000000..f4b0b19 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/select-all.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/show-abbs.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/show-abbs.png new file mode 100644 index 0000000..7406c95 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/show-abbs.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround-comment.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround-comment.png new file mode 100644 index 0000000..8c2b0ce Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround-comment.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround-debug.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround-debug.png new file mode 100644 index 0000000..39b906d Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround-debug.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround-if.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround-if.png new file mode 100644 index 0000000..8391c24 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround-if.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround-try.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround-try.png new file mode 100644 index 0000000..074f882 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround-try.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround-while.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround-while.png new file mode 100644 index 0000000..890e2fc Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround-while.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround-with.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround-with.png new file mode 100644 index 0000000..d4f01a6 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround-with.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround.png new file mode 100644 index 0000000..d0d3331 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/surround.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/toggle-lines.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/toggle-lines.png new file mode 100644 index 0000000..a8909bb Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/toggle-lines.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/toggle-token-marker.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/toggle-token-marker.png new file mode 100644 index 0000000..3cf16ed Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/toggle-token-marker.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/undo.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/undo.png new file mode 100644 index 0000000..8b0fef9 Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/undo.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/unindent.png b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/unindent.png new file mode 100644 index 0000000..1787a7f Binary files /dev/null and b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/images/small-icons/unindent.png differ diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/kitsfortypes.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/kitsfortypes.properties new file mode 100644 index 0000000..06c6eae --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/kitsfortypes.properties @@ -0,0 +1,26 @@ +# This file contains the default content types and the SyntaxKit class names +# that will be used for them. +# The keys are content types, and the values are the fully qualified class +# names +text/c=de.sciss.syntaxpane.syntaxkits.CSyntaxKit +text/cpp=de.sciss.syntaxpane.syntaxkits.CppSyntaxKit +text/java=de.sciss.syntaxpane.syntaxkits.JavaSyntaxKit +text/groovy=de.sciss.syntaxpane.syntaxkits.GroovySyntaxKit +text/javascript=de.sciss.syntaxpane.syntaxkits.JavaScriptSyntaxKit +text/js=de.sciss.syntaxpane.syntaxkits.JavaScriptSyntaxKit +text/json=de.sciss.syntaxpane.syntaxkits.JavaScriptSyntaxKit +text/xml=de.sciss.syntaxpane.syntaxkits.XmlSyntaxKit +text/sql=de.sciss.syntaxpane.syntaxkits.SqlSyntaxKit +text/properties=de.sciss.syntaxpane.syntaxkits.PropertiesSyntaxKit +text/python=de.sciss.syntaxpane.syntaxkits.PythonSyntaxKit +text/tal=de.sciss.syntaxpane.syntaxkits.TALSyntaxKit +text/jflex=de.sciss.syntaxpane.syntaxkits.JFlexSyntaxKit +text/ruby=de.sciss.syntaxpane.syntaxkits.RubySyntaxKit +text/scala=de.sciss.syntaxpane.syntaxkits.ScalaSyntaxKit +text/clojure=de.sciss.syntaxpane.syntaxkits.ClojureSyntaxKit +text/dosbatch=de.sciss.syntaxpane.syntaxkits.DOSBatchSyntaxKit +text/bash=de.sciss.syntaxpane.syntaxkits.BashSyntaxKit +text/xpath=de.sciss.syntaxpane.syntaxkits.XPathSyntaxKit +text/xhtml=de.sciss.syntaxpane.syntaxkits.XHTMLSyntaxKit +text/lua=de.sciss.syntaxpane.syntaxkits.LuaSyntaxKit +text/plain=de.sciss.syntaxpane.syntaxkits.PlainSyntaxKit \ No newline at end of file diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/scripts/insertdate.js b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/scripts/insertdate.js new file mode 100644 index 0000000..6fe7029 --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/scripts/insertdate.js @@ -0,0 +1,8 @@ +// Import the needed java packages and classes +importPackage(java.util); +importClass(javax.swing.JOptionPane) + +function putDate() { + TARGET.replaceSelection("This is a dummy proc that inserts the Current Date:\n" + new Date()); + TARGET.replaceSelection("\nTab Size of doc = " + AU.getTabSize(TARGET)); +} \ No newline at end of file diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/bashsyntaxkit/config.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/bashsyntaxkit/config.properties new file mode 100644 index 0000000..109a717 --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/bashsyntaxkit/config.properties @@ -0,0 +1,5 @@ +# +# BashSyntaxKit Specifics +# +Action.toggle-comments = de.sciss.syntaxpane.actions.ToggleCommentsAction, control NUMBER_SIGN +Action.toggle-comments.LineComments = "# " \ No newline at end of file diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/clojuresyntaxkit/config.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/clojuresyntaxkit/config.properties new file mode 100644 index 0000000..001f45b --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/clojuresyntaxkit/config.properties @@ -0,0 +1,5 @@ +# +# ClojureSyntaxKit +# +Action.toggle-comments = de.sciss.syntaxpane.actions.ToggleCommentsAction, control SLASH +Action.toggle-comments.LineComments = "; " \ No newline at end of file diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/dosbatchsyntaxkit/config.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/dosbatchsyntaxkit/config.properties new file mode 100644 index 0000000..458ec13 --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/dosbatchsyntaxkit/config.properties @@ -0,0 +1,5 @@ +# +# DOS Batch Specifics +# +Action.toggle-comments = de.sciss.syntaxpane.actions.ToggleCommentsAction, control NUMBER_SIGN +Action.toggle-comments.LineComments = "rem " diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/groovysyntaxkit/abbreviations.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/groovysyntaxkit/abbreviations.properties new file mode 100644 index 0000000..b2f71b7 --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/groovysyntaxkit/abbreviations.properties @@ -0,0 +1,41 @@ +# This file contains the code templates that will be used by the Java Syntax +# editor kit. +# The keys are the completion strings, and the values are the full expansion +# of the text. The #{p:TEXT} will be replaced +pu=public +pr=private +st=static +cl=class #{p:TheClass} {\n} +St=String +In=Integer +Bo=Boolean +bo=boolean +fl=float +ch=char +wh=while +ex=extends +im=implements +Ex=Exception +en=enum #{p:TheEnum} {\n} +re=return +df=default: +cs=case #{p:value}:\n break; +sw=switch(#{p:expr}){\n case 1:\n break;\n} +iof=instanceof +trc=try {\n #{p:statements;}\n} catch (Exception e) {\n} +th=throw +thn=throw new +ths=throws +fori=for(int i=0; i<#{p:max}; i++) {\n // statement\n} +fore=for(#{p:Object} o: items) {\n // statement\n} +ife=if(#{p:condition}) {\n // When true\n} else {\n // when false\n} +iff=if(#{p:condition}) {\n // When true\n} +sout=System.out.println("#{p:text}"); +serr=System.err.println("#{p:Error text}"); +psvm=public static void main(String[] args) {\n #{p:}\n} +psfs=public static final String #{p:CONST} = ""; +psfi=public static final int #{p:CONST} = 0; +psfb=public static final boolean #{p:CONST} = true; +Psfs=private static final String #{p:CONST} = ""; +Psfi=private static final int #{p:CONST} = 0; +IAE=IllegalArgumentException \ No newline at end of file diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/groovysyntaxkit/config.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/groovysyntaxkit/config.properties new file mode 100644 index 0000000..f9b01eb --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/groovysyntaxkit/config.properties @@ -0,0 +1,5 @@ +# +# Other Java type actions for other languages: +# +Style.COMMENT = 0x666666, 2 +Style.COMMENT2 = 0x666666, 3 \ No newline at end of file diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/javascriptsyntaxkit/config.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/javascriptsyntaxkit/config.properties new file mode 100644 index 0000000..0cfd451 --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/javascriptsyntaxkit/config.properties @@ -0,0 +1,28 @@ +# +# JavaScript +# +Action.execute-script = de.sciss.syntaxpane.actions.ScriptRunnerAction, control R +Action.execute-script.ScriptExtension = js +Action.execute-script.MenuText = Execute Script +Action.execute-script.ToolTip = Execute JavaScript in internal JRE +Action.execute-script.SmallIcon = play.png + +Action.indent.WordRegex=\\w+|\\/(\\*)+ +Action.parenthesis = de.sciss.syntaxpane.actions.PairAction, typed ( +Action.brackets = de.sciss.syntaxpane.actions.PairAction, typed [ +Action.quotes = de.sciss.syntaxpane.actions.PairAction, typed ' +Action.double-quotes = de.sciss.syntaxpane.actions.PairAction, typed " +Action.close-curly = de.sciss.syntaxpane.actions.JUnindentAction, typed } + +PopupMenu = \ + ${DEFAULT_EDIT_MENU} , \ + - , \ + indent , \ + unindent , \ + - , \ + toggle-comments , \ + - , \ + toggle-lines , \ + - , \ + execute-script + diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/javasyntaxkit/abbreviations.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/javasyntaxkit/abbreviations.properties new file mode 100644 index 0000000..e510d70 --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/javasyntaxkit/abbreviations.properties @@ -0,0 +1,43 @@ +# This file contains the code templates that will be used by the Java Syntax +# editor kit. +# The keys are the completion strings, and the values are the full expansion +# of the text. The #{p:TEXT} will be replaced +pu=public +pr=private +st=static +cl=class #{p:TheClass} {\n} +St=String +In=Integer +Bo=Boolean +bo=boolean +fl=float +ch=char +wh=while +ex=extends +im=implements +Ex=Exception +en=enum #{p:TheEnum} {\n} +re=return +df=default: +cs=case #{p:value}:\n break; +sw=switch(#{p:expr}){\n case 1:\n break;\n} +iof=instanceof +trc=try {\n #{p:statements;}\n} catch (Exception e) {\n} +th=throw +thn=throw new +ths=throws +fori=for(int i=0; i<#{p:max}; i++) {\n // statement\n} +fore=for(#{p:Object} o: items) {\n // statement\n} +ife=if(#{p:condition}) {\n // When true\n} else {\n // when false\n} +iff=if(#{p:condition}) {\n // When true\n} +sout=System.out.println("#{p:text}"); +serr=System.err.println("#{p:Error text}"); +psvm=public static void main(String[] args) {\n #{p:}\n} +psfs=public static final String #{p:CONST} = ""; +psfi=public static final int #{p:CONST} = 0; +psfb=public static final boolean #{p:CONST} = true; +Psfs=private static final String #{p:CONST} = ""; +Psfi=private static final int #{p:CONST} = 0; +IAE=IllegalArgumentException +/*=/* #{p:} */ +/**=/**\n * #{p:}\n */ \ No newline at end of file diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/javasyntaxkit/combocompletions.txt b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/javasyntaxkit/combocompletions.txt new file mode 100644 index 0000000..3a7815c --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/javasyntaxkit/combocompletions.txt @@ -0,0 +1,17 @@ +public +protected +private +class +static +toString() +equals(|) +hashCode() +JTextField +JEditorPane +JTextPane +JComboBox +JList +JTree +setContentType("text/|lang|") +setProperty("|key|") +for(int i=0; i < |max|; i++) {\n\t// loop body \n} diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/javasyntaxkit/config.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/javasyntaxkit/config.properties new file mode 100644 index 0000000..2c557e8 --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/javasyntaxkit/config.properties @@ -0,0 +1,89 @@ +# +# JavaSyntaxKit Specific properties. +# +Components = de.sciss.syntaxpane.components.PairsMarker, \ + de.sciss.syntaxpane.components.LineNumbersRuler, \ + de.sciss.syntaxpane.components.TokenMarker +TokenMarker.TokenTypes = IDENTIFIER, TYPE, TYPE2, TYPE3 +# +# Performs single color selection (Default = false) +# +SingleColorSelect = true +RightMarginColumn = 80 +RightMarginColor = 0xdddddd +# +# Java Actions +Action.indent.WordRegex=\\w+|\\/(\\*)+ +Action.parenthesis = de.sciss.syntaxpane.actions.PairAction, typed ( +Action.toggle-token-marker = de.sciss.syntaxpane.actions.ToggleComponentAction, control F3 +Action.toggle-token-marker.MenuText = Toggle Token Marker +Action.toggle-token-marker.Component = de.sciss.syntaxpane.components.TokenMarker +Action.brackets = de.sciss.syntaxpane.actions.PairAction, typed [ +Action.quotes = de.sciss.syntaxpane.actions.PairAction, typed ' +Action.double-quotes = de.sciss.syntaxpane.actions.PairAction, typed " +Action.close-curly = de.sciss.syntaxpane.actions.JUnindentAction, typed } +Action.toggle-comments = de.sciss.syntaxpane.actions.ToggleCommentsAction, menu SLASH +# For completions, you have to define the Action (key to trigger completions): +Action.combo-completion = de.sciss.syntaxpane.actions.ComboCompletionAction, control SPACE +Action.combo-completion.MenuText = Completions +Action.combo-completion.ItemsURL=${class_path}/combocompletions.txt +Action.reflect = de.sciss.syntaxpane.actions.ReflectCompletionAction, control I, shift F1 +Action.reflect.MenuText = Reflections +# Enclose selection: Try Catch +Action.surround-try = de.sciss.syntaxpane.actions.TemplateAction, control T +Action.surround-try.MenuText = try catch block +Action.surround-try.ToolTip = Surround selection with a try catch block +Action.surround-try.Template = try {\n #{selection}\n} catch (#{p:Exception} ex) {\n} finally {\n} +Action.surround-try.WholeLines= true +Action.surround-while = de.sciss.syntaxpane.actions.TemplateAction, control W +Action.surround-while.MenuText = while loop +Action.surround-while.ToolTip = Surround selection in while loop +Action.surround-while.Template = while(#{p:condition}) {\n #{selection}\n} +Action.surround-while.WholeLines = true +Action.surround-debug = de.sciss.syntaxpane.actions.TemplateAction, control D +Action.surround-debug.MenuText = Debug Expression +Action.surround-debug.ToolTip = Output expression to System.out +Action.surround-debug.Template = System.out.println("The value of #{selection} = " + (#{selection})); +Action.surround-debug.WholeLines = false +Action.surround-debug.MustHaveSelection = true +Action.surround-if = de.sciss.syntaxpane.actions.TemplateAction, control I +Action.surround-if.MenuText = Surround with If +Action.surround-if.ToolTip = Surround expression with If condition +Action.surround-if.Template = if(#{p:condition}) {\n #{selection}\n}\n +Action.surround-if.WholeLines = true +Action.surround-if.MustHaveSelection = true +Action.surround-comment = de.sciss.syntaxpane.actions.TemplateAction +Action.surround-comment.MenuText = Block comment +Action.surround-comment.ToolTip = Surround lines with block comments +Action.surround-comment.Template = /*\n#{selection}\n*/ +Action.surround-comment.WholeLines = true +Action.surround-comment.MustHaveSelection = true +Action.insert-date = de.sciss.syntaxpane.actions.ScriptAction, F12 +Action.insert-date.Function = putDate +Script.insert-date.URL = de/sciss/syntaxpane/scripts/insertdate.js + +# Localizable menu entry for "Surround with" menu item +SURROUND_WITH=Surround with +# +# These are the completions to be in the IntelliSense completion dialog +# comma separated values. +# Vertical bars: if there is one, it will position the cursor. If there are +# two, they will be start and end of selection +PopupMenu = \ + ${DEFAULT_EDIT_MENU} , \ + - , \ + indent , \ + unindent , \ + - , \ + toggle-comments , \ + - , \ + reflect , \ + >${SURROUND_WITH} , \ + surround-try , \ + surround-while , \ + surround-debug , \ + surround-if , \ + surround-comment , \ + < , \ + toggle-lines , \ + toggle-token-marker \ No newline at end of file diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/javasyntaxkit/config_de.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/javasyntaxkit/config_de.properties new file mode 100644 index 0000000..5da8d87 --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/javasyntaxkit/config_de.properties @@ -0,0 +1,19 @@ +# +# German localization overrides for +# JavaSyntaxKit Specific properties. +# +Action.toggle-token-marker.MenuText = Token-Markierung an-/abschalten +Action.combo-completion.MenuText = Vervollständigungen +Action.reflect.MenuText = Reflektionen +Action.surround-try.MenuText = Try-Catch-Block +Action.surround-try.ToolTip = Auswahl mit einem Try-Catch-Block umgeben +Action.surround-while.MenuText = While-Schleife +Action.surround-while.ToolTip = Auswahl mit einer While-Schleife umgeben +Action.surround-debug.MenuText = Ausdruck debuggen +Action.surround-debug.ToolTip = Ausdruck nach System.out ausgeben +Action.surround-if.MenuText = Mit If-Anweisung umgeben +Action.surround-if.ToolTip = Ausdruck mit If-Anweisung umgeben +Action.surround-comment.MenuText = Blockkommentar +Action.surround-comment.ToolTip = Zeilen mit Blockkommentar umgeben + +SURROUND_WITH=Umschließen mit \ No newline at end of file diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/javasyntaxkit/config_de_ch.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/javasyntaxkit/config_de_ch.properties new file mode 100644 index 0000000..14f7300 --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/javasyntaxkit/config_de_ch.properties @@ -0,0 +1,6 @@ +# +# Swiss German localization overrides for +# JavaSyntaxKit Specific properties. (no 'ß') +# + +SURROUND_WITH=Umschliessen mit \ No newline at end of file diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/luasyntaxkit/combocompletions.txt b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/luasyntaxkit/combocompletions.txt new file mode 100644 index 0000000..1d7de5d --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/luasyntaxkit/combocompletions.txt @@ -0,0 +1,30 @@ +and +break +do +else +else \n\t#{p:block} +elseif +elseif (#{p:exp}) then \n\t#{p:block} +end +false +for +for #{p:var}=#{p:num},#{p:max} do \n\t|block \nend +for #{p:namelist} in #{p:explist} do \n\t#{p:block} \nend +function +function #{p:name} () \n\nend +if +if (#{p:exp}) then \n\t#{p:block} \nend +in +local +local function #{p:name} () \n\nend +nil +not +or +repeat +repeat \n\t#{p:block} \nuntil #{p:exp} +return +then +true +until +while +while (#{p:exp}) do \n\t#{p:block} \nend \ No newline at end of file diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/luasyntaxkit/config.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/luasyntaxkit/config.properties new file mode 100644 index 0000000..c33277b --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/luasyntaxkit/config.properties @@ -0,0 +1,23 @@ +# +# Lua Properties: +# + +# For completions, you have to define the Action (key to trigger completions): +Action.combo-completion = de.sciss.syntaxpane.actions.ComboCompletionAction, control SPACE +Action.combo-completion.MenuText = Completions +Action.combo-completion.ItemsURL=${class_path}/combocompletions.txt + +# auto fill-in actions +Action.parenthesis = de.sciss.syntaxpane.actions.PairAction, typed ( +Action.brackets = de.sciss.syntaxpane.actions.PairAction, typed [ +Action.quotes = de.sciss.syntaxpane.actions.PairAction, typed ' +Action.double-quotes = de.sciss.syntaxpane.actions.PairAction, typed " +Action.close-curly = de.sciss.syntaxpane.actions.JUnindentAction, typed } + +# Style is one of: 0 = plain, 1=bold, 2=italic, 3=bold/italic +Style.OPERATOR = 0x000000, 0 +Style.KEYWORD = 0x3333ee, 0 +Style.STRING = 0xcc6600, 0 +Style.NUMBER = 0x999933, 1 +Style.IDENTIFIER = 0x000000, 0 +Style.COMMENT = 0x339933, 2 \ No newline at end of file diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/plainsyntaxkit/config.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/plainsyntaxkit/config.properties new file mode 100644 index 0000000..d98ca01 --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/plainsyntaxkit/config.properties @@ -0,0 +1,19 @@ +# +# Plain / Empty Document +# +Components = de.sciss.syntaxpane.components.LineNumbersRuler +PopupMenu = \ + cut-to-clipboard , \ + copy-to-clipboard , \ + paste-from-clipboard , \ + - , \ + select-all , \ + - , \ + undo , \ + redo , \ + - , \ + find , \ + find-next , \ + goto-line , \ + - , \ + complete-word diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/propertiessyntaxkit/config.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/propertiessyntaxkit/config.properties new file mode 100644 index 0000000..f3c129d --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/propertiessyntaxkit/config.properties @@ -0,0 +1,2 @@ +Action.toggle-comments = de.sciss.syntaxpane.actions.ToggleCommentsAction, control SLASH +Action.toggle-comments.LineComments = "# " \ No newline at end of file diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/pythonsyntaxkit/config.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/pythonsyntaxkit/config.properties new file mode 100644 index 0000000..0aec468 --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/pythonsyntaxkit/config.properties @@ -0,0 +1,14 @@ +Action.toggle-comments = de.sciss.syntaxpane.actions.ToggleCommentsAction, control NUMBER_SIGN +Action.toggle-comments.LineComments = "# " +Action.indent.WordRegex=\\w+|\\/(\\*)+ +Action.jindent = de.sciss.syntaxpane.actions.PythonIndentAction, ENTER +# Action.unindent = de.sciss.syntaxpaneactions.PythonUnindentAction, shift TAB +Action.unindent.MenuText = Un-Indent +Action.unindent.Tooltip = Un-Indent block + +PopupMenu = \ + ${DEFAULT_EDIT_MENU} , \ + - , \ + indent , \ + unindent + diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/rubysyntaxkit/config.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/rubysyntaxkit/config.properties new file mode 100644 index 0000000..85588d4 --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/rubysyntaxkit/config.properties @@ -0,0 +1,6 @@ +# +# Ruby +# +Action.toggle-comments = de.sciss.syntaxpane.actions.ToggleCommentsAction, control NUMBER_SIGN +Action.toggle-comments.LineComments = "# " +Action.complete-word.WordsRegexp = \\w+(\\?)? \ No newline at end of file diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/scalasyntaxkit/config.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/scalasyntaxkit/config.properties new file mode 100644 index 0000000..a56446d --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/scalasyntaxkit/config.properties @@ -0,0 +1,2 @@ +Action.toggle-comments = de.sciss.syntaxpane.actions.ToggleCommentsAction, menu SLASH +Action.toggle-comments.LineComments = "// " diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/sqlsyntaxkit/config.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/sqlsyntaxkit/config.properties new file mode 100644 index 0000000..69f42a0 --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/sqlsyntaxkit/config.properties @@ -0,0 +1,2 @@ +Action.toggle-comments = de.sciss.syntaxpane.actions.ToggleCommentsAction, control SLASH +Action.toggle-comments.LineComments = "-- " \ No newline at end of file diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/talsyntaxkit/config.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/talsyntaxkit/config.properties new file mode 100644 index 0000000..69f42a0 --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/talsyntaxkit/config.properties @@ -0,0 +1,2 @@ +Action.toggle-comments = de.sciss.syntaxpane.actions.ToggleCommentsAction, control SLASH +Action.toggle-comments.LineComments = "-- " \ No newline at end of file diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/xhtmlsyntaxkit/config.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/xhtmlsyntaxkit/config.properties new file mode 100644 index 0000000..57bf69d --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/xhtmlsyntaxkit/config.properties @@ -0,0 +1,18 @@ +# +# XHTMLSyntaxKit +# +Action.html-preview = de.sciss.syntaxpane.actions.HTMLPreviewAction, F1 +Action.html-preview.MenuText = Preview HTML +Action.html-preview.ToolTip = Preview in Java Swing internal Viewer, with auto update +Action.toggle-comments = de.sciss.syntaxpane.actions.TemplateAction, control SLASH +Action.toggle-comments.MenuText = Comment Block +Action.toggle-comments.SmallIcon = comment.png +Action.toggle-comments.MustHaveSelection = true +Action.toggle-comments.Template = +PopupMenu = \ + ${DEFAULT_EDIT_MENU} , \ + - , \ + toggle-comments , \ + html-preview , \ + - , \ + toggle-lines \ No newline at end of file diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/xmlsyntaxkit/config.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/xmlsyntaxkit/config.properties new file mode 100644 index 0000000..56eb1e6 --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/xmlsyntaxkit/config.properties @@ -0,0 +1,24 @@ +Components = de.sciss.syntaxpane.components.PairsMarker, \ + de.sciss.syntaxpane.components.LineNumbersRuler +PairMarker.Color = 0xffeeaa +Action.toggle-comments = de.sciss.syntaxpane.actions.TemplateAction, control SLASH +Action.toggle-comments.MenuText = Comment Block +Action.toggle-comments.SmallIcon = comment.png +Action.toggle-comments.MustHaveSelection = true +Action.toggle-comments.Template = +Action.prettify = de.sciss.syntaxpane.actions.XmlPrettifyAction, control P +Action.prettify.MenuText = Reformat XML +Action.prettify.ToolTip = Reformat XML +# The XmlPrettifyAction takes these config parameters: +# IndentAmount = int (amount of spaces for indentation, default = 4) +# StandAlone = yes/no, default = yes. see OutputKeys.STANDALONE +# OmitDeclaration = yes/no, default = yes. see OutputKeys.OMIT_XML_DECLARATION +# Indent = yes/no, default = yes. see OutputKeys.INDENT +Action.prettify.IndentAmount = 2 +Action.tag-close = de.sciss.syntaxpane.actions.XmlTagCompleteAction, typed > +PopupMenu = \ + ${DEFAULT_EDIT_MENU} , \ + - , \ + toggle-comments , \ + prettify , \ + toggle-lines \ No newline at end of file diff --git a/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/xpathsyntaxkit/config.properties b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/xpathsyntaxkit/config.properties new file mode 100644 index 0000000..3bcbe61 --- /dev/null +++ b/SyntaxPane/src/main/resources/de/sciss/syntaxpane/syntaxkits/xpathsyntaxkit/config.properties @@ -0,0 +1,4 @@ +PopupMenu = \ + ${DEFAULT_EDIT_MENU} , \ + - , \ + Toggle Line Numbers = toggle-lines diff --git a/SyntaxPane/src/test/java/de/sciss/syntaxpane/SyntaxTester.form b/SyntaxPane/src/test/java/de/sciss/syntaxpane/SyntaxTester.form new file mode 100644 index 0000000..b21a1ab --- /dev/null +++ b/SyntaxPane/src/test/java/de/sciss/syntaxpane/SyntaxTester.form @@ -0,0 +1,127 @@ + + +
        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/SyntaxPane/src/test/java/de/sciss/syntaxpane/SyntaxTester.java b/SyntaxPane/src/test/java/de/sciss/syntaxpane/SyntaxTester.java new file mode 100644 index 0000000..bd2125d --- /dev/null +++ b/SyntaxPane/src/test/java/de/sciss/syntaxpane/SyntaxTester.java @@ -0,0 +1,197 @@ +/* + * Copyright 2008 Ayman Al-Sairafi ayman.alsairafi@gmail.com + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License + * at http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package de.sciss.syntaxpane; + +import java.awt.event.ItemEvent; +import java.io.IOException; +import java.io.StringReader; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.DefaultComboBoxModel; +import javax.swing.text.EditorKit; +import de.sciss.syntaxpane.actions.ActionUtils; +import de.sciss.syntaxpane.actions.CaretMonitor; + +public class SyntaxTester extends javax.swing.JFrame { + + /** Creates new form Tester */ + public SyntaxTester() { + // this is a test for adding regex lexer. It wont work unless the + // JavaRegex.properties is found in the classpath + // DefaultSyntaxKit.registerContentType("text/aa_regex", "de.sciss.syntaxpane.JavaRegexKit"); + initComponents(); + jCmbLangs.setModel(new DefaultComboBoxModel(DefaultSyntaxKit.getContentTypes())); + // jEdtTest.setContentType(jCmbLangs.getItemAt(0).toString()); + jCmbLangs.setSelectedItem("text/java"); + new CaretMonitor(jEdtTest, lblCaretPos); + } + + /** + * This method is called from within the constructor to + * initialize the form. + * WARNING: Do NOT modify this code. The content of this method is + * always regenerated by the Form Editor. + */ + // //GEN-BEGIN:initComponents + private void initComponents() { + + lblCaretPos = new javax.swing.JLabel(); + jScrollPane1 = new javax.swing.JScrollPane(); + jEdtTest = new javax.swing.JEditorPane(); + lblToken = new javax.swing.JLabel(); + jCmbLangs = new javax.swing.JComboBox(); + jToolBar1 = new javax.swing.JToolBar(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle"); // NOI18N + setTitle(bundle.getString("SyntaxTester.title")); // NOI18N + + lblCaretPos.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING); + lblCaretPos.setText(bundle.getString("SyntaxTester.lblCaretPos.text")); // NOI18N + + jEdtTest.setContentType(bundle.getString("SyntaxTester.jEdtTest.contentType")); // NOI18N + jEdtTest.setFont(new java.awt.Font("Monospaced", 0, 13)); + jEdtTest.setCaretColor(new java.awt.Color(153, 204, 255)); + jEdtTest.addCaretListener(new javax.swing.event.CaretListener() { + public void caretUpdate(javax.swing.event.CaretEvent evt) { + jEdtTestCaretUpdate(evt); + } + }); + jScrollPane1.setViewportView(jEdtTest); + + lblToken.setFont(new java.awt.Font("Courier New", 0, 12)); + lblToken.setText(bundle.getString("SyntaxTester.lblToken.text")); // NOI18N + + jCmbLangs.setMaximumRowCount(20); + jCmbLangs.setFocusable(false); + jCmbLangs.addItemListener(new java.awt.event.ItemListener() { + public void itemStateChanged(java.awt.event.ItemEvent evt) { + jCmbLangsItemStateChanged(evt); + } + }); + + jToolBar1.setRollover(true); + jToolBar1.setFocusable(false); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addContainerGap() + .addComponent(jCmbLangs, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 441, Short.MAX_VALUE) + .addComponent(lblCaretPos, javax.swing.GroupLayout.PREFERRED_SIZE, 119, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(lblToken, javax.swing.GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE) + .addGap(484, 484, 484)) + .addComponent(jToolBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 715, Short.MAX_VALUE) + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 715, Short.MAX_VALUE) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE) + .addGap(0, 0, 0) + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 382, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(lblToken, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(lblCaretPos, javax.swing.GroupLayout.DEFAULT_SIZE, 21, Short.MAX_VALUE) + .addComponent(jCmbLangs, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addContainerGap()) + ); + + pack(); + }// //GEN-END:initComponents + + private void jEdtTestCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_jEdtTestCaretUpdate + SyntaxDocument sDoc = ActionUtils.getSyntaxDocument(jEdtTest); + if (sDoc != null) { + Token t = sDoc.getTokenAt(evt.getDot()); + if (t != null) { + CharSequence tData = t.getText(sDoc); + if (t.length > 40) { + tData = tData.subSequence(0, 40); + } + lblToken.setText(t.toString() + ": " + tData); + } else { + // null token, remove the status + lblToken.setText(java.util.ResourceBundle.getBundle("de/sciss/syntaxpane/Bundle").getString("NO_TOKEN_AT_CURSOR")); + } + } + + }//GEN-LAST:event_jEdtTestCaretUpdate + + private void jCmbLangsItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jCmbLangsItemStateChanged + if (evt.getStateChange() == ItemEvent.SELECTED) { + String lang = jCmbLangs.getSelectedItem().toString(); + + // save the state of the current JEditorPane, as it's Document is about + // to be replaced. + String oldText = jEdtTest.getText(); + + // install a new DefaultSyntaxKit on the JEditorPane for the requested language. + jEdtTest.setContentType(lang); + // Recreate the Toolbar + jToolBar1.removeAll(); + EditorKit kit = jEdtTest.getEditorKit(); + if (kit instanceof DefaultSyntaxKit) { + DefaultSyntaxKit defaultSyntaxKit = (DefaultSyntaxKit) kit; + defaultSyntaxKit.addToolBarActions(jEdtTest, jToolBar1); + } + jToolBar1.validate(); + try { + // setText should not be called (read the JavaDocs). Better use the read + // method and create a new document. + jEdtTest.read(new StringReader(oldText), lang); + } catch (IOException ex) { + Logger.getLogger(SyntaxTester.class.getName()).log(Level.SEVERE, null, ex); + } + } + jEdtTest.requestFocusInWindow(); + }//GEN-LAST:event_jCmbLangsItemStateChanged + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + + java.awt.EventQueue.invokeLater(new Runnable() { + + @Override + public void run() { + try { + DefaultSyntaxKit.initKit(); + new SyntaxTester().setVisible(true); + } catch (Exception e) { + e.printStackTrace(); + System.exit(2); + } + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JComboBox jCmbLangs; + private javax.swing.JEditorPane jEdtTest; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JToolBar jToolBar1; + private javax.swing.JLabel lblCaretPos; + private javax.swing.JLabel lblToken; + // End of variables declaration//GEN-END:variables +} diff --git a/Test/br/com/console/ByteBufferQueue.java b/Test/br/com/console/ByteBufferQueue.java new file mode 100644 index 0000000..6dc0ff2 --- /dev/null +++ b/Test/br/com/console/ByteBufferQueue.java @@ -0,0 +1,333 @@ +/* + * Semestralni prace KIV/OS - Spravce virtualnich stroju + * Natalia Rubinova, A080082P + * Martin Sloup, A08N0111P + * Jiri Kucera, A08N0092P + * + */ +package br.com.console; + +import java.util.concurrent.Semaphore; + +/** + * The thread safe byte buffer queue
        + * Based on Spencer Rupport code from http://www.siafoo.net/snippet/216 + *
        + *
        + * * Added unlimited buffer size
        + * * Added javadoc comments + */ +public class ByteBufferQueue { + + private byte[] buff; + private volatile int head, tail, count, size; + private Semaphore appendsem, readsem, countsem; + + /** + * Default constructor for {@link ByteBufferQueue}. The inside buffer is initialized for 256 items. + */ + public ByteBufferQueue() { + this(256); + } + + /** + * Constructor for defining the initial size of inside buffer + * @param size initial size of the buffer + */ + public ByteBufferQueue(int size) { + int realSize = 1; + + //use the power of two + for (; realSize < size; realSize *= 2) { + } + + //initialize the semaphores + appendsem = new Semaphore(1, true); + readsem = new Semaphore(1, true); + countsem = new Semaphore(1, true); + + this.size = realSize; + buff = new byte[realSize]; + + head = 0; + tail = 0; + count = 0; + } + + /** + * Reallocate inside buffer for minimal capacity specified by the parameter + * @param minimumCapacity the new minimal capacity of inside buffer + */ + private void realocate(int minimumCapacity) { + try { + appendsem.acquire(); + readsem.acquire(); + } catch (InterruptedException e) { + return; + } + + int newSize = size; + for (; newSize < minimumCapacity; newSize *= 2) { + } + + byte newBuff[]; + int n1, n2; + + if (head <= tail) { + // Create larger array and copy + // data[front]...data[rear] into it. + + newBuff = new byte[newSize]; + System.arraycopy(buff, head, newBuff, head, count); + } else { + // Create a bigger array, but be careful about copying items + // into it. The queue items + // occur in two segments. The first segment goes from data[front] to + // the end of the + // array, and the second segment goes from data[0] to data[rear]. + // The variables n1 + // and n2 will be set to the number of items in these two segments. + // We will copy + // these segments to biggerArray[0...manyItems-1]. + + newBuff = new byte[newSize]; + n1 = size - head; + n2 = tail + 1; + + System.arraycopy(buff, head, newBuff, 0, n1); + System.arraycopy(buff, 0, newBuff, n1, n2); + + head = 0; + tail = count - 1; + } + + buff = newBuff; + + try { + countsem.acquire(); + } catch (InterruptedException e) { + return; + } + size = newSize; + + + countsem.release(); + appendsem.release(); + readsem.release(); + } + + /** + * Get the number of bytes in the buffer + * @return number of the bytes in buffer + */ + public int getCount() { + return count; + } + + /** + * Append byte to the end of buffer + * @param data byte to be appended + */ + public void append(byte data) { + append(new byte[]{data}); + } + + /** + * Append bytes to the end of buffer + * @param data bytes to be appended + */ + public void append(byte[] data) { + if (data != null) { + append(data, 0, data.length); + } + } + + /** + * Append bytes to the end of buffer + * @param data bytes to be appended + * @param offset offset position in data from the bytes be appended + * @param length count of appended bytes + */ + public void append(byte[] data, int offset, int length) { + if (data == null) { + return; + } + if (data.length < offset + length) { + throw new RuntimeException( + "array index out of bounds. offset + length extends beyond the length of the array."); + } + + // Test if is needed to increase buffer size + if (buff.length < count + length) { + realocate(count + length); + } + + try { + appendsem.acquire(); + } catch (InterruptedException e) { + return; + } + // We need to acquire the semaphore so that this.tail doesn't change. + for (int i = 0; i < length; i++) { + buff[(i + this.tail) % this.size] = data[i + offset]; + } + this.tail = (length + this.tail) % this.size; + try { + countsem.acquire(); + } catch (InterruptedException e) { + return; + } + // We need to acquire the semaphore so that this.count doesn't change. + this.count = this.count + length; + countsem.release(); + appendsem.release(); + } + + /** + * Reads some number of bytes from the input stream and stores them into + * the array data. The number of bytes actually read is + * returned as an integer. + * + *

        The read(data) method for class {@link ByteBufferQueue} + * has the same effect as:

        + *
        read(data, 0, data.length)
        + * @param data byte array, where will be read bytes stored + * @return count of read bytes + */ + public int read(byte[] data) { + if (data != null) { + return read(data, 0, data.length); + } else { + return 0; + } + } + + /** + * Reads up to length bytes of data from the buffer into an array of + * bytes. An attempt is made to read as many as length bytes, but a + * smaller number may be read, possibly zero. The number of bytes actually read is + * returned as an integer. + * + * @param data byte array, where will be read bytes stored + * @param offset the start offset in array data at which the data is written. + * @param length the maximum number of bytes to read + * @return the total number of bytes read into the buffer + */ + public int read(byte[] data, int offset, int length) { + if (data == null) { + return 0; + } + if (data.length < offset + length) { + throw new RuntimeException("array index out of bounds. offset + length extends beyond the length of the array."); + } + + int readlength = 0; + + try { + readsem.acquire(); + } catch (InterruptedException e) { + return 0; + } + + // We need to acquire the semaphore so that this.head doesn't change. + for (int i = 0; i < length; i++) { + if (i == count) { + break; + } + data[i + offset] = buff[(i + head) % this.size]; + readlength++; + } + + this.head = (readlength + this.head) % this.size; + + try { + countsem.acquire(); + } catch (InterruptedException e) { + readsem.release(); + return 0; + } + + // We need to acquire the semaphore so that this.count doesn't change. + this.count = this.count - readlength; + + countsem.release(); + readsem.release(); + + return readlength; + } + + /** + * Reads some number of bytes from the input stream and stores them into + * the array data. After the reading, read bytes remain in the + * buffer. The number of bytes actually read is returned as an integer. + * + *

        The peak(data) method for class {@link ByteBufferQueue} + * has the same effect as:

        + *
        peak(data, 0, data.length)
        + * @param data byte array, where will be read bytes stored + * @return count of read bytes + */ + public int peek(byte[] data) { + if (data != null) { + return peek(data, 0, data.length); + } else { + return 0; + } + } + + /** + * Reads up to length bytes of data from the buffer into an array of + * bytes. After the reading, read bytes remain in the buffer. An attempt is made to + * read as many as length bytes, but a smaller number may be read, + * possibly zero. The number of bytes actually read is returned as an integer. + * + * @param data byte array, where will be read bytes stored + * @param offset the start offset in array data at which the data is written. + * @param length the maximum number of bytes to read + * @return the total number of bytes read into the buffer + */ + public int peek(byte[] data, int offset, int length) { + if (data == null) { + return 0; + } + + if (data.length < offset + length) { + throw new RuntimeException("array index out of bounds. offset + length extends beyond the length of the array."); + } + + int readlength = 0; + + try { + readsem.acquire(); + } catch (InterruptedException e) { + return 0; + } + + // We need to acquire the semaphore so that this.head doesn't change. + for (int i = 0; i < length; i++) { + if (i == count) { + break; + } + data[i + offset] = buff[(i + head) % this.size]; + readlength++; + } + + readsem.release(); + + return readlength; + } + + /** + * Read the whole buffer a return it as byte array. + * @return array of bytes + */ + public byte[] readBytes() { + + byte[] data = new byte[count]; + try { + read(data); + } catch (Exception ex) { + } + return data; + } +} \ No newline at end of file diff --git a/Test/br/com/console/CaretConsole.java b/Test/br/com/console/CaretConsole.java new file mode 100644 index 0000000..2bbf625 --- /dev/null +++ b/Test/br/com/console/CaretConsole.java @@ -0,0 +1,90 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package br.com.console; + +/** + * + * @author SIMONETO-2 + */ +// CornerCaret.java +// A custom caret class. +// +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Rectangle; +import java.awt.event.MouseEvent; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultCaret; +import javax.swing.text.JTextComponent; + +public class CaretConsole extends DefaultCaret { + + //private String mark = "<"; + public CaretConsole() { + setBlinkRate(500); + } + + @Override + protected synchronized void damage(Rectangle r) { + if (r == null) { + return; + } + + JTextComponent comp = getComponent(); + FontMetrics fm = comp.getFontMetrics(comp.getFont()); + int textWidth = fm.stringWidth(">"); + int textHeight = fm.getHeight(); + x = r.x; + y = r.y; + width = textWidth; + height = textHeight; + repaint(); // calls getComponent().repaint(x, y, width, height) + } + + @Override + public void paint(Graphics g) { + JTextComponent comp = getComponent(); + if (comp == null) { + return; + } + + int dot = getDot(); + Rectangle r = null; + try { + r = comp.modelToView(dot); + } catch (BadLocationException e) { + return; + } + if (r == null) { + return; + } + + if ((x != r.x) || (y != r.y)) { + repaint(); // erase previous location of caret + damage(r); + } + + if (isVisible()) { + FontMetrics fm = comp.getFontMetrics(comp.getFont()); + int textWidth = fm.stringWidth(">"); + int textHeight = fm.getHeight(); + + g.setColor(comp.getCaretColor()); + g.fillRect(r.x, r.y, 8, r.height); + } + } + + @Override + public void mousePressed(MouseEvent evt) { + evt.consume(); + } + + @Override + public void mouseDragged(MouseEvent e) { + e.consume(); + } + +} diff --git a/Test/br/com/console/Console.form b/Test/br/com/console/Console.form new file mode 100644 index 0000000..aea8432 --- /dev/null +++ b/Test/br/com/console/Console.form @@ -0,0 +1,80 @@ + + +
        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Test/br/com/console/Console.java b/Test/br/com/console/Console.java new file mode 100644 index 0000000..7e1c4b1 --- /dev/null +++ b/Test/br/com/console/Console.java @@ -0,0 +1,129 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package br.com.console; + +import bsh.EvalError; +import bsh.Interpreter; +import com.forms.Editor; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + * @author Andrew + */ +public class Console extends javax.swing.JFrame { + //public static JConsole JConsole = new JConsole(); + public static Thread codeEXEC; + public static ConsoleIO _console; + + /** + * Creates new form Console + */ + public Console() { + initComponents(); + } + + static void t() { + codeEXEC = new Thread() { + @Override + public void run() { + try { + _console.print("Digite seu nome: "); + String nome = _console.writeString(); + _console.print("Qua a sua idade: "); + int idade = _console.writeInt(); + _console.print("Qua a sua massa: "); + float massa = _console.writeFloat(); + _console.print("Seu nome é " + nome + ", sua idade " + idade + ", sua massa " + massa); + } catch (Exception ex) { + Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex); + } + } + }; + codeEXEC.start(); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jScrollPane2 = new javax.swing.JScrollPane(); + console = new javax.swing.JTextPane(); + jButton1 = new javax.swing.JButton(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + + console.setFont(new java.awt.Font("Ubuntu", 0, 14)); // NOI18N + console.setDisabledTextColor(new java.awt.Color(0, 0, 0)); + jScrollPane2.setViewportView(console); + + jButton1.setText("Stop"); + jButton1.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jButton1ActionPerformed(evt); + } + }); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 391, Short.MAX_VALUE) + .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 305, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jButton1) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + pack(); + }// //GEN-END:initComponents + + private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed + // TODO add your handling code here: + codeEXEC.interrupt(); + }//GEN-LAST:event_jButton1ActionPerformed + + /** + * @param args the command line arguments + */ + public static void main(String args[]) throws EvalError { + + new Console().setVisible(true); + + //_console = new ConsoleIO(console); + //t(); + InterpreterTestConsole asd = new InterpreterTestConsole(); + + + + /* + _console.print("Qua a sua idade: "); + int idade = _console.writeInt(); + _console.print("Sua idade "+ idade);*/ + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + public static javax.swing.JTextPane console; + private javax.swing.JButton jButton1; + private javax.swing.JScrollPane jScrollPane2; + // End of variables declaration//GEN-END:variables +} diff --git a/Test/br/com/console/ConsoleIO.java b/Test/br/com/console/ConsoleIO.java new file mode 100644 index 0000000..bb83a20 --- /dev/null +++ b/Test/br/com/console/ConsoleIO.java @@ -0,0 +1,300 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package br.com.console; + +import java.awt.Cursor; +import java.awt.Toolkit; +import java.awt.event.KeyEvent; +import static java.awt.event.KeyEvent.VK_BACK_SPACE; +import static java.awt.event.KeyEvent.VK_DOWN; +import static java.awt.event.KeyEvent.VK_ENTER; +import static java.awt.event.KeyEvent.VK_LEFT; +import static java.awt.event.KeyEvent.VK_UP; +import java.awt.event.KeyListener; +import java.util.concurrent.locks.ReentrantLock; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.JTextPane; +import javax.swing.text.BadLocationException; +import javax.swing.text.Document; +import javax.swing.text.SimpleAttributeSet; + +/** + * + * @author Andrew + */ +public class ConsoleIO implements KeyListener { + + private final ReentrantLock lock = new ReentrantLock(); + + private final String header = "[Sistema ~] > "; + private JTextPane console; + private Document doc; + + //responsavel por pausar o codigo na hora da entrada + private boolean block = true; + //posicao minima do caret + public static int caret_min_position = -1; + //para permitir apenas numeros + private boolean write_tipo_int = false; + private boolean write_tipo_float = false; + private boolean key_enter = false; + + /* + * CLASSE CONSTRUTORA + */ + public ConsoleIO(JTextPane t) { + console = t; + + console.setCaret(new CaretConsole()); + + console.getCaret().setVisible(false); + + doc = console.getDocument(); + + console.setHighlighter(null); + + console.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); + + console.addKeyListener(this); + } + + public void close() { + unlock(); + } + + public void reset() { + console.setText(""); + } + /* + * PRINT + */ + + public void print(Object t) { + try { + doc.insertString(doc.getLength(), header + t, null); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public void print(Object t, SimpleAttributeSet style) { + try { + doc.insertString(doc.getLength(), (String) t, style); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public void print(int position, Object t) { + try { + doc.insertString(position, (String) t, null); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public void print(int position, Object t, SimpleAttributeSet style) { + try { + doc.insertString(position, (String) t, style); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + } + + /* + * PRINLN + */ + public void println(Object t) { + try { + doc.insertString(doc.getLength(), header + t + "\n", null); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public void println(Object t, SimpleAttributeSet style) { + try { + doc.insertString(doc.getLength(), t + "\n", style); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public void println(int position, Object t) { + try { + doc.insertString(position, t + "\n", null); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public void println(int position, Object t, SimpleAttributeSet style) { + try { + doc.insertString(position, t + "\n", style); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + } + + /* + * ENTRADA DE STRING + */ + public synchronized String writeString() { + String retorno = null; + write(); + try { + retorno = doc.getText(caret_min_position, doc.getLength() - caret_min_position); + print(doc.getLength(), "\n"); + console.repaint(); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } finally { + console.getCaret().setVisible(false); + } + return retorno; + } + + /* + * ENTRADA DE INT + */ + public int writeInt() { + int retorno = 0; + write_tipo_int = true; + write(); + try { + String r = doc.getText(caret_min_position, doc.getLength() - caret_min_position); + if ("".equals(r)) { + retorno = 0; + } else { + retorno = new Integer(r); + } + write_tipo_int = false; + print(doc.getLength(), "\n"); + console.repaint(); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } finally { + console.getCaret().setVisible(false); + } + + return retorno; + } + + public float writeFloat() { + float retorno = 0; + write_tipo_float = true; + write(); + try { + String r = doc.getText(caret_min_position, doc.getLength() - caret_min_position).replace(",", "."); + if ("".equals(r)) { + retorno = 0; + } else { + retorno = new Float(r); + } + + write_tipo_float = false; + print(doc.getLength(), "\n"); + console.repaint(); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } finally { + console.getCaret().setVisible(false); + } + + return retorno; + } + + /* + * LOOP PARA TRAVAMENTO DE ENTRADA DE DADOS + */ + private synchronized void write() { + console.getCaret().setVisible(true); + console.requestFocus(); + int tmp_length = doc.getLength(); + console.setCaretPosition(tmp_length); + caret_min_position = tmp_length; + lock(); + } + + /* + * RESETA ALGUMAS CONFIGURACOES + */ + public synchronized void lock() { + while (block) { + try { + wait(); + } catch (InterruptedException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + } + block = true; + } + + public synchronized void unlock() { + block = false; + notify(); + } + + /* + * EVENTOS + */ + @Override + public void keyTyped(KeyEvent e) { + type(e); + } + + @Override + public void keyPressed(KeyEvent e) { + type(e); + key_enter = false; + } + + @Override + public void keyReleased(KeyEvent e) { + key_enter = true; + type(e); + } + + + + private synchronized void type(KeyEvent e) { + switch (e.getKeyCode()) { + case (KeyEvent.VK_ENTER): + if (e.getID() == KeyEvent.KEY_PRESSED) { + if (key_enter) { + unlock(); + e.consume(); + } + } + break; + case (VK_DOWN): + case (VK_UP): + break; + case (VK_LEFT): + case (VK_BACK_SPACE): + if (caret_min_position == console.getCaretPosition()) { + e.consume(); + Toolkit.getDefaultToolkit().beep(); + } + break; + default: + char key = e.getKeyChar(); + if (write_tipo_int) { + String caracteres = "0123456789"; + if (!caracteres.contains(key + "")) { + e.consume(); + } + } else if (write_tipo_float) { + String caracteres = "0123456789,"; + if (!caracteres.contains(key + "")) { + e.consume(); + } + } + break; + } + } +} diff --git a/Test/br/com/console/Interpreter.java b/Test/br/com/console/Interpreter.java new file mode 100644 index 0000000..b04abd3 --- /dev/null +++ b/Test/br/com/console/Interpreter.java @@ -0,0 +1,86 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package br.com.console; + +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +import java.io.IOException; +import java.io.InputStreamReader; + +import javax.swing.JFrame; + +import bsh.EvalError; + + +/** + * The interpreter class. We delegate to a ready-made bsh interpreter. For + * details, see http://www.beanshell.org/ + * + * @author Barak Naveh + */ +public class Interpreter { + private static final boolean SHOW_GUI = true; + + /** + * User can pass file names. We run these files from bsh prior to user + * prompt. + * + * @param args + */ + public static void main( String[] args ) { + bsh.Interpreter bsh; + + if( SHOW_GUI ) { + JConsole console = new JConsole( ); + bsh = new bsh.Interpreter( console ); + createGuiForConsole( console ); + } + else { + InputStreamReader reader = new InputStreamReader( System.in ); + bsh = new bsh.Interpreter( reader, System.out, System.err, true ); + } + + try { + bsh.eval( "import robdd.*;" ); + bsh.eval( "import robdd.operators.*;" ); + } + catch( EvalError e ) { + e.printStackTrace( ); + } + + for( int j = 0; j < args.length; j++ ) { + String fileName = args[ j ]; + + try { + bsh.source( fileName ); + } + catch( IOException e1 ) { + System.err.println( "Could not open file: " + fileName ); + } + catch( EvalError e2 ) { + System.err.println( "Evaluation error in file: " + fileName ); + } + } + + bsh.run( ); + } + + + private static void createGuiForConsole( JConsole console ) { + JFrame frame = new JFrame( "ROBDD Interpreter" ); + frame.getContentPane( ).add( console ); + frame.setSize( 640, 400 ); + frame.setLocation( 160, 200 ); + frame.addWindowListener( new WindowAdapter( ) { + public void windowClosing( WindowEvent e ) { + System.exit( 0 ); + } + } ); + frame.show( ); + } +} \ No newline at end of file diff --git a/Test/br/com/console/InterpreterTestConsole.java b/Test/br/com/console/InterpreterTestConsole.java new file mode 100644 index 0000000..5cab83c --- /dev/null +++ b/Test/br/com/console/InterpreterTestConsole.java @@ -0,0 +1,77 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package br.com.console; + + +import static br.com.console.Console._console; +import bsh.EvalError; +import bsh.Interpreter; +import java.util.logging.Level; +import java.util.logging.Logger; +import java_cup.runtime.Scanner; + +/** + * + * @author Andrew + */ +public class InterpreterTestConsole { + public InterpreterTestConsole(){ + + Interpreter i = new Interpreter(); + try { + + + + i.eval("Scanner t = new Scanner(System.in);"); + //i.eval("System.out.print(\"Digite seu nome: \");"); + //i.eval("String nome = t.next();"); + //i.eval("System.out.print(\"Seu nome e :\"+nome);"); + + i.eval("public void teste(){System.out.print(\"ttttttttt\");}"); + i.eval("teste();"); + + + //i.set("_console", _console); + + //i.set("console", console); + //i.eval("import br.com.console.ConsoleIO"); + //i.set("ConsoleJtextArea", ConsoleJtextArea.class); + //i.eval("ConsoleIO _console = new ConsoleIO(console);"); + //i.eval("_console.print(\"Digite seu nome: \");"); + //i.eval("String nome = _console.writeString();"); + //i.eval("_console.print(\"Qual e sua idade: \");"); + //i.eval("int idade = _console.writeInt();"); + //i.eval("_console.print(\"Seu nome é \" + nome);"); + + //i.eval("int nloop = 0;"); + //i.eval("numero = 0;"); + //i.eval("while(nloop < 10){_console.print(\"Digite \" + nloop + \" de 10: \"); numero = _console.writeFloat(); nloop++; }"); + /* + i.eval("int nloop;"); + i.eval("float numero,soma;"); + + + i.eval("nloop = 0;"); + i.eval("numero = 0;"); + i.eval("soma = 0;"); + + i.eval("while(nloop < 10){"); + i.eval("_console.print(\"Digite \" + nloop + \" de 10: \");"); + i.eval("numero = _console.writeFloat();"); + i.eval("if((numero % 2 == 0)){"); + i.eval("soma = soma + numero;"); + i.eval("}"); + i.eval("nloop = nloop + 1;"); + i.eval("}"); + i.eval("_console.println(\"Soma dos numeros: \" + soma);"); + i.eval("_console.println(\"Média dos numeros: \" + (soma / nloop));"); + */ + } catch (EvalError ex) { + Logger.getLogger(InterpreterTestConsole.class.getName()).log(Level.SEVERE, null, ex); + } + } +} diff --git a/Test/br/com/console/JConsole.java b/Test/br/com/console/JConsole.java new file mode 100644 index 0000000..24bf2d8 --- /dev/null +++ b/Test/br/com/console/JConsole.java @@ -0,0 +1,815 @@ +/** + * *************************************************************************** + * * + * This file is part of the BeanShell Java Scripting distribution. * + * Documentation and updates may be found at http://www.beanshell.org/ * * Sun + * Public License Notice: * * The contents of this file are subject to the Sun + * Public License Version * 1.0 (the "License"); you may not use this file + * except in compliance with * the License. A copy of the License is available + * at http://www.sun.com * * The Original Code is BeanShell. The Initial + * Developer of the Original * Code is Pat Niemeyer. Portions created by Pat + * Niemeyer are Copyright * (C) 2000. All Rights Reserved. * * GNU Public + * License Notice: * * Alternatively, the contents of this file may be used + * under the terms of * the GNU Lesser General Public License (the "LGPL"), in + * which case the * provisions of LGPL are applicable instead of those above. If + * you wish to * allow use of your version of this file only under the terms of + * the LGPL * and not to allow others to use your version of this file under the + * SPL, * indicate your decision by deleting the provisions above and replace * + * them with the notice and other provisions required by the LGPL. If you * do + * not delete the provisions above, a recipient may use your version of * this + * file under either the SPL or the LGPL. * * Patrick Niemeyer (pat@pat.net) * + * Author of Learning Java, O'Reilly & Associates * http://www.pat.net/~pat/ * * + **************************************************************************** + */ +package br.com.console; + +import bsh.util.GUIConsoleInterface; +import bsh.util.NameCompletion; +import java.awt.Color; +import java.awt.Component; +import java.awt.Cursor; +import java.awt.Font; +import java.awt.Insets; +import java.awt.event.*; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.io.*; +import java.util.Vector; +import javax.swing.*; + +// Things that are not in the core packages +import javax.swing.text.*; + +/** + * A JFC/Swing based console for the BeanShell desktop. This is a descendant of + * the old AWTConsole. + * + * Improvements by: Mark Donszelmann + * including Cut & Paste + * + * Improvements by: Daniel Leuck including Color and Image support, key press + * bug workaround + */ +public class JConsole extends JScrollPane implements GUIConsoleInterface, Runnable, KeyListener, MouseListener, ActionListener, PropertyChangeListener { + + private final static String CUT = "Cut"; + private final static String COPY = "Copy"; + private final static String PASTE = "Paste"; + + private OutputStream outPipe; + private InputStream inPipe; + private InputStream in; + private PrintStream out; + + public InputStream getInputStream() { + return in; + } + + public Reader getIn() { + return new InputStreamReader(in); + } + + public PrintStream getOut() { + return out; + } + + public PrintStream getErr() { + return out; + } + + private int cmdStart = 0; + private Vector history = new Vector(); + private String startedLine; + private int histLine = 0; + + private JPopupMenu menu; + private JTextPane text; + private DefaultStyledDocument doc; + + NameCompletion nameCompletion; + final int SHOW_AMBIG_MAX = 10; + + // hack to prevent key repeat for some reason? + private boolean gotUp = true; + + public JConsole() { + this(null, null); + } + + public JConsole(InputStream cin, OutputStream cout) { + super(); + + // Special TextPane which catches for cut and paste, both L&F keys and + // programmatic behaviour + text = new JTextPane(doc = new DefaultStyledDocument()) { + public void cut() { + if (text.getCaretPosition() < cmdStart) { + super.copy(); + } else { + super.cut(); + } + } + + public void paste() { + forceCaretMoveToEnd(); + super.paste(); + } + }; + + Font font = new Font("Monospaced", Font.PLAIN, 14); + text.setText(""); + text.setFont(font); + text.setMargin(new Insets(7, 5, 7, 5)); + text.addKeyListener(this); + setViewportView(text); + + // create popup menu + menu = new JPopupMenu("JConsole Menu"); + menu.add(new JMenuItem(CUT)).addActionListener(this); + menu.add(new JMenuItem(COPY)).addActionListener(this); + menu.add(new JMenuItem(PASTE)).addActionListener(this); + + text.addMouseListener(this); + + // make sure popup menu follows Look & Feel + UIManager.addPropertyChangeListener(this); + + outPipe = cout; + if (outPipe == null) { + outPipe = new PipedOutputStream(); + try { + in = new PipedInputStream((PipedOutputStream) outPipe); + } catch (IOException e) { + print("Console internal error (1)...", Color.red); + } + } + + inPipe = cin; + if (inPipe == null) { + PipedOutputStream pout = new PipedOutputStream(); + out = new PrintStream(pout); + try { + inPipe = new BlockingPipedInputStream(pout); + } catch (IOException e) { + print("Console internal error: " + e); + } + } + // Start the inpipe watcher + new Thread(this).start(); + + requestFocus(); + } + + public void requestFocus() { + super.requestFocus(); + text.requestFocus(); + } + + public void keyPressed(KeyEvent e) { + type(e); + gotUp = false; + } + + public void keyTyped(KeyEvent e) { + type(e); + } + + public void keyReleased(KeyEvent e) { + gotUp = true; + type(e); + } + + private synchronized void type(KeyEvent e) { + switch (e.getKeyCode()) { + case (KeyEvent.VK_ENTER): + if (e.getID() == KeyEvent.KEY_PRESSED) { + if (gotUp) { + enter(); + resetCommandStart(); + text.setCaretPosition(cmdStart); + } + } + e.consume(); + text.repaint(); + break; + + case (KeyEvent.VK_UP): + if (e.getID() == KeyEvent.KEY_PRESSED) { + historyUp(); + } + e.consume(); + break; + + case (KeyEvent.VK_DOWN): + if (e.getID() == KeyEvent.KEY_PRESSED) { + historyDown(); + } + e.consume(); + break; + + case (KeyEvent.VK_LEFT): + case (KeyEvent.VK_BACK_SPACE): + case (KeyEvent.VK_DELETE): + if (text.getCaretPosition() <= cmdStart) { + // This doesn't work for backspace. + // See default case for workaround + e.consume(); + } + break; + + case (KeyEvent.VK_RIGHT): + forceCaretMoveToStart(); + break; + + case (KeyEvent.VK_HOME): + text.setCaretPosition(cmdStart); + e.consume(); + break; + + case (KeyEvent.VK_U): // clear line + if ((e.getModifiers() & InputEvent.CTRL_MASK) > 0) { + replaceRange("", cmdStart, textLength()); + histLine = 0; + e.consume(); + } + break; + + case (KeyEvent.VK_ALT): + case (KeyEvent.VK_CAPS_LOCK): + case (KeyEvent.VK_CONTROL): + case (KeyEvent.VK_META): + case (KeyEvent.VK_SHIFT): + case (KeyEvent.VK_PRINTSCREEN): + case (KeyEvent.VK_SCROLL_LOCK): + case (KeyEvent.VK_PAUSE): + case (KeyEvent.VK_INSERT): + case (KeyEvent.VK_F1): + case (KeyEvent.VK_F2): + case (KeyEvent.VK_F3): + case (KeyEvent.VK_F4): + case (KeyEvent.VK_F5): + case (KeyEvent.VK_F6): + case (KeyEvent.VK_F7): + case (KeyEvent.VK_F8): + case (KeyEvent.VK_F9): + case (KeyEvent.VK_F10): + case (KeyEvent.VK_F11): + case (KeyEvent.VK_F12): + case (KeyEvent.VK_ESCAPE): + + // only modifier pressed + break; + + // Control-C + case (KeyEvent.VK_C): + if (text.getSelectedText() == null) { + if (((e.getModifiers() & InputEvent.CTRL_MASK) > 0) + && (e.getID() == KeyEvent.KEY_PRESSED)) { + append("^C"); + } + e.consume(); + } + break; + + case (KeyEvent.VK_TAB): + if (e.getID() == KeyEvent.KEY_RELEASED) { + String part = text.getText().substring(cmdStart); + doCommandCompletion(part); + } + e.consume(); + break; + + default: + if ((e.getModifiers() + & (InputEvent.CTRL_MASK + | InputEvent.ALT_MASK | InputEvent.META_MASK)) == 0) { + // plain character + forceCaretMoveToEnd(); + } + + /* + The getKeyCode function always returns VK_UNDEFINED for + keyTyped events, so backspace is not fully consumed. + */ + if (e.paramString().indexOf("Backspace") != -1) { + if (text.getCaretPosition() <= cmdStart) { + e.consume(); + break; + } + } + + break; + } + } + + private void doCommandCompletion(String part) { + if (nameCompletion == null) { + return; + } + + int i = part.length() - 1; + + // Character.isJavaIdentifierPart() How convenient for us!! + while (i >= 0 && (Character.isJavaIdentifierPart(part.charAt(i)) || part.charAt(i) == '.')) { + i--; + } + + part = part.substring(i + 1); + + if (part.length() < 2) // reasonable completion length + { + return; + } + + //System.out.println("completing part: "+part); + // no completion + String[] complete = nameCompletion.completeName(part); + if (complete.length == 0) { + java.awt.Toolkit.getDefaultToolkit().beep(); + return; + } + + // Found one completion (possibly what we already have) + if (complete.length == 1 && !complete.equals(part)) { + String append = complete[0].substring(part.length()); + append(append); + return; + } + + // Found ambiguous, show (some of) them + String line = text.getText(); + String command = line.substring(cmdStart); + // Find prompt + for (i = cmdStart; line.charAt(i) != '\n' && i > 0; i--); + String prompt = line.substring(i + 1, cmdStart); + + // Show ambiguous + StringBuffer sb = new StringBuffer("\n"); + for (i = 0; i < complete.length && i < SHOW_AMBIG_MAX; i++) { + sb.append(complete[i] + "\n"); + } + if (i == SHOW_AMBIG_MAX) { + sb.append("...\n"); + } + + print(sb, Color.gray); + print(prompt); // print resets command start + append(command); // append does not reset command start + } + + private void resetCommandStart() { + cmdStart = textLength(); + } + + private void append(String string) { + int slen = textLength(); + text.select(slen, slen); + text.replaceSelection(string); + } + + private String replaceRange(Object s, int start, int end) { + String st = s.toString(); + text.select(start, end); + text.replaceSelection(st); + //text.repaint(); + return st; + } + + private void forceCaretMoveToEnd() { + if (text.getCaretPosition() < cmdStart) { + // move caret first! + text.setCaretPosition(textLength()); + } + text.repaint(); + } + + private void forceCaretMoveToStart() { + if (text.getCaretPosition() < cmdStart) { + // move caret first! + } + text.repaint(); + } + + private void enter() { + String s = getCmd(); + + if (s.length() == 0) // special hack for empty return! + { + s = ";\n"; + } else { + history.addElement(s); + s = s + "\n"; + } + + append("\n"); + histLine = 0; + acceptLine(s); + text.repaint(); + } + + private String getCmd() { + String s = ""; + try { + s = text.getText(cmdStart, textLength() - cmdStart); + } catch (BadLocationException e) { + // should not happen + System.out.println("Internal JConsole Error: " + e); + } + return s; + } + + private void historyUp() { + if (history.size() == 0) { + return; + } + if (histLine == 0) // save current line + { + startedLine = getCmd(); + } + if (histLine < history.size()) { + histLine++; + showHistoryLine(); + } + } + + private void historyDown() { + if (histLine == 0) { + return; + } + + histLine--; + showHistoryLine(); + } + + private void showHistoryLine() { + String showline; + if (histLine == 0) { + showline = startedLine; + } else { + showline = (String) history.elementAt(history.size() - histLine); + } + + replaceRange(showline, cmdStart, textLength()); + text.setCaretPosition(textLength()); + text.repaint(); + } + + String ZEROS = "000"; + + private void acceptLine(String line) { + // Patch to handle Unicode characters + // Submitted by Daniel Leuck + StringBuffer buf = new StringBuffer(); + int lineLength = line.length(); + for (int i = 0; i < lineLength; i++) { + char c = line.charAt(i); + if (c > 127) { + String val = Integer.toString(c, 16); + val = ZEROS.substring(0, 4 - val.length()) + val; + buf.append("\\u" + val); + } else { + buf.append(c); + } + } + line = buf.toString(); + // End unicode patch + + if (outPipe == null) { + print("Console internal error: cannot output ...", Color.red); + } else { + try { + outPipe.write(line.getBytes()); + outPipe.flush(); + } catch (IOException e) { + outPipe = null; + throw new RuntimeException("Console pipe broken..."); + } + } + //text.repaint(); + } + + public void println(Object o) { + print(String.valueOf(o) + "\n"); + text.repaint(); + } + + public void print(final Object o) { + invokeAndWait(new Runnable() { + public void run() { + append(String.valueOf(o)); + resetCommandStart(); + text.setCaretPosition(cmdStart); + } + }); + } + + /** + * Prints "\\n" (i.e. newline) + */ + public void println() { + print("\n"); + text.repaint(); + } + + public void error(Object o) { + print(o, Color.red); + } + + public void println(Icon icon) { + print(icon); + println(); + text.repaint(); + } + + public void print(final Icon icon) { + if (icon == null) { + return; + } + + invokeAndWait(new Runnable() { + public void run() { + text.insertIcon(icon); + resetCommandStart(); + text.setCaretPosition(cmdStart); + } + }); + } + + public void print(Object s, Font font) { + print(s, font, null); + } + + public void print(Object s, Color color) { + print(s, null, color); + } + + public void print(final Object o, final Font font, final Color color) { + invokeAndWait(new Runnable() { + public void run() { + AttributeSet old = getStyle(); + setStyle(font, color); + append(String.valueOf(o)); + resetCommandStart(); + text.setCaretPosition(cmdStart); + setStyle(old, true); + } + }); + } + + public void print( + Object s, + String fontFamilyName, + int size, + Color color + ) { + + print(s, fontFamilyName, size, color, false, false, false); + } + + public void print( + final Object o, + final String fontFamilyName, + final int size, + final Color color, + final boolean bold, + final boolean italic, + final boolean underline + ) { + invokeAndWait(new Runnable() { + public void run() { + AttributeSet old = getStyle(); + setStyle(fontFamilyName, size, color, bold, italic, underline); + append(String.valueOf(o)); + resetCommandStart(); + text.setCaretPosition(cmdStart); + setStyle(old, true); + } + }); + } + + private AttributeSet setStyle(Font font) { + return setStyle(font, null); + } + + private AttributeSet setStyle(Color color) { + return setStyle(null, color); + } + + private AttributeSet setStyle(Font font, Color color) { + if (font != null) { + return setStyle(font.getFamily(), font.getSize(), color, + font.isBold(), font.isItalic(), + StyleConstants.isUnderline(getStyle())); + } else { + return setStyle(null, -1, color); + } + } + + private AttributeSet setStyle( + String fontFamilyName, int size, Color color) { + MutableAttributeSet attr = new SimpleAttributeSet(); + if (color != null) { + StyleConstants.setForeground(attr, color); + } + if (fontFamilyName != null) { + StyleConstants.setFontFamily(attr, fontFamilyName); + } + if (size != -1) { + StyleConstants.setFontSize(attr, size); + } + + setStyle(attr); + + return getStyle(); + } + + private AttributeSet setStyle(String fontFamilyName,int size,Color color,boolean bold,boolean italic,boolean underline) { + MutableAttributeSet attr = new SimpleAttributeSet(); + if (color != null) { + StyleConstants.setForeground(attr, color); + } + if (fontFamilyName != null) { + StyleConstants.setFontFamily(attr, fontFamilyName); + } + if (size != -1) { + StyleConstants.setFontSize(attr, size); + } + StyleConstants.setBold(attr, bold); + StyleConstants.setItalic(attr, italic); + StyleConstants.setUnderline(attr, underline); + + setStyle(attr); + + return getStyle(); + } + + private void setStyle(AttributeSet attributes) { + setStyle(attributes, false); + } + + private void setStyle(AttributeSet attributes, boolean overWrite) { + text.setCharacterAttributes(attributes, overWrite); + } + + private AttributeSet getStyle() { + return text.getCharacterAttributes(); + } + + public void setFont(Font font) { + super.setFont(font); + + if (text != null) { + text.setFont(font); + } + } + + private void inPipeWatcher() throws IOException { + byte[] ba = new byte[256]; // arbitrary blocking factor + int read; + while ((read = inPipe.read(ba)) != -1) { + print(new String(ba, 0, read)); + //text.repaint(); + } + + println("Console: Input closed..."); + } + + public void run() { + try { + inPipeWatcher(); + } catch (IOException e) { + print("Console: I/O Error: " + e + "\n", Color.red); + } + } + + public String toString() { + return "BeanShell console"; + } + + // MouseListener Interface + public void mouseClicked(MouseEvent event) { + } + + public void mousePressed(MouseEvent event) { + if (event.isPopupTrigger()) { + menu.show( + (Component) event.getSource(), event.getX(), event.getY()); + } + } + + public void mouseReleased(MouseEvent event) { + if (event.isPopupTrigger()) { + menu.show((Component) event.getSource(), event.getX(), + event.getY()); + } + text.repaint(); + } + + public void mouseEntered(MouseEvent event) { + } + + public void mouseExited(MouseEvent event) { + } + + // property change + public void propertyChange(PropertyChangeEvent event) { + if (event.getPropertyName().equals("lookAndFeel")) { + SwingUtilities.updateComponentTreeUI(menu); + } + } + + // handle cut, copy and paste + public void actionPerformed(ActionEvent event) { + String cmd = event.getActionCommand(); + if (cmd.equals(CUT)) { + text.cut(); + } else if (cmd.equals(COPY)) { + text.copy(); + } else if (cmd.equals(PASTE)) { + text.paste(); + } + } + + /** + * If not in the event thread run via SwingUtilities.invokeAndWait() + */ + private void invokeAndWait(Runnable run) { + if (!SwingUtilities.isEventDispatchThread()) { + try { + SwingUtilities.invokeAndWait(run); + } catch (Exception e) { + // shouldn't happen + e.printStackTrace(); + } + } else { + run.run(); + } + } + + /** + * The overridden read method in this class will not throw "Broken pipe" + * IOExceptions; It will simply wait for new writers and data. This is used + * by the JConsole internal read thread to allow writers in different (and + * in particular ephemeral) threads to write to the pipe. + * + * It also checks a little more frequently than the original read(). + * + * Warning: read() will not even error on a read to an explicitly closed + * pipe (override closed to for that). + */ + public static class BlockingPipedInputStream extends PipedInputStream { + + boolean closed; + + public BlockingPipedInputStream(PipedOutputStream pout) + throws IOException { + super(pout); + } + + public synchronized int read() throws IOException { + if (closed) { + throw new IOException("stream closed"); + } + + while (super.in < 0) { // While no data */ + notifyAll(); // Notify any writers to wake up + try { + wait(750); + } catch (InterruptedException e) { + throw new InterruptedIOException(); + } + } + // This is what the superclass does. + int ret = buffer[super.out++] & 0xFF; + if (super.out >= buffer.length) { + super.out = 0; + } + if (super.in == super.out) { + super.in = -1; /* now empty */ + } + return ret; + } + + public void close() throws IOException { + closed = true; + super.close(); + } + } + + public void setNameCompletion(NameCompletion nc) { + this.nameCompletion = nc; + } + + public void setWaitFeedback(boolean on) { + if (on) { + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + } else { + setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); + } + } + + private int textLength() { + return text.getDocument().getLength(); + } + +} diff --git a/Test/br/com/console/JConsoleExample.java b/Test/br/com/console/JConsoleExample.java new file mode 100644 index 0000000..43a624e --- /dev/null +++ b/Test/br/com/console/JConsoleExample.java @@ -0,0 +1,87 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package br.com.console; + +import bsh.EvalError; +import bsh.util.GUIConsoleInterface; +import java.awt.Color; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.Reader; +import javax.swing.JFrame; +/** + * + * @author Andrew + */ +public class JConsoleExample { + + public static void main(String[] args) throws EvalError { + + //define a frame and add a console to it + JFrame frame = new JFrame("JConsole example"); + + //PrintWriter p = new PrintWriter(); + + JConsole console = new JConsole(); + + System.setIn(console.getInputStream()); + System.setOut(console.getOut()); + + + + frame.getContentPane().add(console); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setSize(600, 400); + + frame.setVisible(true); + + bsh.Interpreter i = new bsh.Interpreter(); + i.eval("Scanner t = new Scanner(System.in);"); + i.eval("System.out.print(\"Digite seu nome: \");"); + i.eval("String nome = t.next();"); + i.eval("System.out.print(\"Seu nome e \"+nome);"); + + + //new Thread( i ).start(); + //System.exit(0); + } + + /** + * Print prompt and echos commands entered via the JConsole + * + * @param console a GUIConsoleInterface which in addition to basic input and + * output also provides coloured text output and name completion + * @param prompt text to display before each input line + */ + private static void inputLoop(GUIConsoleInterface console, String prompt) { + Reader input = console.getIn(); + BufferedReader bufInput = new BufferedReader(input); + + String newline = System.getProperty("line.separator"); + + console.print(prompt, Color.BLUE); + + String line; + try { + while ((line = bufInput.readLine()) != null) { + console.print("You typed: " + line + newline, Color.ORANGE); + + // try to sync up the console + //System.out.flush(); + //System.err.flush(); + //Thread.yield(); // this helps a little + if (line.equals("quit")) { + break; + } + console.print(prompt, Color.BLUE); + } + bufInput.close(); + } catch (IOException e) { + e.printStackTrace(); + } + + } +} diff --git a/Test/br/com/console2/CaretConsole.java b/Test/br/com/console2/CaretConsole.java new file mode 100644 index 0000000..a2f6ee4 --- /dev/null +++ b/Test/br/com/console2/CaretConsole.java @@ -0,0 +1,91 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package br.com.console2; + +/** + * + * @author SIMONETO-2 + */ +// CornerCaret.java +// A custom caret class. +// +import br.com.console.*; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Rectangle; +import java.awt.event.MouseEvent; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultCaret; +import javax.swing.text.JTextComponent; + +public class CaretConsole extends DefaultCaret { + + //private String mark = "<"; + public CaretConsole() { + setBlinkRate(500); + } + + @Override + protected synchronized void damage(Rectangle r) { + if (r == null) { + return; + } + + JTextComponent comp = getComponent(); + FontMetrics fm = comp.getFontMetrics(comp.getFont()); + int textWidth = fm.stringWidth(">"); + int textHeight = fm.getHeight(); + x = r.x; + y = r.y; + width = textWidth; + height = textHeight; + repaint(); // calls getComponent().repaint(x, y, width, height) + } + + @Override + public void paint(Graphics g) { + JTextComponent comp = getComponent(); + if (comp == null) { + return; + } + + int dot = getDot(); + Rectangle r = null; + try { + r = comp.modelToView(dot); + } catch (BadLocationException e) { + return; + } + if (r == null) { + return; + } + + if ((x != r.x) || (y != r.y)) { + repaint(); // erase previous location of caret + damage(r); + } + + if (isVisible()) { + FontMetrics fm = comp.getFontMetrics(comp.getFont()); + int textWidth = fm.stringWidth(">"); + int textHeight = fm.getHeight(); + + g.setColor(comp.getCaretColor()); + g.fillRect(r.x, r.y, 8, r.height); + } + } + + @Override + public void mousePressed(MouseEvent evt) { + evt.consume(); + } + + @Override + public void mouseDragged(MouseEvent e) { + e.consume(); + } + +} diff --git a/Test/br/com/console2/ConsoleIO.java b/Test/br/com/console2/ConsoleIO.java new file mode 100644 index 0000000..fde9e45 --- /dev/null +++ b/Test/br/com/console2/ConsoleIO.java @@ -0,0 +1,564 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package br.com.console2; + +import bsh.util.GUIConsoleInterface; +import bsh.util.NameCompletion; +import java.awt.Color; +import java.awt.Font; +import java.awt.event.InputEvent; +import java.awt.event.KeyEvent; +import java.awt.event.KeyListener; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.InterruptedIOException; +import java.io.OutputStream; +import java.io.PipedInputStream; +import java.io.PipedOutputStream; +import java.io.PrintStream; +import java.io.Reader; +import java.lang.reflect.InvocationTargetException; +import javax.swing.Icon; +import javax.swing.JTextPane; +import javax.swing.SwingUtilities; +import javax.swing.text.AttributeSet; +import javax.swing.text.BadLocationException; +import javax.swing.text.MutableAttributeSet; +import javax.swing.text.SimpleAttributeSet; +import javax.swing.text.StyleConstants; + +/** + * + * @author SIMONETO-2 + */ +public class ConsoleIO implements GUIConsoleInterface, Runnable, KeyListener { + + private JTextPane console; + + private OutputStream outPipe; + private InputStream inPipe; + private InputStream in; + private PrintStream out; + + private int cmdStart = 0; + private String startedLine; + private int histLine = 0; + + private boolean gotUp = true; + + public InputStream getInputStream() { + return in; + } + + @Override + public Reader getIn() { + return new InputStreamReader(in); + } + + @Override + public PrintStream getOut() { + return out; + } + + @Override + public PrintStream getErr() { + return out; + } + + public ConsoleIO(JTextPane text) { + console = text; + + console.addKeyListener(this); + + console.setCaret(new CaretConsole()); + /* + * OUT + */ + outPipe = new PipedOutputStream(); + try { + in = new PipedInputStream((PipedOutputStream) outPipe); + } catch (IOException e) { + } + + /* + * IN + */ + PipedOutputStream pout = new PipedOutputStream(); + out = new PrintStream(pout); + try { + inPipe = new BlockingPipedInputStream(pout); + } catch (IOException e) { + } + + new Thread(this).start(); + + console.requestFocus(); + + } + + private int textLength() { + return console.getDocument().getLength(); + } + + private void append(String string) { + int slen = textLength(); + console.select(slen, slen); + console.replaceSelection(string); + + } + + private void resetCommandStart() { + cmdStart = textLength(); + } + /* + * + * FUNCOES PRINTS + * + */ + + @Override + public void println(Object o) { + print(String.valueOf(o) + "\n"); + console.repaint(); + } + + @Override + public void print(final Object o) { + invokeAndWait(new Runnable() { + @Override + public void run() { + append(String.valueOf(o)); + resetCommandStart(); + console.setCaretPosition(cmdStart); + } + }); + + } + + /** + * Prints "\\n" (i.e. newline) + */ + public void println() { + print("\n"); + console.repaint(); + } + + @Override + public void error(Object o) { + print(o, Color.red); + } + + public void println(Icon icon) { + print(icon); + println(); + console.repaint(); + } + + public void print(final Icon icon) { + if (icon == null) { + return; + } + + invokeAndWait(new Runnable() { + @Override + public void run() { + console.insertIcon(icon); + resetCommandStart(); + console.setCaretPosition(cmdStart); + } + }); + + } + + public void print(Object s, Font font) { + print(s, font, null); + } + + @Override + public void print(Object s, Color color) { + print(s, null, color); + } + + public void print(final Object o, final Font font, final Color color) { + invokeAndWait(new Runnable() { + @Override + public void run() { + AttributeSet old = getStyle(); + setStyle(font, color); + append(String.valueOf(o)); + resetCommandStart(); + console.setCaretPosition(cmdStart); + setStyle(old, true); + } + }); + + } + + public void print(Object s, String fontFamilyName, int size, Color color) { + print(s, fontFamilyName, size, color, false, false, false); + } + + public void print(final Object o, final String fontFamilyName, final int size, final Color color, final boolean bold, final boolean italic, final boolean underline) { + invokeAndWait(new Runnable() { + @Override + public void run() { + AttributeSet old = getStyle(); + setStyle(fontFamilyName, size, color, bold, italic, underline); + append(String.valueOf(o)); + resetCommandStart(); + console.setCaretPosition(cmdStart); + setStyle(old, true); + } + }); + } + + private void invokeAndWait(Runnable run) { + if (!SwingUtilities.isEventDispatchThread()) { + try { + SwingUtilities.invokeAndWait(run); + } catch (InterruptedException | InvocationTargetException e) { + } + } else { + run.run(); + } + } + + private void inPipeWatcher() throws IOException { + byte[] ba = new byte[256]; // arbitrary blocking factor + int read; + while ((read = inPipe.read(ba)) != -1) { + print(new String(ba, 0, read)); + //text.repaint(); + } + + println("Console: Input closed..."); + } + + @Override + public void run() { + try { + inPipeWatcher(); + } catch (IOException e) { + print("Console: I/O Error: " + e + "\n", Color.red); + } + } + + private void enter() { + String s = getCmd(); + + if (s.length() == 0) // special hack for empty return! + { + s = ";\n"; + } else { + s = s + "\n"; + } + + append("\n"); + histLine = 0; + acceptLine(s); + console.repaint(); + } + + private String getCmd() { + String s = ""; + try { + s = console.getText(cmdStart, textLength() - cmdStart); + } catch (BadLocationException e) { + // should not happen + System.out.println("Internal JConsole Error: " + e); + } + return s; + } + + String ZEROS = "000"; + + private void acceptLine(String line) { + // Patch to handle Unicode characters + // Submitted by Daniel Leuck + StringBuilder buf = new StringBuilder(); + int lineLength = line.length(); + for (int i = 0; i < lineLength; i++) { + char c = line.charAt(i); + if (c > 127) { + String val = Integer.toString(c, 16); + val = ZEROS.substring(0, 4 - val.length()) + val; + buf.append("\\u").append(val); + } else { + buf.append(c); + } + } + line = buf.toString(); + // End unicode patch + + if (outPipe == null) { + print("Console internal error: cannot output ...", Color.red); + } else { + try { + outPipe.write(line.getBytes()); + outPipe.flush(); + } catch (IOException e) { + outPipe = null; + throw new RuntimeException("Console pipe broken..."); + } + } + //text.repaint(); + } + + + @Override + public void setNameCompletion(NameCompletion nc) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public void setWaitFeedback(boolean bln) { + throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + } + + @Override + public void keyTyped(KeyEvent e) { + type(e); + } + + @Override + public void keyPressed(KeyEvent e) { + type(e); + gotUp = false; + } + + @Override + public void keyReleased(KeyEvent e) { + gotUp = true; + type(e); + } + + private synchronized void type(KeyEvent e) { + switch (e.getKeyCode()) { + case (KeyEvent.VK_ENTER): + if (e.getID() == KeyEvent.KEY_PRESSED) { + if (gotUp) { + enter(); + resetCommandStart(); + console.setCaretPosition(cmdStart); + } + } + e.consume(); + console.repaint(); + break; + + case (KeyEvent.VK_UP): + e.consume(); + break; + + case (KeyEvent.VK_DOWN): + e.consume(); + break; + + case (KeyEvent.VK_LEFT): + case (KeyEvent.VK_BACK_SPACE): + case (KeyEvent.VK_DELETE): + if (console.getCaretPosition() <= cmdStart) { + e.consume(); + } + break; + + case (KeyEvent.VK_RIGHT): + forceCaretMoveToStart(); + break; + + case (KeyEvent.VK_HOME): + console.setCaretPosition(cmdStart); + e.consume(); + break; + + case (KeyEvent.VK_ALT): + case (KeyEvent.VK_CAPS_LOCK): + case (KeyEvent.VK_CONTROL): + case (KeyEvent.VK_META): + case (KeyEvent.VK_SHIFT): + case (KeyEvent.VK_PRINTSCREEN): + case (KeyEvent.VK_SCROLL_LOCK): + case (KeyEvent.VK_PAUSE): + case (KeyEvent.VK_INSERT): + case (KeyEvent.VK_F1): + case (KeyEvent.VK_F2): + case (KeyEvent.VK_F3): + case (KeyEvent.VK_F4): + case (KeyEvent.VK_F5): + case (KeyEvent.VK_F6): + case (KeyEvent.VK_F7): + case (KeyEvent.VK_F8): + case (KeyEvent.VK_F9): + case (KeyEvent.VK_F10): + case (KeyEvent.VK_F11): + case (KeyEvent.VK_F12): + case (KeyEvent.VK_ESCAPE): + + // only modifier pressed + break; + + default: + if ((e.getModifiers() & (InputEvent.CTRL_MASK | InputEvent.ALT_MASK | InputEvent.META_MASK)) == 0) { + // plain character + forceCaretMoveToEnd(); + } + + /* + The getKeyCode function always returns VK_UNDEFINED for + keyTyped events, so backspace is not fully consumed. + */ + if (e.paramString().contains("Backspace")) { + if (console.getCaretPosition() <= cmdStart) { + e.consume(); + break; + } + } + + break; + } + } + + private void forceCaretMoveToEnd() { + if (console.getCaretPosition() < cmdStart) { + // move caret first! + console.setCaretPosition(textLength()); + } + console.repaint(); + } + + private void forceCaretMoveToStart() { + if (console.getCaretPosition() < cmdStart) { + // move caret first! + } + console.repaint(); + } + + /** + * The overridden read method in this class will not throw "Broken pipe" + * IOExceptions; It will simply wait for new writers and data. This is used + * by the JConsole internal read thread to allow writers in different (and + * in particular ephemeral) threads to write to the pipe. + * + * It also checks a little more frequently than the original read(). + * + * Warning: read() will not even error on a read to an explicitly closed + * pipe (override closed to for that). + */ + public static class BlockingPipedInputStream extends PipedInputStream { + + boolean closed; + + public BlockingPipedInputStream(PipedOutputStream pout) + throws IOException { + super(pout); + } + + @Override + public synchronized int read() throws IOException { + if (closed) { + throw new IOException("stream closed"); + } + + while (super.in < 0) { // While no data */ + notifyAll(); // Notify any writers to wake up + try { + wait(750); + } catch (InterruptedException e) { + throw new InterruptedIOException(); + } + } + // This is what the superclass does. + int ret = buffer[super.out++] & 0xFF; + if (super.out >= buffer.length) { + super.out = 0; + } + if (super.in == super.out) { + super.in = -1; /* now empty */ + + } + return ret; + } + + @Override + public void close() throws IOException { + closed = true; + super.close(); + } + } + + /* + * + * SET STYLES E GET SYLES + * + */ + private AttributeSet getStyle() { + return console.getCharacterAttributes(); + } + + private AttributeSet setStyle(Font font) { + return setStyle(font, null); + } + + private AttributeSet setStyle(Color color) { + return setStyle(null, color); + } + + private AttributeSet setStyle(Font font, Color color) { + if (font != null) { + return setStyle(font.getFamily(), font.getSize(), color, + font.isBold(), font.isItalic(), + StyleConstants.isUnderline(getStyle())); + } else { + return setStyle(null, -1, color); + } + } + + private AttributeSet setStyle(String fontFamilyName, int size, Color color) { + MutableAttributeSet attr = new SimpleAttributeSet(); + if (color != null) { + StyleConstants.setForeground(attr, color); + } + if (fontFamilyName != null) { + StyleConstants.setFontFamily(attr, fontFamilyName); + } + if (size != -1) { + StyleConstants.setFontSize(attr, size); + } + + setStyle(attr); + + return getStyle(); + } + + private AttributeSet setStyle(String fontFamilyName, int size, Color color, boolean bold, boolean italic, boolean underline) { + MutableAttributeSet attr = new SimpleAttributeSet(); + if (color != null) { + StyleConstants.setForeground(attr, color); + } + if (fontFamilyName != null) { + StyleConstants.setFontFamily(attr, fontFamilyName); + } + if (size != -1) { + StyleConstants.setFontSize(attr, size); + } + StyleConstants.setBold(attr, bold); + StyleConstants.setItalic(attr, italic); + StyleConstants.setUnderline(attr, underline); + + setStyle(attr); + + return getStyle(); + } + + private void setStyle(AttributeSet attributes) { + setStyle(attributes, false); + } + + private void setStyle(AttributeSet attributes, boolean overWrite) { + console.setCharacterAttributes(attributes, overWrite); + } +} diff --git a/Test/br/com/console2/FormConsole.form b/Test/br/com/console2/FormConsole.form new file mode 100644 index 0000000..2b4a8de --- /dev/null +++ b/Test/br/com/console2/FormConsole.form @@ -0,0 +1,64 @@ + + +
        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Test/br/com/console2/FormConsole.java b/Test/br/com/console2/FormConsole.java new file mode 100644 index 0000000..374c57f --- /dev/null +++ b/Test/br/com/console2/FormConsole.java @@ -0,0 +1,99 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package br.com.console2; + +import java.util.Scanner; + +/** + * + * @author SIMONETO-2 + */ +public class FormConsole extends javax.swing.JFrame { + + public static Thread codeEXEC; + + /** + * Creates new form FormConsole + */ + public FormConsole() { + initComponents(); + } + + public void thread() { + codeEXEC = new Thread() { + @Override + public void run() { + Scanner x = new Scanner(System.in); + + System.out.print("Digite seu nome: "); + String nome = x.next(); + System.out.print("Digite sua idade: "); + int idade = x.nextInt(); + System.out.print("Digite sua massa: "); + float massa = x.nextFloat(); + + } + }; + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jScrollPane1 = new javax.swing.JScrollPane(); + console = new javax.swing.JTextPane(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + + console.setFont(new java.awt.Font("Verdana", 0, 12)); // NOI18N + jScrollPane1.setViewportView(console); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE) + .addContainerGap()) + ); + + pack(); + }// //GEN-END:initComponents + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + new FormConsole().setVisible(true); + + ConsoleIO c = new ConsoleIO(console); + + System.setIn(c.getInputStream()); + System.setOut(c.getOut()); + + + + + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private static javax.swing.JTextPane console; + private javax.swing.JScrollPane jScrollPane1; + // End of variables declaration//GEN-END:variables +} diff --git a/Test/br/com/console3/CaretConsole.java b/Test/br/com/console3/CaretConsole.java new file mode 100644 index 0000000..d66c95e --- /dev/null +++ b/Test/br/com/console3/CaretConsole.java @@ -0,0 +1,91 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package br.com.console3; + +/** + * + * @author SIMONETO-2 + */ +// CornerCaret.java +// A custom caret class. +// +import br.com.console.*; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Rectangle; +import java.awt.event.MouseEvent; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultCaret; +import javax.swing.text.JTextComponent; + +public class CaretConsole extends DefaultCaret { + + //private String mark = "<"; + public CaretConsole() { + setBlinkRate(500); + } + + @Override + protected synchronized void damage(Rectangle r) { + if (r == null) { + return; + } + + JTextComponent comp = getComponent(); + FontMetrics fm = comp.getFontMetrics(comp.getFont()); + int textWidth = fm.stringWidth(">"); + int textHeight = fm.getHeight(); + x = r.x; + y = r.y; + width = textWidth; + height = textHeight; + repaint(); // calls getComponent().repaint(x, y, width, height) + } + + @Override + public void paint(Graphics g) { + JTextComponent comp = getComponent(); + if (comp == null) { + return; + } + + int dot = getDot(); + Rectangle r = null; + try { + r = comp.modelToView(dot); + } catch (BadLocationException e) { + return; + } + if (r == null) { + return; + } + + if ((x != r.x) || (y != r.y)) { + repaint(); // erase previous location of caret + damage(r); + } + + if (isVisible()) { + FontMetrics fm = comp.getFontMetrics(comp.getFont()); + int textWidth = fm.stringWidth(">"); + int textHeight = fm.getHeight(); + + g.setColor(comp.getCaretColor()); + g.fillRect(r.x, r.y, 8, r.height); + } + } + + @Override + public void mousePressed(MouseEvent evt) { + evt.consume(); + } + + @Override + public void mouseDragged(MouseEvent e) { + e.consume(); + } + +} diff --git a/Test/br/com/console3/Console.form b/Test/br/com/console3/Console.form new file mode 100644 index 0000000..4ea4f7e --- /dev/null +++ b/Test/br/com/console3/Console.form @@ -0,0 +1,64 @@ + + +
        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Test/br/com/console3/Console.java b/Test/br/com/console3/Console.java new file mode 100644 index 0000000..624565e --- /dev/null +++ b/Test/br/com/console3/Console.java @@ -0,0 +1,76 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package br.com.console3; + +/** + * + * @author SIMONETO-2 + */ +public class Console extends javax.swing.JFrame { + + public Console() { + initComponents(); + } + + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jScrollPane1 = new javax.swing.JScrollPane(); + _console = new javax.swing.JTextPane(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + + _console.setFont(new java.awt.Font("Ubuntu", 0, 14)); // NOI18N + jScrollPane1.setViewportView(_console); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 278, Short.MAX_VALUE) + .addContainerGap()) + ); + + pack(); + }// //GEN-END:initComponents + + public static void main(String args[]) { + + new Console().setVisible(true); + + ConsoleIO ConsoleIO = new ConsoleIO(_console); + + char sexo; + + ConsoleIO.println(("Informe O SEXO M OU F:")); + sexo = ConsoleIO.writeChar(); + while (!(sexo == 'M') && !(sexo == 'F')) { + ConsoleIO.print(("ENTRADA INVALIDA!")); + sexo = ConsoleIO.writeChar(); + } + if (sexo == 'M') { + ConsoleIO.print(("MASCULINO!")); + } else { + ConsoleIO.print(("FEMININO!")); + + } + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private static javax.swing.JTextPane _console; + private javax.swing.JScrollPane jScrollPane1; + // End of variables declaration//GEN-END:variables +} diff --git a/Test/br/com/console3/ConsoleIO.java b/Test/br/com/console3/ConsoleIO.java new file mode 100644 index 0000000..5db331a --- /dev/null +++ b/Test/br/com/console3/ConsoleIO.java @@ -0,0 +1,284 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package br.com.console3; + +import java.awt.Color; +import java.awt.Toolkit; +import java.awt.event.KeyEvent; +import static java.awt.event.KeyEvent.VK_BACK_SPACE; +import static java.awt.event.KeyEvent.VK_DOWN; +import static java.awt.event.KeyEvent.VK_LEFT; +import static java.awt.event.KeyEvent.VK_UP; +import java.awt.event.KeyListener; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.JTextPane; +import javax.swing.text.BadLocationException; +import javax.swing.text.Document; +import javax.swing.text.SimpleAttributeSet; + +/** + * + * @author SIMONETO-2 + */ +public class ConsoleIO implements KeyListener { + + private final String header = "[Sistema ~] > "; + private JTextPane console; + private Document doc; + + public static int caret_min_position = -1; + + private boolean key_enter = false; + private boolean block = true; + private boolean write = false; + private boolean write_tipo_int = false; + private boolean write_tipo_float = false; + private boolean write_tipo_char = false; + private int write_tipo_char_count = 0; + + public ConsoleIO(JTextPane console) { + this.console = console; + doc = this.console.getDocument(); + console.addKeyListener(this); + console.setCaretColor(Color.decode("#999999")); + console.setCaret(new CaretConsole()); + } + + private int textLength() { + return doc.getLength(); + } + + public void print(int position, Object t, SimpleAttributeSet style) { + try { + doc.insertString(position, ""+t, style); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public void print(Object t) { + print(textLength(), t, null); + } + + public void print(Object t, SimpleAttributeSet style) { + print(textLength(), t + "\n", style); + } + + public void println(Object t) { + print(textLength(), t + "\n", null); + } + + public void println(Object t, SimpleAttributeSet style) { + print(textLength(), t + "\n", style); + } + + public String writeString() { + + write(); + String retorno = null; + + lock(); + + try { + retorno = doc.getText(caret_min_position, textLength() - caret_min_position); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + + write = false; + print("\n"); + + return retorno; + } + + public int writeInt() { + + write(); + + write_tipo_int = true; + int retorno = 0; + String r = ""; + + lock(); + + try { + r = doc.getText(caret_min_position, textLength() - caret_min_position); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + + retorno = new Integer(r); + + write = false; + write_tipo_int = false; + print("\n"); + + return retorno; + } + + public float writeFloat() { + + write(); + + write_tipo_int = true; + float retorno = 0; + String r = ""; + + lock(); + + try { + r = doc.getText(caret_min_position, textLength() - caret_min_position); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + + retorno = new Float(r); + + write = false; + write_tipo_int = false; + print("\n"); + + return retorno; + } + + public char writeChar() { + + write(); + + write_tipo_char = true; + char retorno; + String r = ""; + + lock(); + + try { + r = doc.getText(caret_min_position, textLength() - caret_min_position); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + + + retorno = r.charAt(0); + + write = false; + write_tipo_char = false; + write_tipo_char_count = 0; + print("\n"); + + return retorno; + } + + private void write() { + key_enter = false; + write = true; + console.requestFocus(); + int tmp_length = textLength(); + console.setCaretPosition(tmp_length); + caret_min_position = tmp_length; + } + + public void finalizacao() { + console.setCaretPosition(textLength()); + } + + public boolean isLocked() { + return block; + } + + public synchronized void lock() { + while (block) { + try { + wait(); + } catch (InterruptedException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + } + block = true; + } + + public synchronized void unlock() { + block = false; + notify(); + } + + @Override + public void keyTyped(KeyEvent e) { + if (write) { + type(e); + } else { + e.consume(); + } + } + + @Override + public void keyPressed(KeyEvent e) { + if (write) { + type(e); + key_enter = false; + } else { + e.consume(); + } + } + + @Override + public void keyReleased(KeyEvent e) { + if (write) { + key_enter = true; + type(e); + } else { + e.consume(); + } + } + + private synchronized void type(KeyEvent e) { + switch (e.getKeyCode()) { + case (KeyEvent.VK_ENTER): + if (e.getID() == KeyEvent.KEY_PRESSED) { + if (key_enter) { + unlock(); + e.consume(); + } + } + break; + case (VK_DOWN): + case (VK_UP): + break; + case (VK_LEFT): + case (VK_BACK_SPACE): + if (caret_min_position == console.getCaretPosition()) { + e.consume(); + Toolkit.getDefaultToolkit().beep(); + } + + if (write_tipo_char) { + write_tipo_char_count = 0; + } + break; + default: + char key = e.getKeyChar(); + if (write_tipo_int) { + String caracteres = "-0123456789"; + if (!caracteres.contains(key + "")) { + e.consume(); + } + } else if (write_tipo_float) { + String caracteres = "-0123456789."; + if (!caracteres.contains(key + "")) { + e.consume(); + } + } else if (write_tipo_char) { + if (write_tipo_char_count < 2) { + write_tipo_char_count++; + } else { + e.consume(); + } + + } + break; + } + } +} diff --git a/Test/br/com/tabsTest/NotepadDemo.java b/Test/br/com/tabsTest/NotepadDemo.java new file mode 100644 index 0000000..2f65213 --- /dev/null +++ b/Test/br/com/tabsTest/NotepadDemo.java @@ -0,0 +1,500 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package br.com.tabsTest; + + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Window; +import java.awt.event.ActionEvent; +import java.awt.event.ContainerAdapter; +import java.awt.event.ContainerEvent; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; + +import javax.swing.AbstractAction; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTabbedPane; +import javax.swing.JTextArea; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.filechooser.FileNameExtensionFilter; + +import org.sexydock.tabs.DefaultFloatingTabHandler; +import org.sexydock.tabs.DefaultTabDropFailureHandler; +import org.sexydock.tabs.DefaultWindowsClosedHandler; +import org.sexydock.tabs.ITabFactory; +import org.sexydock.tabs.ITabbedPaneDndPolicy; +import org.sexydock.tabs.ITabbedPaneWindow; +import org.sexydock.tabs.ITabbedPaneWindowFactory; +import org.sexydock.tabs.Tab; +import org.sexydock.tabs.demos.ISexyTabsDemo; +import org.sexydock.tabs.jhrome.JhromeTabbedPaneUI; + +@SuppressWarnings( "serial" ) +public class NotepadDemo extends JFrame implements ISexyTabsDemo , ITabbedPaneWindow , ITabbedPaneWindowFactory , ITabFactory +{ + public static void main( String[ ] args ) + { + SwingUtilities.invokeLater( new Runnable( ) + { + @Override + public void run( ) + { + new NotepadDemo( ).start( ); + } + } ); + } + + public NotepadDemo( ) + { + initGUI( ); + } + + private void initGUI( ) + { + setTitle( "Notepad" ); + + tabbedPane = new JTabbedPane( ); + tabbedPane.setUI( new JhromeTabbedPaneUI( ) ); + tabbedPane.putClientProperty( JhromeTabbedPaneUI.NEW_TAB_BUTTON_VISIBLE , true ); + tabbedPane.putClientProperty( JhromeTabbedPaneUI.TAB_CLOSE_BUTTONS_VISIBLE , true ); + tabbedPane.putClientProperty( JhromeTabbedPaneUI.TAB_DROP_FAILURE_HANDLER , new DefaultTabDropFailureHandler( this ) ); + tabbedPane.putClientProperty( JhromeTabbedPaneUI.TAB_FACTORY , this ); + tabbedPane.putClientProperty( JhromeTabbedPaneUI.FLOATING_TAB_HANDLER , new DefaultFloatingTabHandler( ) ); + tabbedPane.putClientProperty( JhromeTabbedPaneUI.TAB_CLOSE_BUTTONS_VISIBLE , true ); + tabbedPane.putClientProperty( JhromeTabbedPaneUI.DND_POLICY , new ITabbedPaneDndPolicy( ) + { + @Override + public boolean isTearAwayAllowed( JTabbedPane tabbedPane , Tab tab ) + { + return true; + } + + @Override + public boolean isSnapInAllowed( JTabbedPane tabbedPane , Tab tab ) + { + return tab.getContent( ) instanceof NotepadPane; + } + }); + + getContentPane( ).add( tabbedPane , BorderLayout.CENTER ); + + setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE ); + addWindowListener( new DefaultWindowsClosedHandler( ) ); + + saveAction = new SaveAction( ); + JMenuItem openItem = new JMenuItem( new OpenAction( ) ); + JMenuItem saveItem = new JMenuItem( saveAction ); + JMenuItem saveAsItem = new JMenuItem( new SaveAsAction( ) ); + final JMenu fileMenu = new JMenu( "File" ); + fileMenu.add( openItem ); + fileMenu.add( saveItem ); + fileMenu.add( saveAsItem ); + JMenuBar menuBar = new JMenuBar( ); + menuBar.add( fileMenu ); + setJMenuBar( menuBar ); + + tabbedPane.addChangeListener( new ChangeListener( ) + { + @Override + public void stateChanged( ChangeEvent e ) + { + updateTitle( ); + saveAction.update( ); + + fileMenu.setEnabled( tabbedPane.getSelectedComponent( ) instanceof NotepadPane ); + } + } ); + + tabbedPane.addContainerListener( new ContainerAdapter( ) + { + @Override + public void componentRemoved( ContainerEvent e ) + { + if( tabbedPane.getTabCount( ) == 0 ) + { + dispose( ); + } + } + } ); + + tabbedPane.addPropertyChangeListener( new PropertyChangeListener( ) + { + @Override + public void propertyChange( PropertyChangeEvent evt ) + { + if( "indexForTitle".equals( evt.getPropertyName( ) ) ) + { + updateTitle( ); + } + } + } ); + } + + private void updateTitle( ) + { + int index = tabbedPane.getSelectedIndex( ); + setTitle( index < 0 ? "Notepad" : "Notepad - " + tabbedPane.getTitleAt( tabbedPane.getSelectedIndex( ) ) ); + } + + private JTabbedPane tabbedPane; + private SaveAction saveAction; + + private static class NotepadPane extends JPanel + { + public NotepadPane( ) + { + initGUI( ); + } + + private JTextArea textArea; + private JScrollPane textScrollPane; + + private String savedText = ""; + private boolean dirty; + + private File file; + + private void initGUI( ) + { + textArea = new JTextArea( ); + textArea.setLineWrap( true ); + textScrollPane = new JScrollPane( textArea ); + textScrollPane.setPreferredSize( new Dimension( 800 , 600 ) ); + + setLayout( new BorderLayout( ) ); + add( textScrollPane , BorderLayout.CENTER ); + + textArea.getDocument( ).addDocumentListener( new DocumentListener( ) + { + @Override + public void removeUpdate( DocumentEvent e ) + { + updateDirty( ); + } + + @Override + public void insertUpdate( DocumentEvent e ) + { + updateDirty( ); + } + + @Override + public void changedUpdate( DocumentEvent e ) + { + updateDirty( ); + } + } ); + } + + private void updateDirty( ) + { + boolean newDirty = !textArea.getText( ).equals( savedText ); + if( dirty != newDirty ) + { + dirty = newDirty; + updateTabTitle( ); + NotepadDemo notepadDemo = getNotepadDemo( ); + if( notepadDemo != null ) + { + notepadDemo.saveAction.update( ); + } + } + } + + public boolean isDirty( ) + { + return dirty; + } + + public File getFile( ) + { + return file; + } + + public void open( File file ) throws IOException + { + InputStream is = null; + try + { + is = new FileInputStream( file ); + byte[ ] data = new byte[ is.available( ) ]; + is.read( data ); + textArea.setText( new String( data ) ); + savedText = textArea.getText( ); + this.file = file; + updateDirty( ); + updateTabTitle( ); + } + finally + { + if( is != null ) + { + is.close( ); + } + } + } + + public void saveTo( File destFile ) throws IOException + { + BufferedWriter writer = null; + try + { + writer = new BufferedWriter( new FileWriter( destFile ) ); + writer.write( textArea.getText( ) ); + } + finally + { + if( writer != null ) + { + writer.close( ); + } + } + file = destFile; + savedText = textArea.getText( ); + updateDirty( ); + updateTabTitle( ); + } + + public void save( ) throws IOException + { + saveTo( file ); + } + + public JTextArea getTextArea( ) + { + return textArea; + } + + private void updateTabTitle( ) + { + JTabbedPane tabbedPane = getTabbedPane( ); + if( tabbedPane != null ) + { + int index = tabbedPane.indexOfComponent( this ); + if( index >= 0 ) + { + tabbedPane.setTitleAt( index , getTitle( ) ); + } + } + } + + public String getTitle( ) + { + return ( isDirty( ) ? "*" : "" ) + ( file == null ? "Untitled" : file.getName( ) ); + } + + private JTabbedPane getTabbedPane( ) + { + Component c = getParent( ); + while( c != null ) + { + if( c instanceof JTabbedPane ) + { + return ( JTabbedPane ) c; + } + c = c.getParent( ); + } + return null; + } + + private NotepadDemo getNotepadDemo( ) + { + Component c = getParent( ); + while( c != null ) + { + if( c instanceof NotepadDemo ) + { + return ( NotepadDemo ) c; + } + c = c.getParent( ); + } + return null; + } + } + + private class OpenAction extends AbstractAction + { + public OpenAction( ) + { + super( "Open..." ); + } + + @Override + public void actionPerformed( ActionEvent e ) + { + NotepadPane currentPane = ( NotepadPane ) tabbedPane.getSelectedComponent( ); + File file = currentPane.getFile( ); + + JFileChooser fileChooser = new JFileChooser( ); + fileChooser.addChoosableFileFilter( new FileNameExtensionFilter( "Text Files (*.txt)" , "txt" ) ); + fileChooser.setAcceptAllFileFilterUsed( true ); + if( file != null ) + { + fileChooser.setCurrentDirectory( file.getParentFile( ) ); + } + + int choice = fileChooser.showOpenDialog( NotepadDemo.this ); + + if( choice == JFileChooser.APPROVE_OPTION ) + { + try + { + NotepadPane pane = currentPane; + if( currentPane.getFile( ) != null || currentPane.isDirty( ) ) + { + pane = new NotepadPane( ); + } + pane.open( fileChooser.getSelectedFile( ) ); + if( pane != currentPane ) + { + tabbedPane.addTab( pane.getTitle( ) , pane ); + tabbedPane.setSelectedComponent( pane ); + } + } + catch( IOException e1 ) + { + handleException( "Failed to open file; " , e1 ); + } + } + } + } + + private class SaveAction extends AbstractAction + { + public SaveAction( ) + { + super( "Save" ); + } + + public void update( ) + { + if( tabbedPane.getSelectedComponent( ) instanceof NotepadPane ) + { + NotepadPane currentPane = ( NotepadPane ) tabbedPane.getSelectedComponent( ); + setEnabled( currentPane != null && currentPane.getFile( ) != null && currentPane.isDirty( ) ); + } + } + + @Override + public void actionPerformed( ActionEvent e ) + { + NotepadPane currentPane = ( NotepadPane ) tabbedPane.getSelectedComponent( ); + try + { + currentPane.save( ); + } + catch( IOException e1 ) + { + handleException( "Failed to save file" , e1 ); + } + } + } + + private class SaveAsAction extends AbstractAction + { + public SaveAsAction( ) + { + super( "Save As..." ); + } + + @Override + public void actionPerformed( ActionEvent e ) + { + NotepadPane currentPane = ( NotepadPane ) tabbedPane.getSelectedComponent( ); + File file = currentPane.getFile( ); + + JFileChooser fileChooser = new JFileChooser( ); + fileChooser.addChoosableFileFilter( new FileNameExtensionFilter( "Text Files (*.txt)" , "txt" ) ); + fileChooser.setAcceptAllFileFilterUsed( true ); + fileChooser.setSelectedFile( file ); + + int choice = fileChooser.showSaveDialog( NotepadDemo.this ); + + if( choice == JFileChooser.APPROVE_OPTION ) + { + try + { + currentPane.saveTo( fileChooser.getSelectedFile( ) ); + } + catch( IOException e1 ) + { + handleException( "Failed to save file; " , e1 ); + } + } + } + } + + private void handleException( String message , Exception e ) + { + JOptionPane.showConfirmDialog( this , message + e.getLocalizedMessage( ) , "I/O error" , JOptionPane.ERROR_MESSAGE ); + } + + @Override + public Tab createTab( ) + { + return new Tab( ); + } + + @Override + public Tab createTabWithContent( ) + { + Tab tab = new Tab( ); + tab.setTitle( "Untitled" ); + tab.setContent( new NotepadPane( ) ); + return tab; + } + + @Override + public ITabbedPaneWindow createWindow( ) + { + return new NotepadDemo( ); + } + + @Override + public JTabbedPane getTabbedPane( ) + { + return tabbedPane; + } + + @Override + public Window getWindow( ) + { + return this; + } + + @Override + public void start( ) + { + NotepadDemo notepadDemo = new NotepadDemo( ); + Tab newTab = notepadDemo.createTabWithContent( ); + notepadDemo.getTabbedPane( ).addTab( newTab.getTitle( ) , newTab.getContent( ) ); + notepadDemo.pack( ); + notepadDemo.setLocationRelativeTo( null ); + notepadDemo.setVisible( true ); + NotepadPane notepadPane = ( NotepadPane ) newTab.getContent( ); + notepadPane.getTextArea( ).requestFocus( ); + } +} \ No newline at end of file diff --git a/Test/br/com/tabsTest/TabTest.form b/Test/br/com/tabsTest/TabTest.form new file mode 100644 index 0000000..7bc1123 --- /dev/null +++ b/Test/br/com/tabsTest/TabTest.form @@ -0,0 +1,124 @@ + + +
        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        diff --git a/Test/br/com/tabsTest/TabTest.java b/Test/br/com/tabsTest/TabTest.java new file mode 100644 index 0000000..dc6b9f0 --- /dev/null +++ b/Test/br/com/tabsTest/TabTest.java @@ -0,0 +1,124 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package br.com.tabsTest; + +import com.alee.laf.WebLookAndFeel; +import java.awt.Color; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.LookAndFeel; +import javax.swing.UIManager; +import javax.swing.UnsupportedLookAndFeelException; +import org.sexydock.tabs.jhrome.JhromeTabbedPaneUI; + +/** + * + * @author SIMONETO-2 + */ +public class TabTest extends javax.swing.JFrame { + + /** + * Creates new form TabTest + */ + public TabTest() { + initComponents(); + + tab.putClientProperty(JhromeTabbedPaneUI.TAB_CLOSE_BUTTONS_VISIBLE, true); + + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + tab = new javax.swing.JTabbedPane(); + jScrollPane1 = new javax.swing.JScrollPane(); + jEditorPane1 = new javax.swing.JEditorPane(); + jScrollPane2 = new javax.swing.JScrollPane(); + jEditorPane2 = new javax.swing.JEditorPane(); + jScrollPane3 = new javax.swing.JScrollPane(); + jEditorPane3 = new javax.swing.JEditorPane(); + jMenuBar1 = new javax.swing.JMenuBar(); + jMenu1 = new javax.swing.JMenu(); + jMenu2 = new javax.swing.JMenu(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + + jEditorPane1.setBorder(javax.swing.BorderFactory.createEtchedBorder()); + jScrollPane1.setViewportView(jEditorPane1); + + tab.addTab("tab1", jScrollPane1); + + jScrollPane2.setViewportView(jEditorPane2); + + tab.addTab("tab2", jScrollPane2); + + jScrollPane3.setViewportView(jEditorPane3); + + tab.addTab("tab3", jScrollPane3); + + jMenu1.setText("File"); + jMenuBar1.add(jMenu1); + + jMenu2.setText("Edit"); + jMenuBar1.add(jMenu2); + + setJMenuBar(jMenuBar1); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(tab, javax.swing.GroupLayout.DEFAULT_SIZE, 591, Short.MAX_VALUE) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addContainerGap() + .addComponent(tab, javax.swing.GroupLayout.DEFAULT_SIZE, 402, Short.MAX_VALUE)) + ); + + pack(); + }// //GEN-END:initComponents + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { + Logger.getLogger(TabTest.class.getName()).log(Level.SEVERE, null, ex); + } + + UIManager.getDefaults().put("TabbedPaneUI", JhromeTabbedPaneUI.class.getName()); + + /* Create and display the form */ + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() { + new TabTest().setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JEditorPane jEditorPane1; + private javax.swing.JEditorPane jEditorPane2; + private javax.swing.JEditorPane jEditorPane3; + private javax.swing.JMenu jMenu1; + private javax.swing.JMenu jMenu2; + private javax.swing.JMenuBar jMenuBar1; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JScrollPane jScrollPane2; + private javax.swing.JScrollPane jScrollPane3; + private javax.swing.JTabbedPane tab; + // End of variables declaration//GEN-END:variables +} diff --git a/Test/br/forms/Portugol/DnDTabbedPane.java b/Test/br/forms/Portugol/DnDTabbedPane.java new file mode 100644 index 0000000..17f5d4c --- /dev/null +++ b/Test/br/forms/Portugol/DnDTabbedPane.java @@ -0,0 +1,417 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package br.forms.Portugol; + +import java.awt.*; +import java.awt.datatransfer.*; +import java.awt.dnd.*; +import java.awt.event.*; +import java.awt.image.*; +import javax.swing.*; + +class DnDTabbedPane extends JTabbedPane { + + private static final int LINEWIDTH = 3; + private static final String NAME = "test"; + private final GhostGlassPane glassPane = new GhostGlassPane(); + private final Rectangle lineRect = new Rectangle(); + private final Color lineColor = new Color(0, 0, 0); + private int dragTabIndex = -1; + + private void clickArrowButton(String actionKey) { + ActionMap map = getActionMap(); + if (map != null) { + Action action = map.get(actionKey); + if (action != null && action.isEnabled()) { + action.actionPerformed(new ActionEvent( + this, ActionEvent.ACTION_PERFORMED, null, 0, 0)); + } + } + } + private static Rectangle rBackward = new Rectangle(); + private static Rectangle rForward = new Rectangle(); + private static int rwh = 20; + private static int buttonsize = 30;//XXX: magic number of scroll button size + + private void autoScrollTest(Point glassPt) { + Rectangle r = getTabAreaBounds(); + int tabPlacement = getTabPlacement(); + if (tabPlacement == TOP || tabPlacement == BOTTOM) { + rBackward.setBounds(r.x, r.y, rwh, r.height); + rForward.setBounds( + r.x + r.width - rwh - buttonsize, r.y, rwh + buttonsize, r.height); + } else if (tabPlacement == LEFT || tabPlacement == RIGHT) { + rBackward.setBounds(r.x, r.y, r.width, rwh); + rForward.setBounds( + r.x, r.y + r.height - rwh - buttonsize, r.width, rwh + buttonsize); + } + rBackward = SwingUtilities.convertRectangle( + getParent(), rBackward, glassPane); + rForward = SwingUtilities.convertRectangle( + getParent(), rForward, glassPane); + if (rBackward.contains(glassPt)) { + //System.out.println(new java.util.Date() + "Backward"); + clickArrowButton("scrollTabsBackwardAction"); + } else if (rForward.contains(glassPt)) { + //System.out.println(new java.util.Date() + "Forward"); + clickArrowButton("scrollTabsForwardAction"); + } + } + + public DnDTabbedPane() { + super(); + final DragSourceListener dsl = new DragSourceListener() { + @Override + public void dragEnter(DragSourceDragEvent e) { + e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop); + } + + @Override + public void dragExit(DragSourceEvent e) { + e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop); + lineRect.setRect(0, 0, 0, 0); + glassPane.setPoint(new Point(-1000, -1000)); + glassPane.repaint(); + } + + @Override + public void dragOver(DragSourceDragEvent e) { + Point glassPt = e.getLocation(); + SwingUtilities.convertPointFromScreen(glassPt, glassPane); + int targetIdx = getTargetTabIndex(glassPt); + //if(getTabAreaBounds().contains(tabPt) && targetIdx>=0 && + if (getTabAreaBounds().contains(glassPt) && targetIdx >= 0 + && targetIdx != dragTabIndex && targetIdx != dragTabIndex + 1) { + e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop); + glassPane.setCursor(DragSource.DefaultMoveDrop); + } else { + e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop); + glassPane.setCursor(DragSource.DefaultMoveNoDrop); + } + } + + @Override + public void dragDropEnd(DragSourceDropEvent e) { + lineRect.setRect(0, 0, 0, 0); + dragTabIndex = -1; + glassPane.setVisible(false); + if (hasGhost()) { + glassPane.setVisible(false); + glassPane.setImage(null); + } + } + + @Override + public void dropActionChanged(DragSourceDragEvent e) { + } + }; + final Transferable t = new Transferable() { + private final DataFlavor FLAVOR = new DataFlavor( + DataFlavor.javaJVMLocalObjectMimeType, NAME); + + @Override + public Object getTransferData(DataFlavor flavor) { + return DnDTabbedPane.this; + } + + @Override + public DataFlavor[] getTransferDataFlavors() { + DataFlavor[] f = new DataFlavor[1]; + f[0] = this.FLAVOR; + return f; + } + + @Override + public boolean isDataFlavorSupported(DataFlavor flavor) { + return flavor.getHumanPresentableName().equals(NAME); + } + }; + final DragGestureListener dgl = new DragGestureListener() { + @Override + public void dragGestureRecognized(DragGestureEvent e) { + if (getTabCount() <= 1) { + return; + } + Point tabPt = e.getDragOrigin(); + dragTabIndex = indexAtLocation(tabPt.x, tabPt.y); + //"disabled tab problem". + if (dragTabIndex < 0 || !isEnabledAt(dragTabIndex)) { + return; + } + initGlassPane(e.getComponent(), e.getDragOrigin()); + try { + e.startDrag(DragSource.DefaultMoveDrop, t, dsl); + } catch (InvalidDnDOperationException idoe) { + idoe.printStackTrace(); + } + } + }; + new DropTarget(glassPane, DnDConstants.ACTION_COPY_OR_MOVE, + new CDropTargetListener(), true); + new DragSource().createDefaultDragGestureRecognizer( + this, DnDConstants.ACTION_COPY_OR_MOVE, dgl); + } + + class CDropTargetListener implements DropTargetListener { + + @Override + public void dragEnter(DropTargetDragEvent e) { + if (isDragAcceptable(e)) { + e.acceptDrag(e.getDropAction()); + } else { + e.rejectDrag(); + } + } + + @Override + public void dragExit(DropTargetEvent e) { + } + + @Override + public void dropActionChanged(DropTargetDragEvent e) { + } + + private Point _glassPt = new Point(); + + @Override + public void dragOver(final DropTargetDragEvent e) { + Point glassPt = e.getLocation(); + if (getTabPlacement() == JTabbedPane.TOP + || getTabPlacement() == JTabbedPane.BOTTOM) { + initTargetLeftRightLine(getTargetTabIndex(glassPt)); + } else { + initTargetTopBottomLine(getTargetTabIndex(glassPt)); + } + if (hasGhost()) { + glassPane.setPoint(glassPt); + } + if (!_glassPt.equals(glassPt)) { + glassPane.repaint(); + } + _glassPt = glassPt; + autoScrollTest(glassPt); + } + + @Override + public void drop(DropTargetDropEvent e) { + if (isDropAcceptable(e)) { + convertTab(dragTabIndex, getTargetTabIndex(e.getLocation())); + e.dropComplete(true); + } else { + e.dropComplete(false); + } + repaint(); + } + + private boolean isDragAcceptable(DropTargetDragEvent e) { + Transferable t = e.getTransferable(); + if (t == null) { + return false; + } + DataFlavor[] f = e.getCurrentDataFlavors(); + if (t.isDataFlavorSupported(f[0]) && dragTabIndex >= 0) { + return true; + } + return false; + } + + private boolean isDropAcceptable(DropTargetDropEvent e) { + Transferable t = e.getTransferable(); + if (t == null) { + return false; + } + DataFlavor[] f = t.getTransferDataFlavors(); + if (t.isDataFlavorSupported(f[0]) && dragTabIndex >= 0) { + return true; + } + return false; + } + } + + private boolean hasGhost = true; + + public void setPaintGhost(boolean flag) { + hasGhost = flag; + } + + public boolean hasGhost() { + return hasGhost; + } + private boolean isPaintScrollArea = false; + + public void setPaintScrollArea(boolean flag) { + isPaintScrollArea = flag; + } + + public boolean isPaintScrollArea() { + return isPaintScrollArea; + } + + private int getTargetTabIndex(Point glassPt) { + Point tabPt = SwingUtilities.convertPoint( + glassPane, glassPt, DnDTabbedPane.this); + boolean isTB = getTabPlacement() == JTabbedPane.TOP + || getTabPlacement() == JTabbedPane.BOTTOM; + for (int i = 0; i < getTabCount(); i++) { + Rectangle r = getBoundsAt(i); + if (isTB) { + r.setRect(r.x - r.width / 2, r.y, r.width, r.height); + } else { + r.setRect(r.x, r.y - r.height / 2, r.width, r.height); + } + if (r.contains(tabPt)) { + return i; + } + } + Rectangle r = getBoundsAt(getTabCount() - 1); + if (isTB) { + r.setRect(r.x + r.width / 2, r.y, r.width, r.height); + } else { + r.setRect(r.x, r.y + r.height / 2, r.width, r.height); + } + return r.contains(tabPt) ? getTabCount() : -1; + } + + private void convertTab(int prev, int next) { + if (next < 0 || prev == next) { + return; + } + Component cmp = getComponentAt(prev); + Component tab = getTabComponentAt(prev); + String str = getTitleAt(prev); + Icon icon = getIconAt(prev); + String tip = getToolTipTextAt(prev); + boolean flg = isEnabledAt(prev); + int tgtindex = prev > next ? next : next - 1; + remove(prev); + insertTab(str, icon, cmp, tip, tgtindex); + setEnabledAt(tgtindex, flg); + //When you drag'n'drop a disabled tab, it finishes enabled and selected. + //pointed out by dlorde + if (flg) { + setSelectedIndex(tgtindex); + } + + //I have a component in all tabs (jlabel with an X to close the tab) + //and when i move a tab the component disappear. + //pointed out by Daniel Dario Morales Salas + setTabComponentAt(tgtindex, tab); + } + + private void initTargetLeftRightLine(int next) { + if (next < 0 || dragTabIndex == next || next - dragTabIndex == 1) { + lineRect.setRect(0, 0, 0, 0); + } else if (next == 0) { + Rectangle r = SwingUtilities.convertRectangle( + this, getBoundsAt(0), glassPane); + lineRect.setRect(r.x - LINEWIDTH / 2, r.y, LINEWIDTH, r.height); + } else { + Rectangle r = SwingUtilities.convertRectangle( + this, getBoundsAt(next - 1), glassPane); + lineRect.setRect(r.x + r.width - LINEWIDTH / 2, r.y, LINEWIDTH, r.height); + } + } + + private void initTargetTopBottomLine(int next) { + if (next < 0 || dragTabIndex == next || next - dragTabIndex == 1) { + lineRect.setRect(0, 0, 0, 0); + } else if (next == 0) { + Rectangle r = SwingUtilities.convertRectangle( + this, getBoundsAt(0), glassPane); + lineRect.setRect(r.x, r.y - LINEWIDTH / 2, r.width, LINEWIDTH); + } else { + Rectangle r = SwingUtilities.convertRectangle( + this, getBoundsAt(next - 1), glassPane); + lineRect.setRect(r.x, r.y + r.height - LINEWIDTH / 2, r.width, LINEWIDTH); + } + } + + private void initGlassPane(Component c, Point tabPt) { + getRootPane().setGlassPane(glassPane); + if (hasGhost()) { + Rectangle rect = getBoundsAt(dragTabIndex); + BufferedImage image = new BufferedImage( + c.getWidth(), c.getHeight(), BufferedImage.TYPE_INT_ARGB); + Graphics g = image.getGraphics(); + c.paint(g); + rect.x = rect.x < 0 ? 0 : rect.x; + rect.y = rect.y < 0 ? 0 : rect.y; + image = image.getSubimage(rect.x, rect.y, rect.width, rect.height); + glassPane.setImage(image); + } + Point glassPt = SwingUtilities.convertPoint(c, tabPt, glassPane); + glassPane.setPoint(glassPt); + glassPane.setVisible(true); + } + + private Rectangle getTabAreaBounds() { + Rectangle tabbedRect = getBounds(); + //pointed out by daryl. NullPointerException: i.e. addTab("Tab",null) + //Rectangle compRect = getSelectedComponent().getBounds(); + Component comp = getSelectedComponent(); + int idx = 0; + while (comp == null && idx < getTabCount()) { + comp = getComponentAt(idx++); + } + Rectangle compRect = (comp == null) ? new Rectangle() : comp.getBounds(); + int tabPlacement = getTabPlacement(); + if (tabPlacement == TOP) { + tabbedRect.height = tabbedRect.height - compRect.height; + } else if (tabPlacement == BOTTOM) { + tabbedRect.y = tabbedRect.y + compRect.y + compRect.height; + tabbedRect.height = tabbedRect.height - compRect.height; + } else if (tabPlacement == LEFT) { + tabbedRect.width = tabbedRect.width - compRect.width; + } else if (tabPlacement == RIGHT) { + tabbedRect.x = tabbedRect.x + compRect.x + compRect.width; + tabbedRect.width = tabbedRect.width - compRect.width; + } + tabbedRect.grow(2, 2); + return tabbedRect; + } + + class GhostGlassPane extends JPanel { + + private final AlphaComposite composite; + private Point location = new Point(0, 0); + private BufferedImage draggingGhost = null; + + public GhostGlassPane() { + setOpaque(false); + composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f); + //http://bugs.sun.com/view_bug.do?bug_id=6700748 + //setCursor(null); + } + + public void setImage(BufferedImage draggingGhost) { + this.draggingGhost = draggingGhost; + } + + public void setPoint(Point location) { + this.location = location; + } + + @Override + public void paintComponent(Graphics g) { + Graphics2D g2 = (Graphics2D) g; + g2.setComposite(composite); + if (isPaintScrollArea() && getTabLayoutPolicy() == SCROLL_TAB_LAYOUT) { + g2.setPaint(Color.RED); + g2.fill(rBackward); + g2.fill(rForward); + } + if (draggingGhost != null) { + double xx = location.getX() - (draggingGhost.getWidth(this) / 2d); + double yy = location.getY() - (draggingGhost.getHeight(this) / 2d); + g2.drawImage(draggingGhost, (int) xx, (int) yy, null); + } + if (dragTabIndex >= 0) { + g2.setPaint(lineColor); + g2.fill(lineRect); + } + } + } +} diff --git a/Test/br/forms/Portugol/config.properties b/Test/br/forms/Portugol/config.properties new file mode 100644 index 0000000..fcbf8a0 --- /dev/null +++ b/Test/br/forms/Portugol/config.properties @@ -0,0 +1,75 @@ +Components = jsyntaxpane.components.PairsMarker, \jsyntaxpane.components.LineNumbersRuler +#, \jsyntaxpane.components.TokenMarker +TokenMarker.TokenTypes = IDENTIFIER, TYPE + + +TokenMarker.Color = 0x646464 +PairMarker.Color = 0x646464 + + +LineNumbers.RightMargin = 7 +LineNumbers.Foreground = 0xFFFFFF +LineNumbers.Background 0x272822 + +CaretColor = 0xFFFFFF +DefaultFont = Ubuntu, 13 + +Style.KEYWORD = 0x66d9ef, 0 +Style.KEYWORD2 = 0xf92672, 0 +Style.STRING = 0xe6db74, 0 +Style.COMMENT = 0x8f908a, 2 +Style.TYPE = 0xf92672, 0 +Style.NUMBER = 0xae81ff, 1 + +Style.DEFAULT = 0xFFFFFF, 0 +Style.IDENTIFIER = 0xFFFFFF, 0 +Style.OPERATOR = 0xFFFFFF, 0 + + +Action.complete-word.WordsRegexp = \\w+(\\?)? + +Action.undo = jsyntaxpane.actions.UndoAction, menu Z +Action.undo.MenuText = Voltar + +Action.redo = jsyntaxpane.actions.RedoAction, menu Y +Action.redo.MenuText = Refazer + +Action.indent.MenuText = Identar + +DefaultAction.select-all.MenuText = Selecionar tudo +DefaultAction.copy-to-clipboard.MenuText = Copiar +DefaultAction.cut-to-clipboard.MenuText = Recortar +DefaultAction.paste-from-clipboard.MenuText = Colar + +TextAA = ON + +DEFAULT_EDIT_MENU= \ + cut-to-clipboard , \ + copy-to-clipboard , \ + paste-from-clipboard , \ + - , \ + select-all , \ + - , \ + undo , \ + redo , \ + - , \ + indent +PopupMenu = \ + ${DEFAULT_EDIT_MENU} , \ + - , \ + goto-line + + + +ReplaceDialog.jChkRegex.text=Regular Expression +ReplaceDialog.jChkIgnoreCase.text=Ignore Case +ReplaceDialog.jLblReplace.text=Replace +ReplaceDialog.jTglHighlight.text=Highlight +ReplaceDialog.jBtnReplaceAll.text=Replace All +ReplaceDialog.jBtnPrev.text=Anterior +ReplaceDialog.jChkWrap.toolTipText=Wrap to beginning when end is reached +ReplaceDialog.jChkWrap.text=Wrap around +ReplaceDialog.title=Localizar e substituir +ReplaceDialog.jBtnNext.text=Next +ReplaceDialog.jLblFind.text=Find +ReplaceDialog.jBtnReplace.text=Replace \ No newline at end of file diff --git a/Test/com/analizador/algoritmoName/AlgoritmoName.cup b/Test/com/analizador/algoritmoName/AlgoritmoName.cup new file mode 100644 index 0000000..4600097 --- /dev/null +++ b/Test/com/analizador/algoritmoName/AlgoritmoName.cup @@ -0,0 +1,23 @@ +package com.analizador.algoritmoName; + +import java_cup.runtime.*; + +parser code +{: + public static void main(String args[]) throws Exception{ + new parser(new Yylex(System.in)).parse(); + } + public void syntax_error(Symbol s){ + report_error("Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right)+". Trecho desconhecido: \""+s.value+"\"",null); + } +:} + +terminal ALGORITMO,ID,STRING; + +non terminal algoritmo,instanciacao; + + + +algoritmo ::= algoritmo instanciacao | instanciacao | error {: :}; + +instanciacao ::= ALGORITMO ID:e {: System.out.println("String ALGORITMO = \""+e+"\";"); :} | ALGORITMO STRING:e {: System.out.println("String ALGORITMO = \""+e+"\";"); :}; \ No newline at end of file diff --git a/Test/com/analizador/algoritmoName/AlgoritmoName.flex b/Test/com/analizador/algoritmoName/AlgoritmoName.flex new file mode 100644 index 0000000..cdd1e1e --- /dev/null +++ b/Test/com/analizador/algoritmoName/AlgoritmoName.flex @@ -0,0 +1,53 @@ +package com.analizador.algoritmoName; + +import java_cup.runtime.*; + + +%% +/* +* LEXICAL FUNCTIONS: +*/ +%cup +%line +%char +%column + +%{ + + Symbol newSym(int tokenId) { + return new Symbol(tokenId , yyline, yycolumn); + } + + Symbol newSym(int tokenId, Object value) { + return new Symbol(tokenId , yyline, yycolumn, value); + } + +%} + + +letras = [A-Za-z] +numeros = [0-9] +alphanumeric = {letras}|{numeros} +underline = [_] +identifier = {letras}({alphanumeric}|{underline})* + +whitespace = [\n\r\ \t] +string_content = (\\\"|[^\n\r\"]|\\{whitespace}+\\)* +string_literal = {double_qoute}{string_content}{double_qoute} +double_qoute = \" +newline = \r|\n|\r\n + + +%% +(algoritmo|ALGORITMO) {return newSym(sym.ALGORITMO,yytext());} + +{identifier} {return newSym(sym.ID,yytext());} +{string_literal} { return newSym(sym.STRING, yytext().substring(1, yylength()-1)); } + +{newline} {/* IGNORE */} +{whitespace} {/* IGNORE */} + + + +<> {return newSym(sym.EOF);} +. {return newSym(sym.error,yytext());} \ No newline at end of file diff --git a/Test/com/analizador/algoritmoName/AnalizerP1.java b/Test/com/analizador/algoritmoName/AnalizerP1.java new file mode 100644 index 0000000..0664d23 --- /dev/null +++ b/Test/com/analizador/algoritmoName/AnalizerP1.java @@ -0,0 +1,26 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package com.analizador.algoritmoName; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; + +/** + * + * @author Andrew + */ +public class AnalizerP1 { + + public AnalizerP1() throws FileNotFoundException, Exception{ + File f = new File("C:\\Users\\Andrew\\Documents\\NetBeansProjects\\portugol-projeto\\Test\\com\\analizador\\algoritmoName\\Exemplo.txt"); + Yylex lexer = new Yylex(new FileInputStream(f)); + parser p = new parser(lexer); + p.parse(); + } + +} diff --git a/Test/com/analizador/algoritmoName/Exemplo.txt b/Test/com/analizador/algoritmoName/Exemplo.txt new file mode 100644 index 0000000..71d8e33 --- /dev/null +++ b/Test/com/analizador/algoritmoName/Exemplo.txt @@ -0,0 +1 @@ +algoritmo "andrew" \ No newline at end of file diff --git a/Test/com/analizador/algoritmoName/Inicializador.java b/Test/com/analizador/algoritmoName/Inicializador.java new file mode 100644 index 0000000..1b15684 --- /dev/null +++ b/Test/com/analizador/algoritmoName/Inicializador.java @@ -0,0 +1,36 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.analizador.algoritmoName; + +import com.analizador.exe_expressao.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.StringReader; + +/** + * + * @author Andrew + */ +public class Inicializador { + + public static void main(String[] args) throws IOException, Exception { + //Yylex lexer = new Yylex(new StringReader("2+9")); + Yylex lexer = new Yylex(Inicializador.class.getResourceAsStream("Exemplo.txt")); + /* + Symbol sym; + for (sym = lexer.next_token(); sym.sym != 0; sym = lexer.next_token()) { + System.out.println("Token " + sym.sym + ", with value = " + sym.value + "; at line " + sym.left + ", column " + sym.right); + } + */ + + + parser p = new parser(lexer); + p.parse(); + + } + +} diff --git a/Test/com/analizador/algoritmoName/Yylex.java b/Test/com/analizador/algoritmoName/Yylex.java new file mode 100644 index 0000000..301172c --- /dev/null +++ b/Test/com/analizador/algoritmoName/Yylex.java @@ -0,0 +1,665 @@ +/* The following code was generated by JFlex 1.5.1 */ + +package com.analizador.algoritmoName; + +import java_cup.runtime.*; + + + +/** + * This class is a scanner generated by + * JFlex 1.5.1 + * from the specification file C:/Users/Andrew/Documents/NetBeansProjects/portugol-projeto/Test/com/analizador/algoritmoName/AlgoritmoName.flex + */ +class Yylex implements java_cup.runtime.Scanner { + + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int YYINITIAL = 0; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l + * at the beginning of a line + * l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { + 0, 0 + }; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = + "\11\0\1\3\1\6\1\30\1\30\1\7\22\0\1\3\1\0\1\5"+ + "\15\0\12\2\7\0\1\20\5\1\1\22\1\1\1\25\2\1\1\21"+ + "\1\27\1\1\1\23\2\1\1\24\1\1\1\26\6\1\1\0\1\4"+ + "\2\0\1\2\1\0\1\10\5\1\1\12\1\1\1\15\2\1\1\11"+ + "\1\17\1\1\1\13\2\1\1\14\1\1\1\16\6\1\12\0\1\30"+ + "\u1fa2\0\1\30\1\30\udfd6\0"; + + /** + * Translates characters to character classes + */ + private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int [] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = + "\1\0\1\1\1\2\1\3\1\1\1\3\2\2\2\0"+ + "\1\4\2\2\1\0\1\4\1\0\14\2\1\5"; + + private static int [] zzUnpackAction() { + int [] result = new int[29]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /** + * Translates a state to a row index in the transition table + */ + private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = + "\0\0\0\31\0\62\0\31\0\113\0\144\0\175\0\226"+ + "\0\113\0\257\0\31\0\310\0\341\0\372\0\113\0\u0113"+ + "\0\u012c\0\u0145\0\u015e\0\u0177\0\u0190\0\u01a9\0\u01c2\0\u01db"+ + "\0\u01f4\0\u020d\0\u0226\0\u023f\0\62"; + + private static int [] zzUnpackRowMap() { + int [] result = new int[29]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int [] ZZ_TRANS = zzUnpackTrans(); + + private static final String ZZ_TRANS_PACKED_0 = + "\1\2\1\3\1\2\1\4\1\2\1\5\1\4\1\6"+ + "\1\7\7\3\1\10\7\3\33\0\2\3\5\0\20\3"+ + "\1\0\4\11\1\12\1\13\2\0\21\11\6\0\1\4"+ + "\23\0\2\3\5\0\1\3\1\14\16\3\2\0\2\3"+ + "\5\0\11\3\1\15\6\3\1\0\3\11\1\16\1\12"+ + "\1\17\2\20\21\11\1\0\2\3\5\0\2\3\1\21"+ + "\15\3\2\0\2\3\5\0\12\3\1\22\5\3\1\0"+ + "\3\11\1\16\1\12\1\13\2\20\21\11\3\0\1\20"+ + "\1\11\1\0\2\20\22\0\2\3\5\0\3\3\1\23"+ + "\14\3\2\0\2\3\5\0\13\3\1\24\4\3\2\0"+ + "\2\3\5\0\4\3\1\25\13\3\2\0\2\3\5\0"+ + "\14\3\1\26\3\3\2\0\2\3\5\0\5\3\1\27"+ + "\12\3\2\0\2\3\5\0\15\3\1\30\2\3\2\0"+ + "\2\3\5\0\6\3\1\31\11\3\2\0\2\3\5\0"+ + "\16\3\1\32\1\3\2\0\2\3\5\0\7\3\1\33"+ + "\10\3\2\0\2\3\5\0\17\3\1\34\2\0\2\3"+ + "\5\0\3\3\1\35\14\3\2\0\2\3\5\0\13\3"+ + "\1\35\4\3\1\0"; + + private static int [] zzUnpackTrans() { + int [] result = new int[600]; + int offset = 0; + offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackTrans(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + value--; + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", + "Error: could not match input", + "Error: pushback value was too large" + }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state aState + */ + private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = + "\1\0\1\11\1\1\1\11\4\1\2\0\1\11\2\1"+ + "\1\0\1\1\1\0\15\1"; + + private static int [] zzUnpackAttribute() { + int [] result = new int[29]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** this buffer contains the current text to be matched and is + the source of the yytext() string */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** endRead marks the last character in the buffer, that has been read + from input */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /** denotes if the user-EOF-code has already been executed */ + private boolean zzEOFDone; + + /* user code: */ + + Symbol newSym(int tokenId) { + return new Symbol(tokenId , yyline, yycolumn); + } + + Symbol newSym(int tokenId, Object value) { + return new Symbol(tokenId , yyline, yycolumn, value); + } + + + + /** + * Creates a new scanner + * There is also a java.io.InputStream version of this constructor. + * + * @param in the java.io.Reader to read input from. + */ + Yylex(java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. + * There is also java.io.Reader version of this constructor. + * + * @param in the java.io.Inputstream to read input from. + */ + Yylex(java.io.InputStream in) { + this(new java.io.InputStreamReader + (in, java.nio.charset.Charset.forName("UTF-8"))); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed the packed character translation table + * @return the unpacked character translation table + */ + private static char [] zzUnpackCMap(String packed) { + char [] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 108) { + int count = packed.charAt(i++); + char value = packed.charAt(i++); + do map[j++] = value; while (--count > 0); + } + return map; + } + + + /** + * Refills the input buffer. + * + * @return false, iff there was new input. + * + * @exception java.io.IOException if any I/O-Error occurs + */ + private boolean zzRefill() throws java.io.IOException { + + /* first: make room (if you can) */ + if (zzStartRead > 0) { + System.arraycopy(zzBuffer, zzStartRead, + zzBuffer, 0, + zzEndRead-zzStartRead); + + /* translate stored positions */ + zzEndRead-= zzStartRead; + zzCurrentPos-= zzStartRead; + zzMarkedPos-= zzStartRead; + zzStartRead = 0; + } + + /* is the buffer big enough? */ + if (zzCurrentPos >= zzBuffer.length) { + /* if not: blow it up */ + char newBuffer[] = new char[zzCurrentPos*2]; + System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); + zzBuffer = newBuffer; + } + + /* finally: fill the buffer with new input */ + int numRead = zzReader.read(zzBuffer, zzEndRead, + zzBuffer.length-zzEndRead); + + if (numRead > 0) { + zzEndRead+= numRead; + return false; + } + // unlikely but not impossible: read 0 characters, but not at end of stream + if (numRead == 0) { + int c = zzReader.read(); + if (c == -1) { + return true; + } else { + zzBuffer[zzEndRead++] = (char) c; + return false; + } + } + + // numRead < 0 + return true; + } + + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) + zzReader.close(); + } + + + /** + * Resets the scanner to read from a new input stream. + * Does not close the old reader. + * + * All internal variables are reset, the old input stream + * cannot be reused (internal buffer is discarded and lost). + * Lexical state is set to ZZ_INITIAL. + * + * Internal scan buffer is resized down to its initial length, if it has grown. + * + * @param reader the new input stream + */ + public final void yyreset(java.io.Reader reader) { + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + zzEOFDone = false; + zzEndRead = zzStartRead = 0; + zzCurrentPos = zzMarkedPos = 0; + yyline = yychar = yycolumn = 0; + zzLexicalState = YYINITIAL; + if (zzBuffer.length > ZZ_BUFFERSIZE) + zzBuffer = new char[ZZ_BUFFERSIZE]; + } + + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + + /** + * Enters a new lexical state + * + * @param newState the new lexical state + */ + public final void yybegin(int newState) { + zzLexicalState = newState; + } + + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); + } + + + /** + * Returns the character at position pos from the + * matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. + * A value from 0 to yylength()-1. + * + * @return the character at position pos + */ + public final char yycharat(int pos) { + return zzBuffer[zzStartRead+pos]; + } + + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos-zzStartRead; + } + + + /** + * Reports an error that occured while scanning. + * + * In a wellformed scanner (no or only correct usage of + * yypushback(int) and a match-all fallback rule) this method + * will only be called with things that "Can't Possibly Happen". + * If this method is called, something is seriously wrong + * (e.g. a JFlex bug producing a faulty scanner etc.). + * + * Usual syntax/scanner level error handling should be done + * in error fallback rules. + * + * @param errorCode the code of the errormessage to display + */ + private void zzScanError(int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } + catch (ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + + /** + * Pushes the specified amount of characters back into the input stream. + * + * They will be read again by then next call of the scanning method + * + * @param number the number of characters to be read again. + * This number must not be greater than yylength()! + */ + public void yypushback(int number) { + if ( number > yylength() ) + zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + + /** + * Contains user EOF-code, which will be executed exactly once, + * when the end of file is reached + */ + private void zzDoEOF() throws java.io.IOException { + if (!zzEOFDone) { + zzEOFDone = true; + yyclose(); + } + } + + + /** + * Resumes scanning until the next regular expression is matched, + * the end of input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException if any I/O-Error occurs + */ + public java_cup.runtime.Symbol next_token() throws java.io.IOException { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char [] zzBufferL = zzBuffer; + char [] zzCMapL = ZZ_CMAP; + + int [] zzTransL = ZZ_TRANS; + int [] zzRowMapL = ZZ_ROWMAP; + int [] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + yychar+= zzMarkedPosL-zzStartRead; + + boolean zzR = false; + for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL; + zzCurrentPosL++) { + switch (zzBufferL[zzCurrentPosL]) { + case '\u000B': + case '\u000C': + case '\u0085': + case '\u2028': + case '\u2029': + yyline++; + yycolumn = 0; + zzR = false; + break; + case '\r': + yyline++; + yycolumn = 0; + zzR = true; + break; + case '\n': + if (zzR) + zzR = false; + else { + yyline++; + yycolumn = 0; + } + break; + default: + zzR = false; + yycolumn++; + } + } + + if (zzR) { + // peek one character ahead if it is \n (if we have counted one line too much) + boolean zzPeek; + if (zzMarkedPosL < zzEndReadL) + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + else if (zzAtEOF) + zzPeek = false; + else { + boolean eof = zzRefill(); + zzEndReadL = zzEndRead; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + if (eof) + zzPeek = false; + else + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + } + if (zzPeek) yyline--; + } + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = ZZ_LEXSTATE[zzLexicalState]; + + // set up zzAction for empty match case: + int zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + } + + + zzForAction: { + while (true) { + + if (zzCurrentPosL < zzEndReadL) + zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } + else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } + else { + zzInput = zzBufferL[zzCurrentPosL++]; + } + } + int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; + if (zzNext == -1) break zzForAction; + zzState = zzNext; + + zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ( (zzAttributes & 8) == 8 ) break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 1: + { return newSym(sym.error,yytext()); + } + case 6: break; + case 2: + { return newSym(sym.ID,yytext()); + } + case 7: break; + case 3: + { /* IGNORE */ + } + case 8: break; + case 4: + { return newSym(sym.STRING, yytext().substring(1, yylength()-1)); + } + case 9: break; + case 5: + { return newSym(sym.ALGORITMO,yytext()); + } + case 10: break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + zzDoEOF(); + { + return newSym(sym.EOF); + } + } + else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + + +} diff --git a/Test/com/analizador/algoritmoName/Yylex.java~ b/Test/com/analizador/algoritmoName/Yylex.java~ new file mode 100644 index 0000000..2cb5f5b --- /dev/null +++ b/Test/com/analizador/algoritmoName/Yylex.java~ @@ -0,0 +1,665 @@ +/* The following code was generated by JFlex 1.5.1 */ + +package com.analizador.exe_expressao; + +import java_cup.runtime.*; + + + +/** + * This class is a scanner generated by + * JFlex 1.5.1 + * from the specification file C:/Users/Andrew/Documents/NetBeansProjects/portugol-projeto/Test/com/analizador/algoritmoName/AlgoritmoName.flex + */ +class Yylex implements java_cup.runtime.Scanner { + + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int YYINITIAL = 0; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l + * at the beginning of a line + * l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { + 0, 0 + }; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = + "\11\0\1\3\1\6\1\30\1\30\1\7\22\0\1\3\1\0\1\5"+ + "\15\0\12\2\7\0\1\20\5\1\1\22\1\1\1\25\2\1\1\21"+ + "\1\27\1\1\1\23\2\1\1\24\1\1\1\26\6\1\1\0\1\4"+ + "\2\0\1\2\1\0\1\10\5\1\1\12\1\1\1\15\2\1\1\11"+ + "\1\17\1\1\1\13\2\1\1\14\1\1\1\16\6\1\12\0\1\30"+ + "\u1fa2\0\1\30\1\30\udfd6\0"; + + /** + * Translates characters to character classes + */ + private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int [] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = + "\1\0\1\1\1\2\1\3\1\1\1\3\2\2\2\0"+ + "\1\4\2\2\1\0\1\4\1\0\14\2\1\5"; + + private static int [] zzUnpackAction() { + int [] result = new int[29]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /** + * Translates a state to a row index in the transition table + */ + private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = + "\0\0\0\31\0\62\0\31\0\113\0\144\0\175\0\226"+ + "\0\113\0\257\0\31\0\310\0\341\0\372\0\113\0\u0113"+ + "\0\u012c\0\u0145\0\u015e\0\u0177\0\u0190\0\u01a9\0\u01c2\0\u01db"+ + "\0\u01f4\0\u020d\0\u0226\0\u023f\0\62"; + + private static int [] zzUnpackRowMap() { + int [] result = new int[29]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int [] ZZ_TRANS = zzUnpackTrans(); + + private static final String ZZ_TRANS_PACKED_0 = + "\1\2\1\3\1\2\1\4\1\2\1\5\1\4\1\6"+ + "\1\7\7\3\1\10\7\3\33\0\2\3\5\0\20\3"+ + "\1\0\4\11\1\12\1\13\2\0\21\11\6\0\1\4"+ + "\23\0\2\3\5\0\1\3\1\14\16\3\2\0\2\3"+ + "\5\0\11\3\1\15\6\3\1\0\3\11\1\16\1\12"+ + "\1\17\2\20\21\11\1\0\2\3\5\0\2\3\1\21"+ + "\15\3\2\0\2\3\5\0\12\3\1\22\5\3\1\0"+ + "\3\11\1\16\1\12\1\13\2\20\21\11\3\0\1\20"+ + "\1\11\1\0\2\20\22\0\2\3\5\0\3\3\1\23"+ + "\14\3\2\0\2\3\5\0\13\3\1\24\4\3\2\0"+ + "\2\3\5\0\4\3\1\25\13\3\2\0\2\3\5\0"+ + "\14\3\1\26\3\3\2\0\2\3\5\0\5\3\1\27"+ + "\12\3\2\0\2\3\5\0\15\3\1\30\2\3\2\0"+ + "\2\3\5\0\6\3\1\31\11\3\2\0\2\3\5\0"+ + "\16\3\1\32\1\3\2\0\2\3\5\0\7\3\1\33"+ + "\10\3\2\0\2\3\5\0\17\3\1\34\2\0\2\3"+ + "\5\0\3\3\1\35\14\3\2\0\2\3\5\0\13\3"+ + "\1\35\4\3\1\0"; + + private static int [] zzUnpackTrans() { + int [] result = new int[600]; + int offset = 0; + offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackTrans(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + value--; + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", + "Error: could not match input", + "Error: pushback value was too large" + }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state aState + */ + private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = + "\1\0\1\11\1\1\1\11\4\1\2\0\1\11\2\1"+ + "\1\0\1\1\1\0\15\1"; + + private static int [] zzUnpackAttribute() { + int [] result = new int[29]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** this buffer contains the current text to be matched and is + the source of the yytext() string */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** endRead marks the last character in the buffer, that has been read + from input */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /** denotes if the user-EOF-code has already been executed */ + private boolean zzEOFDone; + + /* user code: */ + + Symbol newSym(int tokenId) { + return new Symbol(tokenId , yyline, yycolumn); + } + + Symbol newSym(int tokenId, Object value) { + return new Symbol(tokenId , yyline, yycolumn, value); + } + + + + /** + * Creates a new scanner + * There is also a java.io.InputStream version of this constructor. + * + * @param in the java.io.Reader to read input from. + */ + Yylex(java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. + * There is also java.io.Reader version of this constructor. + * + * @param in the java.io.Inputstream to read input from. + */ + Yylex(java.io.InputStream in) { + this(new java.io.InputStreamReader + (in, java.nio.charset.Charset.forName("UTF-8"))); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed the packed character translation table + * @return the unpacked character translation table + */ + private static char [] zzUnpackCMap(String packed) { + char [] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 108) { + int count = packed.charAt(i++); + char value = packed.charAt(i++); + do map[j++] = value; while (--count > 0); + } + return map; + } + + + /** + * Refills the input buffer. + * + * @return false, iff there was new input. + * + * @exception java.io.IOException if any I/O-Error occurs + */ + private boolean zzRefill() throws java.io.IOException { + + /* first: make room (if you can) */ + if (zzStartRead > 0) { + System.arraycopy(zzBuffer, zzStartRead, + zzBuffer, 0, + zzEndRead-zzStartRead); + + /* translate stored positions */ + zzEndRead-= zzStartRead; + zzCurrentPos-= zzStartRead; + zzMarkedPos-= zzStartRead; + zzStartRead = 0; + } + + /* is the buffer big enough? */ + if (zzCurrentPos >= zzBuffer.length) { + /* if not: blow it up */ + char newBuffer[] = new char[zzCurrentPos*2]; + System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); + zzBuffer = newBuffer; + } + + /* finally: fill the buffer with new input */ + int numRead = zzReader.read(zzBuffer, zzEndRead, + zzBuffer.length-zzEndRead); + + if (numRead > 0) { + zzEndRead+= numRead; + return false; + } + // unlikely but not impossible: read 0 characters, but not at end of stream + if (numRead == 0) { + int c = zzReader.read(); + if (c == -1) { + return true; + } else { + zzBuffer[zzEndRead++] = (char) c; + return false; + } + } + + // numRead < 0 + return true; + } + + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) + zzReader.close(); + } + + + /** + * Resets the scanner to read from a new input stream. + * Does not close the old reader. + * + * All internal variables are reset, the old input stream + * cannot be reused (internal buffer is discarded and lost). + * Lexical state is set to ZZ_INITIAL. + * + * Internal scan buffer is resized down to its initial length, if it has grown. + * + * @param reader the new input stream + */ + public final void yyreset(java.io.Reader reader) { + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + zzEOFDone = false; + zzEndRead = zzStartRead = 0; + zzCurrentPos = zzMarkedPos = 0; + yyline = yychar = yycolumn = 0; + zzLexicalState = YYINITIAL; + if (zzBuffer.length > ZZ_BUFFERSIZE) + zzBuffer = new char[ZZ_BUFFERSIZE]; + } + + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + + /** + * Enters a new lexical state + * + * @param newState the new lexical state + */ + public final void yybegin(int newState) { + zzLexicalState = newState; + } + + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); + } + + + /** + * Returns the character at position pos from the + * matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. + * A value from 0 to yylength()-1. + * + * @return the character at position pos + */ + public final char yycharat(int pos) { + return zzBuffer[zzStartRead+pos]; + } + + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos-zzStartRead; + } + + + /** + * Reports an error that occured while scanning. + * + * In a wellformed scanner (no or only correct usage of + * yypushback(int) and a match-all fallback rule) this method + * will only be called with things that "Can't Possibly Happen". + * If this method is called, something is seriously wrong + * (e.g. a JFlex bug producing a faulty scanner etc.). + * + * Usual syntax/scanner level error handling should be done + * in error fallback rules. + * + * @param errorCode the code of the errormessage to display + */ + private void zzScanError(int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } + catch (ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + + /** + * Pushes the specified amount of characters back into the input stream. + * + * They will be read again by then next call of the scanning method + * + * @param number the number of characters to be read again. + * This number must not be greater than yylength()! + */ + public void yypushback(int number) { + if ( number > yylength() ) + zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + + /** + * Contains user EOF-code, which will be executed exactly once, + * when the end of file is reached + */ + private void zzDoEOF() throws java.io.IOException { + if (!zzEOFDone) { + zzEOFDone = true; + yyclose(); + } + } + + + /** + * Resumes scanning until the next regular expression is matched, + * the end of input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException if any I/O-Error occurs + */ + public java_cup.runtime.Symbol next_token() throws java.io.IOException { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char [] zzBufferL = zzBuffer; + char [] zzCMapL = ZZ_CMAP; + + int [] zzTransL = ZZ_TRANS; + int [] zzRowMapL = ZZ_ROWMAP; + int [] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + yychar+= zzMarkedPosL-zzStartRead; + + boolean zzR = false; + for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL; + zzCurrentPosL++) { + switch (zzBufferL[zzCurrentPosL]) { + case '\u000B': + case '\u000C': + case '\u0085': + case '\u2028': + case '\u2029': + yyline++; + yycolumn = 0; + zzR = false; + break; + case '\r': + yyline++; + yycolumn = 0; + zzR = true; + break; + case '\n': + if (zzR) + zzR = false; + else { + yyline++; + yycolumn = 0; + } + break; + default: + zzR = false; + yycolumn++; + } + } + + if (zzR) { + // peek one character ahead if it is \n (if we have counted one line too much) + boolean zzPeek; + if (zzMarkedPosL < zzEndReadL) + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + else if (zzAtEOF) + zzPeek = false; + else { + boolean eof = zzRefill(); + zzEndReadL = zzEndRead; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + if (eof) + zzPeek = false; + else + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + } + if (zzPeek) yyline--; + } + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = ZZ_LEXSTATE[zzLexicalState]; + + // set up zzAction for empty match case: + int zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + } + + + zzForAction: { + while (true) { + + if (zzCurrentPosL < zzEndReadL) + zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } + else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } + else { + zzInput = zzBufferL[zzCurrentPosL++]; + } + } + int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; + if (zzNext == -1) break zzForAction; + zzState = zzNext; + + zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ( (zzAttributes & 8) == 8 ) break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 1: + { return newSym(sym.error,yytext()); + } + case 6: break; + case 2: + { return newSym(sym.ID,yytext()); + } + case 7: break; + case 3: + { /* IGNORE */ + } + case 8: break; + case 4: + { return newSym(sym.STRING, yytext().substring(1, yylength()-1)); + } + case 9: break; + case 5: + { return newSym(sym.ALGORITMO,yytext()); + } + case 10: break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + zzDoEOF(); + { + return newSym(sym.EOF); + } + } + else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + + +} diff --git a/Test/com/analizador/algoritmoName/java_cup.jar b/Test/com/analizador/algoritmoName/java_cup.jar new file mode 100644 index 0000000..73ffa0b Binary files /dev/null and b/Test/com/analizador/algoritmoName/java_cup.jar differ diff --git a/Test/com/analizador/algoritmoName/parser.java b/Test/com/analizador/algoritmoName/parser.java new file mode 100644 index 0000000..8cc4f58 --- /dev/null +++ b/Test/com/analizador/algoritmoName/parser.java @@ -0,0 +1,198 @@ + +//---------------------------------------------------- +// The following code was generated by CUP v0.11a beta 20060608 +// Fri Jun 20 21:54:45 BRT 2014 +//---------------------------------------------------- + +package com.analizador.algoritmoName; + +import java_cup.runtime.*; + +/** CUP v0.11a beta 20060608 generated parser. + * @version Fri Jun 20 21:54:45 BRT 2014 + */ +public class parser extends java_cup.runtime.lr_parser { + + /** Default constructor. */ + public parser() {super();} + + /** Constructor which sets the default scanner. */ + public parser(java_cup.runtime.Scanner s) {super(s);} + + /** Constructor which sets the default scanner. */ + public parser(java_cup.runtime.Scanner s, java_cup.runtime.SymbolFactory sf) {super(s,sf);} + + /** Production table. */ + protected static final short _production_table[][] = + unpackFromStrings(new String[] { + "\000\006\000\002\002\004\000\002\002\004\000\002\002" + + "\003\000\002\002\003\000\002\003\004\000\002\003\004" + + "" }); + + /** Access to production table. */ + public short[][] production_table() {return _production_table;} + + /** Parse-action table. */ + protected static final short[][] _action_table = + unpackFromStrings(new String[] { + "\000\011\000\006\003\004\004\006\001\002\000\006\002" + + "\ufffe\004\ufffe\001\002\000\006\002\uffff\004\uffff\001\002" + + "\000\006\005\012\006\013\001\002\000\006\002\011\004" + + "\006\001\002\000\006\002\001\004\001\001\002\000\004" + + "\002\000\001\002\000\006\002\ufffd\004\ufffd\001\002\000" + + "\006\002\ufffc\004\ufffc\001\002" }); + + /** Access to parse-action table. */ + public short[][] action_table() {return _action_table;} + + /** reduce_goto table. */ + protected static final short[][] _reduce_table = + unpackFromStrings(new String[] { + "\000\011\000\006\002\006\003\004\001\001\000\002\001" + + "\001\000\002\001\001\000\002\001\001\000\004\003\007" + + "\001\001\000\002\001\001\000\002\001\001\000\002\001" + + "\001\000\002\001\001" }); + + /** Access to reduce_goto table. */ + public short[][] reduce_table() {return _reduce_table;} + + /** Instance of action encapsulation class. */ + protected CUP$parser$actions action_obj; + + /** Action encapsulation object initializer. */ + protected void init_actions() + { + action_obj = new CUP$parser$actions(this); + } + + /** Invoke a user supplied parse action. */ + public java_cup.runtime.Symbol do_action( + int act_num, + java_cup.runtime.lr_parser parser, + java.util.Stack stack, + int top) + throws java.lang.Exception + { + /* call code in generated class */ + return action_obj.CUP$parser$do_action(act_num, parser, stack, top); + } + + /** Indicates start state. */ + public int start_state() {return 0;} + /** Indicates start production. */ + public int start_production() {return 1;} + + /** EOF Symbol index. */ + public int EOF_sym() {return 0;} + + /** error Symbol index. */ + public int error_sym() {return 1;} + + + + public static void main(String args[]) throws Exception{ + new parser(new Yylex(System.in)).parse(); + } + public void syntax_error(Symbol s){ + report_error("Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right)+". Trecho desconhecido: \""+s.value+"\"",null); + } + +} + +/** Cup generated class to encapsulate user supplied action code.*/ +class CUP$parser$actions { + private final parser parser; + + /** Constructor */ + CUP$parser$actions(parser parser) { + this.parser = parser; + } + + /** Method with the actual generated action code. */ + public final java_cup.runtime.Symbol CUP$parser$do_action( + int CUP$parser$act_num, + java_cup.runtime.lr_parser CUP$parser$parser, + java.util.Stack CUP$parser$stack, + int CUP$parser$top) + throws java.lang.Exception + { + /* Symbol object for return from actions */ + java_cup.runtime.Symbol CUP$parser$result; + + /* select the action based on the action number */ + switch (CUP$parser$act_num) + { + /*. . . . . . . . . . . . . . . . . . . .*/ + case 5: // instanciacao ::= ALGORITMO STRING + { + Object RESULT =null; + int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + Object e = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + System.out.println("String ALGORITMO = \""+e+"\";"); + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao",1, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 4: // instanciacao ::= ALGORITMO ID + { + Object RESULT =null; + int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + Object e = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + System.out.println("String ALGORITMO = \""+e+"\";"); + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao",1, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 3: // algoritmo ::= error + { + Object RESULT =null; + + CUP$parser$result = parser.getSymbolFactory().newSymbol("algoritmo",0, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 2: // algoritmo ::= instanciacao + { + Object RESULT =null; + + CUP$parser$result = parser.getSymbolFactory().newSymbol("algoritmo",0, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 1: // $START ::= algoritmo EOF + { + Object RESULT =null; + int start_valleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int start_valright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + Object start_val = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + RESULT = start_val; + CUP$parser$result = parser.getSymbolFactory().newSymbol("$START",0, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + /* ACCEPT */ + CUP$parser$parser.done_parsing(); + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 0: // algoritmo ::= algoritmo instanciacao + { + Object RESULT =null; + + CUP$parser$result = parser.getSymbolFactory().newSymbol("algoritmo",0, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /* . . . . . .*/ + default: + throw new Exception( + "Invalid action number found in internal parse table"); + + } + } +} + diff --git a/Test/com/analizador/algoritmoName/sym.java b/Test/com/analizador/algoritmoName/sym.java new file mode 100644 index 0000000..1219291 --- /dev/null +++ b/Test/com/analizador/algoritmoName/sym.java @@ -0,0 +1,18 @@ + +//---------------------------------------------------- +// The following code was generated by CUP v0.11a beta 20060608 +// Fri Jun 20 21:54:45 BRT 2014 +//---------------------------------------------------- + +package com.analizador.algoritmoName; + +/** CUP generated class containing symbol constants. */ +public class sym { + /* terminals */ + public static final int ID = 3; + public static final int STRING = 4; + public static final int error = 1; + public static final int ALGORITMO = 2; + public static final int EOF = 0; +} + diff --git a/Test/com/analizador/exe_expressao/Exemplo.txt b/Test/com/analizador/exe_expressao/Exemplo.txt new file mode 100644 index 0000000..44a475e --- /dev/null +++ b/Test/com/analizador/exe_expressao/Exemplo.txt @@ -0,0 +1 @@ +2+(5*2)+4; \ No newline at end of file diff --git a/Test/com/analizador/exe_expressao/Expressao.cup b/Test/com/analizador/exe_expressao/Expressao.cup new file mode 100644 index 0000000..951fab0 --- /dev/null +++ b/Test/com/analizador/exe_expressao/Expressao.cup @@ -0,0 +1,44 @@ +package com.analizador.exe_expressao; + +import java_cup.runtime.*; + +parser code +{: + public static void main(String args[]) throws Exception{ + new parser(new Yylex(System.in)).parse(); + } + public void syntax_error(Symbol s){ + report_error("Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right)+". Trecho desconhecido: \""+s.value+"\"",null); + } +:} + +/* Terminals (tokens returned by the scanner). */ +terminal SEMI, PLUS, MINUS, TIMES, DIVIDE, MOD; +terminal UMINUS, LPAREN, RPAREN; +terminal Integer NUMBER; + +/* Non-terminals */ +non terminal expr_list, expr_part; +non terminal Integer expr; + +/* Precedences */ +precedence left PLUS, MINUS; +precedence left TIMES, DIVIDE, MOD; +precedence left UMINUS; + +/* The grammar */ +expr_list ::= expr_list expr_part | + expr_part | + error {::} ; + +expr_part ::= expr:e SEMI {: System.out.println("= " + e); :}; + + +expr ::= expr:e1 PLUS expr:e2 {: RESULT = new Integer(e1.intValue() + e2.intValue()); :} | + expr:e1 MINUS expr:e2 {: RESULT = new Integer(e1.intValue() - e2.intValue()); :} | + expr:e1 TIMES expr:e2 {: RESULT = new Integer(e1.intValue() * e2.intValue()); :} | + expr:e1 DIVIDE expr:e2 {: RESULT = new Integer(e1.intValue() / e2.intValue()); :} | + expr:e1 MOD expr:e2 {: RESULT = new Integer(e1.intValue() % e2.intValue()); :} | + NUMBER:n {: RESULT = n; :} | + MINUS expr:e {: RESULT = new Integer(0 - e.intValue()); :} %prec UMINUS | + LPAREN expr:e RPAREN {: RESULT = e; :} ; \ No newline at end of file diff --git a/Test/com/analizador/exe_expressao/Expressao.flex b/Test/com/analizador/exe_expressao/Expressao.flex new file mode 100644 index 0000000..f2ec872 --- /dev/null +++ b/Test/com/analizador/exe_expressao/Expressao.flex @@ -0,0 +1,46 @@ +package com.analizador.exe_expressao; + +import java_cup.runtime.*; + + +%% +/* +* LEXICAL FUNCTIONS: +*/ +%cup +%line +%char +%column + +%{ + + Symbol newSym(int tokenId) { + return new Symbol(tokenId , yyline, yycolumn); + } + + Symbol newSym(int tokenId, Object value) { + return new Symbol(tokenId , yyline, yycolumn, value); + } + +%} + + +/*-* + * PATTERN DEFINITIONS: + */ +digit = [0-9] +integer = {digit}+ + + +%% +{integer} {return newSym(sym.NUMBER, new Integer(yytext()));} +";" {return newSym(sym.SEMI);} +"+" {return newSym(sym.PLUS);} +"-" {return newSym(sym.MINUS);} +"*" {return newSym(sym.TIMES);} +"/" {return newSym(sym.DIVIDE);} +"%" {return newSym(sym.MOD);} +"(" {return newSym(sym.LPAREN);} +")" {return newSym(sym.RPAREN);} +<> {return newSym(sym.EOF);} +. {return newSym(sym.error);} \ No newline at end of file diff --git a/Test/com/analizador/exe_expressao/Inicializador.java b/Test/com/analizador/exe_expressao/Inicializador.java new file mode 100644 index 0000000..2b88ff1 --- /dev/null +++ b/Test/com/analizador/exe_expressao/Inicializador.java @@ -0,0 +1,35 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.analizador.exe_expressao; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.StringReader; + +/** + * + * @author Andrew + */ +public class Inicializador { + + public static void main(String[] args) throws IOException, Exception { + //Yylex lexer = new Yylex(new StringReader("2+9")); + Yylex lexer = new Yylex(Inicializador.class.getResourceAsStream("Exemplo.txt")); + /* + Symbol sym; + for (sym = lexer.next_token(); sym.sym != 0; sym = lexer.next_token()) { + System.out.println("Token " + sym.sym + ", with value = " + sym.value + "; at line " + sym.left + ", column " + sym.right); + } + */ + + + parser p = new parser(lexer); + p.parse(); + + } + +} diff --git a/Test/com/analizador/exe_expressao/Yylex.java b/Test/com/analizador/exe_expressao/Yylex.java new file mode 100644 index 0000000..f3dd5cc --- /dev/null +++ b/Test/com/analizador/exe_expressao/Yylex.java @@ -0,0 +1,663 @@ +/* The following code was generated by JFlex 1.5.1 */ + +package com.analizador.exe_expressao; + +import java_cup.runtime.*; + + + +/** + * This class is a scanner generated by + * JFlex 1.5.1 + * from the specification file C:/Users/SIMONETO-2/Documents/NetBeansProjects/portugol-projeto/Test/com/analizador/expressao/flex.flex + */ +class Yylex implements java_cup.runtime.Scanner { + + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int YYINITIAL = 0; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l + * at the beginning of a line + * l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { + 0, 0 + }; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = + "\12\0\1\12\1\12\1\12\1\12\27\0\1\7\2\0\1\10\1\11"+ + "\1\5\1\3\1\0\1\4\1\0\1\6\12\1\1\0\1\2\111\0"+ + "\1\12\u1fa2\0\1\12\1\12\udfd6\0"; + + /** + * Translates characters to character classes + */ + private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int [] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = + "\1\0\1\1\1\2\1\3\1\4\1\5\1\6\1\7"+ + "\1\10\1\11\1\12"; + + private static int [] zzUnpackAction() { + int [] result = new int[11]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /** + * Translates a state to a row index in the transition table + */ + private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = + "\0\0\0\13\0\26\0\13\0\13\0\13\0\13\0\13"+ + "\0\13\0\13\0\13"; + + private static int [] zzUnpackRowMap() { + int [] result = new int[11]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int [] ZZ_TRANS = zzUnpackTrans(); + + private static final String ZZ_TRANS_PACKED_0 = + "\1\2\1\3\1\4\1\5\1\6\1\7\1\10\1\11"+ + "\1\12\1\13\15\0\1\3\11\0"; + + private static int [] zzUnpackTrans() { + int [] result = new int[33]; + int offset = 0; + offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackTrans(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + value--; + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", + "Error: could not match input", + "Error: pushback value was too large" + }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state aState + */ + private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = + "\1\0\1\11\1\1\10\11"; + + private static int [] zzUnpackAttribute() { + int [] result = new int[11]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** this buffer contains the current text to be matched and is + the source of the yytext() string */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** endRead marks the last character in the buffer, that has been read + from input */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /** denotes if the user-EOF-code has already been executed */ + private boolean zzEOFDone; + + /* user code: */ + + Symbol newSym(int tokenId) { + return new Symbol(tokenId , yyline, yycolumn); + } + + Symbol newSym(int tokenId, Object value) { + return new Symbol(tokenId , yyline, yycolumn, value); + } + + + + /** + * Creates a new scanner + * There is also a java.io.InputStream version of this constructor. + * + * @param in the java.io.Reader to read input from. + */ + Yylex(java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. + * There is also java.io.Reader version of this constructor. + * + * @param in the java.io.Inputstream to read input from. + */ + Yylex(java.io.InputStream in) { + this(new java.io.InputStreamReader + (in, java.nio.charset.Charset.forName("UTF-8"))); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed the packed character translation table + * @return the unpacked character translation table + */ + private static char [] zzUnpackCMap(String packed) { + char [] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 50) { + int count = packed.charAt(i++); + char value = packed.charAt(i++); + do map[j++] = value; while (--count > 0); + } + return map; + } + + + /** + * Refills the input buffer. + * + * @return false, iff there was new input. + * + * @exception java.io.IOException if any I/O-Error occurs + */ + private boolean zzRefill() throws java.io.IOException { + + /* first: make room (if you can) */ + if (zzStartRead > 0) { + System.arraycopy(zzBuffer, zzStartRead, + zzBuffer, 0, + zzEndRead-zzStartRead); + + /* translate stored positions */ + zzEndRead-= zzStartRead; + zzCurrentPos-= zzStartRead; + zzMarkedPos-= zzStartRead; + zzStartRead = 0; + } + + /* is the buffer big enough? */ + if (zzCurrentPos >= zzBuffer.length) { + /* if not: blow it up */ + char newBuffer[] = new char[zzCurrentPos*2]; + System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); + zzBuffer = newBuffer; + } + + /* finally: fill the buffer with new input */ + int numRead = zzReader.read(zzBuffer, zzEndRead, + zzBuffer.length-zzEndRead); + + if (numRead > 0) { + zzEndRead+= numRead; + return false; + } + // unlikely but not impossible: read 0 characters, but not at end of stream + if (numRead == 0) { + int c = zzReader.read(); + if (c == -1) { + return true; + } else { + zzBuffer[zzEndRead++] = (char) c; + return false; + } + } + + // numRead < 0 + return true; + } + + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) + zzReader.close(); + } + + + /** + * Resets the scanner to read from a new input stream. + * Does not close the old reader. + * + * All internal variables are reset, the old input stream + * cannot be reused (internal buffer is discarded and lost). + * Lexical state is set to ZZ_INITIAL. + * + * Internal scan buffer is resized down to its initial length, if it has grown. + * + * @param reader the new input stream + */ + public final void yyreset(java.io.Reader reader) { + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + zzEOFDone = false; + zzEndRead = zzStartRead = 0; + zzCurrentPos = zzMarkedPos = 0; + yyline = yychar = yycolumn = 0; + zzLexicalState = YYINITIAL; + if (zzBuffer.length > ZZ_BUFFERSIZE) + zzBuffer = new char[ZZ_BUFFERSIZE]; + } + + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + + /** + * Enters a new lexical state + * + * @param newState the new lexical state + */ + public final void yybegin(int newState) { + zzLexicalState = newState; + } + + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); + } + + + /** + * Returns the character at position pos from the + * matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. + * A value from 0 to yylength()-1. + * + * @return the character at position pos + */ + public final char yycharat(int pos) { + return zzBuffer[zzStartRead+pos]; + } + + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos-zzStartRead; + } + + + /** + * Reports an error that occured while scanning. + * + * In a wellformed scanner (no or only correct usage of + * yypushback(int) and a match-all fallback rule) this method + * will only be called with things that "Can't Possibly Happen". + * If this method is called, something is seriously wrong + * (e.g. a JFlex bug producing a faulty scanner etc.). + * + * Usual syntax/scanner level error handling should be done + * in error fallback rules. + * + * @param errorCode the code of the errormessage to display + */ + private void zzScanError(int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } + catch (ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + + /** + * Pushes the specified amount of characters back into the input stream. + * + * They will be read again by then next call of the scanning method + * + * @param number the number of characters to be read again. + * This number must not be greater than yylength()! + */ + public void yypushback(int number) { + if ( number > yylength() ) + zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + + /** + * Contains user EOF-code, which will be executed exactly once, + * when the end of file is reached + */ + private void zzDoEOF() throws java.io.IOException { + if (!zzEOFDone) { + zzEOFDone = true; + yyclose(); + } + } + + + /** + * Resumes scanning until the next regular expression is matched, + * the end of input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException if any I/O-Error occurs + */ + public java_cup.runtime.Symbol next_token() throws java.io.IOException { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char [] zzBufferL = zzBuffer; + char [] zzCMapL = ZZ_CMAP; + + int [] zzTransL = ZZ_TRANS; + int [] zzRowMapL = ZZ_ROWMAP; + int [] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + yychar+= zzMarkedPosL-zzStartRead; + + boolean zzR = false; + for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL; + zzCurrentPosL++) { + switch (zzBufferL[zzCurrentPosL]) { + case '\u000B': + case '\u000C': + case '\u0085': + case '\u2028': + case '\u2029': + yyline++; + yycolumn = 0; + zzR = false; + break; + case '\r': + yyline++; + yycolumn = 0; + zzR = true; + break; + case '\n': + if (zzR) + zzR = false; + else { + yyline++; + yycolumn = 0; + } + break; + default: + zzR = false; + yycolumn++; + } + } + + if (zzR) { + // peek one character ahead if it is \n (if we have counted one line too much) + boolean zzPeek; + if (zzMarkedPosL < zzEndReadL) + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + else if (zzAtEOF) + zzPeek = false; + else { + boolean eof = zzRefill(); + zzEndReadL = zzEndRead; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + if (eof) + zzPeek = false; + else + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + } + if (zzPeek) yyline--; + } + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = ZZ_LEXSTATE[zzLexicalState]; + + // set up zzAction for empty match case: + int zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + } + + + zzForAction: { + while (true) { + + if (zzCurrentPosL < zzEndReadL) + zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } + else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } + else { + zzInput = zzBufferL[zzCurrentPosL++]; + } + } + int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; + if (zzNext == -1) break zzForAction; + zzState = zzNext; + + zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ( (zzAttributes & 8) == 8 ) break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 1: + { return newSym(sym.error); + } + case 11: break; + case 2: + { return newSym(sym.NUMBER, new Integer(yytext())); + } + case 12: break; + case 3: + { return newSym(sym.SEMI); + } + case 13: break; + case 4: + { return newSym(sym.PLUS); + } + case 14: break; + case 5: + { return newSym(sym.MINUS); + } + case 15: break; + case 6: + { return newSym(sym.TIMES); + } + case 16: break; + case 7: + { return newSym(sym.DIVIDE); + } + case 17: break; + case 8: + { return newSym(sym.MOD); + } + case 18: break; + case 9: + { return newSym(sym.LPAREN); + } + case 19: break; + case 10: + { return newSym(sym.RPAREN); + } + case 20: break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + zzDoEOF(); + { + return newSym(sym.EOF); + } + } + else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + + +} diff --git a/Test/com/analizador/exe_expressao/Yylex.java~ b/Test/com/analizador/exe_expressao/Yylex.java~ new file mode 100644 index 0000000..0b6c252 --- /dev/null +++ b/Test/com/analizador/exe_expressao/Yylex.java~ @@ -0,0 +1,663 @@ +/* The following code was generated by JFlex 1.5.1 */ + +package com.analizador.expressao; + +import java_cup.runtime.*; + + + +/** + * This class is a scanner generated by + * JFlex 1.5.1 + * from the specification file C:/Users/SIMONETO-2/Documents/NetBeansProjects/portugol-projeto/Test/com/analizador/expressao/flex.flex + */ +class Yylex implements java_cup.runtime.Scanner { + + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int YYINITIAL = 0; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l + * at the beginning of a line + * l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { + 0, 0 + }; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = + "\12\0\1\12\1\12\1\12\1\12\27\0\1\7\2\0\1\10\1\11"+ + "\1\5\1\3\1\0\1\4\1\0\1\6\12\1\1\0\1\2\111\0"+ + "\1\12\u1fa2\0\1\12\1\12\udfd6\0"; + + /** + * Translates characters to character classes + */ + private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int [] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = + "\1\0\1\1\1\2\1\3\1\4\1\5\1\6\1\7"+ + "\1\10\1\11\1\12"; + + private static int [] zzUnpackAction() { + int [] result = new int[11]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /** + * Translates a state to a row index in the transition table + */ + private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = + "\0\0\0\13\0\26\0\13\0\13\0\13\0\13\0\13"+ + "\0\13\0\13\0\13"; + + private static int [] zzUnpackRowMap() { + int [] result = new int[11]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int [] ZZ_TRANS = zzUnpackTrans(); + + private static final String ZZ_TRANS_PACKED_0 = + "\1\2\1\3\1\4\1\5\1\6\1\7\1\10\1\11"+ + "\1\12\1\13\15\0\1\3\11\0"; + + private static int [] zzUnpackTrans() { + int [] result = new int[33]; + int offset = 0; + offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackTrans(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + value--; + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", + "Error: could not match input", + "Error: pushback value was too large" + }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state aState + */ + private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = + "\1\0\1\11\1\1\10\11"; + + private static int [] zzUnpackAttribute() { + int [] result = new int[11]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** this buffer contains the current text to be matched and is + the source of the yytext() string */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** endRead marks the last character in the buffer, that has been read + from input */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /** denotes if the user-EOF-code has already been executed */ + private boolean zzEOFDone; + + /* user code: */ + + Symbol newSym(int tokenId) { + return new Symbol(tokenId , yyline, yycolumn); + } + + Symbol newSym(int tokenId, Object value) { + return new Symbol(tokenId , yyline, yycolumn, value); + } + + + + /** + * Creates a new scanner + * There is also a java.io.InputStream version of this constructor. + * + * @param in the java.io.Reader to read input from. + */ + Yylex(java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. + * There is also java.io.Reader version of this constructor. + * + * @param in the java.io.Inputstream to read input from. + */ + Yylex(java.io.InputStream in) { + this(new java.io.InputStreamReader + (in, java.nio.charset.Charset.forName("UTF-8"))); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed the packed character translation table + * @return the unpacked character translation table + */ + private static char [] zzUnpackCMap(String packed) { + char [] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 50) { + int count = packed.charAt(i++); + char value = packed.charAt(i++); + do map[j++] = value; while (--count > 0); + } + return map; + } + + + /** + * Refills the input buffer. + * + * @return false, iff there was new input. + * + * @exception java.io.IOException if any I/O-Error occurs + */ + private boolean zzRefill() throws java.io.IOException { + + /* first: make room (if you can) */ + if (zzStartRead > 0) { + System.arraycopy(zzBuffer, zzStartRead, + zzBuffer, 0, + zzEndRead-zzStartRead); + + /* translate stored positions */ + zzEndRead-= zzStartRead; + zzCurrentPos-= zzStartRead; + zzMarkedPos-= zzStartRead; + zzStartRead = 0; + } + + /* is the buffer big enough? */ + if (zzCurrentPos >= zzBuffer.length) { + /* if not: blow it up */ + char newBuffer[] = new char[zzCurrentPos*2]; + System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); + zzBuffer = newBuffer; + } + + /* finally: fill the buffer with new input */ + int numRead = zzReader.read(zzBuffer, zzEndRead, + zzBuffer.length-zzEndRead); + + if (numRead > 0) { + zzEndRead+= numRead; + return false; + } + // unlikely but not impossible: read 0 characters, but not at end of stream + if (numRead == 0) { + int c = zzReader.read(); + if (c == -1) { + return true; + } else { + zzBuffer[zzEndRead++] = (char) c; + return false; + } + } + + // numRead < 0 + return true; + } + + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) + zzReader.close(); + } + + + /** + * Resets the scanner to read from a new input stream. + * Does not close the old reader. + * + * All internal variables are reset, the old input stream + * cannot be reused (internal buffer is discarded and lost). + * Lexical state is set to ZZ_INITIAL. + * + * Internal scan buffer is resized down to its initial length, if it has grown. + * + * @param reader the new input stream + */ + public final void yyreset(java.io.Reader reader) { + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + zzEOFDone = false; + zzEndRead = zzStartRead = 0; + zzCurrentPos = zzMarkedPos = 0; + yyline = yychar = yycolumn = 0; + zzLexicalState = YYINITIAL; + if (zzBuffer.length > ZZ_BUFFERSIZE) + zzBuffer = new char[ZZ_BUFFERSIZE]; + } + + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + + /** + * Enters a new lexical state + * + * @param newState the new lexical state + */ + public final void yybegin(int newState) { + zzLexicalState = newState; + } + + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); + } + + + /** + * Returns the character at position pos from the + * matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. + * A value from 0 to yylength()-1. + * + * @return the character at position pos + */ + public final char yycharat(int pos) { + return zzBuffer[zzStartRead+pos]; + } + + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos-zzStartRead; + } + + + /** + * Reports an error that occured while scanning. + * + * In a wellformed scanner (no or only correct usage of + * yypushback(int) and a match-all fallback rule) this method + * will only be called with things that "Can't Possibly Happen". + * If this method is called, something is seriously wrong + * (e.g. a JFlex bug producing a faulty scanner etc.). + * + * Usual syntax/scanner level error handling should be done + * in error fallback rules. + * + * @param errorCode the code of the errormessage to display + */ + private void zzScanError(int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } + catch (ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + + /** + * Pushes the specified amount of characters back into the input stream. + * + * They will be read again by then next call of the scanning method + * + * @param number the number of characters to be read again. + * This number must not be greater than yylength()! + */ + public void yypushback(int number) { + if ( number > yylength() ) + zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + + /** + * Contains user EOF-code, which will be executed exactly once, + * when the end of file is reached + */ + private void zzDoEOF() throws java.io.IOException { + if (!zzEOFDone) { + zzEOFDone = true; + yyclose(); + } + } + + + /** + * Resumes scanning until the next regular expression is matched, + * the end of input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException if any I/O-Error occurs + */ + public java_cup.runtime.Symbol next_token() throws java.io.IOException { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char [] zzBufferL = zzBuffer; + char [] zzCMapL = ZZ_CMAP; + + int [] zzTransL = ZZ_TRANS; + int [] zzRowMapL = ZZ_ROWMAP; + int [] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + yychar+= zzMarkedPosL-zzStartRead; + + boolean zzR = false; + for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL; + zzCurrentPosL++) { + switch (zzBufferL[zzCurrentPosL]) { + case '\u000B': + case '\u000C': + case '\u0085': + case '\u2028': + case '\u2029': + yyline++; + yycolumn = 0; + zzR = false; + break; + case '\r': + yyline++; + yycolumn = 0; + zzR = true; + break; + case '\n': + if (zzR) + zzR = false; + else { + yyline++; + yycolumn = 0; + } + break; + default: + zzR = false; + yycolumn++; + } + } + + if (zzR) { + // peek one character ahead if it is \n (if we have counted one line too much) + boolean zzPeek; + if (zzMarkedPosL < zzEndReadL) + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + else if (zzAtEOF) + zzPeek = false; + else { + boolean eof = zzRefill(); + zzEndReadL = zzEndRead; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + if (eof) + zzPeek = false; + else + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + } + if (zzPeek) yyline--; + } + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = ZZ_LEXSTATE[zzLexicalState]; + + // set up zzAction for empty match case: + int zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + } + + + zzForAction: { + while (true) { + + if (zzCurrentPosL < zzEndReadL) + zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } + else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } + else { + zzInput = zzBufferL[zzCurrentPosL++]; + } + } + int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; + if (zzNext == -1) break zzForAction; + zzState = zzNext; + + zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ( (zzAttributes & 8) == 8 ) break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 1: + { System.out.println("Illegal char, '" + yytext() +"' line: " + yyline + ", column: " + yychar); + } + case 11: break; + case 2: + { return newSym(sym.NUMBER, new Integer(yytext())); + } + case 12: break; + case 3: + { return newSym(sym.SEMI); + } + case 13: break; + case 4: + { return newSym(sym.PLUS); + } + case 14: break; + case 5: + { return newSym(sym.MINUS); + } + case 15: break; + case 6: + { return newSym(sym.TIMES); + } + case 16: break; + case 7: + { return newSym(sym.DIVIDE); + } + case 17: break; + case 8: + { return newSym(sym.MOD); + } + case 18: break; + case 9: + { return newSym(sym.LPAREN); + } + case 19: break; + case 10: + { return newSym(sym.RPAREN); + } + case 20: break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + zzDoEOF(); + { + return newSym(sym.EOF); + } + } + else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + + +} diff --git a/Test/com/analizador/exe_expressao/java_cup.jar b/Test/com/analizador/exe_expressao/java_cup.jar new file mode 100644 index 0000000..73ffa0b Binary files /dev/null and b/Test/com/analizador/exe_expressao/java_cup.jar differ diff --git a/Test/com/analizador/exe_expressao/parser.java b/Test/com/analizador/exe_expressao/parser.java new file mode 100644 index 0000000..66b78a8 --- /dev/null +++ b/Test/com/analizador/exe_expressao/parser.java @@ -0,0 +1,325 @@ + +//---------------------------------------------------- +// The following code was generated by CUP v0.11a beta 20060608 +// Fri Jun 20 14:14:23 BRT 2014 +//---------------------------------------------------- + +package com.analizador.exe_expressao; + +import java_cup.runtime.*; + +/** CUP v0.11a beta 20060608 generated parser. + * @version Fri Jun 20 14:14:23 BRT 2014 + */ +public class parser extends java_cup.runtime.lr_parser { + + /** Default constructor. */ + public parser() {super();} + + /** Constructor which sets the default scanner. */ + public parser(java_cup.runtime.Scanner s) {super(s);} + + /** Constructor which sets the default scanner. */ + public parser(java_cup.runtime.Scanner s, java_cup.runtime.SymbolFactory sf) {super(s,sf);} + + /** Production table. */ + protected static final short _production_table[][] = + unpackFromStrings(new String[] { + "\000\015\000\002\002\004\000\002\002\004\000\002\002" + + "\003\000\002\002\003\000\002\003\004\000\002\004\005" + + "\000\002\004\005\000\002\004\005\000\002\004\005\000" + + "\002\004\005\000\002\004\003\000\002\004\004\000\002" + + "\004\005" }); + + /** Access to production table. */ + public short[][] production_table() {return _production_table;} + + /** Parse-action table. */ + protected static final short[][] _action_table = + unpackFromStrings(new String[] { + "\000\030\000\012\003\004\006\007\013\010\015\006\001" + + "\002\000\012\002\ufffe\006\ufffe\013\ufffe\015\ufffe\001\002" + + "\000\012\002\uffff\006\uffff\013\uffff\015\uffff\001\002\000" + + "\020\004\ufff7\005\ufff7\006\ufff7\007\ufff7\010\ufff7\011\ufff7" + + "\014\ufff7\001\002\000\010\006\007\013\010\015\006\001" + + "\002\000\010\006\007\013\010\015\006\001\002\000\012" + + "\002\027\006\007\013\010\015\006\001\002\000\016\004" + + "\016\005\014\006\015\007\020\010\017\011\013\001\002" + + "\000\010\006\007\013\010\015\006\001\002\000\010\006" + + "\007\013\010\015\006\001\002\000\010\006\007\013\010" + + "\015\006\001\002\000\012\002\ufffd\006\ufffd\013\ufffd\015" + + "\ufffd\001\002\000\010\006\007\013\010\015\006\001\002" + + "\000\010\006\007\013\010\015\006\001\002\000\020\004" + + "\ufffa\005\ufffa\006\ufffa\007\ufffa\010\ufffa\011\ufffa\014\ufffa" + + "\001\002\000\020\004\ufff9\005\ufff9\006\ufff9\007\ufff9\010" + + "\ufff9\011\ufff9\014\ufff9\001\002\000\020\004\ufffb\005\ufffb" + + "\006\ufffb\007\020\010\017\011\013\014\ufffb\001\002\000" + + "\020\004\ufffc\005\ufffc\006\ufffc\007\020\010\017\011\013" + + "\014\ufffc\001\002\000\020\004\ufff8\005\ufff8\006\ufff8\007" + + "\ufff8\010\ufff8\011\ufff8\014\ufff8\001\002\000\012\002\001" + + "\006\001\013\001\015\001\001\002\000\004\002\000\001" + + "\002\000\016\005\014\006\015\007\020\010\017\011\013" + + "\014\031\001\002\000\020\004\ufff5\005\ufff5\006\ufff5\007" + + "\ufff5\010\ufff5\011\ufff5\014\ufff5\001\002\000\020\004\ufff6" + + "\005\ufff6\006\ufff6\007\ufff6\010\ufff6\011\ufff6\014\ufff6\001" + + "\002" }); + + /** Access to parse-action table. */ + public short[][] action_table() {return _action_table;} + + /** reduce_goto table. */ + protected static final short[][] _reduce_table = + unpackFromStrings(new String[] { + "\000\030\000\010\002\010\003\004\004\011\001\001\000" + + "\002\001\001\000\002\001\001\000\002\001\001\000\004" + + "\004\031\001\001\000\004\004\027\001\001\000\006\003" + + "\025\004\011\001\001\000\002\001\001\000\004\004\024" + + "\001\001\000\004\004\023\001\001\000\004\004\022\001" + + "\001\000\002\001\001\000\004\004\021\001\001\000\004" + + "\004\020\001\001\000\002\001\001\000\002\001\001\000" + + "\002\001\001\000\002\001\001\000\002\001\001\000\002" + + "\001\001\000\002\001\001\000\002\001\001\000\002\001" + + "\001\000\002\001\001" }); + + /** Access to reduce_goto table. */ + public short[][] reduce_table() {return _reduce_table;} + + /** Instance of action encapsulation class. */ + protected CUP$parser$actions action_obj; + + /** Action encapsulation object initializer. */ + protected void init_actions() + { + action_obj = new CUP$parser$actions(this); + } + + /** Invoke a user supplied parse action. */ + public java_cup.runtime.Symbol do_action( + int act_num, + java_cup.runtime.lr_parser parser, + java.util.Stack stack, + int top) + throws java.lang.Exception + { + /* call code in generated class */ + return action_obj.CUP$parser$do_action(act_num, parser, stack, top); + } + + /** Indicates start state. */ + public int start_state() {return 0;} + /** Indicates start production. */ + public int start_production() {return 1;} + + /** EOF Symbol index. */ + public int EOF_sym() {return 0;} + + /** error Symbol index. */ + public int error_sym() {return 1;} + + + + public static void main(String args[]) throws Exception{ + new parser(new Yylex(System.in)).parse(); + } + public void syntax_error(Symbol s){ + report_error("Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right)+". Trecho desconhecido: \""+s.value+"\"",null); + } + +} + +/** Cup generated class to encapsulate user supplied action code.*/ +class CUP$parser$actions { + private final parser parser; + + /** Constructor */ + CUP$parser$actions(parser parser) { + this.parser = parser; + } + + /** Method with the actual generated action code. */ + public final java_cup.runtime.Symbol CUP$parser$do_action( + int CUP$parser$act_num, + java_cup.runtime.lr_parser CUP$parser$parser, + java.util.Stack CUP$parser$stack, + int CUP$parser$top) + throws java.lang.Exception + { + /* Symbol object for return from actions */ + java_cup.runtime.Symbol CUP$parser$result; + + /* select the action based on the action number */ + switch (CUP$parser$act_num) + { + /*. . . . . . . . . . . . . . . . . . . .*/ + case 12: // expr ::= LPAREN expr RPAREN + { + Integer RESULT =null; + int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + Integer e = (Integer)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + RESULT = e; + CUP$parser$result = parser.getSymbolFactory().newSymbol("expr",2, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 11: // expr ::= MINUS expr + { + Integer RESULT =null; + int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + Integer e = (Integer)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = new Integer(0 - e.intValue()); + CUP$parser$result = parser.getSymbolFactory().newSymbol("expr",2, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 10: // expr ::= NUMBER + { + Integer RESULT =null; + int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + Integer n = (Integer)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = n; + CUP$parser$result = parser.getSymbolFactory().newSymbol("expr",2, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 9: // expr ::= expr MOD expr + { + Integer RESULT =null; + int e1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left; + int e1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right; + Integer e1 = (Integer)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; + int e2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int e2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + Integer e2 = (Integer)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = new Integer(e1.intValue() % e2.intValue()); + CUP$parser$result = parser.getSymbolFactory().newSymbol("expr",2, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 8: // expr ::= expr DIVIDE expr + { + Integer RESULT =null; + int e1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left; + int e1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right; + Integer e1 = (Integer)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; + int e2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int e2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + Integer e2 = (Integer)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = new Integer(e1.intValue() / e2.intValue()); + CUP$parser$result = parser.getSymbolFactory().newSymbol("expr",2, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 7: // expr ::= expr TIMES expr + { + Integer RESULT =null; + int e1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left; + int e1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right; + Integer e1 = (Integer)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; + int e2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int e2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + Integer e2 = (Integer)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = new Integer(e1.intValue() * e2.intValue()); + CUP$parser$result = parser.getSymbolFactory().newSymbol("expr",2, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 6: // expr ::= expr MINUS expr + { + Integer RESULT =null; + int e1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left; + int e1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right; + Integer e1 = (Integer)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; + int e2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int e2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + Integer e2 = (Integer)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = new Integer(e1.intValue() - e2.intValue()); + CUP$parser$result = parser.getSymbolFactory().newSymbol("expr",2, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 5: // expr ::= expr PLUS expr + { + Integer RESULT =null; + int e1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left; + int e1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right; + Integer e1 = (Integer)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; + int e2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int e2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + Integer e2 = (Integer)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = new Integer(e1.intValue() + e2.intValue()); + CUP$parser$result = parser.getSymbolFactory().newSymbol("expr",2, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 4: // expr_part ::= expr SEMI + { + Object RESULT =null; + int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + Integer e = (Integer)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + System.out.println("= " + e); + CUP$parser$result = parser.getSymbolFactory().newSymbol("expr_part",1, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 3: // expr_list ::= error + { + Object RESULT =null; + + CUP$parser$result = parser.getSymbolFactory().newSymbol("expr_list",0, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 2: // expr_list ::= expr_part + { + Object RESULT =null; + + CUP$parser$result = parser.getSymbolFactory().newSymbol("expr_list",0, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 1: // $START ::= expr_list EOF + { + Object RESULT =null; + int start_valleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int start_valright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + Object start_val = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + RESULT = start_val; + CUP$parser$result = parser.getSymbolFactory().newSymbol("$START",0, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + /* ACCEPT */ + CUP$parser$parser.done_parsing(); + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 0: // expr_list ::= expr_list expr_part + { + Object RESULT =null; + + CUP$parser$result = parser.getSymbolFactory().newSymbol("expr_list",0, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /* . . . . . .*/ + default: + throw new Exception( + "Invalid action number found in internal parse table"); + + } + } +} + diff --git a/Test/com/analizador/exe_expressao/sym.java b/Test/com/analizador/exe_expressao/sym.java new file mode 100644 index 0000000..fa633c8 --- /dev/null +++ b/Test/com/analizador/exe_expressao/sym.java @@ -0,0 +1,25 @@ + +//---------------------------------------------------- +// The following code was generated by CUP v0.11a beta 20060608 +// Fri Jun 20 14:14:23 BRT 2014 +//---------------------------------------------------- + +package com.analizador.exe_expressao; + +/** CUP generated class containing symbol constants. */ +public class sym { + /* terminals */ + public static final int MINUS = 4; + public static final int DIVIDE = 6; + public static final int UMINUS = 8; + public static final int NUMBER = 11; + public static final int MOD = 7; + public static final int SEMI = 2; + public static final int EOF = 0; + public static final int PLUS = 3; + public static final int error = 1; + public static final int RPAREN = 10; + public static final int TIMES = 5; + public static final int LPAREN = 9; +} + diff --git a/Test/com/analizador/exp_condicional/Condicionais.cup b/Test/com/analizador/exp_condicional/Condicionais.cup new file mode 100644 index 0000000..6c1af9c --- /dev/null +++ b/Test/com/analizador/exp_condicional/Condicionais.cup @@ -0,0 +1,75 @@ +//////////////////////////////////////////////////////////////////////// +/* //// +* DECLARACAO DE EXPRESSOES EM PORTUGOL (ANALIZADOR E COMPILADOR). //// +* BY: ANDREW NETO //// +* 20/06/2014 //// +*/ //// +//////////////////////////////////////////////////////////////////////// + +package com.analizador.exp_condicional; + +import java_cup.runtime.*; + +parser code +{: + public static void main(String args[]) throws Exception{ + new parser(new Yylex(System.in)).parse(); + } + public void syntax_error(Symbol s){ + report_error("Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right)+". Trecho desconhecido: \""+s.value+"\"",null); + } +:} + + +terminal SE,ENTAO; +terminal CONDICIONAL,CONDICIONAL_ESPECIAL,CONDICIONAL_ADITIVA; +terminal OPERADOR; +terminal ABRIR_PARENTESE, FECHAR_PARENTESE; +terminal String NUMERO,ID,STRING; + + +/* +* PARA OPERACOES DENTRO DA CONDICIONAL.: EX-> (a+b > a+c) +*/ +non terminal gramatica,instanciacao_global; +non terminal String instanciacao_ligativa,instanciacao_fragmental,instanciacao_operativa; + +non terminal String instanciacao_ligativa_string,instanciacao_string; + + + +precedence left CONDICIONAL_ADITIVA,CONDICIONAL_ESPECIAL,CONDICIONAL; +precedence left ABRIR_PARENTESE,FECHAR_PARENTESE; +precedence left OPERADOR; + + +gramatica ::= gramatica instanciacao_global | instanciacao_global | error {::}; + + + +instanciacao_global ::= SE instanciacao_ligativa:x ENTAO {: System.out.println("if(" + x + ")"); :}; + + +/* +* PARA IDS,NUMEROS (RELIZAM OPERACOES) +*/ +instanciacao_ligativa ::= instanciacao_ligativa:x1 CONDICIONAL_ADITIVA:y instanciacao_ligativa:x2 {: RESULT = x1 + " " + y + " " + x2; :} | + ABRIR_PARENTESE instanciacao_ligativa:x FECHAR_PARENTESE {: RESULT = "("+x+")"; :} | + instanciacao_fragmental:z {: RESULT = z; System.out.println("instanciacao_fragmental:z = "+z); :}; + +instanciacao_fragmental ::= instanciacao_fragmental:x1 CONDICIONAL:y instanciacao_fragmental:x2 {: RESULT = x1 + " " + y + " " + x2; :} | + instanciacao_fragmental:x1 CONDICIONAL_ESPECIAL:y instanciacao_fragmental:x2 {: RESULT = x1 + " " + y + " " + x2; :} | + instanciacao_operativa:e {: RESULT = e;System.out.println("instanciacao_operativa:e = "+e); :}; + + +instanciacao_operativa ::= instanciacao_operativa:e1 OPERADOR:op instanciacao_operativa:e2 {: RESULT = e1+" "+op+" "+e2; :} | + ABRIR_PARENTESE instanciacao_operativa:e FECHAR_PARENTESE {: RESULT = "("+e+")"; :} | + NUMERO:n {: RESULT = n; System.out.println("NUMERO:n = "+n); :} | + ID:n {: RESULT = n; System.out.println("ID:n = "+n); :}; + +/* +* PARA STRINGS (CASO ESPECIFICO (SOMENTE = E <> )) +*/ +instanciacao_string ::= instanciacao_string:x1 CONDICIONAL_ESPECIAL:x instanciacao_string:x2 {: RESULT = x1+" "+x+" "+x2; :} | + ABRIR_PARENTESE instanciacao_string:e FECHAR_PARENTESE {: RESULT = "("+e+")"; :} | + STRING:n {: RESULT = "\""+n+"\""; :}; \ No newline at end of file diff --git a/Test/com/analizador/exp_condicional/Condicionais.flex b/Test/com/analizador/exp_condicional/Condicionais.flex new file mode 100644 index 0000000..2e488c3 --- /dev/null +++ b/Test/com/analizador/exp_condicional/Condicionais.flex @@ -0,0 +1,88 @@ +//////////////////////////////////////////////////////////////////// +/* //// +* DECLARACAO DE VARIAVEIS EM PORTUGOL (ANALIZADOR LEXICO). //// +* BY: ANDREW NETO //// +* 20/06/2014 //// +*/ //// +//////////////////////////////////////////////////////////////////// + +package com.analizador.exp_condicional; + +import java_cup.runtime.*; + + +%% +%cup +%line +%char +%column + +%{ + + Symbol newSym(int tokenId) { + return new Symbol(tokenId , yyline, yycolumn); + } + + Symbol newSym(int tokenId, Object value) { + return new Symbol(tokenId , yyline, yycolumn, value); + } + +%} + +caracters = [A-Za-z] +numerais = [0-9] +alphanumeric = {caracters}|{numerais} +outros = [_] +ids = {caracters}({alphanumeric}|{outros})* +espaco = [\n\r\ \t] +nova_linha = \r|\n|\r\n +inteiro = {numerais}+ +string_content = (\\\"|[^\n\r\"]|\\{espaco}+\\)* +string_literal = {double_qoute}{string_content}{double_qoute} +double_qoute = \" + + +%% +/* PARA TESTE LIMITADOR */ + +(se|SE) { return newSym(sym.SE,yytext());} +(entao|ENTAO) { return newSym(sym.ENTAO,yytext());} + +(e|E) { return newSym(sym.CONDICIONAL_E,"&&");} +(ou|OU) { return newSym(sym.CONDICIONAL_OU,"||");} + + +"<" { return newSym(sym.CONDICIONAL,yytext());} +"<=" { return newSym(sym.CONDICIONAL,yytext());} +">" { return newSym(sym.CONDICIONAL,yytext());} +">=" { return newSym(sym.CONDICIONAL,yytext());} + + + +"<>" { return newSym(sym.CONDICIONAL_ESPECIAL,"!=");} +"=" {return newSym(sym.CONDICIONAL_ESPECIAL,"==");} + + + +"+" {return newSym(sym.OPERADOR,yytext());} +"-" {return newSym(sym.OPERADOR,yytext());} +"*" {return newSym(sym.OPERADOR,yytext());} +"/" {return newSym(sym.OPERADOR,yytext());} +"%" {return newSym(sym.OPERADOR,"%");} + + + +"(" {return newSym(sym.ABRIR_PARENTESE);} +")" {return newSym(sym.FECHAR_PARENTESE);} + + + +{string_literal} { return newSym(sym.STRING, (String) yytext().substring(1, yylength()-1)); } +{inteiro} {return newSym(sym.NUMERO,(String) yytext());} +{ids} {return newSym(sym.ID,yytext());} +{espaco} {/* IGNORAR */} +{nova_linha} {/* IGNORAR */} + + +<> { return newSym(sym.EOF);} +. { return newSym(sym.error,yytext()); } \ No newline at end of file diff --git a/Test/com/analizador/exp_condicional/Exemplo.txt b/Test/com/analizador/exp_condicional/Exemplo.txt new file mode 100644 index 0000000..38f64e4 --- /dev/null +++ b/Test/com/analizador/exp_condicional/Exemplo.txt @@ -0,0 +1 @@ +se "asd" ou "asdsad" entao \ No newline at end of file diff --git a/Test/com/analizador/exp_condicional/Inicializador.java b/Test/com/analizador/exp_condicional/Inicializador.java new file mode 100644 index 0000000..d53abce --- /dev/null +++ b/Test/com/analizador/exp_condicional/Inicializador.java @@ -0,0 +1,37 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.analizador.exp_condicional; + +import com.analizador.exe_expressao.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.StringReader; +import java_cup.runtime.Symbol; + +/** + * + * @author Andrew + */ +public class Inicializador { + + public static void main(String[] args) throws IOException, Exception { + //Yylex lexer = new Yylex(new StringReader("2+9")); + Yylex lexer = new Yylex(Inicializador.class.getResourceAsStream("Exemplo.txt")); + /* + Symbol sym; + for (sym = lexer.next_token(); sym.sym != 0; sym = lexer.next_token()) { + System.out.println("Token " + sym.sym + ", with value = " + sym.value + "; at line " + sym.left + ", column " + sym.right); + } + */ + + + parser p = new parser(lexer); + p.parse(); + + } + +} diff --git a/Test/com/analizador/exp_condicional/Yylex.java b/Test/com/analizador/exp_condicional/Yylex.java new file mode 100644 index 0000000..23230f0 --- /dev/null +++ b/Test/com/analizador/exp_condicional/Yylex.java @@ -0,0 +1,719 @@ +/* The following code was generated by JFlex 1.5.1 */ + +//////////////////////////////////////////////////////////////////// +/* //// +* DECLARACAO DE VARIAVEIS EM PORTUGOL (ANALIZADOR LEXICO). //// +* BY: ANDREW NETO //// +* 20/06/2014 //// +*/ //// +//////////////////////////////////////////////////////////////////// + +package com.analizador.exp_condicional; + +import java_cup.runtime.*; + + + +/** + * This class is a scanner generated by + * JFlex 1.5.1 + * from the specification file C:/Users/SIMONETO-2/Documents/NetBeansProjects/portugol-projeto/Test/com/analizador/exp_condicional/Condicionais.flex + */ +class Yylex implements java_cup.runtime.Scanner { + + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int YYINITIAL = 0; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l + * at the beginning of a line + * l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { + 0, 0 + }; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = + "\11\0\1\4\1\6\1\36\1\36\1\5\22\0\1\4\1\0\1\10"+ + "\2\0\1\33\2\0\1\34\1\35\1\32\1\32\1\0\1\32\1\0"+ + "\1\32\12\2\2\0\1\27\1\30\1\31\2\0\1\23\3\1\1\14"+ + "\10\1\1\21\1\24\3\1\1\13\1\22\1\26\5\1\1\0\1\7"+ + "\2\0\1\3\1\0\1\17\3\1\1\12\10\1\1\15\1\20\3\1"+ + "\1\11\1\16\1\25\5\1\12\0\1\36\u1fa2\0\1\36\1\36\udfd6\0"; + + /** + * Translates characters to character classes + */ + private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int [] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = + "\1\0\1\1\1\2\1\3\2\4\1\1\1\2\1\5"+ + "\1\2\1\5\2\2\1\6\1\7\1\6\1\10\1\11"+ + "\1\12\1\13\2\0\1\14\1\15\2\2\1\16\1\6"+ + "\1\17\2\0\1\14\4\2\1\20"; + + private static int [] zzUnpackAction() { + int [] result = new int[37]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /** + * Translates a state to a row index in the transition table + */ + private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = + "\0\0\0\37\0\76\0\135\0\37\0\174\0\233\0\272"+ + "\0\331\0\370\0\u0117\0\u0136\0\u0155\0\u0174\0\37\0\u0193"+ + "\0\37\0\37\0\37\0\37\0\233\0\u01b2\0\37\0\76"+ + "\0\u01d1\0\u01f0\0\76\0\37\0\37\0\u020f\0\u022e\0\233"+ + "\0\u024d\0\u026c\0\u028b\0\u02aa\0\76"; + + private static int [] zzUnpackRowMap() { + int [] result = new int[37]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int [] ZZ_TRANS = zzUnpackTrans(); + + private static final String ZZ_TRANS_PACKED_0 = + "\1\2\1\3\1\4\1\2\1\5\1\6\1\5\1\2"+ + "\1\7\1\10\1\11\1\12\1\13\3\3\1\14\3\3"+ + "\1\15\2\3\1\16\1\17\1\20\1\21\1\22\1\23"+ + "\1\24\41\0\3\3\5\0\16\3\12\0\1\4\42\0"+ + "\1\5\30\0\5\25\2\0\1\26\1\27\26\25\1\0"+ + "\3\3\5\0\1\3\1\30\14\3\11\0\3\3\5\0"+ + "\4\3\1\31\11\3\11\0\3\3\5\0\3\3\1\30"+ + "\12\3\11\0\3\3\5\0\10\3\1\32\5\3\11\0"+ + "\3\3\5\0\14\3\1\33\1\3\11\0\3\3\5\0"+ + "\15\3\1\33\40\0\1\34\1\35\35\0\1\34\6\0"+ + "\4\25\1\36\2\37\1\26\1\40\26\25\1\0\3\3"+ + "\5\0\5\3\1\41\10\3\11\0\3\3\5\0\11\3"+ + "\1\42\4\3\10\0\4\25\1\36\2\37\1\26\1\27"+ + "\26\25\4\0\3\37\1\25\30\0\3\3\5\0\6\3"+ + "\1\43\7\3\11\0\3\3\5\0\12\3\1\44\3\3"+ + "\11\0\3\3\5\0\7\3\1\45\6\3\11\0\3\3"+ + "\5\0\13\3\1\45\2\3\10\0"; + + private static int [] zzUnpackTrans() { + int [] result = new int[713]; + int offset = 0; + offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackTrans(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + value--; + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", + "Error: could not match input", + "Error: pushback value was too large" + }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state aState + */ + private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = + "\1\0\1\11\2\1\1\11\11\1\1\11\1\1\4\11"+ + "\2\0\1\11\4\1\2\11\2\0\6\1"; + + private static int [] zzUnpackAttribute() { + int [] result = new int[37]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** this buffer contains the current text to be matched and is + the source of the yytext() string */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** endRead marks the last character in the buffer, that has been read + from input */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /** denotes if the user-EOF-code has already been executed */ + private boolean zzEOFDone; + + /* user code: */ + + Symbol newSym(int tokenId) { + return new Symbol(tokenId , yyline, yycolumn); + } + + Symbol newSym(int tokenId, Object value) { + return new Symbol(tokenId , yyline, yycolumn, value); + } + + + + /** + * Creates a new scanner + * There is also a java.io.InputStream version of this constructor. + * + * @param in the java.io.Reader to read input from. + */ + Yylex(java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. + * There is also java.io.Reader version of this constructor. + * + * @param in the java.io.Inputstream to read input from. + */ + Yylex(java.io.InputStream in) { + this(new java.io.InputStreamReader + (in, java.nio.charset.Charset.forName("UTF-8"))); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed the packed character translation table + * @return the unpacked character translation table + */ + private static char [] zzUnpackCMap(String packed) { + char [] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 120) { + int count = packed.charAt(i++); + char value = packed.charAt(i++); + do map[j++] = value; while (--count > 0); + } + return map; + } + + + /** + * Refills the input buffer. + * + * @return false, iff there was new input. + * + * @exception java.io.IOException if any I/O-Error occurs + */ + private boolean zzRefill() throws java.io.IOException { + + /* first: make room (if you can) */ + if (zzStartRead > 0) { + System.arraycopy(zzBuffer, zzStartRead, + zzBuffer, 0, + zzEndRead-zzStartRead); + + /* translate stored positions */ + zzEndRead-= zzStartRead; + zzCurrentPos-= zzStartRead; + zzMarkedPos-= zzStartRead; + zzStartRead = 0; + } + + /* is the buffer big enough? */ + if (zzCurrentPos >= zzBuffer.length) { + /* if not: blow it up */ + char newBuffer[] = new char[zzCurrentPos*2]; + System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); + zzBuffer = newBuffer; + } + + /* finally: fill the buffer with new input */ + int numRead = zzReader.read(zzBuffer, zzEndRead, + zzBuffer.length-zzEndRead); + + if (numRead > 0) { + zzEndRead+= numRead; + return false; + } + // unlikely but not impossible: read 0 characters, but not at end of stream + if (numRead == 0) { + int c = zzReader.read(); + if (c == -1) { + return true; + } else { + zzBuffer[zzEndRead++] = (char) c; + return false; + } + } + + // numRead < 0 + return true; + } + + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) + zzReader.close(); + } + + + /** + * Resets the scanner to read from a new input stream. + * Does not close the old reader. + * + * All internal variables are reset, the old input stream + * cannot be reused (internal buffer is discarded and lost). + * Lexical state is set to ZZ_INITIAL. + * + * Internal scan buffer is resized down to its initial length, if it has grown. + * + * @param reader the new input stream + */ + public final void yyreset(java.io.Reader reader) { + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + zzEOFDone = false; + zzEndRead = zzStartRead = 0; + zzCurrentPos = zzMarkedPos = 0; + yyline = yychar = yycolumn = 0; + zzLexicalState = YYINITIAL; + if (zzBuffer.length > ZZ_BUFFERSIZE) + zzBuffer = new char[ZZ_BUFFERSIZE]; + } + + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + + /** + * Enters a new lexical state + * + * @param newState the new lexical state + */ + public final void yybegin(int newState) { + zzLexicalState = newState; + } + + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); + } + + + /** + * Returns the character at position pos from the + * matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. + * A value from 0 to yylength()-1. + * + * @return the character at position pos + */ + public final char yycharat(int pos) { + return zzBuffer[zzStartRead+pos]; + } + + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos-zzStartRead; + } + + + /** + * Reports an error that occured while scanning. + * + * In a wellformed scanner (no or only correct usage of + * yypushback(int) and a match-all fallback rule) this method + * will only be called with things that "Can't Possibly Happen". + * If this method is called, something is seriously wrong + * (e.g. a JFlex bug producing a faulty scanner etc.). + * + * Usual syntax/scanner level error handling should be done + * in error fallback rules. + * + * @param errorCode the code of the errormessage to display + */ + private void zzScanError(int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } + catch (ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + + /** + * Pushes the specified amount of characters back into the input stream. + * + * They will be read again by then next call of the scanning method + * + * @param number the number of characters to be read again. + * This number must not be greater than yylength()! + */ + public void yypushback(int number) { + if ( number > yylength() ) + zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + + /** + * Contains user EOF-code, which will be executed exactly once, + * when the end of file is reached + */ + private void zzDoEOF() throws java.io.IOException { + if (!zzEOFDone) { + zzEOFDone = true; + yyclose(); + } + } + + + /** + * Resumes scanning until the next regular expression is matched, + * the end of input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException if any I/O-Error occurs + */ + public java_cup.runtime.Symbol next_token() throws java.io.IOException { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char [] zzBufferL = zzBuffer; + char [] zzCMapL = ZZ_CMAP; + + int [] zzTransL = ZZ_TRANS; + int [] zzRowMapL = ZZ_ROWMAP; + int [] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + yychar+= zzMarkedPosL-zzStartRead; + + boolean zzR = false; + for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL; + zzCurrentPosL++) { + switch (zzBufferL[zzCurrentPosL]) { + case '\u000B': + case '\u000C': + case '\u0085': + case '\u2028': + case '\u2029': + yyline++; + yycolumn = 0; + zzR = false; + break; + case '\r': + yyline++; + yycolumn = 0; + zzR = true; + break; + case '\n': + if (zzR) + zzR = false; + else { + yyline++; + yycolumn = 0; + } + break; + default: + zzR = false; + yycolumn++; + } + } + + if (zzR) { + // peek one character ahead if it is \n (if we have counted one line too much) + boolean zzPeek; + if (zzMarkedPosL < zzEndReadL) + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + else if (zzAtEOF) + zzPeek = false; + else { + boolean eof = zzRefill(); + zzEndReadL = zzEndRead; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + if (eof) + zzPeek = false; + else + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + } + if (zzPeek) yyline--; + } + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = ZZ_LEXSTATE[zzLexicalState]; + + // set up zzAction for empty match case: + int zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + } + + + zzForAction: { + while (true) { + + if (zzCurrentPosL < zzEndReadL) + zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } + else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } + else { + zzInput = zzBufferL[zzCurrentPosL++]; + } + } + int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; + if (zzNext == -1) break zzForAction; + zzState = zzNext; + + zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ( (zzAttributes & 8) == 8 ) break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 1: + { return newSym(sym.error,yytext()); + } + case 17: break; + case 2: + { return newSym(sym.ID,yytext()); + } + case 18: break; + case 3: + { return newSym(sym.NUMERO,(String) yytext()); + } + case 19: break; + case 4: + { /* IGNORAR */ + } + case 20: break; + case 5: + { return newSym(sym.CONDICIONAL_ADITIVA,"&&"); + } + case 21: break; + case 6: + { return newSym(sym.CONDICIONAL,yytext()); + } + case 22: break; + case 7: + { return newSym(sym.CONDICIONAL_ESPECIAL,"=="); + } + case 23: break; + case 8: + { return newSym(sym.OPERADOR,yytext()); + } + case 24: break; + case 9: + { return newSym(sym.OPERADOR,"%"); + } + case 25: break; + case 10: + { return newSym(sym.ABRIR_PARENTESE); + } + case 26: break; + case 11: + { return newSym(sym.FECHAR_PARENTESE); + } + case 27: break; + case 12: + { return newSym(sym.STRING, (String) yytext().substring(1, yylength()-1)); + } + case 28: break; + case 13: + { return newSym(sym.SE,yytext()); + } + case 29: break; + case 14: + { return newSym(sym.CONDICIONAL_ADITIVA,"||"); + } + case 30: break; + case 15: + { return newSym(sym.CONDICIONAL_ESPECIAL,"!="); + } + case 31: break; + case 16: + { return newSym(sym.ENTAO,yytext()); + } + case 32: break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + zzDoEOF(); + { + return newSym(sym.EOF); + } + } + else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + + +} diff --git a/Test/com/analizador/exp_condicional/Yylex.java~ b/Test/com/analizador/exp_condicional/Yylex.java~ new file mode 100644 index 0000000..23230f0 --- /dev/null +++ b/Test/com/analizador/exp_condicional/Yylex.java~ @@ -0,0 +1,719 @@ +/* The following code was generated by JFlex 1.5.1 */ + +//////////////////////////////////////////////////////////////////// +/* //// +* DECLARACAO DE VARIAVEIS EM PORTUGOL (ANALIZADOR LEXICO). //// +* BY: ANDREW NETO //// +* 20/06/2014 //// +*/ //// +//////////////////////////////////////////////////////////////////// + +package com.analizador.exp_condicional; + +import java_cup.runtime.*; + + + +/** + * This class is a scanner generated by + * JFlex 1.5.1 + * from the specification file C:/Users/SIMONETO-2/Documents/NetBeansProjects/portugol-projeto/Test/com/analizador/exp_condicional/Condicionais.flex + */ +class Yylex implements java_cup.runtime.Scanner { + + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int YYINITIAL = 0; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l + * at the beginning of a line + * l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { + 0, 0 + }; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = + "\11\0\1\4\1\6\1\36\1\36\1\5\22\0\1\4\1\0\1\10"+ + "\2\0\1\33\2\0\1\34\1\35\1\32\1\32\1\0\1\32\1\0"+ + "\1\32\12\2\2\0\1\27\1\30\1\31\2\0\1\23\3\1\1\14"+ + "\10\1\1\21\1\24\3\1\1\13\1\22\1\26\5\1\1\0\1\7"+ + "\2\0\1\3\1\0\1\17\3\1\1\12\10\1\1\15\1\20\3\1"+ + "\1\11\1\16\1\25\5\1\12\0\1\36\u1fa2\0\1\36\1\36\udfd6\0"; + + /** + * Translates characters to character classes + */ + private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int [] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = + "\1\0\1\1\1\2\1\3\2\4\1\1\1\2\1\5"+ + "\1\2\1\5\2\2\1\6\1\7\1\6\1\10\1\11"+ + "\1\12\1\13\2\0\1\14\1\15\2\2\1\16\1\6"+ + "\1\17\2\0\1\14\4\2\1\20"; + + private static int [] zzUnpackAction() { + int [] result = new int[37]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /** + * Translates a state to a row index in the transition table + */ + private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = + "\0\0\0\37\0\76\0\135\0\37\0\174\0\233\0\272"+ + "\0\331\0\370\0\u0117\0\u0136\0\u0155\0\u0174\0\37\0\u0193"+ + "\0\37\0\37\0\37\0\37\0\233\0\u01b2\0\37\0\76"+ + "\0\u01d1\0\u01f0\0\76\0\37\0\37\0\u020f\0\u022e\0\233"+ + "\0\u024d\0\u026c\0\u028b\0\u02aa\0\76"; + + private static int [] zzUnpackRowMap() { + int [] result = new int[37]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int [] ZZ_TRANS = zzUnpackTrans(); + + private static final String ZZ_TRANS_PACKED_0 = + "\1\2\1\3\1\4\1\2\1\5\1\6\1\5\1\2"+ + "\1\7\1\10\1\11\1\12\1\13\3\3\1\14\3\3"+ + "\1\15\2\3\1\16\1\17\1\20\1\21\1\22\1\23"+ + "\1\24\41\0\3\3\5\0\16\3\12\0\1\4\42\0"+ + "\1\5\30\0\5\25\2\0\1\26\1\27\26\25\1\0"+ + "\3\3\5\0\1\3\1\30\14\3\11\0\3\3\5\0"+ + "\4\3\1\31\11\3\11\0\3\3\5\0\3\3\1\30"+ + "\12\3\11\0\3\3\5\0\10\3\1\32\5\3\11\0"+ + "\3\3\5\0\14\3\1\33\1\3\11\0\3\3\5\0"+ + "\15\3\1\33\40\0\1\34\1\35\35\0\1\34\6\0"+ + "\4\25\1\36\2\37\1\26\1\40\26\25\1\0\3\3"+ + "\5\0\5\3\1\41\10\3\11\0\3\3\5\0\11\3"+ + "\1\42\4\3\10\0\4\25\1\36\2\37\1\26\1\27"+ + "\26\25\4\0\3\37\1\25\30\0\3\3\5\0\6\3"+ + "\1\43\7\3\11\0\3\3\5\0\12\3\1\44\3\3"+ + "\11\0\3\3\5\0\7\3\1\45\6\3\11\0\3\3"+ + "\5\0\13\3\1\45\2\3\10\0"; + + private static int [] zzUnpackTrans() { + int [] result = new int[713]; + int offset = 0; + offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackTrans(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + value--; + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", + "Error: could not match input", + "Error: pushback value was too large" + }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state aState + */ + private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = + "\1\0\1\11\2\1\1\11\11\1\1\11\1\1\4\11"+ + "\2\0\1\11\4\1\2\11\2\0\6\1"; + + private static int [] zzUnpackAttribute() { + int [] result = new int[37]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** this buffer contains the current text to be matched and is + the source of the yytext() string */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** endRead marks the last character in the buffer, that has been read + from input */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /** denotes if the user-EOF-code has already been executed */ + private boolean zzEOFDone; + + /* user code: */ + + Symbol newSym(int tokenId) { + return new Symbol(tokenId , yyline, yycolumn); + } + + Symbol newSym(int tokenId, Object value) { + return new Symbol(tokenId , yyline, yycolumn, value); + } + + + + /** + * Creates a new scanner + * There is also a java.io.InputStream version of this constructor. + * + * @param in the java.io.Reader to read input from. + */ + Yylex(java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. + * There is also java.io.Reader version of this constructor. + * + * @param in the java.io.Inputstream to read input from. + */ + Yylex(java.io.InputStream in) { + this(new java.io.InputStreamReader + (in, java.nio.charset.Charset.forName("UTF-8"))); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed the packed character translation table + * @return the unpacked character translation table + */ + private static char [] zzUnpackCMap(String packed) { + char [] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 120) { + int count = packed.charAt(i++); + char value = packed.charAt(i++); + do map[j++] = value; while (--count > 0); + } + return map; + } + + + /** + * Refills the input buffer. + * + * @return false, iff there was new input. + * + * @exception java.io.IOException if any I/O-Error occurs + */ + private boolean zzRefill() throws java.io.IOException { + + /* first: make room (if you can) */ + if (zzStartRead > 0) { + System.arraycopy(zzBuffer, zzStartRead, + zzBuffer, 0, + zzEndRead-zzStartRead); + + /* translate stored positions */ + zzEndRead-= zzStartRead; + zzCurrentPos-= zzStartRead; + zzMarkedPos-= zzStartRead; + zzStartRead = 0; + } + + /* is the buffer big enough? */ + if (zzCurrentPos >= zzBuffer.length) { + /* if not: blow it up */ + char newBuffer[] = new char[zzCurrentPos*2]; + System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); + zzBuffer = newBuffer; + } + + /* finally: fill the buffer with new input */ + int numRead = zzReader.read(zzBuffer, zzEndRead, + zzBuffer.length-zzEndRead); + + if (numRead > 0) { + zzEndRead+= numRead; + return false; + } + // unlikely but not impossible: read 0 characters, but not at end of stream + if (numRead == 0) { + int c = zzReader.read(); + if (c == -1) { + return true; + } else { + zzBuffer[zzEndRead++] = (char) c; + return false; + } + } + + // numRead < 0 + return true; + } + + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) + zzReader.close(); + } + + + /** + * Resets the scanner to read from a new input stream. + * Does not close the old reader. + * + * All internal variables are reset, the old input stream + * cannot be reused (internal buffer is discarded and lost). + * Lexical state is set to ZZ_INITIAL. + * + * Internal scan buffer is resized down to its initial length, if it has grown. + * + * @param reader the new input stream + */ + public final void yyreset(java.io.Reader reader) { + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + zzEOFDone = false; + zzEndRead = zzStartRead = 0; + zzCurrentPos = zzMarkedPos = 0; + yyline = yychar = yycolumn = 0; + zzLexicalState = YYINITIAL; + if (zzBuffer.length > ZZ_BUFFERSIZE) + zzBuffer = new char[ZZ_BUFFERSIZE]; + } + + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + + /** + * Enters a new lexical state + * + * @param newState the new lexical state + */ + public final void yybegin(int newState) { + zzLexicalState = newState; + } + + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); + } + + + /** + * Returns the character at position pos from the + * matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. + * A value from 0 to yylength()-1. + * + * @return the character at position pos + */ + public final char yycharat(int pos) { + return zzBuffer[zzStartRead+pos]; + } + + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos-zzStartRead; + } + + + /** + * Reports an error that occured while scanning. + * + * In a wellformed scanner (no or only correct usage of + * yypushback(int) and a match-all fallback rule) this method + * will only be called with things that "Can't Possibly Happen". + * If this method is called, something is seriously wrong + * (e.g. a JFlex bug producing a faulty scanner etc.). + * + * Usual syntax/scanner level error handling should be done + * in error fallback rules. + * + * @param errorCode the code of the errormessage to display + */ + private void zzScanError(int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } + catch (ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + + /** + * Pushes the specified amount of characters back into the input stream. + * + * They will be read again by then next call of the scanning method + * + * @param number the number of characters to be read again. + * This number must not be greater than yylength()! + */ + public void yypushback(int number) { + if ( number > yylength() ) + zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + + /** + * Contains user EOF-code, which will be executed exactly once, + * when the end of file is reached + */ + private void zzDoEOF() throws java.io.IOException { + if (!zzEOFDone) { + zzEOFDone = true; + yyclose(); + } + } + + + /** + * Resumes scanning until the next regular expression is matched, + * the end of input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException if any I/O-Error occurs + */ + public java_cup.runtime.Symbol next_token() throws java.io.IOException { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char [] zzBufferL = zzBuffer; + char [] zzCMapL = ZZ_CMAP; + + int [] zzTransL = ZZ_TRANS; + int [] zzRowMapL = ZZ_ROWMAP; + int [] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + yychar+= zzMarkedPosL-zzStartRead; + + boolean zzR = false; + for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL; + zzCurrentPosL++) { + switch (zzBufferL[zzCurrentPosL]) { + case '\u000B': + case '\u000C': + case '\u0085': + case '\u2028': + case '\u2029': + yyline++; + yycolumn = 0; + zzR = false; + break; + case '\r': + yyline++; + yycolumn = 0; + zzR = true; + break; + case '\n': + if (zzR) + zzR = false; + else { + yyline++; + yycolumn = 0; + } + break; + default: + zzR = false; + yycolumn++; + } + } + + if (zzR) { + // peek one character ahead if it is \n (if we have counted one line too much) + boolean zzPeek; + if (zzMarkedPosL < zzEndReadL) + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + else if (zzAtEOF) + zzPeek = false; + else { + boolean eof = zzRefill(); + zzEndReadL = zzEndRead; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + if (eof) + zzPeek = false; + else + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + } + if (zzPeek) yyline--; + } + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = ZZ_LEXSTATE[zzLexicalState]; + + // set up zzAction for empty match case: + int zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + } + + + zzForAction: { + while (true) { + + if (zzCurrentPosL < zzEndReadL) + zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } + else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } + else { + zzInput = zzBufferL[zzCurrentPosL++]; + } + } + int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; + if (zzNext == -1) break zzForAction; + zzState = zzNext; + + zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ( (zzAttributes & 8) == 8 ) break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 1: + { return newSym(sym.error,yytext()); + } + case 17: break; + case 2: + { return newSym(sym.ID,yytext()); + } + case 18: break; + case 3: + { return newSym(sym.NUMERO,(String) yytext()); + } + case 19: break; + case 4: + { /* IGNORAR */ + } + case 20: break; + case 5: + { return newSym(sym.CONDICIONAL_ADITIVA,"&&"); + } + case 21: break; + case 6: + { return newSym(sym.CONDICIONAL,yytext()); + } + case 22: break; + case 7: + { return newSym(sym.CONDICIONAL_ESPECIAL,"=="); + } + case 23: break; + case 8: + { return newSym(sym.OPERADOR,yytext()); + } + case 24: break; + case 9: + { return newSym(sym.OPERADOR,"%"); + } + case 25: break; + case 10: + { return newSym(sym.ABRIR_PARENTESE); + } + case 26: break; + case 11: + { return newSym(sym.FECHAR_PARENTESE); + } + case 27: break; + case 12: + { return newSym(sym.STRING, (String) yytext().substring(1, yylength()-1)); + } + case 28: break; + case 13: + { return newSym(sym.SE,yytext()); + } + case 29: break; + case 14: + { return newSym(sym.CONDICIONAL_ADITIVA,"||"); + } + case 30: break; + case 15: + { return newSym(sym.CONDICIONAL_ESPECIAL,"!="); + } + case 31: break; + case 16: + { return newSym(sym.ENTAO,yytext()); + } + case 32: break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + zzDoEOF(); + { + return newSym(sym.EOF); + } + } + else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + + +} diff --git a/Test/com/analizador/exp_condicional/java_cup.jar b/Test/com/analizador/exp_condicional/java_cup.jar new file mode 100644 index 0000000..73ffa0b Binary files /dev/null and b/Test/com/analizador/exp_condicional/java_cup.jar differ diff --git a/Test/com/analizador/exp_condicional/parser.java b/Test/com/analizador/exp_condicional/parser.java new file mode 100644 index 0000000..108ea70 --- /dev/null +++ b/Test/com/analizador/exp_condicional/parser.java @@ -0,0 +1,424 @@ + +//---------------------------------------------------- +// The following code was generated by CUP v0.11a beta 20060608 +// Tue Jun 24 15:37:09 BRT 2014 +//---------------------------------------------------- + +package com.analizador.exp_condicional; + +import java_cup.runtime.*; + +/** CUP v0.11a beta 20060608 generated parser. + * @version Tue Jun 24 15:37:09 BRT 2014 + */ +public class parser extends java_cup.runtime.lr_parser { + + /** Default constructor. */ + public parser() {super();} + + /** Constructor which sets the default scanner. */ + public parser(java_cup.runtime.Scanner s) {super(s);} + + /** Constructor which sets the default scanner. */ + public parser(java_cup.runtime.Scanner s, java_cup.runtime.SymbolFactory sf) {super(s,sf);} + + /** Production table. */ + protected static final short _production_table[][] = + unpackFromStrings(new String[] { + "\000\023\000\002\002\004\000\002\002\004\000\002\002" + + "\003\000\002\002\003\000\002\003\005\000\002\004\005" + + "\000\002\004\005\000\002\004\003\000\002\004\003\000" + + "\002\005\005\000\002\005\005\000\002\005\003\000\002" + + "\006\005\000\002\006\005\000\002\006\003\000\002\006" + + "\003\000\002\007\005\000\002\007\005\000\002\007\003" + + "" }); + + /** Access to production table. */ + public short[][] production_table() {return _production_table;} + + /** Parse-action table. */ + protected static final short[][] _action_table = + unpackFromStrings(new String[] { + "\000\044\000\006\003\005\004\007\001\002\000\006\002" + + "\046\004\007\001\002\000\006\002\ufffe\004\ufffe\001\002" + + "\000\006\002\uffff\004\uffff\001\002\000\012\012\016\014" + + "\012\015\010\016\014\001\002\000\016\005\ufff2\006\ufff2" + + "\007\ufff2\010\ufff2\011\ufff2\013\ufff2\001\002\000\012\005" + + "\ufff9\007\033\010\ufff9\013\ufff9\001\002\000\016\005\ufff3" + + "\006\ufff3\007\ufff3\010\ufff3\011\ufff3\013\ufff3\001\002\000" + + "\014\005\ufffa\006\042\007\041\010\ufffa\013\ufffa\001\002" + + "\000\012\005\uffef\007\uffef\010\uffef\013\uffef\001\002\000" + + "\006\005\040\010\030\001\002\000\012\012\016\014\012" + + "\015\010\016\014\001\002\000\016\005\ufff6\006\ufff6\007" + + "\ufff6\010\ufff6\011\020\013\ufff6\001\002\000\010\012\021" + + "\014\012\015\010\001\002\000\010\012\021\014\012\015" + + "\010\001\002\000\016\005\ufff5\006\ufff5\007\ufff5\010\ufff5" + + "\011\ufff5\013\ufff5\001\002\000\006\011\020\013\024\001" + + "\002\000\016\005\ufff4\006\ufff4\007\ufff4\010\ufff4\011\ufff4" + + "\013\ufff4\001\002\000\010\007\033\010\ufff9\013\034\001" + + "\002\000\006\010\030\013\031\001\002\000\014\006\ufff6" + + "\007\ufff6\010\ufff6\011\020\013\024\001\002\000\012\012" + + "\016\014\012\015\010\016\014\001\002\000\010\005\ufffb" + + "\010\ufffb\013\ufffb\001\002\000\010\005\ufffc\010\ufffc\013" + + "\ufffc\001\002\000\006\012\036\016\014\001\002\000\012" + + "\005\ufff0\007\ufff0\010\ufff0\013\ufff0\001\002\000\012\005" + + "\ufff1\007\ufff1\010\ufff1\013\ufff1\001\002\000\006\012\036" + + "\016\014\001\002\000\006\007\033\013\034\001\002\000" + + "\006\002\ufffd\004\ufffd\001\002\000\010\012\021\014\012" + + "\015\010\001\002\000\010\012\021\014\012\015\010\001" + + "\002\000\014\005\ufff8\006\ufff8\007\ufff8\010\ufff8\013\ufff8" + + "\001\002\000\014\005\ufff7\006\ufff7\007\ufff7\010\ufff7\013" + + "\ufff7\001\002\000\006\002\001\004\001\001\002\000\004" + + "\002\000\001\002" }); + + /** Access to parse-action table. */ + public short[][] action_table() {return _action_table;} + + /** reduce_goto table. */ + protected static final short[][] _reduce_table = + unpackFromStrings(new String[] { + "\000\044\000\006\002\003\003\005\001\001\000\004\003" + + "\044\001\001\000\002\001\001\000\002\001\001\000\012" + + "\004\014\005\012\006\016\007\010\001\001\000\002\001" + + "\001\000\002\001\001\000\002\001\001\000\002\001\001" + + "\000\002\001\001\000\002\001\001\000\012\004\025\005" + + "\012\006\026\007\024\001\001\000\002\001\001\000\004" + + "\006\021\001\001\000\004\006\022\001\001\000\002\001" + + "\001\000\002\001\001\000\002\001\001\000\002\001\001" + + "\000\002\001\001\000\002\001\001\000\012\004\031\005" + + "\012\006\016\007\010\001\001\000\002\001\001\000\002" + + "\001\001\000\004\007\034\001\001\000\002\001\001\000" + + "\002\001\001\000\004\007\036\001\001\000\002\001\001" + + "\000\002\001\001\000\006\005\043\006\016\001\001\000" + + "\006\005\042\006\016\001\001\000\002\001\001\000\002" + + "\001\001\000\002\001\001\000\002\001\001" }); + + /** Access to reduce_goto table. */ + public short[][] reduce_table() {return _reduce_table;} + + /** Instance of action encapsulation class. */ + protected CUP$parser$actions action_obj; + + /** Action encapsulation object initializer. */ + protected void init_actions() + { + action_obj = new CUP$parser$actions(this); + } + + /** Invoke a user supplied parse action. */ + public java_cup.runtime.Symbol do_action( + int act_num, + java_cup.runtime.lr_parser parser, + java.util.Stack stack, + int top) + throws java.lang.Exception + { + /* call code in generated class */ + return action_obj.CUP$parser$do_action(act_num, parser, stack, top); + } + + /** Indicates start state. */ + public int start_state() {return 0;} + /** Indicates start production. */ + public int start_production() {return 1;} + + /** EOF Symbol index. */ + public int EOF_sym() {return 0;} + + /** error Symbol index. */ + public int error_sym() {return 1;} + + + + public static void main(String args[]) throws Exception{ + new parser(new Yylex(System.in)).parse(); + } + public void syntax_error(Symbol s){ + report_error("Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right)+". Trecho desconhecido: \""+s.value+"\"",null); + } + +} + +/** Cup generated class to encapsulate user supplied action code.*/ +class CUP$parser$actions { + private final parser parser; + + /** Constructor */ + CUP$parser$actions(parser parser) { + this.parser = parser; + } + + /** Method with the actual generated action code. */ + public final java_cup.runtime.Symbol CUP$parser$do_action( + int CUP$parser$act_num, + java_cup.runtime.lr_parser CUP$parser$parser, + java.util.Stack CUP$parser$stack, + int CUP$parser$top) + throws java.lang.Exception + { + /* Symbol object for return from actions */ + java_cup.runtime.Symbol CUP$parser$result; + + /* select the action based on the action number */ + switch (CUP$parser$act_num) + { + /*. . . . . . . . . . . . . . . . . . . .*/ + case 18: // instanciacao_string ::= STRING + { + String RESULT =null; + int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = "\""+n+"\""; + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao_string",5, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 17: // instanciacao_string ::= ABRIR_PARENTESE instanciacao_string FECHAR_PARENTESE + { + String RESULT =null; + int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + RESULT = "("+e+")"; + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao_string",5, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 16: // instanciacao_string ::= instanciacao_string CONDICIONAL_ESPECIAL instanciacao_string + { + String RESULT =null; + int x1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left; + int x1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right; + String x1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; + int xleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int xright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + Object x = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + int x2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int x2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String x2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = x1+" "+x+" "+x2; + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao_string",5, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 15: // instanciacao_operativa ::= ID + { + String RESULT =null; + int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = n; System.out.println("ID:n = "+n); + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao_operativa",4, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 14: // instanciacao_operativa ::= NUMERO + { + String RESULT =null; + int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = n; System.out.println("NUMERO:n = "+n); + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao_operativa",4, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 13: // instanciacao_operativa ::= ABRIR_PARENTESE instanciacao_operativa FECHAR_PARENTESE + { + String RESULT =null; + int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + RESULT = "("+e+")"; + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao_operativa",4, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 12: // instanciacao_operativa ::= instanciacao_operativa OPERADOR instanciacao_operativa + { + String RESULT =null; + int e1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left; + int e1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right; + String e1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; + int opleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int opright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + Object op = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + int e2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int e2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String e2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = e1+" "+op+" "+e2; + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao_operativa",4, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 11: // instanciacao_fragmental ::= instanciacao_operativa + { + String RESULT =null; + int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = e;System.out.println("instanciacao_operativa:e = "+e); + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao_fragmental",3, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 10: // instanciacao_fragmental ::= instanciacao_fragmental CONDICIONAL_ESPECIAL instanciacao_fragmental + { + String RESULT =null; + int x1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left; + int x1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right; + String x1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; + int yleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int yright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + Object y = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + int x2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int x2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String x2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = x1 + " " + y + " " + x2; + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao_fragmental",3, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 9: // instanciacao_fragmental ::= instanciacao_fragmental CONDICIONAL instanciacao_fragmental + { + String RESULT =null; + int x1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left; + int x1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right; + String x1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; + int yleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int yright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + Object y = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + int x2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int x2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String x2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = x1 + " " + y + " " + x2; + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao_fragmental",3, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 8: // instanciacao_ligativa ::= instanciacao_string + { + String RESULT =null; + int zleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int zright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String z = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = z; System.out.println("instanciacao_fragmental:z = "+z); + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao_ligativa",2, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 7: // instanciacao_ligativa ::= instanciacao_fragmental + { + String RESULT =null; + int zleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int zright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String z = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = z; System.out.println("instanciacao_fragmental:z = "+z); + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao_ligativa",2, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 6: // instanciacao_ligativa ::= ABRIR_PARENTESE instanciacao_ligativa FECHAR_PARENTESE + { + String RESULT =null; + int xleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int xright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + String x = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + RESULT = "("+x+")"; + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao_ligativa",2, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 5: // instanciacao_ligativa ::= instanciacao_ligativa CONDICIONAL_ADITIVA instanciacao_ligativa + { + String RESULT =null; + int x1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left; + int x1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right; + String x1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; + int yleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int yright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + Object y = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + int x2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int x2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String x2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = x1 + " " + y + " " + x2; + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao_ligativa",2, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 4: // instanciacao_global ::= SE instanciacao_ligativa ENTAO + { + Object RESULT =null; + int xleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int xright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + String x = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + System.out.println("if(" + x + ")"); + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao_global",1, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 3: // gramatica ::= error + { + Object RESULT =null; + + CUP$parser$result = parser.getSymbolFactory().newSymbol("gramatica",0, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 2: // gramatica ::= instanciacao_global + { + Object RESULT =null; + + CUP$parser$result = parser.getSymbolFactory().newSymbol("gramatica",0, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 1: // $START ::= gramatica EOF + { + Object RESULT =null; + int start_valleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int start_valright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + Object start_val = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + RESULT = start_val; + CUP$parser$result = parser.getSymbolFactory().newSymbol("$START",0, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + /* ACCEPT */ + CUP$parser$parser.done_parsing(); + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 0: // gramatica ::= gramatica instanciacao_global + { + Object RESULT =null; + + CUP$parser$result = parser.getSymbolFactory().newSymbol("gramatica",0, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /* . . . . . .*/ + default: + throw new Exception( + "Invalid action number found in internal parse table"); + + } + } +} + diff --git a/Test/com/analizador/exp_condicional/sym.java b/Test/com/analizador/exp_condicional/sym.java new file mode 100644 index 0000000..1c39b12 --- /dev/null +++ b/Test/com/analizador/exp_condicional/sym.java @@ -0,0 +1,26 @@ + +//---------------------------------------------------- +// The following code was generated by CUP v0.11a beta 20060608 +// Tue Jun 24 15:37:09 BRT 2014 +//---------------------------------------------------- + +package com.analizador.exp_condicional; + +/** CUP generated class containing symbol constants. */ +public class sym { + /* terminals */ + public static final int OPERADOR = 7; + public static final int SE = 2; + public static final int CONDICIONAL_ESPECIAL = 5; + public static final int CONDICIONAL_ADITIVA = 6; + public static final int ABRIR_PARENTESE = 8; + public static final int STRING = 12; + public static final int EOF = 0; + public static final int NUMERO = 10; + public static final int ID = 11; + public static final int CONDICIONAL = 4; + public static final int error = 1; + public static final int FECHAR_PARENTESE = 9; + public static final int ENTAO = 3; +} + diff --git a/Test/com/analizador/expressao/Exemplo.txt b/Test/com/analizador/expressao/Exemplo.txt new file mode 100644 index 0000000..f67595d --- /dev/null +++ b/Test/com/analizador/expressao/Exemplo.txt @@ -0,0 +1 @@ +variavel <- ((a+2)/2) \ No newline at end of file diff --git a/Test/com/analizador/expressao/Expressao.cup b/Test/com/analizador/expressao/Expressao.cup new file mode 100644 index 0000000..2d6ed12 --- /dev/null +++ b/Test/com/analizador/expressao/Expressao.cup @@ -0,0 +1,46 @@ +//////////////////////////////////////////////////////////////////////// +/* //// +* DECLARACAO DE EXPRESSOES EM PORTUGOL (ANALIZADOR E COMPILADOR). //// +* BY: ANDREW NETO //// +* 20/06/2014 //// +*/ //// +//////////////////////////////////////////////////////////////////////// + +package com.analizador.expressao; + +import java_cup.runtime.*; + +parser code +{: + public static void main(String args[]) throws Exception{ + new parser(new Yylex(System.in)).parse(); + } + public void syntax_error(Symbol s){ + report_error("Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right)+". Trecho desconhecido: \""+s.value+"\"",null); + } +:} + + +terminal ATRIBUIR; +terminal OPERADOR; +terminal ABRIR_PARENTESE, FECHAR_PARENTESE; +terminal String NUMERO,ID,STRING; + + +non terminal gramatica, instanciacao; +non terminal String valor; + + +precedence left OPERADOR; + +gramatica ::= gramatica instanciacao | + instanciacao | + error {::} ; + +instanciacao ::= ID:x ATRIBUIR valor:e {: System.out.println(x+" = "+e); :} | ID:x ATRIBUIR STRING:e {: System.out.println(x+" = \""+e+"\""); :}; + + +valor ::= valor:e1 OPERADOR:op valor:e2 {: RESULT = (String) e1+" "+op+" "+e2; :} | + ABRIR_PARENTESE valor:e FECHAR_PARENTESE {: RESULT = "("+e+")"; :} | + NUMERO:n {: RESULT = n; :} | + ID:n {: RESULT = n; :} ; \ No newline at end of file diff --git a/Test/com/analizador/expressao/Expressao.flex b/Test/com/analizador/expressao/Expressao.flex new file mode 100644 index 0000000..b547758 --- /dev/null +++ b/Test/com/analizador/expressao/Expressao.flex @@ -0,0 +1,68 @@ +//////////////////////////////////////////////////////////////////// +/* //// +* DECLARACAO DE EXPRESSOES EM PORTUGOL (ANALIZADOR LEXICO). //// +* BY: ANDREW NETO //// +* 20/06/2014 //// +*/ //// +//////////////////////////////////////////////////////////////////// + + +package com.analizador.expressao; + +import java_cup.runtime.*; + + +%% +%cup +%line +%column + +%{ + + Symbol newSym(int tokenId) { + return new Symbol(tokenId , yyline, yycolumn); + } + + Symbol newSym(int tokenId, Object value) { + return new Symbol(tokenId , yyline, yycolumn, value); + } + +%} + +caracters = [A-Za-z] +numerais = [0-9] +alphanumeric = {caracters}|{numerais} +outros = [_] +ids = {caracters}({alphanumeric}|{outros})* +espaco = [\n\r\ \t] +nova_linha = \r|\n|\r\n +inteiro = {numerais}+ + + +string_content = (\\\"|[^\n\r\"]|\\{espaco}+\\)* +string_literal = {double_qoute}{string_content}{double_qoute} +double_qoute = \" +%% + +/* +* PARA TESTE +*/ +"<-" { return newSym(sym.ATRIBUIR,yytext());} +":=" { return newSym(sym.ATRIBUIR,yytext());} + + + +{string_literal} { return newSym(sym.STRING, yytext().substring(1, yylength()-1)); } +{inteiro} {return newSym(sym.NUMERO,(String) yytext());} +{ids} {return newSym(sym.ID,yytext());} +{espaco} {/* IGNORAR */} +{nova_linha} {/* IGNORAR */} +"+" {return newSym(sym.OPERADOR,yytext());} +"-" {return newSym(sym.OPERADOR,yytext());} +"*" {return newSym(sym.OPERADOR,yytext());} +"/" {return newSym(sym.OPERADOR,yytext());} +"%" {return newSym(sym.OPERADOR,"%");} +"(" {return newSym(sym.ABRIR_PARENTESE,yytext());} +")" {return newSym(sym.FECHAR_PARENTESE,yytext());} +<> {return newSym(sym.EOF);} +. {return newSym(sym.error,yytext());} \ No newline at end of file diff --git a/Test/com/analizador/expressao/Inicializador.java b/Test/com/analizador/expressao/Inicializador.java new file mode 100644 index 0000000..adcb564 --- /dev/null +++ b/Test/com/analizador/expressao/Inicializador.java @@ -0,0 +1,34 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.analizador.expressao; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; + +/** + * + * @author Andrew + */ +public class Inicializador { + + public static void main(String[] args) throws IOException, Exception { + //Yylex lexer = new Yylex(new StringReader("2+9")); + Yylex lexer = new Yylex(Inicializador.class.getResourceAsStream("Exemplo.txt")); + /* + Symbol sym; + for (sym = lexer.next_token(); sym.sym != 0; sym = lexer.next_token()) { + System.out.println("Token " + sym.sym + ", with value = " + sym.value + "; at line " + sym.left + ", column " + sym.right); + } + */ + + + parser p = new parser(lexer); + p.parse(); + + } + +} diff --git a/Test/com/analizador/expressao/Yylex.java b/Test/com/analizador/expressao/Yylex.java new file mode 100644 index 0000000..31e671e --- /dev/null +++ b/Test/com/analizador/expressao/Yylex.java @@ -0,0 +1,678 @@ +/* The following code was generated by JFlex 1.5.1 */ + +//////////////////////////////////////////////////////////////////// +/* //// +* DECLARACAO DE EXPRESSOES EM PORTUGOL (ANALIZADOR LEXICO). //// +* BY: ANDREW NETO //// +* 20/06/2014 //// +*/ //// +//////////////////////////////////////////////////////////////////// + + +package com.analizador.expressao; + +import java_cup.runtime.*; + + + +/** + * This class is a scanner generated by + * JFlex 1.5.1 + * from the specification file C:/Users/SIMONETO-2/Documents/NetBeansProjects/portugol-projeto/Test/com/analizador/expressao/Expressao.flex + */ +class Yylex implements java_cup.runtime.Scanner { + + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int YYINITIAL = 0; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l + * at the beginning of a line + * l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { + 0, 0 + }; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = + "\11\0\1\4\1\6\1\21\1\21\1\5\22\0\1\4\1\0\1\10"+ + "\2\0\1\16\2\0\1\17\1\20\1\15\1\15\1\0\1\12\1\0"+ + "\1\15\12\2\1\13\1\0\1\11\1\14\3\0\32\1\1\0\1\7"+ + "\2\0\1\3\1\0\32\1\12\0\1\21\u1fa2\0\1\21\1\21\udfd6\0"; + + /** + * Translates characters to character classes + */ + private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int [] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = + "\1\0\1\1\1\2\1\3\2\4\2\1\1\5\1\1"+ + "\1\6\1\7\1\10\2\0\1\11\1\12\2\0\1\11"; + + private static int [] zzUnpackAction() { + int [] result = new int[20]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /** + * Translates a state to a row index in the transition table + */ + private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = + "\0\0\0\22\0\44\0\66\0\22\0\110\0\132\0\154"+ + "\0\22\0\176\0\22\0\22\0\22\0\132\0\220\0\22"+ + "\0\22\0\242\0\264\0\132"; + + private static int [] zzUnpackRowMap() { + int [] result = new int[20]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int [] ZZ_TRANS = zzUnpackTrans(); + + private static final String ZZ_TRANS_PACKED_0 = + "\1\2\1\3\1\4\1\2\1\5\1\6\1\5\1\2"+ + "\1\7\1\10\1\11\1\12\1\2\1\11\1\13\1\14"+ + "\1\15\24\0\3\3\20\0\1\4\25\0\1\5\13\0"+ + "\5\16\2\0\1\17\1\20\11\16\12\0\1\21\23\0"+ + "\1\21\5\0\4\16\1\22\2\23\1\17\1\24\15\16"+ + "\1\22\2\23\1\17\1\20\11\16\4\0\3\23\1\16"+ + "\12\0"; + + private static int [] zzUnpackTrans() { + int [] result = new int[198]; + int offset = 0; + offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackTrans(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + value--; + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", + "Error: could not match input", + "Error: pushback value was too large" + }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state aState + */ + private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = + "\1\0\1\11\2\1\1\11\3\1\1\11\1\1\3\11"+ + "\2\0\2\11\2\0\1\1"; + + private static int [] zzUnpackAttribute() { + int [] result = new int[20]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** this buffer contains the current text to be matched and is + the source of the yytext() string */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** endRead marks the last character in the buffer, that has been read + from input */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /** denotes if the user-EOF-code has already been executed */ + private boolean zzEOFDone; + + /* user code: */ + + Symbol newSym(int tokenId) { + return new Symbol(tokenId , yyline, yycolumn); + } + + Symbol newSym(int tokenId, Object value) { + return new Symbol(tokenId , yyline, yycolumn, value); + } + + + + /** + * Creates a new scanner + * There is also a java.io.InputStream version of this constructor. + * + * @param in the java.io.Reader to read input from. + */ + Yylex(java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. + * There is also java.io.Reader version of this constructor. + * + * @param in the java.io.Inputstream to read input from. + */ + Yylex(java.io.InputStream in) { + this(new java.io.InputStreamReader + (in, java.nio.charset.Charset.forName("UTF-8"))); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed the packed character translation table + * @return the unpacked character translation table + */ + private static char [] zzUnpackCMap(String packed) { + char [] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 80) { + int count = packed.charAt(i++); + char value = packed.charAt(i++); + do map[j++] = value; while (--count > 0); + } + return map; + } + + + /** + * Refills the input buffer. + * + * @return false, iff there was new input. + * + * @exception java.io.IOException if any I/O-Error occurs + */ + private boolean zzRefill() throws java.io.IOException { + + /* first: make room (if you can) */ + if (zzStartRead > 0) { + System.arraycopy(zzBuffer, zzStartRead, + zzBuffer, 0, + zzEndRead-zzStartRead); + + /* translate stored positions */ + zzEndRead-= zzStartRead; + zzCurrentPos-= zzStartRead; + zzMarkedPos-= zzStartRead; + zzStartRead = 0; + } + + /* is the buffer big enough? */ + if (zzCurrentPos >= zzBuffer.length) { + /* if not: blow it up */ + char newBuffer[] = new char[zzCurrentPos*2]; + System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); + zzBuffer = newBuffer; + } + + /* finally: fill the buffer with new input */ + int numRead = zzReader.read(zzBuffer, zzEndRead, + zzBuffer.length-zzEndRead); + + if (numRead > 0) { + zzEndRead+= numRead; + return false; + } + // unlikely but not impossible: read 0 characters, but not at end of stream + if (numRead == 0) { + int c = zzReader.read(); + if (c == -1) { + return true; + } else { + zzBuffer[zzEndRead++] = (char) c; + return false; + } + } + + // numRead < 0 + return true; + } + + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) + zzReader.close(); + } + + + /** + * Resets the scanner to read from a new input stream. + * Does not close the old reader. + * + * All internal variables are reset, the old input stream + * cannot be reused (internal buffer is discarded and lost). + * Lexical state is set to ZZ_INITIAL. + * + * Internal scan buffer is resized down to its initial length, if it has grown. + * + * @param reader the new input stream + */ + public final void yyreset(java.io.Reader reader) { + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + zzEOFDone = false; + zzEndRead = zzStartRead = 0; + zzCurrentPos = zzMarkedPos = 0; + yyline = yychar = yycolumn = 0; + zzLexicalState = YYINITIAL; + if (zzBuffer.length > ZZ_BUFFERSIZE) + zzBuffer = new char[ZZ_BUFFERSIZE]; + } + + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + + /** + * Enters a new lexical state + * + * @param newState the new lexical state + */ + public final void yybegin(int newState) { + zzLexicalState = newState; + } + + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); + } + + + /** + * Returns the character at position pos from the + * matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. + * A value from 0 to yylength()-1. + * + * @return the character at position pos + */ + public final char yycharat(int pos) { + return zzBuffer[zzStartRead+pos]; + } + + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos-zzStartRead; + } + + + /** + * Reports an error that occured while scanning. + * + * In a wellformed scanner (no or only correct usage of + * yypushback(int) and a match-all fallback rule) this method + * will only be called with things that "Can't Possibly Happen". + * If this method is called, something is seriously wrong + * (e.g. a JFlex bug producing a faulty scanner etc.). + * + * Usual syntax/scanner level error handling should be done + * in error fallback rules. + * + * @param errorCode the code of the errormessage to display + */ + private void zzScanError(int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } + catch (ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + + /** + * Pushes the specified amount of characters back into the input stream. + * + * They will be read again by then next call of the scanning method + * + * @param number the number of characters to be read again. + * This number must not be greater than yylength()! + */ + public void yypushback(int number) { + if ( number > yylength() ) + zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + + /** + * Contains user EOF-code, which will be executed exactly once, + * when the end of file is reached + */ + private void zzDoEOF() throws java.io.IOException { + if (!zzEOFDone) { + zzEOFDone = true; + yyclose(); + } + } + + + /** + * Resumes scanning until the next regular expression is matched, + * the end of input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException if any I/O-Error occurs + */ + public java_cup.runtime.Symbol next_token() throws java.io.IOException { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char [] zzBufferL = zzBuffer; + char [] zzCMapL = ZZ_CMAP; + + int [] zzTransL = ZZ_TRANS; + int [] zzRowMapL = ZZ_ROWMAP; + int [] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + boolean zzR = false; + for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL; + zzCurrentPosL++) { + switch (zzBufferL[zzCurrentPosL]) { + case '\u000B': + case '\u000C': + case '\u0085': + case '\u2028': + case '\u2029': + yyline++; + yycolumn = 0; + zzR = false; + break; + case '\r': + yyline++; + yycolumn = 0; + zzR = true; + break; + case '\n': + if (zzR) + zzR = false; + else { + yyline++; + yycolumn = 0; + } + break; + default: + zzR = false; + yycolumn++; + } + } + + if (zzR) { + // peek one character ahead if it is \n (if we have counted one line too much) + boolean zzPeek; + if (zzMarkedPosL < zzEndReadL) + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + else if (zzAtEOF) + zzPeek = false; + else { + boolean eof = zzRefill(); + zzEndReadL = zzEndRead; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + if (eof) + zzPeek = false; + else + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + } + if (zzPeek) yyline--; + } + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = ZZ_LEXSTATE[zzLexicalState]; + + // set up zzAction for empty match case: + int zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + } + + + zzForAction: { + while (true) { + + if (zzCurrentPosL < zzEndReadL) + zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } + else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } + else { + zzInput = zzBufferL[zzCurrentPosL++]; + } + } + int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; + if (zzNext == -1) break zzForAction; + zzState = zzNext; + + zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ( (zzAttributes & 8) == 8 ) break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 1: + { return newSym(sym.error,yytext()); + } + case 11: break; + case 2: + { return newSym(sym.ID,yytext()); + } + case 12: break; + case 3: + { return newSym(sym.NUMERO,(String) yytext()); + } + case 13: break; + case 4: + { /* IGNORAR */ + } + case 14: break; + case 5: + { return newSym(sym.OPERADOR,yytext()); + } + case 15: break; + case 6: + { return newSym(sym.OPERADOR,"%"); + } + case 16: break; + case 7: + { return newSym(sym.ABRIR_PARENTESE,yytext()); + } + case 17: break; + case 8: + { return newSym(sym.FECHAR_PARENTESE,yytext()); + } + case 18: break; + case 9: + { return newSym(sym.STRING, yytext().substring(1, yylength()-1)); + } + case 19: break; + case 10: + { return newSym(sym.ATRIBUIR,yytext()); + } + case 20: break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + zzDoEOF(); + { + return newSym(sym.EOF); + } + } + else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + + +} diff --git a/Test/com/analizador/expressao/Yylex.java~ b/Test/com/analizador/expressao/Yylex.java~ new file mode 100644 index 0000000..31e671e --- /dev/null +++ b/Test/com/analizador/expressao/Yylex.java~ @@ -0,0 +1,678 @@ +/* The following code was generated by JFlex 1.5.1 */ + +//////////////////////////////////////////////////////////////////// +/* //// +* DECLARACAO DE EXPRESSOES EM PORTUGOL (ANALIZADOR LEXICO). //// +* BY: ANDREW NETO //// +* 20/06/2014 //// +*/ //// +//////////////////////////////////////////////////////////////////// + + +package com.analizador.expressao; + +import java_cup.runtime.*; + + + +/** + * This class is a scanner generated by + * JFlex 1.5.1 + * from the specification file C:/Users/SIMONETO-2/Documents/NetBeansProjects/portugol-projeto/Test/com/analizador/expressao/Expressao.flex + */ +class Yylex implements java_cup.runtime.Scanner { + + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int YYINITIAL = 0; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l + * at the beginning of a line + * l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { + 0, 0 + }; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = + "\11\0\1\4\1\6\1\21\1\21\1\5\22\0\1\4\1\0\1\10"+ + "\2\0\1\16\2\0\1\17\1\20\1\15\1\15\1\0\1\12\1\0"+ + "\1\15\12\2\1\13\1\0\1\11\1\14\3\0\32\1\1\0\1\7"+ + "\2\0\1\3\1\0\32\1\12\0\1\21\u1fa2\0\1\21\1\21\udfd6\0"; + + /** + * Translates characters to character classes + */ + private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int [] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = + "\1\0\1\1\1\2\1\3\2\4\2\1\1\5\1\1"+ + "\1\6\1\7\1\10\2\0\1\11\1\12\2\0\1\11"; + + private static int [] zzUnpackAction() { + int [] result = new int[20]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /** + * Translates a state to a row index in the transition table + */ + private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = + "\0\0\0\22\0\44\0\66\0\22\0\110\0\132\0\154"+ + "\0\22\0\176\0\22\0\22\0\22\0\132\0\220\0\22"+ + "\0\22\0\242\0\264\0\132"; + + private static int [] zzUnpackRowMap() { + int [] result = new int[20]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int [] ZZ_TRANS = zzUnpackTrans(); + + private static final String ZZ_TRANS_PACKED_0 = + "\1\2\1\3\1\4\1\2\1\5\1\6\1\5\1\2"+ + "\1\7\1\10\1\11\1\12\1\2\1\11\1\13\1\14"+ + "\1\15\24\0\3\3\20\0\1\4\25\0\1\5\13\0"+ + "\5\16\2\0\1\17\1\20\11\16\12\0\1\21\23\0"+ + "\1\21\5\0\4\16\1\22\2\23\1\17\1\24\15\16"+ + "\1\22\2\23\1\17\1\20\11\16\4\0\3\23\1\16"+ + "\12\0"; + + private static int [] zzUnpackTrans() { + int [] result = new int[198]; + int offset = 0; + offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackTrans(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + value--; + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", + "Error: could not match input", + "Error: pushback value was too large" + }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state aState + */ + private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = + "\1\0\1\11\2\1\1\11\3\1\1\11\1\1\3\11"+ + "\2\0\2\11\2\0\1\1"; + + private static int [] zzUnpackAttribute() { + int [] result = new int[20]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** this buffer contains the current text to be matched and is + the source of the yytext() string */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** endRead marks the last character in the buffer, that has been read + from input */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /** denotes if the user-EOF-code has already been executed */ + private boolean zzEOFDone; + + /* user code: */ + + Symbol newSym(int tokenId) { + return new Symbol(tokenId , yyline, yycolumn); + } + + Symbol newSym(int tokenId, Object value) { + return new Symbol(tokenId , yyline, yycolumn, value); + } + + + + /** + * Creates a new scanner + * There is also a java.io.InputStream version of this constructor. + * + * @param in the java.io.Reader to read input from. + */ + Yylex(java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. + * There is also java.io.Reader version of this constructor. + * + * @param in the java.io.Inputstream to read input from. + */ + Yylex(java.io.InputStream in) { + this(new java.io.InputStreamReader + (in, java.nio.charset.Charset.forName("UTF-8"))); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed the packed character translation table + * @return the unpacked character translation table + */ + private static char [] zzUnpackCMap(String packed) { + char [] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 80) { + int count = packed.charAt(i++); + char value = packed.charAt(i++); + do map[j++] = value; while (--count > 0); + } + return map; + } + + + /** + * Refills the input buffer. + * + * @return false, iff there was new input. + * + * @exception java.io.IOException if any I/O-Error occurs + */ + private boolean zzRefill() throws java.io.IOException { + + /* first: make room (if you can) */ + if (zzStartRead > 0) { + System.arraycopy(zzBuffer, zzStartRead, + zzBuffer, 0, + zzEndRead-zzStartRead); + + /* translate stored positions */ + zzEndRead-= zzStartRead; + zzCurrentPos-= zzStartRead; + zzMarkedPos-= zzStartRead; + zzStartRead = 0; + } + + /* is the buffer big enough? */ + if (zzCurrentPos >= zzBuffer.length) { + /* if not: blow it up */ + char newBuffer[] = new char[zzCurrentPos*2]; + System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); + zzBuffer = newBuffer; + } + + /* finally: fill the buffer with new input */ + int numRead = zzReader.read(zzBuffer, zzEndRead, + zzBuffer.length-zzEndRead); + + if (numRead > 0) { + zzEndRead+= numRead; + return false; + } + // unlikely but not impossible: read 0 characters, but not at end of stream + if (numRead == 0) { + int c = zzReader.read(); + if (c == -1) { + return true; + } else { + zzBuffer[zzEndRead++] = (char) c; + return false; + } + } + + // numRead < 0 + return true; + } + + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) + zzReader.close(); + } + + + /** + * Resets the scanner to read from a new input stream. + * Does not close the old reader. + * + * All internal variables are reset, the old input stream + * cannot be reused (internal buffer is discarded and lost). + * Lexical state is set to ZZ_INITIAL. + * + * Internal scan buffer is resized down to its initial length, if it has grown. + * + * @param reader the new input stream + */ + public final void yyreset(java.io.Reader reader) { + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + zzEOFDone = false; + zzEndRead = zzStartRead = 0; + zzCurrentPos = zzMarkedPos = 0; + yyline = yychar = yycolumn = 0; + zzLexicalState = YYINITIAL; + if (zzBuffer.length > ZZ_BUFFERSIZE) + zzBuffer = new char[ZZ_BUFFERSIZE]; + } + + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + + /** + * Enters a new lexical state + * + * @param newState the new lexical state + */ + public final void yybegin(int newState) { + zzLexicalState = newState; + } + + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); + } + + + /** + * Returns the character at position pos from the + * matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. + * A value from 0 to yylength()-1. + * + * @return the character at position pos + */ + public final char yycharat(int pos) { + return zzBuffer[zzStartRead+pos]; + } + + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos-zzStartRead; + } + + + /** + * Reports an error that occured while scanning. + * + * In a wellformed scanner (no or only correct usage of + * yypushback(int) and a match-all fallback rule) this method + * will only be called with things that "Can't Possibly Happen". + * If this method is called, something is seriously wrong + * (e.g. a JFlex bug producing a faulty scanner etc.). + * + * Usual syntax/scanner level error handling should be done + * in error fallback rules. + * + * @param errorCode the code of the errormessage to display + */ + private void zzScanError(int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } + catch (ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + + /** + * Pushes the specified amount of characters back into the input stream. + * + * They will be read again by then next call of the scanning method + * + * @param number the number of characters to be read again. + * This number must not be greater than yylength()! + */ + public void yypushback(int number) { + if ( number > yylength() ) + zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + + /** + * Contains user EOF-code, which will be executed exactly once, + * when the end of file is reached + */ + private void zzDoEOF() throws java.io.IOException { + if (!zzEOFDone) { + zzEOFDone = true; + yyclose(); + } + } + + + /** + * Resumes scanning until the next regular expression is matched, + * the end of input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException if any I/O-Error occurs + */ + public java_cup.runtime.Symbol next_token() throws java.io.IOException { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char [] zzBufferL = zzBuffer; + char [] zzCMapL = ZZ_CMAP; + + int [] zzTransL = ZZ_TRANS; + int [] zzRowMapL = ZZ_ROWMAP; + int [] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + boolean zzR = false; + for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL; + zzCurrentPosL++) { + switch (zzBufferL[zzCurrentPosL]) { + case '\u000B': + case '\u000C': + case '\u0085': + case '\u2028': + case '\u2029': + yyline++; + yycolumn = 0; + zzR = false; + break; + case '\r': + yyline++; + yycolumn = 0; + zzR = true; + break; + case '\n': + if (zzR) + zzR = false; + else { + yyline++; + yycolumn = 0; + } + break; + default: + zzR = false; + yycolumn++; + } + } + + if (zzR) { + // peek one character ahead if it is \n (if we have counted one line too much) + boolean zzPeek; + if (zzMarkedPosL < zzEndReadL) + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + else if (zzAtEOF) + zzPeek = false; + else { + boolean eof = zzRefill(); + zzEndReadL = zzEndRead; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + if (eof) + zzPeek = false; + else + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + } + if (zzPeek) yyline--; + } + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = ZZ_LEXSTATE[zzLexicalState]; + + // set up zzAction for empty match case: + int zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + } + + + zzForAction: { + while (true) { + + if (zzCurrentPosL < zzEndReadL) + zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } + else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } + else { + zzInput = zzBufferL[zzCurrentPosL++]; + } + } + int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; + if (zzNext == -1) break zzForAction; + zzState = zzNext; + + zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ( (zzAttributes & 8) == 8 ) break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 1: + { return newSym(sym.error,yytext()); + } + case 11: break; + case 2: + { return newSym(sym.ID,yytext()); + } + case 12: break; + case 3: + { return newSym(sym.NUMERO,(String) yytext()); + } + case 13: break; + case 4: + { /* IGNORAR */ + } + case 14: break; + case 5: + { return newSym(sym.OPERADOR,yytext()); + } + case 15: break; + case 6: + { return newSym(sym.OPERADOR,"%"); + } + case 16: break; + case 7: + { return newSym(sym.ABRIR_PARENTESE,yytext()); + } + case 17: break; + case 8: + { return newSym(sym.FECHAR_PARENTESE,yytext()); + } + case 18: break; + case 9: + { return newSym(sym.STRING, yytext().substring(1, yylength()-1)); + } + case 19: break; + case 10: + { return newSym(sym.ATRIBUIR,yytext()); + } + case 20: break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + zzDoEOF(); + { + return newSym(sym.EOF); + } + } + else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + + +} diff --git a/Test/com/analizador/expressao/java_cup.jar b/Test/com/analizador/expressao/java_cup.jar new file mode 100644 index 0000000..73ffa0b Binary files /dev/null and b/Test/com/analizador/expressao/java_cup.jar differ diff --git a/Test/com/analizador/expressao/parser.java b/Test/com/analizador/expressao/parser.java new file mode 100644 index 0000000..0ad1ae7 --- /dev/null +++ b/Test/com/analizador/expressao/parser.java @@ -0,0 +1,269 @@ + +//---------------------------------------------------- +// The following code was generated by CUP v0.11a beta 20060608 +// Sat Jun 21 09:26:22 BRT 2014 +//---------------------------------------------------- + +package com.analizador.expressao; + +import java_cup.runtime.*; + +/** CUP v0.11a beta 20060608 generated parser. + * @version Sat Jun 21 09:26:22 BRT 2014 + */ +public class parser extends java_cup.runtime.lr_parser { + + /** Default constructor. */ + public parser() {super();} + + /** Constructor which sets the default scanner. */ + public parser(java_cup.runtime.Scanner s) {super(s);} + + /** Constructor which sets the default scanner. */ + public parser(java_cup.runtime.Scanner s, java_cup.runtime.SymbolFactory sf) {super(s,sf);} + + /** Production table. */ + protected static final short _production_table[][] = + unpackFromStrings(new String[] { + "\000\012\000\002\002\004\000\002\002\004\000\002\002" + + "\003\000\002\002\003\000\002\003\005\000\002\003\005" + + "\000\002\004\005\000\002\004\005\000\002\004\003\000" + + "\002\004\003" }); + + /** Access to production table. */ + public short[][] production_table() {return _production_table;} + + /** Parse-action table. */ + protected static final short[][] _action_table = + unpackFromStrings(new String[] { + "\000\021\000\006\003\006\011\004\001\002\000\004\004" + + "\012\001\002\000\006\002\011\011\004\001\002\000\006" + + "\002\ufffe\011\ufffe\001\002\000\006\002\uffff\011\uffff\001" + + "\002\000\006\002\001\011\001\001\002\000\004\002\000" + + "\001\002\000\012\006\016\010\014\011\013\012\015\001" + + "\002\000\012\002\ufff8\005\ufff8\007\ufff8\011\ufff8\001\002" + + "\000\012\002\ufff9\005\ufff9\007\ufff9\011\ufff9\001\002\000" + + "\006\002\ufffc\011\ufffc\001\002\000\010\006\016\010\014" + + "\011\013\001\002\000\010\002\ufffd\005\020\011\ufffd\001" + + "\002\000\010\006\016\010\014\011\013\001\002\000\012" + + "\002\ufffb\005\ufffb\007\ufffb\011\ufffb\001\002\000\006\005" + + "\020\007\023\001\002\000\012\002\ufffa\005\ufffa\007\ufffa" + + "\011\ufffa\001\002" }); + + /** Access to parse-action table. */ + public short[][] action_table() {return _action_table;} + + /** reduce_goto table. */ + protected static final short[][] _reduce_table = + unpackFromStrings(new String[] { + "\000\021\000\006\002\004\003\006\001\001\000\002\001" + + "\001\000\004\003\007\001\001\000\002\001\001\000\002" + + "\001\001\000\002\001\001\000\002\001\001\000\004\004" + + "\016\001\001\000\002\001\001\000\002\001\001\000\002" + + "\001\001\000\004\004\021\001\001\000\002\001\001\000" + + "\004\004\020\001\001\000\002\001\001\000\002\001\001" + + "\000\002\001\001" }); + + /** Access to reduce_goto table. */ + public short[][] reduce_table() {return _reduce_table;} + + /** Instance of action encapsulation class. */ + protected CUP$parser$actions action_obj; + + /** Action encapsulation object initializer. */ + protected void init_actions() + { + action_obj = new CUP$parser$actions(this); + } + + /** Invoke a user supplied parse action. */ + public java_cup.runtime.Symbol do_action( + int act_num, + java_cup.runtime.lr_parser parser, + java.util.Stack stack, + int top) + throws java.lang.Exception + { + /* call code in generated class */ + return action_obj.CUP$parser$do_action(act_num, parser, stack, top); + } + + /** Indicates start state. */ + public int start_state() {return 0;} + /** Indicates start production. */ + public int start_production() {return 1;} + + /** EOF Symbol index. */ + public int EOF_sym() {return 0;} + + /** error Symbol index. */ + public int error_sym() {return 1;} + + + + public static void main(String args[]) throws Exception{ + new parser(new Yylex(System.in)).parse(); + } + public void syntax_error(Symbol s){ + report_error("Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right)+". Trecho desconhecido: \""+s.value+"\"",null); + } + +} + +/** Cup generated class to encapsulate user supplied action code.*/ +class CUP$parser$actions { + private final parser parser; + + /** Constructor */ + CUP$parser$actions(parser parser) { + this.parser = parser; + } + + /** Method with the actual generated action code. */ + public final java_cup.runtime.Symbol CUP$parser$do_action( + int CUP$parser$act_num, + java_cup.runtime.lr_parser CUP$parser$parser, + java.util.Stack CUP$parser$stack, + int CUP$parser$top) + throws java.lang.Exception + { + /* Symbol object for return from actions */ + java_cup.runtime.Symbol CUP$parser$result; + + /* select the action based on the action number */ + switch (CUP$parser$act_num) + { + /*. . . . . . . . . . . . . . . . . . . .*/ + case 9: // valor ::= ID + { + String RESULT =null; + int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = n; + CUP$parser$result = parser.getSymbolFactory().newSymbol("valor",2, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 8: // valor ::= NUMERO + { + String RESULT =null; + int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = n; + CUP$parser$result = parser.getSymbolFactory().newSymbol("valor",2, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 7: // valor ::= ABRIR_PARENTESE valor FECHAR_PARENTESE + { + String RESULT =null; + int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + RESULT = "("+e+")"; + CUP$parser$result = parser.getSymbolFactory().newSymbol("valor",2, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 6: // valor ::= valor OPERADOR valor + { + String RESULT =null; + int e1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left; + int e1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right; + String e1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; + int opleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int opright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + Object op = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + int e2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int e2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String e2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = (String) e1+" "+op+" "+e2; + CUP$parser$result = parser.getSymbolFactory().newSymbol("valor",2, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 5: // instanciacao ::= ID ATRIBUIR STRING + { + Object RESULT =null; + int xleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left; + int xright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right; + String x = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; + int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + System.out.println(x+" = \""+e+"\""); + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao",1, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 4: // instanciacao ::= ID ATRIBUIR valor + { + Object RESULT =null; + int xleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left; + int xright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right; + String x = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; + int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + System.out.println(x+" = "+e); + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao",1, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 3: // gramatica ::= error + { + Object RESULT =null; + + CUP$parser$result = parser.getSymbolFactory().newSymbol("gramatica",0, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 2: // gramatica ::= instanciacao + { + Object RESULT =null; + + CUP$parser$result = parser.getSymbolFactory().newSymbol("gramatica",0, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 1: // $START ::= gramatica EOF + { + Object RESULT =null; + int start_valleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int start_valright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + Object start_val = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + RESULT = start_val; + CUP$parser$result = parser.getSymbolFactory().newSymbol("$START",0, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + /* ACCEPT */ + CUP$parser$parser.done_parsing(); + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 0: // gramatica ::= gramatica instanciacao + { + Object RESULT =null; + + CUP$parser$result = parser.getSymbolFactory().newSymbol("gramatica",0, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /* . . . . . .*/ + default: + throw new Exception( + "Invalid action number found in internal parse table"); + + } + } +} + diff --git a/Test/com/analizador/expressao/sym.java b/Test/com/analizador/expressao/sym.java new file mode 100644 index 0000000..c518b83 --- /dev/null +++ b/Test/com/analizador/expressao/sym.java @@ -0,0 +1,22 @@ + +//---------------------------------------------------- +// The following code was generated by CUP v0.11a beta 20060608 +// Sat Jun 21 09:26:22 BRT 2014 +//---------------------------------------------------- + +package com.analizador.expressao; + +/** CUP generated class containing symbol constants. */ +public class sym { + /* terminals */ + public static final int OPERADOR = 3; + public static final int ABRIR_PARENTESE = 4; + public static final int STRING = 8; + public static final int EOF = 0; + public static final int NUMERO = 6; + public static final int ID = 7; + public static final int error = 1; + public static final int FECHAR_PARENTESE = 5; + public static final int ATRIBUIR = 2; +} + diff --git a/Test/com/analizador/inicializacao/Exemplo.txt b/Test/com/analizador/inicializacao/Exemplo.txt new file mode 100644 index 0000000..e69de29 diff --git a/Test/com/analizador/inicializacao/Inicializador.java b/Test/com/analizador/inicializacao/Inicializador.java new file mode 100644 index 0000000..c652aea --- /dev/null +++ b/Test/com/analizador/inicializacao/Inicializador.java @@ -0,0 +1,26 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.analizador.inicializacao; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; + +/** + * + * @author Andrew + */ +public class Inicializador { + + + public static void main(String[] args) throws IOException, Exception { + //Yylex lexer = new Yylex(new StringReader("2+9")); + File f = new File("C:\\Users\\Andrew\\Documents\\NetBeansProjects\\portugol-projeto\\Test\\com\\analizador\\inicializacao\\Exemplo.txt"); + + + + } +} diff --git a/Test/com/analizador/separadorLoop/Exemplo.txt b/Test/com/analizador/separadorLoop/Exemplo.txt new file mode 100644 index 0000000..7f22d84 --- /dev/null +++ b/Test/com/analizador/separadorLoop/Exemplo.txt @@ -0,0 +1 @@ +escreva("massa menor: ",(massa_menor/100)*5,"\n","massa maior",massa_maior) \ No newline at end of file diff --git a/Test/com/analizador/separadorLoop/Inicializador.java b/Test/com/analizador/separadorLoop/Inicializador.java new file mode 100644 index 0000000..cd102c5 --- /dev/null +++ b/Test/com/analizador/separadorLoop/Inicializador.java @@ -0,0 +1,34 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.analizador.separadorLoop; + +import java.io.IOException; +import java_cup.runtime.Symbol; + +/** + * + * @author Andrew + */ +public class Inicializador { + + public static void main(String[] args) throws IOException, Exception { + Yylex lexer = new Yylex(Inicializador.class.getResourceAsStream("Exemplo.txt")); + + //Yylex lexer = new Yylex(new StringReader("teste1,teste2,teste3,testeN : caracter")); + /* + Symbol sym; + for (sym = lexer.next_token(); sym.sym != 0; sym = lexer.next_token()) { + System.out.println("Token " + sym.sym + ", with value = " + sym.value + "; at line " + sym.left + ", column " + sym.right); + } + */ + + + parser p = new parser(lexer); + p.parse(); + + } + +} diff --git a/Test/com/analizador/separadorLoop/Separador.cup b/Test/com/analizador/separadorLoop/Separador.cup new file mode 100644 index 0000000..87e999b --- /dev/null +++ b/Test/com/analizador/separadorLoop/Separador.cup @@ -0,0 +1,49 @@ +//////////////////////////////////////////////////////////////////////////////// +/* //// +* DECLARACAO DE FUNCAO COM LOOP EM PORTUGOL (ANALIZADOR E COMPILADOR). //// +* BY: ANDREW NETO //// +* 19/06/2014 //// +*/ //// +//////////////////////////////////////////////////////////////////////////////// +package com.analizador.separadorLoop; + +import java_cup.runtime.*; + +parser code +{: + public static void main(String args[]) throws Exception{ + new parser(new Yylex(System.in)).parse(); + } + public void syntax_error(Symbol s){ + report_error("Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right)+". Trecho desconhecido: \""+s.value+"\"",null); + } +:} + + +terminal ESCREVA; +terminal SEPARADOR,ABRIR_PARENTESE,FECHAR_PARENTESE, OPERADOR; +terminal String ID,STRING,NUMERO; + + + +non terminal gramatica,instanciacao; +non terminal String instanciacao_loop,valor; + +precedence left SEPARADOR,OPERADOR; +precedence left ABRIR_PARENTESE,FECHAR_PARENTESE; + + +gramatica ::= gramatica instanciacao | instanciacao | error {::}; + + +instanciacao ::= ESCREVA ABRIR_PARENTESE instanciacao_loop:e FECHAR_PARENTESE {: System.out.println("System.out.print("+e+");"); :}; + +instanciacao_loop ::= instanciacao_loop:e1 SEPARADOR instanciacao_loop:e2 {: RESULT = e1 + " + " + e2; :} | + valor:e {: RESULT = e; :} | + STRING:e {: RESULT = "\""+e+"\""; :}; + + +valor ::= valor:e1 OPERADOR:op valor:e2 {: RESULT = (String) e1+" "+op+" "+e2; :} | + ABRIR_PARENTESE valor:e FECHAR_PARENTESE {: RESULT = "("+e+")"; :} | + NUMERO:n {: RESULT = n; :} | + ID:n {: RESULT = n; :} ; \ No newline at end of file diff --git a/Test/com/analizador/separadorLoop/Separador.flex b/Test/com/analizador/separadorLoop/Separador.flex new file mode 100644 index 0000000..b0e6e1d --- /dev/null +++ b/Test/com/analizador/separadorLoop/Separador.flex @@ -0,0 +1,74 @@ +//////////////////////////////////////////////////////////////////// +/* //// +* DECLARACAO DE VARIAVEIS EM PORTUGOL (ANALIZADOR LEXICO). //// +* BY: ANDREW NETO //// +* 19/06/2014 //// +*/ //// +//////////////////////////////////////////////////////////////////// + +package com.analizador.separadorLoop; + +import java_cup.runtime.*; + + +%% +%cup +%line +%char +%column + +%{ + + Symbol newSym(int tokenId) { + return new Symbol(tokenId , yyline, yycolumn); + } + + Symbol newSym(int tokenId, Object value) { + return new Symbol(tokenId , yyline, yycolumn, value); + } + +%} + +caracters = [A-Za-z] +numerais = [0-9] +alphanumeric = {caracters}|{numerais} +outros = [_] +ids = {caracters}({alphanumeric}|{outros})* +espaco = [\n\r\ \t] +nova_linha = \r|\n|\r\n + +inteiro = {numerais}+ + +string_content = (\\\"|[^\n\r\"]|\\{espaco}+\\)* +string_literal = {double_qoute}{string_content}{double_qoute} +double_qoute = \" + + + +%% + +(escreva|ESCREVA) { return newSym(sym.ESCREVA,yytext());} + + +"," { return newSym(sym.SEPARADOR,yytext());} + + +"(" {return newSym(sym.ABRIR_PARENTESE);} +")" {return newSym(sym.FECHAR_PARENTESE);} + +"+" {return newSym(sym.OPERADOR,yytext());} +"-" {return newSym(sym.OPERADOR,yytext());} +"*" {return newSym(sym.OPERADOR,yytext());} +"/" {return newSym(sym.OPERADOR,yytext());} +"%" {return newSym(sym.OPERADOR,"%");} + +{inteiro} {return newSym(sym.NUMERO,yytext());} +{string_literal} { return newSym(sym.STRING,yytext().substring(1, yylength()-1)); } +{ids} { return newSym(sym.ID,yytext());} +{espaco} {/*IGNORAR*/} +{nova_linha} {/*IGNORAR*/} + + + +<> { return newSym(sym.EOF);} +. { return newSym(sym.error,yytext()); } \ No newline at end of file diff --git a/Test/com/analizador/separadorLoop/Yylex.java b/Test/com/analizador/separadorLoop/Yylex.java new file mode 100644 index 0000000..74548c7 --- /dev/null +++ b/Test/com/analizador/separadorLoop/Yylex.java @@ -0,0 +1,695 @@ +/* The following code was generated by JFlex 1.5.1 */ + +//////////////////////////////////////////////////////////////////// +/* //// +* DECLARACAO DE VARIAVEIS EM PORTUGOL (ANALIZADOR LEXICO). //// +* BY: ANDREW NETO //// +* 19/06/2014 //// +*/ //// +//////////////////////////////////////////////////////////////////// + +package com.analizador.separadorLoop; + +import java_cup.runtime.*; + + + +/** + * This class is a scanner generated by + * JFlex 1.5.1 + * from the specification file C:/Users/SIMONETO-2/Documents/NetBeansProjects/portugol-projeto/Test/com/analizador/separadorLoop/Separador.flex + */ +class Yylex implements java_cup.runtime.Scanner { + + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int YYINITIAL = 0; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l + * at the beginning of a line + * l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { + 0, 0 + }; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = + "\11\0\1\4\1\6\1\32\1\32\1\5\22\0\1\4\1\0\1\10"+ + "\2\0\1\31\2\0\1\26\1\27\1\30\1\30\1\25\1\30\1\0"+ + "\1\30\12\2\7\0\1\24\1\1\1\21\1\1\1\17\14\1\1\22"+ + "\1\20\2\1\1\23\4\1\1\0\1\7\2\0\1\3\1\0\1\16"+ + "\1\1\1\13\1\1\1\11\14\1\1\14\1\12\2\1\1\15\4\1"+ + "\12\0\1\32\u1fa2\0\1\32\1\32\udfd6\0"; + + /** + * Translates characters to character classes + */ + private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int [] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = + "\1\0\1\1\1\2\1\3\2\4\1\1\2\2\1\5"+ + "\1\6\1\7\1\10\1\11\2\0\1\12\2\2\2\0"+ + "\1\12\10\2\1\13"; + + private static int [] zzUnpackAction() { + int [] result = new int[31]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /** + * Translates a state to a row index in the transition table + */ + private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = + "\0\0\0\33\0\66\0\121\0\33\0\154\0\207\0\242"+ + "\0\275\0\33\0\33\0\33\0\33\0\33\0\207\0\330"+ + "\0\33\0\363\0\u010e\0\u0129\0\u0144\0\207\0\u015f\0\u017a"+ + "\0\u0195\0\u01b0\0\u01cb\0\u01e6\0\u0201\0\u021c\0\66"; + + private static int [] zzUnpackRowMap() { + int [] result = new int[31]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int [] ZZ_TRANS = zzUnpackTrans(); + + private static final String ZZ_TRANS_PACKED_0 = + "\1\2\1\3\1\4\1\2\1\5\1\6\1\5\1\2"+ + "\1\7\1\10\5\3\1\11\5\3\1\12\1\13\1\14"+ + "\1\15\1\16\35\0\3\3\5\0\14\3\10\0\1\4"+ + "\36\0\1\5\24\0\5\17\2\0\1\20\1\21\22\17"+ + "\1\0\3\3\5\0\1\3\1\22\12\3\7\0\3\3"+ + "\5\0\7\3\1\23\4\3\6\0\4\17\1\24\2\25"+ + "\1\20\1\26\22\17\1\0\3\3\5\0\2\3\1\27"+ + "\11\3\7\0\3\3\5\0\10\3\1\30\3\3\6\0"+ + "\4\17\1\24\2\25\1\20\1\21\22\17\4\0\3\25"+ + "\1\17\24\0\3\3\5\0\3\3\1\31\10\3\7\0"+ + "\3\3\5\0\11\3\1\32\2\3\7\0\3\3\5\0"+ + "\1\33\13\3\7\0\3\3\5\0\6\3\1\34\5\3"+ + "\7\0\3\3\5\0\4\3\1\35\7\3\7\0\3\3"+ + "\5\0\12\3\1\36\1\3\7\0\3\3\5\0\5\3"+ + "\1\37\6\3\7\0\3\3\5\0\13\3\1\37\6\0"; + + private static int [] zzUnpackTrans() { + int [] result = new int[567]; + int offset = 0; + offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackTrans(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + value--; + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", + "Error: could not match input", + "Error: pushback value was too large" + }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state aState + */ + private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = + "\1\0\1\11\2\1\1\11\4\1\5\11\2\0\1\11"+ + "\2\1\2\0\12\1"; + + private static int [] zzUnpackAttribute() { + int [] result = new int[31]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** this buffer contains the current text to be matched and is + the source of the yytext() string */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** endRead marks the last character in the buffer, that has been read + from input */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /** denotes if the user-EOF-code has already been executed */ + private boolean zzEOFDone; + + /* user code: */ + + Symbol newSym(int tokenId) { + return new Symbol(tokenId , yyline, yycolumn); + } + + Symbol newSym(int tokenId, Object value) { + return new Symbol(tokenId , yyline, yycolumn, value); + } + + + + /** + * Creates a new scanner + * There is also a java.io.InputStream version of this constructor. + * + * @param in the java.io.Reader to read input from. + */ + Yylex(java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. + * There is also java.io.Reader version of this constructor. + * + * @param in the java.io.Inputstream to read input from. + */ + Yylex(java.io.InputStream in) { + this(new java.io.InputStreamReader + (in, java.nio.charset.Charset.forName("UTF-8"))); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed the packed character translation table + * @return the unpacked character translation table + */ + private static char [] zzUnpackCMap(String packed) { + char [] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 112) { + int count = packed.charAt(i++); + char value = packed.charAt(i++); + do map[j++] = value; while (--count > 0); + } + return map; + } + + + /** + * Refills the input buffer. + * + * @return false, iff there was new input. + * + * @exception java.io.IOException if any I/O-Error occurs + */ + private boolean zzRefill() throws java.io.IOException { + + /* first: make room (if you can) */ + if (zzStartRead > 0) { + System.arraycopy(zzBuffer, zzStartRead, + zzBuffer, 0, + zzEndRead-zzStartRead); + + /* translate stored positions */ + zzEndRead-= zzStartRead; + zzCurrentPos-= zzStartRead; + zzMarkedPos-= zzStartRead; + zzStartRead = 0; + } + + /* is the buffer big enough? */ + if (zzCurrentPos >= zzBuffer.length) { + /* if not: blow it up */ + char newBuffer[] = new char[zzCurrentPos*2]; + System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); + zzBuffer = newBuffer; + } + + /* finally: fill the buffer with new input */ + int numRead = zzReader.read(zzBuffer, zzEndRead, + zzBuffer.length-zzEndRead); + + if (numRead > 0) { + zzEndRead+= numRead; + return false; + } + // unlikely but not impossible: read 0 characters, but not at end of stream + if (numRead == 0) { + int c = zzReader.read(); + if (c == -1) { + return true; + } else { + zzBuffer[zzEndRead++] = (char) c; + return false; + } + } + + // numRead < 0 + return true; + } + + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) + zzReader.close(); + } + + + /** + * Resets the scanner to read from a new input stream. + * Does not close the old reader. + * + * All internal variables are reset, the old input stream + * cannot be reused (internal buffer is discarded and lost). + * Lexical state is set to ZZ_INITIAL. + * + * Internal scan buffer is resized down to its initial length, if it has grown. + * + * @param reader the new input stream + */ + public final void yyreset(java.io.Reader reader) { + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + zzEOFDone = false; + zzEndRead = zzStartRead = 0; + zzCurrentPos = zzMarkedPos = 0; + yyline = yychar = yycolumn = 0; + zzLexicalState = YYINITIAL; + if (zzBuffer.length > ZZ_BUFFERSIZE) + zzBuffer = new char[ZZ_BUFFERSIZE]; + } + + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + + /** + * Enters a new lexical state + * + * @param newState the new lexical state + */ + public final void yybegin(int newState) { + zzLexicalState = newState; + } + + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); + } + + + /** + * Returns the character at position pos from the + * matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. + * A value from 0 to yylength()-1. + * + * @return the character at position pos + */ + public final char yycharat(int pos) { + return zzBuffer[zzStartRead+pos]; + } + + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos-zzStartRead; + } + + + /** + * Reports an error that occured while scanning. + * + * In a wellformed scanner (no or only correct usage of + * yypushback(int) and a match-all fallback rule) this method + * will only be called with things that "Can't Possibly Happen". + * If this method is called, something is seriously wrong + * (e.g. a JFlex bug producing a faulty scanner etc.). + * + * Usual syntax/scanner level error handling should be done + * in error fallback rules. + * + * @param errorCode the code of the errormessage to display + */ + private void zzScanError(int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } + catch (ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + + /** + * Pushes the specified amount of characters back into the input stream. + * + * They will be read again by then next call of the scanning method + * + * @param number the number of characters to be read again. + * This number must not be greater than yylength()! + */ + public void yypushback(int number) { + if ( number > yylength() ) + zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + + /** + * Contains user EOF-code, which will be executed exactly once, + * when the end of file is reached + */ + private void zzDoEOF() throws java.io.IOException { + if (!zzEOFDone) { + zzEOFDone = true; + yyclose(); + } + } + + + /** + * Resumes scanning until the next regular expression is matched, + * the end of input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException if any I/O-Error occurs + */ + public java_cup.runtime.Symbol next_token() throws java.io.IOException { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char [] zzBufferL = zzBuffer; + char [] zzCMapL = ZZ_CMAP; + + int [] zzTransL = ZZ_TRANS; + int [] zzRowMapL = ZZ_ROWMAP; + int [] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + yychar+= zzMarkedPosL-zzStartRead; + + boolean zzR = false; + for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL; + zzCurrentPosL++) { + switch (zzBufferL[zzCurrentPosL]) { + case '\u000B': + case '\u000C': + case '\u0085': + case '\u2028': + case '\u2029': + yyline++; + yycolumn = 0; + zzR = false; + break; + case '\r': + yyline++; + yycolumn = 0; + zzR = true; + break; + case '\n': + if (zzR) + zzR = false; + else { + yyline++; + yycolumn = 0; + } + break; + default: + zzR = false; + yycolumn++; + } + } + + if (zzR) { + // peek one character ahead if it is \n (if we have counted one line too much) + boolean zzPeek; + if (zzMarkedPosL < zzEndReadL) + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + else if (zzAtEOF) + zzPeek = false; + else { + boolean eof = zzRefill(); + zzEndReadL = zzEndRead; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + if (eof) + zzPeek = false; + else + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + } + if (zzPeek) yyline--; + } + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = ZZ_LEXSTATE[zzLexicalState]; + + // set up zzAction for empty match case: + int zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + } + + + zzForAction: { + while (true) { + + if (zzCurrentPosL < zzEndReadL) + zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } + else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } + else { + zzInput = zzBufferL[zzCurrentPosL++]; + } + } + int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; + if (zzNext == -1) break zzForAction; + zzState = zzNext; + + zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ( (zzAttributes & 8) == 8 ) break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 1: + { return newSym(sym.error,yytext()); + } + case 12: break; + case 2: + { return newSym(sym.ID,yytext()); + } + case 13: break; + case 3: + { return newSym(sym.NUMERO,yytext()); + } + case 14: break; + case 4: + { /*IGNORAR*/ + } + case 15: break; + case 5: + { return newSym(sym.SEPARADOR,yytext()); + } + case 16: break; + case 6: + { return newSym(sym.ABRIR_PARENTESE); + } + case 17: break; + case 7: + { return newSym(sym.FECHAR_PARENTESE); + } + case 18: break; + case 8: + { return newSym(sym.OPERADOR,yytext()); + } + case 19: break; + case 9: + { return newSym(sym.OPERADOR,"%"); + } + case 20: break; + case 10: + { return newSym(sym.STRING,yytext().substring(1, yylength()-1)); + } + case 21: break; + case 11: + { return newSym(sym.ESCREVA,yytext()); + } + case 22: break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + zzDoEOF(); + { + return newSym(sym.EOF); + } + } + else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + + +} diff --git a/Test/com/analizador/separadorLoop/Yylex.java~ b/Test/com/analizador/separadorLoop/Yylex.java~ new file mode 100644 index 0000000..3d1082d --- /dev/null +++ b/Test/com/analizador/separadorLoop/Yylex.java~ @@ -0,0 +1,695 @@ +/* The following code was generated by JFlex 1.5.1 */ + +//////////////////////////////////////////////////////////////////// +/* //// +* DECLARACAO DE VARIAVEIS EM PORTUGOL (ANALIZADOR LEXICO). //// +* BY: ANDREW NETO //// +* 19/06/2014 //// +*/ //// +//////////////////////////////////////////////////////////////////// + +package com.analizador.separadorLoop; + +import java_cup.runtime.*; + + + +/** + * This class is a scanner generated by + * JFlex 1.5.1 + * from the specification file C:/Users/SIMONETO-2/Documents/NetBeansProjects/portugol-projeto/Test/com/analizador/separadorLoop/Separador.flex + */ +class Yylex implements java_cup.runtime.Scanner { + + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int YYINITIAL = 0; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l + * at the beginning of a line + * l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { + 0, 0 + }; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = + "\11\0\1\4\1\6\1\32\1\32\1\5\22\0\1\4\1\0\1\10"+ + "\2\0\1\31\2\0\1\26\1\27\1\30\1\30\1\25\1\30\1\0"+ + "\1\30\12\2\7\0\1\24\1\1\1\21\1\1\1\17\14\1\1\22"+ + "\1\20\2\1\1\23\4\1\1\0\1\7\2\0\1\3\1\0\1\16"+ + "\1\1\1\13\1\1\1\11\14\1\1\14\1\12\2\1\1\15\4\1"+ + "\12\0\1\32\u1fa2\0\1\32\1\32\udfd6\0"; + + /** + * Translates characters to character classes + */ + private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int [] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = + "\1\0\1\1\1\2\1\3\2\4\1\1\2\2\1\5"+ + "\1\6\1\7\1\10\1\11\2\0\1\12\2\2\2\0"+ + "\1\12\10\2\1\13"; + + private static int [] zzUnpackAction() { + int [] result = new int[31]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /** + * Translates a state to a row index in the transition table + */ + private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = + "\0\0\0\33\0\66\0\121\0\33\0\154\0\207\0\242"+ + "\0\275\0\33\0\33\0\33\0\33\0\33\0\207\0\330"+ + "\0\33\0\363\0\u010e\0\u0129\0\u0144\0\207\0\u015f\0\u017a"+ + "\0\u0195\0\u01b0\0\u01cb\0\u01e6\0\u0201\0\u021c\0\66"; + + private static int [] zzUnpackRowMap() { + int [] result = new int[31]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int [] ZZ_TRANS = zzUnpackTrans(); + + private static final String ZZ_TRANS_PACKED_0 = + "\1\2\1\3\1\4\1\2\1\5\1\6\1\5\1\2"+ + "\1\7\1\10\5\3\1\11\5\3\1\12\1\13\1\14"+ + "\1\15\1\16\35\0\3\3\5\0\14\3\10\0\1\4"+ + "\36\0\1\5\24\0\5\17\2\0\1\20\1\21\22\17"+ + "\1\0\3\3\5\0\1\3\1\22\12\3\7\0\3\3"+ + "\5\0\7\3\1\23\4\3\6\0\4\17\1\24\2\25"+ + "\1\20\1\26\22\17\1\0\3\3\5\0\2\3\1\27"+ + "\11\3\7\0\3\3\5\0\10\3\1\30\3\3\6\0"+ + "\4\17\1\24\2\25\1\20\1\21\22\17\4\0\3\25"+ + "\1\17\24\0\3\3\5\0\3\3\1\31\10\3\7\0"+ + "\3\3\5\0\11\3\1\32\2\3\7\0\3\3\5\0"+ + "\1\33\13\3\7\0\3\3\5\0\6\3\1\34\5\3"+ + "\7\0\3\3\5\0\4\3\1\35\7\3\7\0\3\3"+ + "\5\0\12\3\1\36\1\3\7\0\3\3\5\0\5\3"+ + "\1\37\6\3\7\0\3\3\5\0\13\3\1\37\6\0"; + + private static int [] zzUnpackTrans() { + int [] result = new int[567]; + int offset = 0; + offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackTrans(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + value--; + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", + "Error: could not match input", + "Error: pushback value was too large" + }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state aState + */ + private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = + "\1\0\1\11\2\1\1\11\4\1\5\11\2\0\1\11"+ + "\2\1\2\0\12\1"; + + private static int [] zzUnpackAttribute() { + int [] result = new int[31]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** this buffer contains the current text to be matched and is + the source of the yytext() string */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** endRead marks the last character in the buffer, that has been read + from input */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /** denotes if the user-EOF-code has already been executed */ + private boolean zzEOFDone; + + /* user code: */ + + Symbol newSym(int tokenId) { + return new Symbol(tokenId , yyline, yycolumn); + } + + Symbol newSym(int tokenId, Object value) { + return new Symbol(tokenId , yyline, yycolumn, value); + } + + + + /** + * Creates a new scanner + * There is also a java.io.InputStream version of this constructor. + * + * @param in the java.io.Reader to read input from. + */ + Yylex(java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. + * There is also java.io.Reader version of this constructor. + * + * @param in the java.io.Inputstream to read input from. + */ + Yylex(java.io.InputStream in) { + this(new java.io.InputStreamReader + (in, java.nio.charset.Charset.forName("UTF-8"))); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed the packed character translation table + * @return the unpacked character translation table + */ + private static char [] zzUnpackCMap(String packed) { + char [] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 112) { + int count = packed.charAt(i++); + char value = packed.charAt(i++); + do map[j++] = value; while (--count > 0); + } + return map; + } + + + /** + * Refills the input buffer. + * + * @return false, iff there was new input. + * + * @exception java.io.IOException if any I/O-Error occurs + */ + private boolean zzRefill() throws java.io.IOException { + + /* first: make room (if you can) */ + if (zzStartRead > 0) { + System.arraycopy(zzBuffer, zzStartRead, + zzBuffer, 0, + zzEndRead-zzStartRead); + + /* translate stored positions */ + zzEndRead-= zzStartRead; + zzCurrentPos-= zzStartRead; + zzMarkedPos-= zzStartRead; + zzStartRead = 0; + } + + /* is the buffer big enough? */ + if (zzCurrentPos >= zzBuffer.length) { + /* if not: blow it up */ + char newBuffer[] = new char[zzCurrentPos*2]; + System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); + zzBuffer = newBuffer; + } + + /* finally: fill the buffer with new input */ + int numRead = zzReader.read(zzBuffer, zzEndRead, + zzBuffer.length-zzEndRead); + + if (numRead > 0) { + zzEndRead+= numRead; + return false; + } + // unlikely but not impossible: read 0 characters, but not at end of stream + if (numRead == 0) { + int c = zzReader.read(); + if (c == -1) { + return true; + } else { + zzBuffer[zzEndRead++] = (char) c; + return false; + } + } + + // numRead < 0 + return true; + } + + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) + zzReader.close(); + } + + + /** + * Resets the scanner to read from a new input stream. + * Does not close the old reader. + * + * All internal variables are reset, the old input stream + * cannot be reused (internal buffer is discarded and lost). + * Lexical state is set to ZZ_INITIAL. + * + * Internal scan buffer is resized down to its initial length, if it has grown. + * + * @param reader the new input stream + */ + public final void yyreset(java.io.Reader reader) { + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + zzEOFDone = false; + zzEndRead = zzStartRead = 0; + zzCurrentPos = zzMarkedPos = 0; + yyline = yychar = yycolumn = 0; + zzLexicalState = YYINITIAL; + if (zzBuffer.length > ZZ_BUFFERSIZE) + zzBuffer = new char[ZZ_BUFFERSIZE]; + } + + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + + /** + * Enters a new lexical state + * + * @param newState the new lexical state + */ + public final void yybegin(int newState) { + zzLexicalState = newState; + } + + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); + } + + + /** + * Returns the character at position pos from the + * matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. + * A value from 0 to yylength()-1. + * + * @return the character at position pos + */ + public final char yycharat(int pos) { + return zzBuffer[zzStartRead+pos]; + } + + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos-zzStartRead; + } + + + /** + * Reports an error that occured while scanning. + * + * In a wellformed scanner (no or only correct usage of + * yypushback(int) and a match-all fallback rule) this method + * will only be called with things that "Can't Possibly Happen". + * If this method is called, something is seriously wrong + * (e.g. a JFlex bug producing a faulty scanner etc.). + * + * Usual syntax/scanner level error handling should be done + * in error fallback rules. + * + * @param errorCode the code of the errormessage to display + */ + private void zzScanError(int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } + catch (ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + + /** + * Pushes the specified amount of characters back into the input stream. + * + * They will be read again by then next call of the scanning method + * + * @param number the number of characters to be read again. + * This number must not be greater than yylength()! + */ + public void yypushback(int number) { + if ( number > yylength() ) + zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + + /** + * Contains user EOF-code, which will be executed exactly once, + * when the end of file is reached + */ + private void zzDoEOF() throws java.io.IOException { + if (!zzEOFDone) { + zzEOFDone = true; + yyclose(); + } + } + + + /** + * Resumes scanning until the next regular expression is matched, + * the end of input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException if any I/O-Error occurs + */ + public java_cup.runtime.Symbol next_token() throws java.io.IOException { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char [] zzBufferL = zzBuffer; + char [] zzCMapL = ZZ_CMAP; + + int [] zzTransL = ZZ_TRANS; + int [] zzRowMapL = ZZ_ROWMAP; + int [] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + yychar+= zzMarkedPosL-zzStartRead; + + boolean zzR = false; + for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL; + zzCurrentPosL++) { + switch (zzBufferL[zzCurrentPosL]) { + case '\u000B': + case '\u000C': + case '\u0085': + case '\u2028': + case '\u2029': + yyline++; + yycolumn = 0; + zzR = false; + break; + case '\r': + yyline++; + yycolumn = 0; + zzR = true; + break; + case '\n': + if (zzR) + zzR = false; + else { + yyline++; + yycolumn = 0; + } + break; + default: + zzR = false; + yycolumn++; + } + } + + if (zzR) { + // peek one character ahead if it is \n (if we have counted one line too much) + boolean zzPeek; + if (zzMarkedPosL < zzEndReadL) + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + else if (zzAtEOF) + zzPeek = false; + else { + boolean eof = zzRefill(); + zzEndReadL = zzEndRead; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + if (eof) + zzPeek = false; + else + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + } + if (zzPeek) yyline--; + } + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = ZZ_LEXSTATE[zzLexicalState]; + + // set up zzAction for empty match case: + int zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + } + + + zzForAction: { + while (true) { + + if (zzCurrentPosL < zzEndReadL) + zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } + else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } + else { + zzInput = zzBufferL[zzCurrentPosL++]; + } + } + int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; + if (zzNext == -1) break zzForAction; + zzState = zzNext; + + zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ( (zzAttributes & 8) == 8 ) break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 1: + { return newSym(sym.error,yytext()); + } + case 12: break; + case 2: + { return newSym(sym.ID,(String) yytext()); + } + case 13: break; + case 3: + { return newSym(sym.NUMERO,(String) yytext()); + } + case 14: break; + case 4: + { /*IGNORAR*/ + } + case 15: break; + case 5: + { return newSym(sym.SEPARADOR,yytext()); + } + case 16: break; + case 6: + { return newSym(sym.ABRIR_PARENTESE); + } + case 17: break; + case 7: + { return newSym(sym.FECHAR_PARENTESE); + } + case 18: break; + case 8: + { return newSym(sym.OPERADOR,yytext()); + } + case 19: break; + case 9: + { return newSym(sym.OPERADOR,"%"); + } + case 20: break; + case 10: + { return newSym(sym.STRING, (String) yytext().substring(1, yylength()-1)); + } + case 21: break; + case 11: + { return newSym(sym.ESCREVA,yytext()); + } + case 22: break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + zzDoEOF(); + { + return newSym(sym.EOF); + } + } + else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + + +} diff --git a/Test/com/analizador/separadorLoop/java_cup.jar b/Test/com/analizador/separadorLoop/java_cup.jar new file mode 100644 index 0000000..73ffa0b Binary files /dev/null and b/Test/com/analizador/separadorLoop/java_cup.jar differ diff --git a/Test/com/analizador/separadorLoop/parser.java b/Test/com/analizador/separadorLoop/parser.java new file mode 100644 index 0000000..8254c1c --- /dev/null +++ b/Test/com/analizador/separadorLoop/parser.java @@ -0,0 +1,294 @@ + +//---------------------------------------------------- +// The following code was generated by CUP v0.11a beta 20060608 +// Thu Jun 26 11:55:25 BRT 2014 +//---------------------------------------------------- + +package com.analizador.separadorLoop; + +import java_cup.runtime.*; + +/** CUP v0.11a beta 20060608 generated parser. + * @version Thu Jun 26 11:55:25 BRT 2014 + */ +public class parser extends java_cup.runtime.lr_parser { + + /** Default constructor. */ + public parser() {super();} + + /** Constructor which sets the default scanner. */ + public parser(java_cup.runtime.Scanner s) {super(s);} + + /** Constructor which sets the default scanner. */ + public parser(java_cup.runtime.Scanner s, java_cup.runtime.SymbolFactory sf) {super(s,sf);} + + /** Production table. */ + protected static final short _production_table[][] = + unpackFromStrings(new String[] { + "\000\014\000\002\002\004\000\002\002\004\000\002\002" + + "\003\000\002\002\003\000\002\003\006\000\002\004\005" + + "\000\002\004\003\000\002\004\003\000\002\005\005\000" + + "\002\005\005\000\002\005\003\000\002\005\003" }); + + /** Access to production table. */ + public short[][] production_table() {return _production_table;} + + /** Parse-action table. */ + protected static final short[][] _action_table = + unpackFromStrings(new String[] { + "\000\025\000\006\003\006\004\004\001\002\000\004\006" + + "\012\001\002\000\006\002\011\004\004\001\002\000\006" + + "\002\ufffe\004\ufffe\001\002\000\006\002\uffff\004\uffff\001" + + "\002\000\006\002\001\004\001\001\002\000\004\002\000" + + "\001\002\000\012\006\016\011\013\012\015\013\014\001" + + "\002\000\010\005\ufff6\007\ufff6\010\ufff6\001\002\000\010" + + "\005\ufff7\007\ufff7\010\ufff7\001\002\000\006\005\ufffa\007" + + "\ufffa\001\002\000\010\006\016\011\013\013\014\001\002" + + "\000\010\005\ufffb\007\ufffb\010\024\001\002\000\006\005" + + "\021\007\022\001\002\000\012\006\016\011\013\012\015" + + "\013\014\001\002\000\006\002\ufffd\004\ufffd\001\002\000" + + "\006\005\ufffc\007\ufffc\001\002\000\010\006\016\011\013" + + "\013\014\001\002\000\010\005\ufff9\007\ufff9\010\ufff9\001" + + "\002\000\006\007\027\010\024\001\002\000\010\005\ufff8" + + "\007\ufff8\010\ufff8\001\002" }); + + /** Access to parse-action table. */ + public short[][] action_table() {return _action_table;} + + /** reduce_goto table. */ + protected static final short[][] _reduce_table = + unpackFromStrings(new String[] { + "\000\025\000\006\002\004\003\006\001\001\000\002\001" + + "\001\000\004\003\007\001\001\000\002\001\001\000\002" + + "\001\001\000\002\001\001\000\002\001\001\000\006\004" + + "\017\005\016\001\001\000\002\001\001\000\002\001\001" + + "\000\002\001\001\000\004\005\025\001\001\000\002\001" + + "\001\000\002\001\001\000\006\004\022\005\016\001\001" + + "\000\002\001\001\000\002\001\001\000\004\005\024\001" + + "\001\000\002\001\001\000\002\001\001\000\002\001\001" + + "" }); + + /** Access to reduce_goto table. */ + public short[][] reduce_table() {return _reduce_table;} + + /** Instance of action encapsulation class. */ + protected CUP$parser$actions action_obj; + + /** Action encapsulation object initializer. */ + protected void init_actions() + { + action_obj = new CUP$parser$actions(this); + } + + /** Invoke a user supplied parse action. */ + public java_cup.runtime.Symbol do_action( + int act_num, + java_cup.runtime.lr_parser parser, + java.util.Stack stack, + int top) + throws java.lang.Exception + { + /* call code in generated class */ + return action_obj.CUP$parser$do_action(act_num, parser, stack, top); + } + + /** Indicates start state. */ + public int start_state() {return 0;} + /** Indicates start production. */ + public int start_production() {return 1;} + + /** EOF Symbol index. */ + public int EOF_sym() {return 0;} + + /** error Symbol index. */ + public int error_sym() {return 1;} + + + + public static void main(String args[]) throws Exception{ + new parser(new Yylex(System.in)).parse(); + } + public void syntax_error(Symbol s){ + report_error("Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right)+". Trecho desconhecido: \""+s.value+"\"",null); + } + +} + +/** Cup generated class to encapsulate user supplied action code.*/ +class CUP$parser$actions { + private final parser parser; + + /** Constructor */ + CUP$parser$actions(parser parser) { + this.parser = parser; + } + + /** Method with the actual generated action code. */ + public final java_cup.runtime.Symbol CUP$parser$do_action( + int CUP$parser$act_num, + java_cup.runtime.lr_parser CUP$parser$parser, + java.util.Stack CUP$parser$stack, + int CUP$parser$top) + throws java.lang.Exception + { + /* Symbol object for return from actions */ + java_cup.runtime.Symbol CUP$parser$result; + + /* select the action based on the action number */ + switch (CUP$parser$act_num) + { + /*. . . . . . . . . . . . . . . . . . . .*/ + case 11: // valor ::= ID + { + String RESULT =null; + int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = n; + CUP$parser$result = parser.getSymbolFactory().newSymbol("valor",3, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 10: // valor ::= NUMERO + { + String RESULT =null; + int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = n; + CUP$parser$result = parser.getSymbolFactory().newSymbol("valor",3, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 9: // valor ::= ABRIR_PARENTESE valor FECHAR_PARENTESE + { + String RESULT =null; + int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + RESULT = "("+e+")"; + CUP$parser$result = parser.getSymbolFactory().newSymbol("valor",3, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 8: // valor ::= valor OPERADOR valor + { + String RESULT =null; + int e1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left; + int e1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right; + String e1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; + int opleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int opright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + Object op = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + int e2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int e2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String e2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = (String) e1+" "+op+" "+e2; + CUP$parser$result = parser.getSymbolFactory().newSymbol("valor",3, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 7: // instanciacao_loop ::= STRING + { + String RESULT =null; + int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = "\""+e+"\""; + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao_loop",2, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 6: // instanciacao_loop ::= valor + { + String RESULT =null; + int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = e; + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao_loop",2, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 5: // instanciacao_loop ::= instanciacao_loop SEPARADOR instanciacao_loop + { + String RESULT =null; + int e1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left; + int e1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right; + String e1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; + int e2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int e2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String e2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = e1 + " + " + e2; + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao_loop",2, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 4: // instanciacao ::= ESCREVA ABRIR_PARENTESE instanciacao_loop FECHAR_PARENTESE + { + Object RESULT =null; + int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + System.out.println("System.out.print("+e+");"); + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao",1, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 3: // gramatica ::= error + { + Object RESULT =null; + + CUP$parser$result = parser.getSymbolFactory().newSymbol("gramatica",0, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 2: // gramatica ::= instanciacao + { + Object RESULT =null; + + CUP$parser$result = parser.getSymbolFactory().newSymbol("gramatica",0, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 1: // $START ::= gramatica EOF + { + Object RESULT =null; + int start_valleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int start_valright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + Object start_val = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + RESULT = start_val; + CUP$parser$result = parser.getSymbolFactory().newSymbol("$START",0, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + /* ACCEPT */ + CUP$parser$parser.done_parsing(); + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 0: // gramatica ::= gramatica instanciacao + { + Object RESULT =null; + + CUP$parser$result = parser.getSymbolFactory().newSymbol("gramatica",0, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /* . . . . . .*/ + default: + throw new Exception( + "Invalid action number found in internal parse table"); + + } + } +} + diff --git a/Test/com/analizador/separadorLoop/sym.java b/Test/com/analizador/separadorLoop/sym.java new file mode 100644 index 0000000..4ff55de --- /dev/null +++ b/Test/com/analizador/separadorLoop/sym.java @@ -0,0 +1,23 @@ + +//---------------------------------------------------- +// The following code was generated by CUP v0.11a beta 20060608 +// Thu Jun 26 11:55:25 BRT 2014 +//---------------------------------------------------- + +package com.analizador.separadorLoop; + +/** CUP generated class containing symbol constants. */ +public class sym { + /* terminals */ + public static final int OPERADOR = 6; + public static final int ABRIR_PARENTESE = 4; + public static final int STRING = 8; + public static final int EOF = 0; + public static final int NUMERO = 9; + public static final int SEPARADOR = 3; + public static final int ID = 7; + public static final int error = 1; + public static final int FECHAR_PARENTESE = 5; + public static final int ESCREVA = 2; +} + diff --git a/Test/com/analizador/var/AnalizerP2.java b/Test/com/analizador/var/AnalizerP2.java new file mode 100644 index 0000000..e133038 --- /dev/null +++ b/Test/com/analizador/var/AnalizerP2.java @@ -0,0 +1,24 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package com.analizador.var; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; + +/** + * + * @author Andrew + */ +public class AnalizerP2 { + public AnalizerP2() throws FileNotFoundException, Exception{ + File f = new File("C:\\Users\\Andrew\\Documents\\NetBeansProjects\\portugol-projeto\\Test\\com\\analizador\\var\\Exemplo.txt"); + Yylex lexer = new Yylex(new FileInputStream(f)); + parser p = new parser(lexer); + p.parse(); + } +} diff --git a/Test/com/analizador/var/Exemplo.txt b/Test/com/analizador/var/Exemplo.txt new file mode 100644 index 0000000..ad01560 --- /dev/null +++ b/Test/com/analizador/var/Exemplo.txt @@ -0,0 +1,4 @@ +var + Nome,sobrenome : caracter + idade : inteiro + massa : real \ No newline at end of file diff --git a/Test/com/analizador/var/Inicializador.java b/Test/com/analizador/var/Inicializador.java new file mode 100644 index 0000000..e1d3805 --- /dev/null +++ b/Test/com/analizador/var/Inicializador.java @@ -0,0 +1,33 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.analizador.var; + +import java.io.IOException; + +/** + * + * @author Andrew + */ +public class Inicializador { + + public static void main(String[] args) throws IOException, Exception { + Yylex lexer = new Yylex(Inicializador.class.getResourceAsStream("Exemplo.txt")); + + //Yylex lexer = new Yylex(new StringReader("teste1,teste2,teste3,testeN : caracter")); + /* + Symbol sym; + for (sym = lexer.next_token(); sym.sym != 0; sym = lexer.next_token()) { + System.out.println("Token " + sym.sym + ", with value = " + sym.value + "; at line " + sym.left + ", column " + sym.right); + } + */ + + + parser p = new parser(lexer); + p.parse(); + + } + +} diff --git a/Test/com/analizador/var/Var.cup b/Test/com/analizador/var/Var.cup new file mode 100644 index 0000000..18039cb --- /dev/null +++ b/Test/com/analizador/var/Var.cup @@ -0,0 +1,41 @@ +//////////////////////////////////////////////////////////////////////// +/* //// +* DECLARACAO DE VARIAVEIS EM PORTUGOL (ANALIZADOR E COMPILADOR). //// +* BY: ANDREW NETO //// +* 19/06/2014 //// +*/ //// +//////////////////////////////////////////////////////////////////////// +package com.analizador.var; + +import java_cup.runtime.*; + +parser code +{: + public static void main(String args[]) throws Exception{ + new parser(new Yylex(System.in)).parse(); + } + public void syntax_error(Symbol s){ + report_error("Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right)+". Trecho desconhecido: \""+s.value+"\"",null); + } +:} + +terminal VAR; +terminal ID; +terminal TIPO_VARIAVEL, ADD_ATTR_VAR, SEPARADOR; + + +non terminal estrutura,variaveis, instanciacao; +non terminal String listagem; + + +/* ELIMINAR CONFLIO */ +precedence left SEPARADOR; + + +estrutura ::= VAR variaveis | error {: System.out.println("Detalhe: Erro de estruturacao. Exemplo de estruturacao.: var variavel1,variavel2 : tipo_de_variavel"); :}; + +variaveis ::= variaveis instanciacao | instanciacao | error {: :}; + +instanciacao ::= listagem:e ADD_ATTR_VAR TIPO_VARIAVEL:x {: System.out.println(x+" "+ e +";"); :} ; + +listagem ::= listagem:e1 SEPARADOR listagem:e2 {: RESULT = (String) e1+","+e2; :} | ID:value /* PARA ATRIBUIR O VALOR DO ID EM LISTAGEM */ {: RESULT = (String) value; :}; \ No newline at end of file diff --git a/Test/com/analizador/var/Var.flex b/Test/com/analizador/var/Var.flex new file mode 100644 index 0000000..bac016d --- /dev/null +++ b/Test/com/analizador/var/Var.flex @@ -0,0 +1,57 @@ +//////////////////////////////////////////////////////////////////// +/* //// +* DECLARACAO DE VARIAVEIS EM PORTUGOL (ANALIZADOR LEXICO). //// +* BY: ANDREW NETO //// +* 19/06/2014 //// +*/ //// +//////////////////////////////////////////////////////////////////// + +package com.analizador.var; + +import java_cup.runtime.*; + + +%% +%cup +%line +%char +%column + +%{ + + Symbol newSym(int tokenId) { + return new Symbol(tokenId , yyline, yycolumn); + } + + Symbol newSym(int tokenId, Object value) { + return new Symbol(tokenId , yyline, yycolumn, value); + } + +%} + +caracters = [A-Za-z] +numerais = [0-9] +alphanumeric = {caracters}|{numerais} +outros = [_] +ids = {caracters}({alphanumeric}|{outros})* +espaco = [\n\r\ \t] +nova_linha = \r|\n|\r\n + + +%% + +(var|VAR) { return newSym(sym.VAR,yytext());} + +(inteiro|INTEIRO) { return newSym(sym.TIPO_VARIAVEL,"int");} +(real|REAL) { return newSym(sym.TIPO_VARIAVEL,"float");} +(caracter|CARACTER) { return newSym(sym.TIPO_VARIAVEL,"String");} + +":" { return newSym(sym.ADD_ATTR_VAR,yytext());} +"," { return newSym(sym.SEPARADOR,yytext());} + +{ids} { return newSym(sym.ID,(String) yytext());} +{espaco} {/*IGNORAR*/} +{nova_linha} {/*IGNORAR*/} + +<> { return newSym(sym.EOF);} +. { return newSym(sym.error,yytext()); } \ No newline at end of file diff --git a/Test/com/analizador/var/Yylex.java b/Test/com/analizador/var/Yylex.java new file mode 100644 index 0000000..14eec74 --- /dev/null +++ b/Test/com/analizador/var/Yylex.java @@ -0,0 +1,704 @@ +/* The following code was generated by JFlex 1.5.1 */ + +//////////////////////////////////////////////////////////////////// +/* //// +* DECLARACAO DE VARIAVEIS EM PORTUGOL (ANALIZADOR LEXICO). //// +* BY: ANDREW NETO //// +* 19/06/2014 //// +*/ //// +//////////////////////////////////////////////////////////////////// + +package com.analizador.var; + +import java_cup.runtime.*; + + + +/** + * This class is a scanner generated by + * JFlex 1.5.1 + * from the specification file C:/Users/Andrew/Documents/NetBeansProjects/portugol-projeto/Test/com/anailizador/var/var.flex + */ +class Yylex implements java_cup.runtime.Scanner { + + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int YYINITIAL = 0; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l + * at the beginning of a line + * l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { + 0, 0 + }; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = + "\11\0\1\3\1\5\1\34\1\34\1\4\22\0\1\3\13\0\1\33"+ + "\3\0\12\2\1\32\6\0\1\12\1\1\1\31\1\1\1\24\3\1"+ + "\1\21\2\1\1\27\1\1\1\22\1\25\2\1\1\13\1\1\1\23"+ + "\1\1\1\11\4\1\4\0\1\2\1\0\1\7\1\1\1\30\1\1"+ + "\1\17\3\1\1\14\2\1\1\26\1\1\1\15\1\20\2\1\1\10"+ + "\1\1\1\16\1\1\1\6\4\1\12\0\1\34\u1fa2\0\1\34\1\34"+ + "\udfd6\0"; + + /** + * Translates characters to character classes + */ + private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int [] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = + "\1\0\1\1\1\2\2\3\10\2\1\4\1\5\10\2"+ + "\1\6\6\2\1\7\14\2\1\10\2\2\1\11"; + + private static int [] zzUnpackAction() { + int [] result = new int[47]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /** + * Translates a state to a row index in the transition table + */ + private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = + "\0\0\0\35\0\72\0\35\0\127\0\164\0\221\0\256"+ + "\0\313\0\350\0\u0105\0\u0122\0\u013f\0\35\0\35\0\u015c"+ + "\0\u0179\0\u0196\0\u01b3\0\u01d0\0\u01ed\0\u020a\0\u0227\0\72"+ + "\0\u0244\0\u0261\0\u027e\0\u029b\0\u02b8\0\u02d5\0\72\0\u02f2"+ + "\0\u030f\0\u032c\0\u0349\0\u0366\0\u0383\0\u03a0\0\u03bd\0\u03da"+ + "\0\u03f7\0\u0414\0\u0431\0\72\0\u044e\0\u046b\0\72"; + + private static int [] zzUnpackRowMap() { + int [] result = new int[47]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int [] ZZ_TRANS = zzUnpackTrans(); + + private static final String ZZ_TRANS_PACKED_0 = + "\1\2\1\3\1\2\1\4\1\5\1\4\1\6\1\3"+ + "\1\7\1\10\1\3\1\11\1\12\4\3\1\13\6\3"+ + "\1\14\1\15\1\16\1\17\37\0\2\3\3\0\24\3"+ + "\10\0\1\4\30\0\2\3\3\0\1\3\1\20\22\3"+ + "\4\0\2\3\3\0\11\3\1\21\12\3\4\0\2\3"+ + "\3\0\4\3\1\22\17\3\4\0\2\3\3\0\16\3"+ + "\1\23\5\3\4\0\2\3\3\0\7\3\1\24\14\3"+ + "\4\0\2\3\3\0\14\3\1\25\7\3\4\0\2\3"+ + "\3\0\1\3\1\26\22\3\4\0\2\3\3\0\4\3"+ + "\1\27\17\3\4\0\2\3\3\0\2\3\1\30\21\3"+ + "\4\0\2\3\3\0\1\3\1\31\22\3\4\0\2\3"+ + "\3\0\5\3\1\30\16\3\4\0\2\3\3\0\4\3"+ + "\1\32\17\3\4\0\2\3\3\0\10\3\1\33\13\3"+ + "\4\0\2\3\3\0\15\3\1\34\6\3\4\0\2\3"+ + "\3\0\2\3\1\35\21\3\4\0\2\3\3\0\5\3"+ + "\1\36\16\3\4\0\2\3\3\0\20\3\1\37\3\3"+ + "\4\0\2\3\3\0\21\3\1\37\2\3\4\0\2\3"+ + "\3\0\11\3\1\40\12\3\4\0\2\3\3\0\16\3"+ + "\1\41\5\3\4\0\2\3\3\0\1\3\1\42\22\3"+ + "\4\0\2\3\3\0\4\3\1\43\17\3\4\0\2\3"+ + "\3\0\6\3\1\44\15\3\4\0\2\3\3\0\13\3"+ + "\1\45\10\3\4\0\2\3\3\0\22\3\1\46\1\3"+ + "\4\0\2\3\3\0\23\3\1\47\4\0\2\3\3\0"+ + "\2\3\1\50\21\3\4\0\2\3\3\0\5\3\1\51"+ + "\16\3\4\0\2\3\3\0\10\3\1\52\13\3\4\0"+ + "\2\3\3\0\15\3\1\53\6\3\4\0\2\3\3\0"+ + "\12\3\1\54\11\3\4\0\2\3\3\0\17\3\1\54"+ + "\4\3\4\0\2\3\3\0\11\3\1\55\12\3\4\0"+ + "\2\3\3\0\16\3\1\56\5\3\4\0\2\3\3\0"+ + "\2\3\1\57\21\3\4\0\2\3\3\0\5\3\1\57"+ + "\16\3\3\0"; + + private static int [] zzUnpackTrans() { + int [] result = new int[1160]; + int offset = 0; + offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackTrans(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + value--; + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", + "Error: could not match input", + "Error: pushback value was too large" + }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state aState + */ + private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = + "\1\0\1\11\1\1\1\11\11\1\2\11\40\1"; + + private static int [] zzUnpackAttribute() { + int [] result = new int[47]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** this buffer contains the current text to be matched and is + the source of the yytext() string */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** endRead marks the last character in the buffer, that has been read + from input */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /** denotes if the user-EOF-code has already been executed */ + private boolean zzEOFDone; + + /* user code: */ + + Symbol newSym(int tokenId) { + return new Symbol(tokenId , yyline, yycolumn); + } + + Symbol newSym(int tokenId, Object value) { + return new Symbol(tokenId , yyline, yycolumn, value); + } + + + + /** + * Creates a new scanner + * There is also a java.io.InputStream version of this constructor. + * + * @param in the java.io.Reader to read input from. + */ + Yylex(java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. + * There is also java.io.Reader version of this constructor. + * + * @param in the java.io.Inputstream to read input from. + */ + Yylex(java.io.InputStream in) { + this(new java.io.InputStreamReader + (in, java.nio.charset.Charset.forName("UTF-8"))); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed the packed character translation table + * @return the unpacked character translation table + */ + private static char [] zzUnpackCMap(String packed) { + char [] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 122) { + int count = packed.charAt(i++); + char value = packed.charAt(i++); + do map[j++] = value; while (--count > 0); + } + return map; + } + + + /** + * Refills the input buffer. + * + * @return false, iff there was new input. + * + * @exception java.io.IOException if any I/O-Error occurs + */ + private boolean zzRefill() throws java.io.IOException { + + /* first: make room (if you can) */ + if (zzStartRead > 0) { + System.arraycopy(zzBuffer, zzStartRead, + zzBuffer, 0, + zzEndRead-zzStartRead); + + /* translate stored positions */ + zzEndRead-= zzStartRead; + zzCurrentPos-= zzStartRead; + zzMarkedPos-= zzStartRead; + zzStartRead = 0; + } + + /* is the buffer big enough? */ + if (zzCurrentPos >= zzBuffer.length) { + /* if not: blow it up */ + char newBuffer[] = new char[zzCurrentPos*2]; + System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); + zzBuffer = newBuffer; + } + + /* finally: fill the buffer with new input */ + int numRead = zzReader.read(zzBuffer, zzEndRead, + zzBuffer.length-zzEndRead); + + if (numRead > 0) { + zzEndRead+= numRead; + return false; + } + // unlikely but not impossible: read 0 characters, but not at end of stream + if (numRead == 0) { + int c = zzReader.read(); + if (c == -1) { + return true; + } else { + zzBuffer[zzEndRead++] = (char) c; + return false; + } + } + + // numRead < 0 + return true; + } + + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) + zzReader.close(); + } + + + /** + * Resets the scanner to read from a new input stream. + * Does not close the old reader. + * + * All internal variables are reset, the old input stream + * cannot be reused (internal buffer is discarded and lost). + * Lexical state is set to ZZ_INITIAL. + * + * Internal scan buffer is resized down to its initial length, if it has grown. + * + * @param reader the new input stream + */ + public final void yyreset(java.io.Reader reader) { + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + zzEOFDone = false; + zzEndRead = zzStartRead = 0; + zzCurrentPos = zzMarkedPos = 0; + yyline = yychar = yycolumn = 0; + zzLexicalState = YYINITIAL; + if (zzBuffer.length > ZZ_BUFFERSIZE) + zzBuffer = new char[ZZ_BUFFERSIZE]; + } + + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + + /** + * Enters a new lexical state + * + * @param newState the new lexical state + */ + public final void yybegin(int newState) { + zzLexicalState = newState; + } + + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); + } + + + /** + * Returns the character at position pos from the + * matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. + * A value from 0 to yylength()-1. + * + * @return the character at position pos + */ + public final char yycharat(int pos) { + return zzBuffer[zzStartRead+pos]; + } + + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos-zzStartRead; + } + + + /** + * Reports an error that occured while scanning. + * + * In a wellformed scanner (no or only correct usage of + * yypushback(int) and a match-all fallback rule) this method + * will only be called with things that "Can't Possibly Happen". + * If this method is called, something is seriously wrong + * (e.g. a JFlex bug producing a faulty scanner etc.). + * + * Usual syntax/scanner level error handling should be done + * in error fallback rules. + * + * @param errorCode the code of the errormessage to display + */ + private void zzScanError(int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } + catch (ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + + /** + * Pushes the specified amount of characters back into the input stream. + * + * They will be read again by then next call of the scanning method + * + * @param number the number of characters to be read again. + * This number must not be greater than yylength()! + */ + public void yypushback(int number) { + if ( number > yylength() ) + zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + + /** + * Contains user EOF-code, which will be executed exactly once, + * when the end of file is reached + */ + private void zzDoEOF() throws java.io.IOException { + if (!zzEOFDone) { + zzEOFDone = true; + yyclose(); + } + } + + + /** + * Resumes scanning until the next regular expression is matched, + * the end of input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException if any I/O-Error occurs + */ + public java_cup.runtime.Symbol next_token() throws java.io.IOException { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char [] zzBufferL = zzBuffer; + char [] zzCMapL = ZZ_CMAP; + + int [] zzTransL = ZZ_TRANS; + int [] zzRowMapL = ZZ_ROWMAP; + int [] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + yychar+= zzMarkedPosL-zzStartRead; + + boolean zzR = false; + for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL; + zzCurrentPosL++) { + switch (zzBufferL[zzCurrentPosL]) { + case '\u000B': + case '\u000C': + case '\u0085': + case '\u2028': + case '\u2029': + yyline++; + yycolumn = 0; + zzR = false; + break; + case '\r': + yyline++; + yycolumn = 0; + zzR = true; + break; + case '\n': + if (zzR) + zzR = false; + else { + yyline++; + yycolumn = 0; + } + break; + default: + zzR = false; + yycolumn++; + } + } + + if (zzR) { + // peek one character ahead if it is \n (if we have counted one line too much) + boolean zzPeek; + if (zzMarkedPosL < zzEndReadL) + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + else if (zzAtEOF) + zzPeek = false; + else { + boolean eof = zzRefill(); + zzEndReadL = zzEndRead; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + if (eof) + zzPeek = false; + else + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + } + if (zzPeek) yyline--; + } + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = ZZ_LEXSTATE[zzLexicalState]; + + // set up zzAction for empty match case: + int zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + } + + + zzForAction: { + while (true) { + + if (zzCurrentPosL < zzEndReadL) + zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } + else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } + else { + zzInput = zzBufferL[zzCurrentPosL++]; + } + } + int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; + if (zzNext == -1) break zzForAction; + zzState = zzNext; + + zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ( (zzAttributes & 8) == 8 ) break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 1: + { System.out.println("Illegal char, '" + yytext() +"' line: " + yyline + ", column: " + yychar); + } + case 10: break; + case 2: + { return newSym(sym.ID,(String) yytext()); + } + case 11: break; + case 3: + { /*IGNORAR*/ + } + case 12: break; + case 4: + { return newSym(sym.ADD_ATTR_VAR,yytext()); + } + case 13: break; + case 5: + { return newSym(sym.SEPARADOR,yytext()); + } + case 14: break; + case 6: + { return newSym(sym.VAR,yytext()); + } + case 15: break; + case 7: + { return newSym(sym.TIPO_VARIAVEL,"float"); + } + case 16: break; + case 8: + { return newSym(sym.TIPO_VARIAVEL,"int"); + } + case 17: break; + case 9: + { return newSym(sym.TIPO_VARIAVEL,"String"); + } + case 18: break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + zzDoEOF(); + { + return newSym(sym.EOF); + } + } + else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + + +} diff --git a/Test/com/analizador/var/Yylex.java~ b/Test/com/analizador/var/Yylex.java~ new file mode 100644 index 0000000..f571a73 --- /dev/null +++ b/Test/com/analizador/var/Yylex.java~ @@ -0,0 +1,696 @@ +/* The following code was generated by JFlex 1.5.1 */ + +package com.anailizador.var; + +import java_cup.runtime.*; + + + +/** + * This class is a scanner generated by + * JFlex 1.5.1 + * from the specification file C:/Users/Andrew/Documents/NetBeansProjects/portugol-projeto/Test/com/anailizador/var/var.flex + */ +class Yylex implements java_cup.runtime.Scanner { + + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int YYINITIAL = 0; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l + * at the beginning of a line + * l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { + 0, 0 + }; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = + "\11\0\1\3\1\5\1\34\1\34\1\4\22\0\1\3\13\0\1\33"+ + "\3\0\12\2\1\32\6\0\1\12\1\1\1\31\1\1\1\24\3\1"+ + "\1\21\2\1\1\27\1\1\1\22\1\25\2\1\1\13\1\1\1\23"+ + "\1\1\1\11\4\1\4\0\1\2\1\0\1\7\1\1\1\30\1\1"+ + "\1\17\3\1\1\14\2\1\1\26\1\1\1\15\1\20\2\1\1\10"+ + "\1\1\1\16\1\1\1\6\4\1\12\0\1\34\u1fa2\0\1\34\1\34"+ + "\udfd6\0"; + + /** + * Translates characters to character classes + */ + private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int [] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = + "\1\0\1\1\1\2\2\3\10\2\1\4\1\5\10\2"+ + "\1\6\6\2\1\7\14\2\1\10\2\2\1\11"; + + private static int [] zzUnpackAction() { + int [] result = new int[47]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /** + * Translates a state to a row index in the transition table + */ + private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = + "\0\0\0\35\0\72\0\35\0\127\0\164\0\221\0\256"+ + "\0\313\0\350\0\u0105\0\u0122\0\u013f\0\35\0\35\0\u015c"+ + "\0\u0179\0\u0196\0\u01b3\0\u01d0\0\u01ed\0\u020a\0\u0227\0\72"+ + "\0\u0244\0\u0261\0\u027e\0\u029b\0\u02b8\0\u02d5\0\72\0\u02f2"+ + "\0\u030f\0\u032c\0\u0349\0\u0366\0\u0383\0\u03a0\0\u03bd\0\u03da"+ + "\0\u03f7\0\u0414\0\u0431\0\72\0\u044e\0\u046b\0\72"; + + private static int [] zzUnpackRowMap() { + int [] result = new int[47]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int [] ZZ_TRANS = zzUnpackTrans(); + + private static final String ZZ_TRANS_PACKED_0 = + "\1\2\1\3\1\2\1\4\1\5\1\4\1\6\1\3"+ + "\1\7\1\10\1\3\1\11\1\12\4\3\1\13\6\3"+ + "\1\14\1\15\1\16\1\17\37\0\2\3\3\0\24\3"+ + "\10\0\1\4\30\0\2\3\3\0\1\3\1\20\22\3"+ + "\4\0\2\3\3\0\11\3\1\21\12\3\4\0\2\3"+ + "\3\0\4\3\1\22\17\3\4\0\2\3\3\0\16\3"+ + "\1\23\5\3\4\0\2\3\3\0\7\3\1\24\14\3"+ + "\4\0\2\3\3\0\14\3\1\25\7\3\4\0\2\3"+ + "\3\0\1\3\1\26\22\3\4\0\2\3\3\0\4\3"+ + "\1\27\17\3\4\0\2\3\3\0\2\3\1\30\21\3"+ + "\4\0\2\3\3\0\1\3\1\31\22\3\4\0\2\3"+ + "\3\0\5\3\1\30\16\3\4\0\2\3\3\0\4\3"+ + "\1\32\17\3\4\0\2\3\3\0\10\3\1\33\13\3"+ + "\4\0\2\3\3\0\15\3\1\34\6\3\4\0\2\3"+ + "\3\0\2\3\1\35\21\3\4\0\2\3\3\0\5\3"+ + "\1\36\16\3\4\0\2\3\3\0\20\3\1\37\3\3"+ + "\4\0\2\3\3\0\21\3\1\37\2\3\4\0\2\3"+ + "\3\0\11\3\1\40\12\3\4\0\2\3\3\0\16\3"+ + "\1\41\5\3\4\0\2\3\3\0\1\3\1\42\22\3"+ + "\4\0\2\3\3\0\4\3\1\43\17\3\4\0\2\3"+ + "\3\0\6\3\1\44\15\3\4\0\2\3\3\0\13\3"+ + "\1\45\10\3\4\0\2\3\3\0\22\3\1\46\1\3"+ + "\4\0\2\3\3\0\23\3\1\47\4\0\2\3\3\0"+ + "\2\3\1\50\21\3\4\0\2\3\3\0\5\3\1\51"+ + "\16\3\4\0\2\3\3\0\10\3\1\52\13\3\4\0"+ + "\2\3\3\0\15\3\1\53\6\3\4\0\2\3\3\0"+ + "\12\3\1\54\11\3\4\0\2\3\3\0\17\3\1\54"+ + "\4\3\4\0\2\3\3\0\11\3\1\55\12\3\4\0"+ + "\2\3\3\0\16\3\1\56\5\3\4\0\2\3\3\0"+ + "\2\3\1\57\21\3\4\0\2\3\3\0\5\3\1\57"+ + "\16\3\3\0"; + + private static int [] zzUnpackTrans() { + int [] result = new int[1160]; + int offset = 0; + offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackTrans(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + value--; + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", + "Error: could not match input", + "Error: pushback value was too large" + }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state aState + */ + private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = + "\1\0\1\11\1\1\1\11\11\1\2\11\40\1"; + + private static int [] zzUnpackAttribute() { + int [] result = new int[47]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** this buffer contains the current text to be matched and is + the source of the yytext() string */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** endRead marks the last character in the buffer, that has been read + from input */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /** denotes if the user-EOF-code has already been executed */ + private boolean zzEOFDone; + + /* user code: */ + + Symbol newSym(int tokenId) { + return new Symbol(tokenId , yyline, yycolumn); + } + + Symbol newSym(int tokenId, Object value) { + return new Symbol(tokenId , yyline, yycolumn, value); + } + + + + /** + * Creates a new scanner + * There is also a java.io.InputStream version of this constructor. + * + * @param in the java.io.Reader to read input from. + */ + Yylex(java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. + * There is also java.io.Reader version of this constructor. + * + * @param in the java.io.Inputstream to read input from. + */ + Yylex(java.io.InputStream in) { + this(new java.io.InputStreamReader + (in, java.nio.charset.Charset.forName("UTF-8"))); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed the packed character translation table + * @return the unpacked character translation table + */ + private static char [] zzUnpackCMap(String packed) { + char [] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 122) { + int count = packed.charAt(i++); + char value = packed.charAt(i++); + do map[j++] = value; while (--count > 0); + } + return map; + } + + + /** + * Refills the input buffer. + * + * @return false, iff there was new input. + * + * @exception java.io.IOException if any I/O-Error occurs + */ + private boolean zzRefill() throws java.io.IOException { + + /* first: make room (if you can) */ + if (zzStartRead > 0) { + System.arraycopy(zzBuffer, zzStartRead, + zzBuffer, 0, + zzEndRead-zzStartRead); + + /* translate stored positions */ + zzEndRead-= zzStartRead; + zzCurrentPos-= zzStartRead; + zzMarkedPos-= zzStartRead; + zzStartRead = 0; + } + + /* is the buffer big enough? */ + if (zzCurrentPos >= zzBuffer.length) { + /* if not: blow it up */ + char newBuffer[] = new char[zzCurrentPos*2]; + System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); + zzBuffer = newBuffer; + } + + /* finally: fill the buffer with new input */ + int numRead = zzReader.read(zzBuffer, zzEndRead, + zzBuffer.length-zzEndRead); + + if (numRead > 0) { + zzEndRead+= numRead; + return false; + } + // unlikely but not impossible: read 0 characters, but not at end of stream + if (numRead == 0) { + int c = zzReader.read(); + if (c == -1) { + return true; + } else { + zzBuffer[zzEndRead++] = (char) c; + return false; + } + } + + // numRead < 0 + return true; + } + + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) + zzReader.close(); + } + + + /** + * Resets the scanner to read from a new input stream. + * Does not close the old reader. + * + * All internal variables are reset, the old input stream + * cannot be reused (internal buffer is discarded and lost). + * Lexical state is set to ZZ_INITIAL. + * + * Internal scan buffer is resized down to its initial length, if it has grown. + * + * @param reader the new input stream + */ + public final void yyreset(java.io.Reader reader) { + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + zzEOFDone = false; + zzEndRead = zzStartRead = 0; + zzCurrentPos = zzMarkedPos = 0; + yyline = yychar = yycolumn = 0; + zzLexicalState = YYINITIAL; + if (zzBuffer.length > ZZ_BUFFERSIZE) + zzBuffer = new char[ZZ_BUFFERSIZE]; + } + + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + + /** + * Enters a new lexical state + * + * @param newState the new lexical state + */ + public final void yybegin(int newState) { + zzLexicalState = newState; + } + + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); + } + + + /** + * Returns the character at position pos from the + * matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. + * A value from 0 to yylength()-1. + * + * @return the character at position pos + */ + public final char yycharat(int pos) { + return zzBuffer[zzStartRead+pos]; + } + + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos-zzStartRead; + } + + + /** + * Reports an error that occured while scanning. + * + * In a wellformed scanner (no or only correct usage of + * yypushback(int) and a match-all fallback rule) this method + * will only be called with things that "Can't Possibly Happen". + * If this method is called, something is seriously wrong + * (e.g. a JFlex bug producing a faulty scanner etc.). + * + * Usual syntax/scanner level error handling should be done + * in error fallback rules. + * + * @param errorCode the code of the errormessage to display + */ + private void zzScanError(int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } + catch (ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + + /** + * Pushes the specified amount of characters back into the input stream. + * + * They will be read again by then next call of the scanning method + * + * @param number the number of characters to be read again. + * This number must not be greater than yylength()! + */ + public void yypushback(int number) { + if ( number > yylength() ) + zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + + /** + * Contains user EOF-code, which will be executed exactly once, + * when the end of file is reached + */ + private void zzDoEOF() throws java.io.IOException { + if (!zzEOFDone) { + zzEOFDone = true; + yyclose(); + } + } + + + /** + * Resumes scanning until the next regular expression is matched, + * the end of input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException if any I/O-Error occurs + */ + public java_cup.runtime.Symbol next_token() throws java.io.IOException { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char [] zzBufferL = zzBuffer; + char [] zzCMapL = ZZ_CMAP; + + int [] zzTransL = ZZ_TRANS; + int [] zzRowMapL = ZZ_ROWMAP; + int [] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + yychar+= zzMarkedPosL-zzStartRead; + + boolean zzR = false; + for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL; + zzCurrentPosL++) { + switch (zzBufferL[zzCurrentPosL]) { + case '\u000B': + case '\u000C': + case '\u0085': + case '\u2028': + case '\u2029': + yyline++; + yycolumn = 0; + zzR = false; + break; + case '\r': + yyline++; + yycolumn = 0; + zzR = true; + break; + case '\n': + if (zzR) + zzR = false; + else { + yyline++; + yycolumn = 0; + } + break; + default: + zzR = false; + yycolumn++; + } + } + + if (zzR) { + // peek one character ahead if it is \n (if we have counted one line too much) + boolean zzPeek; + if (zzMarkedPosL < zzEndReadL) + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + else if (zzAtEOF) + zzPeek = false; + else { + boolean eof = zzRefill(); + zzEndReadL = zzEndRead; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + if (eof) + zzPeek = false; + else + zzPeek = zzBufferL[zzMarkedPosL] == '\n'; + } + if (zzPeek) yyline--; + } + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = ZZ_LEXSTATE[zzLexicalState]; + + // set up zzAction for empty match case: + int zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + } + + + zzForAction: { + while (true) { + + if (zzCurrentPosL < zzEndReadL) + zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } + else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } + else { + zzInput = zzBufferL[zzCurrentPosL++]; + } + } + int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; + if (zzNext == -1) break zzForAction; + zzState = zzNext; + + zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ( (zzAttributes & 8) == 8 ) break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 1: + { System.out.println("Illegal char, '" + yytext() +"' line: " + yyline + ", column: " + yychar); + } + case 10: break; + case 2: + { return newSym(sym.ID,(String) yytext()); + } + case 11: break; + case 3: + { /*IGNORAR*/ + } + case 12: break; + case 4: + { return newSym(sym.ADD_ATTR_VAR); + } + case 13: break; + case 5: + { return newSym(sym.SEPARADOR); + } + case 14: break; + case 6: + { return newSym(sym.VAR); + } + case 15: break; + case 7: + { return newSym(sym.TIPO_VARIAVEL,"float"); + } + case 16: break; + case 8: + { return newSym(sym.TIPO_VARIAVEL,"int"); + } + case 17: break; + case 9: + { return newSym(sym.TIPO_VARIAVEL,"String"); + } + case 18: break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + zzDoEOF(); + { + return newSym(sym.EOF); + } + } + else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + + +} diff --git a/Test/com/analizador/var/java_cup.jar b/Test/com/analizador/var/java_cup.jar new file mode 100644 index 0000000..73ffa0b Binary files /dev/null and b/Test/com/analizador/var/java_cup.jar differ diff --git a/Test/com/analizador/var/parser.java b/Test/com/analizador/var/parser.java new file mode 100644 index 0000000..f1f61c0 --- /dev/null +++ b/Test/com/analizador/var/parser.java @@ -0,0 +1,239 @@ + +//---------------------------------------------------- +// The following code was generated by CUP v0.11a beta 20060608 +// Fri Jun 20 12:54:33 BRT 2014 +//---------------------------------------------------- + +package com.analizador.var; + +import java_cup.runtime.*; + +/** CUP v0.11a beta 20060608 generated parser. + * @version Fri Jun 20 12:54:33 BRT 2014 + */ +public class parser extends java_cup.runtime.lr_parser { + + /** Default constructor. */ + public parser() {super();} + + /** Constructor which sets the default scanner. */ + public parser(java_cup.runtime.Scanner s) {super(s);} + + /** Constructor which sets the default scanner. */ + public parser(java_cup.runtime.Scanner s, java_cup.runtime.SymbolFactory sf) {super(s,sf);} + + /** Production table. */ + protected static final short _production_table[][] = + unpackFromStrings(new String[] { + "\000\011\000\002\002\004\000\002\002\004\000\002\002" + + "\003\000\002\003\004\000\002\003\003\000\002\003\003" + + "\000\002\004\005\000\002\005\005\000\002\005\003" }); + + /** Access to production table. */ + public short[][] production_table() {return _production_table;} + + /** Parse-action table. */ + protected static final short[][] _action_table = + unpackFromStrings(new String[] { + "\000\017\000\006\003\005\004\004\001\002\000\006\003" + + "\012\005\010\001\002\000\004\002\uffff\001\002\000\004" + + "\002\007\001\002\000\004\002\000\001\002\000\006\007" + + "\ufff9\010\ufff9\001\002\000\006\002\ufffd\005\ufffd\001\002" + + "\000\006\002\ufffc\005\ufffc\001\002\000\006\002\001\005" + + "\010\001\002\000\006\007\016\010\015\001\002\000\004" + + "\005\010\001\002\000\004\006\017\001\002\000\006\002" + + "\ufffb\005\ufffb\001\002\000\006\007\ufffa\010\ufffa\001\002" + + "\000\006\002\ufffe\005\ufffe\001\002" }); + + /** Access to parse-action table. */ + public short[][] action_table() {return _action_table;} + + /** reduce_goto table. */ + protected static final short[][] _reduce_table = + unpackFromStrings(new String[] { + "\000\017\000\004\002\005\001\001\000\010\003\012\004" + + "\010\005\013\001\001\000\002\001\001\000\002\001\001" + + "\000\002\001\001\000\002\001\001\000\002\001\001\000" + + "\002\001\001\000\006\004\020\005\013\001\001\000\002" + + "\001\001\000\004\005\017\001\001\000\002\001\001\000" + + "\002\001\001\000\002\001\001\000\002\001\001" }); + + /** Access to reduce_goto table. */ + public short[][] reduce_table() {return _reduce_table;} + + /** Instance of action encapsulation class. */ + protected CUP$parser$actions action_obj; + + /** Action encapsulation object initializer. */ + protected void init_actions() + { + action_obj = new CUP$parser$actions(this); + } + + /** Invoke a user supplied parse action. */ + public java_cup.runtime.Symbol do_action( + int act_num, + java_cup.runtime.lr_parser parser, + java.util.Stack stack, + int top) + throws java.lang.Exception + { + /* call code in generated class */ + return action_obj.CUP$parser$do_action(act_num, parser, stack, top); + } + + /** Indicates start state. */ + public int start_state() {return 0;} + /** Indicates start production. */ + public int start_production() {return 1;} + + /** EOF Symbol index. */ + public int EOF_sym() {return 0;} + + /** error Symbol index. */ + public int error_sym() {return 1;} + + + + public static void main(String args[]) throws Exception{ + new parser(new Yylex(System.in)).parse(); + } + public void syntax_error(Symbol s){ + report_error("Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right)+". Trecho desconhecido: \""+s.value+"\"",null); + } + +} + +/** Cup generated class to encapsulate user supplied action code.*/ +class CUP$parser$actions { + private final parser parser; + + /** Constructor */ + CUP$parser$actions(parser parser) { + this.parser = parser; + } + + /** Method with the actual generated action code. */ + public final java_cup.runtime.Symbol CUP$parser$do_action( + int CUP$parser$act_num, + java_cup.runtime.lr_parser CUP$parser$parser, + java.util.Stack CUP$parser$stack, + int CUP$parser$top) + throws java.lang.Exception + { + /* Symbol object for return from actions */ + java_cup.runtime.Symbol CUP$parser$result; + + /* select the action based on the action number */ + switch (CUP$parser$act_num) + { + /*. . . . . . . . . . . . . . . . . . . .*/ + case 8: // listagem ::= ID + { + String RESULT =null; + int valueleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int valueright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + Object value = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = (String) value; + CUP$parser$result = parser.getSymbolFactory().newSymbol("listagem",3, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 7: // listagem ::= listagem SEPARADOR listagem + { + String RESULT =null; + int e1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left; + int e1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right; + String e1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; + int e2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int e2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + String e2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + RESULT = (String) e1+","+e2; + CUP$parser$result = parser.getSymbolFactory().newSymbol("listagem",3, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 6: // instanciacao ::= listagem ADD_ATTR_VAR TIPO_VARIAVEL + { + Object RESULT =null; + int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left; + int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right; + String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value; + int xleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left; + int xright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right; + Object x = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value; + System.out.println(x+" "+ e +";"); + CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao",2, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 5: // variaveis ::= error + { + Object RESULT =null; + + CUP$parser$result = parser.getSymbolFactory().newSymbol("variaveis",1, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 4: // variaveis ::= instanciacao + { + Object RESULT =null; + + CUP$parser$result = parser.getSymbolFactory().newSymbol("variaveis",1, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 3: // variaveis ::= variaveis instanciacao + { + Object RESULT =null; + + CUP$parser$result = parser.getSymbolFactory().newSymbol("variaveis",1, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 2: // estrutura ::= error + { + Object RESULT =null; + System.out.println("Detalhe: Erro de estruturacao. Exemplo de estruturacao.: var variavel1,variavel2 : tipo_de_variavel"); + CUP$parser$result = parser.getSymbolFactory().newSymbol("estrutura",0, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 1: // $START ::= estrutura EOF + { + Object RESULT =null; + int start_valleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left; + int start_valright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right; + Object start_val = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value; + RESULT = start_val; + CUP$parser$result = parser.getSymbolFactory().newSymbol("$START",0, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + /* ACCEPT */ + CUP$parser$parser.done_parsing(); + return CUP$parser$result; + + /*. . . . . . . . . . . . . . . . . . . .*/ + case 0: // estrutura ::= VAR variaveis + { + Object RESULT =null; + + CUP$parser$result = parser.getSymbolFactory().newSymbol("estrutura",0, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT); + } + return CUP$parser$result; + + /* . . . . . .*/ + default: + throw new Exception( + "Invalid action number found in internal parse table"); + + } + } +} + diff --git a/Test/com/analizador/var/sym.java b/Test/com/analizador/var/sym.java new file mode 100644 index 0000000..7b044d0 --- /dev/null +++ b/Test/com/analizador/var/sym.java @@ -0,0 +1,20 @@ + +//---------------------------------------------------- +// The following code was generated by CUP v0.11a beta 20060608 +// Fri Jun 20 12:54:33 BRT 2014 +//---------------------------------------------------- + +package com.analizador.var; + +/** CUP generated class containing symbol constants. */ +public class sym { + /* terminals */ + public static final int ID = 3; + public static final int VAR = 2; + public static final int error = 1; + public static final int SEPARADOR = 6; + public static final int TIPO_VARIAVEL = 4; + public static final int ADD_ATTR_VAR = 5; + public static final int EOF = 0; +} + diff --git a/Test/com/classes/editor/EditorTxT.java b/Test/com/classes/editor/EditorTxT.java new file mode 100644 index 0000000..3a6d264 --- /dev/null +++ b/Test/com/classes/editor/EditorTxT.java @@ -0,0 +1,169 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.classes.editor; + +import com.classes.editor.HighlightingStyledDocument; +import com.classes.editor.LinePainter; +import com.classes.editor.TextLineNumber; +import com.classes.editor.UndoAndRedo; +import static com.forms.Editor.tab; +import java.awt.Color; +import javax.swing.JScrollPane; +import javax.swing.JTextPane; +import javax.swing.event.UndoableEditEvent; +import javax.swing.event.UndoableEditListener; +import javax.swing.text.AttributeSet; +import javax.swing.text.SimpleAttributeSet; +import javax.swing.text.StyleConstants; +import javax.swing.text.StyleContext; +import javax.swing.text.TabSet; +import javax.swing.text.TabStop; +import javax.swing.undo.UndoManager; + +/** + * + * @author SIMONETO-2 + */ +public class EditorTxT { + + /* + * VARIAVEIS + */ + private JTextPane campo = null; + private final int tabSize = 5; + private TextLineNumber tln = null; + private final HighlightingStyledDocument highlight = new HighlightingStyledDocument(); + private LinePainter painter = null; + private UndoAndRedo undoRedo = null; + + private UndoManager undoManager = new UndoManager(); + /* + * FUNCAO PRINCIPAL + */ + + public EditorTxT(final JTextPane campo, JScrollPane scroll) { + //SETANDO CAMPO VARIAVEL + this.campo = campo; + + //MUDANDO COR DO CURSOR + this.campo.setCaretColor(Color.WHITE); + + //APLICANDO A NUMERCAO DE LINHAS + tln = new TextLineNumber(this.campo, 2); + scroll.setRowHeaderView(tln); + + //APLICANDO O FUCUS DE LINHA + painter = new LinePainter(this.campo); + painter.setColor(Color.decode("#353535")); + + + //CONFIGURACOES DE COR E ESTILO DO EDTITOR + SimpleAttributeSet syle_comentario = new SimpleAttributeSet(); + syle_comentario.addAttribute(StyleConstants.Foreground, Color.decode("#8f908a")); + //syle_comentario.addAttribute(StyleConstants.CharacterConstants.Italic, Boolean.TRUE); + + SimpleAttributeSet style_key_principais = new SimpleAttributeSet(); + style_key_principais.addAttribute(StyleConstants.Foreground, Color.decode("#66d9ef")); + style_key_principais.addAttribute(StyleConstants.CharacterConstants.Bold, Boolean.TRUE); + + SimpleAttributeSet style_funcoes = new SimpleAttributeSet(); + style_funcoes.addAttribute(StyleConstants.Foreground, Color.decode("#f92672")); + //style_funcoes.addAttribute(StyleConstants.CharacterConstants.Bold, Boolean.TRUE); + + SimpleAttributeSet syle_string = new SimpleAttributeSet(); + syle_string.addAttribute(StyleConstants.Foreground, Color.decode("#e6db74")); + + SimpleAttributeSet style_default = new SimpleAttributeSet(); + style_default.addAttribute(StyleConstants.Foreground, Color.WHITE); + + highlight.setCommentStyle(syle_comentario); + highlight.setDefaultStyle(style_default); + highlight.setKeywordStyle(style_key_principais); + highlight.setEnvironmentWordStyle(style_funcoes); + highlight.setStringStyle(syle_string); + + + this.campo.setDocument(highlight); + + //SETANDO TAMANHO DA TAB + setTabSize(this.campo, tabSize); + + //SETANDO O UNDO MANAGE + this.campo.getDocument().addUndoableEditListener(new UndoableEditListener() { + @Override + public void undoableEditHappened(UndoableEditEvent e) { + undoManager.addEdit(e.getEdit()); + updateUndoRedo(); + } + }); + + /* + //EVENTO DE MODIFICAO DO TXT + this.campo.getDocument().addDocumentListener(new DocumentListener() { + + @Override + public void removeUpdate(DocumentEvent e) { + //System.out.println("nao modificado "+campo.getName()); + } + + @Override + public void insertUpdate(DocumentEvent e) { + //System.out.println("modificado "+campo.getName()); + } + + @Override + public void changedUpdate(DocumentEvent arg0) { + //System.out.println("modificado "+campo.getName()); + } + }); + */ + } + + /* + * FUNCOES PARA SETAR O CTRL+Z E CTRL+V + */ + public void setUndo(){ + if(undoManager.canUndo()) undoManager.undo(); + } + public void setRedo(){ + if(undoManager.canRedo()) undoManager.redo(); + } + + public boolean canUndo(){ + return undoManager.canUndo(); + } + + public boolean canRedo(){ + return undoManager.canRedo(); + } + public void updateUndoRedo(){ + //System.out.println(canUndo()); + //jMenuItem8.setEnabled(canRedo()); + //jMenuItem7.setEnabled(canUndo()); + } + + + /* + * FUNCAO PARA SETAR O TABSIZE + */ + public void setTabSize(JTextPane pane, int size) { + String tab = ""; + for (int i = 0; i < size; i++) { + tab += " "; + } + float f = (float) pane.getFontMetrics(pane.getFont()).stringWidth(tab); + TabStop[] tabs = new TabStop[500]; // this sucks + + for (int i = 0; i < tabs.length; i++) { + tabs[i] = new TabStop(f * (i + 1), TabStop.ALIGN_LEFT, TabStop.LEAD_NONE); + } + + TabSet tabset = new TabSet(tabs); + StyleContext sc = StyleContext.getDefaultStyleContext(); + AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.TabSet, tabset); + pane.setParagraphAttributes(aset, false); + } +} diff --git a/Test/com/classes/editor/HighlightingStyledDocument.java b/Test/com/classes/editor/HighlightingStyledDocument.java new file mode 100644 index 0000000..c77c141 --- /dev/null +++ b/Test/com/classes/editor/HighlightingStyledDocument.java @@ -0,0 +1,342 @@ +package com.classes.editor; + +import static com.forms.Editor.files_opens; +import static com.forms.Editor.tab; +import java.awt.Color; +import java.util.*; +import java.util.regex.*; +import javax.swing.event.*; +import javax.swing.text.*; + +/** + * Highlights jython syntax in a Document Created for the Jython Environment for + * Students (JES) Hilghights keywords and environment words that are defined for + * it. It will also highlight single-line comments that start with '#', and + * single-line strings that start with "'" or '"'. + * + * @author Adam Wilson, awilson@cc.gatech.edu + */ +public class HighlightingStyledDocument extends DefaultStyledDocument { + + + //Portugol port = new Portugol(); + + + /* Keyword text style */ + private SimpleAttributeSet keywordStyle = new SimpleAttributeSet(); + + /* Environment word text style */ + private SimpleAttributeSet environmentWordStyle = new SimpleAttributeSet(); + + /* Comment Style */ + private SimpleAttributeSet commentStyle = new SimpleAttributeSet(); + + /* String style */ + private SimpleAttributeSet stringStyle = new SimpleAttributeSet(); + + /* Default Style */ + private SimpleAttributeSet defaultStyle = new SimpleAttributeSet(); + + /* Jython keywords */ + private Vector keywords = new Vector(); + + /* Gutters */ + private Vector gutters = new Vector(); + + /* Jython environment words */ + private Vector environmentWords = new Vector(); + + /* Generated Regular expression for keywords */ + private Pattern keyReg = Pattern.compile(""); + + /* Generated regular expression for environment words */ + private Pattern envReg = Pattern.compile("inteiro|caracter|real|leia|se|entao|fimse|senao|enquanto|escreva"); + + /* Regular Expression for comments */ + private Pattern commentReg = Pattern.compile("#++[^\n]*"); + + /* Regular Expression for double quote Strings */ + private Pattern doubleStringReg = Pattern.compile("\"[^\n\"]*\""); + + /* Regular Expression for single quote strings */ + private Pattern singleStringReg = Pattern.compile("'[^\n']*'"); + + /* Regular Expression for string & comments */ + /* "\\\"" - why not?!? \p" */ + private Pattern stringComments = Pattern.compile("(\\/\\/[^\n]*|\"([^\n\"\\x5c]|(\\x5c\")|(\\x5c))*\"|'([^\n'\\x5c]|(\\x5c')|(\\x5c))*')"); + + /* Regular Expression to match multi-line strings */ + private Pattern mlString = Pattern.compile("\"\"\".*\"\"\"", Pattern.DOTALL); + + /* Regular Expression to match triple qoutes */ + private Pattern triQuote = Pattern.compile("\"\"\""); + + /** + * insertString Overrides the default method from DefaultStyledDocument. + * Calls appropriate syntax highlighting code and then class super. + * @throws javax.swing.text.BadLocationException + */ + @Override + public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { + super.insertString(offs, str, a); + updateHighlightingInRange(offs, str.length()); + } + + /** + * fireRemoveUpdate Overrides the default method from DefaultStyledDocument. + * Calls appropriate syntax highlighting code and then class super. + * + * @param e the DocumentEvent + */ + @Override + protected void fireRemoveUpdate(DocumentEvent e) { + int offset = e.getOffset(); + int length = e.getLength(); + updateHighlightingInRange(offset - 1, 0); + super.fireRemoveUpdate(e); + } + + /** + * Method: updateHighlightingInRange Looks at a given range of text in a + * document and highlights it according to keywords, environment, strings, + * and comments. + * + * @param offset Where in the document the change started + * @param length The length of change measured from the offset + */ + public void updateHighlightingInRange(int offset, int length) { + try { + String textAll = getText(0, getLength()); + int start = getLineStart(textAll, offset); + int end = getLineEnd(textAll, offset + length); + String text = getText(start, end - start); + setCharacterAttributes(start, end - start, defaultStyle, true); + + //Do Block Highlighting: + //Find and highlight keywords: + Matcher m = keyReg.matcher(text); + while (m.find()) { + setCharacterAttributes(start + m.start(), m.end() - m.start(), keywordStyle, true); + } + + //Find and highlight keywords: + m = envReg.matcher(text); + while (m.find()) { + setCharacterAttributes(start + m.start(), m.end() - m.start(), environmentWordStyle, true); + } + + //Find and highlight Comments and strings: + m = stringComments.matcher(text); + while (m.find()) { + //System.out.println("Matched: " + getText(start + m.start(), m.end() - m.start())); + if (text.charAt(m.start()) == '/') { + setCharacterAttributes(start + m.start(), m.end() - m.start(), commentStyle, true); + } + if (text.charAt(m.start()) == '\'' || text.charAt(m.start()) == '"') { + setCharacterAttributes(start + m.start(), m.end() - m.start(), stringStyle, true); + } + } + //Matches Multi-line strings starting with triple quotes: + /*m = mlString.matcher(textAll); + while(m.find()) + setCharacterAttributes(m.start(), m.end() - m.start(), stringStyle, true);*/ + } catch (BadLocationException e) { + } + } + + /** + * getLineStart Finds the start of a line in a document. Takes in an offset + * and finds the index of the beginning of that line. + * + * @param text The text to find the start of the line in + * @param offset An index of a character on that line + */ + private int getLineStart(String text, int offset) { + while (offset > 0) { + if (text.charAt(offset) == '\n') { + return (offset + 1); + } + offset--; + } + return offset; + } + + /** + * getLineEnd Takes in an index and finds the offset of the end of the line + * + * @param text The text to find the end of the line in + * @param offset An index of a character on that line. + */ + private int getLineEnd(String text, int offset) { + while (offset < text.length()) { + if (text.charAt(offset) == '\n') { + return (offset); + } + offset++; + } + return offset; + } + + /** + * Method: isString Looks at a location in the given document and determines + * if that location is inside a string. Supports """ for multi-line strings. + * + * @param doc The document to look in for the text + * @param offset The location to check for string-ness + * @return True for is a string, false for is not a string + */ + private boolean isString(int offset) { + return false; + } + + /** + * Method: isComment Looks at a location inside a document and determines if + * it is a comment. + * + * @param doc The document to look in for the text + * @param offset The location to check for stringness + * @return True for is a comment, false for is not a comment + */ + private boolean isComment(int offset) { + return false; + } + + /** + * Method: setKeywords Sets a collection of keywords to highlight. + * + * @param words An array of all the words + */ + public void setKeywords(String[] words) { + keywords.clear(); + for (int i = 0; i < words.length; i++) { + keywords.add(words[i]); + } + compileKeywords(); + } + + /** + * Method: setEnvironmentWords Sets a collection of environment words to + * highlight. + * + * @param words An array of all the words + */ + public void setEnvironmentWords(String[] words) { + environmentWords.clear(); + for (int i = 0; i < words.length; i++) { + environmentWords.add(words[i]); + } + compileEnvironmentWords(); + } + + /** + * Method: addKeyword Adds a keyword to the Vector of keywords. + * + * @param word The word to add + */ + public void addKeyword(String word) { + keywords.add(word); + compileKeywords(); + } + + /** + * Method: addEnvironmentWord Adds an environment word to the Vector of + * environment words. + * + * @param word The word to add + */ + public void addEnvironmentWord(String word) { + environmentWords.add(word); + compileEnvironmentWords(); + } + + /** + * Method: setKeywordStyle Sets the style of text to use for keywords + * + * @param style The new text style + */ + public void setKeywordStyle(SimpleAttributeSet style) { + keywordStyle = style; + } + + /** + * Method: setEnvironmentWordStyle Sets the style of text to use for + * environment words + * + * @param style The new text style + */ + public void setEnvironmentWordStyle(SimpleAttributeSet style) { + environmentWordStyle = style; + } + + /** + * Method: setCommentStyle Sets the style of text to use for comments + * + * @param style The new text style + */ + public void setCommentStyle(SimpleAttributeSet style) { + commentStyle = style; + } + + /** + * Method: setStringStyle Sets the style of text to use for strings + * + * @param style The new text style + */ + public void setStringStyle(SimpleAttributeSet style) { + stringStyle = style; + } + + /** + * Method: setDefaultStyle Sets the default style of text to use + * + * @param style The new text style + */ + public void setDefaultStyle(SimpleAttributeSet style) { + defaultStyle = style; + } + + /** + * compileKeywords Recompiles the regular expression used for matching key + * words. Takes the collection of keywords and generates a regular + * expression string. It then compiles that string into the Pattern class + * and stores it in keyReg. Example: if the keywords were "if" and "for", + * the regular expression would be: "\W(if|for)\W". The \W isolate the + * keywords by non-word characters. + */ + private void compileKeywords() { + String exp = new String(); + exp = "\\b("; //Start the expression to match non-word characters, + //i.e. [^a-zA-Z0-9], and then start the OR block. + for (int i = 0; i < keywords.size(); i++) { + if (i == 0) { + exp = exp + ((String) keywords.elementAt(i)).trim(); + } + exp = exp + "|" + ((String) keywords.elementAt(i)).trim(); + } + exp = exp + ")\\b"; + keyReg = Pattern.compile(exp); + } + + /** + * compileEnvironmentWords Recompiles the regular expression used for + * matching environment words. Takes the collection of environment words and + * generates a regular expression string. It then compiles that string into + * the Pattern class and stores it in envReg. Example: if the envwords were + * "if" and "for", the regular expression would be: "\W(if|for)\W". The \W + * isolate the envwords by non-word characters. + */ + private void compileEnvironmentWords() { + String exp = new String(); + exp = "\\b("; //Start the expression to match non-word characters, + //i.e. [^a-zA-Z0-9], and then start the OR block. + for (int i = 0; i < environmentWords.size(); i++) { + if (i == 0) { + exp = exp + ((String) environmentWords.elementAt(i)).trim(); + } + exp = exp + "|" + ((String) environmentWords.elementAt(i)).trim(); + } + exp = exp + ")\\b"; + envReg = Pattern.compile(exp); + } + +}//END OF HighlightingStyledDocument Class diff --git a/Test/com/classes/editor/LinePainter.java b/Test/com/classes/editor/LinePainter.java new file mode 100644 index 0000000..bce86fe --- /dev/null +++ b/Test/com/classes/editor/LinePainter.java @@ -0,0 +1,166 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package com.classes.editor; + +/** + * + * @author SIMONETO-2 + */ +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.event.*; +import javax.swing.text.*; + +/* + * Track the movement of the Caret by painting a background line at the + * current caret position. + */ +public class LinePainter + implements Highlighter.HighlightPainter, CaretListener, MouseListener, MouseMotionListener +{ + private JTextComponent component; + + private Color color; + + private Rectangle lastView; + + /* + * The line color will be calculated automatically by attempting + * to make the current selection lighter by a factor of 1.2. + * + * @param component text component that requires background line painting + */ + public LinePainter(JTextComponent component) + { + this(component, null); + setLighter(component.getSelectionColor()); + } + + /* + * Manually control the line color + * + * @param component text component that requires background line painting + * @param color the color of the background line + */ + public LinePainter(JTextComponent component, Color color) + { + this.component = component; + setColor( color ); + + // Add listeners so we know when to change highlighting + + component.addCaretListener( this ); + component.addMouseListener( this ); + component.addMouseMotionListener( this ); + + // Turn highlighting on by adding a dummy highlight + + try + { + component.getHighlighter().addHighlight(0, 0, this); + } + catch(BadLocationException ble) {} + } + + /* + * You can reset the line color at any time + * + * @param color the color of the background line + */ + public void setColor(Color color) + { + this.color = color; + } + + /* + * Calculate the line color by making the selection color lighter + * + * @return the color of the background line + */ + public void setLighter(Color color) + { + int red = Math.min(255, (int)(color.getRed() * 1.2)); + int green = Math.min(255, (int)(color.getGreen() * 1.2)); + int blue = Math.min(255, (int)(color.getBlue() * 1.2)); + setColor(new Color(red, green, blue)); + } + + // Paint the background highlight + + public void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent c) + { + try + { + Rectangle r = c.modelToView(c.getCaretPosition()); + g.setColor( color ); + g.fillRect(0, r.y, c.getWidth(), r.height); + + if (lastView == null) + lastView = r; + } + catch(BadLocationException ble) {System.out.println(ble);} + } + + /* + * Caret position has changed, remove the highlight + */ + private void resetHighlight() + { + // Use invokeLater to make sure updates to the Document are completed, + // otherwise Undo processing causes the modelToView method to loop. + + SwingUtilities.invokeLater(new Runnable() + { + public void run() + { + try + { + int offset = component.getCaretPosition(); + Rectangle currentView = component.modelToView(offset); + + // Remove the highlighting from the previously highlighted line + + if (lastView.y != currentView.y) + { + component.repaint(0, lastView.y, component.getWidth(), lastView.height); + lastView = currentView; + } + } + catch(BadLocationException ble) {} + } + }); + } + + // Implement CaretListener + + public void caretUpdate(CaretEvent e) + { + resetHighlight(); + } + + // Implement MouseListener + + public void mousePressed(MouseEvent e) + { + resetHighlight(); + } + + public void mouseClicked(MouseEvent e) {} + public void mouseEntered(MouseEvent e) {} + public void mouseExited(MouseEvent e) {} + public void mouseReleased(MouseEvent e) {} + + // Implement MouseMotionListener + + public void mouseDragged(MouseEvent e) + { + resetHighlight(); + } + + public void mouseMoved(MouseEvent e) {} +} diff --git a/Test/com/classes/editor/TextLineNumber.java b/Test/com/classes/editor/TextLineNumber.java new file mode 100644 index 0000000..3045aad --- /dev/null +++ b/Test/com/classes/editor/TextLineNumber.java @@ -0,0 +1,455 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.classes.editor; + +/** + * + * @author SIMONETO-2 + */ +import java.awt.*; +import java.awt.event.*; +import java.beans.*; +import java.util.HashMap; +import javax.swing.*; +import javax.swing.border.*; +import javax.swing.event.*; +import javax.swing.text.*; + +/** + * This class will display line numbers for a related text component. The text + * component must use the same line height for each line. TextLineNumber + * supports wrapped lines and will highlight the line number of the current line + * in the text component. + * + * This class was designed to be used as a component added to the row header of + * a JScrollPane. + */ +public class TextLineNumber extends JPanel + implements CaretListener, DocumentListener, PropertyChangeListener { + + public final static float LEFT = 0.0f; + public final static float CENTER = 0.5f; + public final static float RIGHT = 1.0f; + + private final static Border OUTER = new MatteBorder(0, 0, 0, 0, Color.BLACK); + + private final static int HEIGHT = Integer.MAX_VALUE - 1000000; + + // Text component this TextTextLineNumber component is in sync with + private JTextComponent component; + + // Properties that can be changed + private boolean updateFont; + private int borderGap; + + private Color LineForeground; + private Color currentLineForeground; + private Color background; + + + private float digitAlignment; + private int minimumDisplayDigits; + + // Keep history information to reduce the number of times the component + // needs to be repainted + private int lastDigits; + private int lastHeight; + private int lastLine; + + private HashMap fonts; + + /** + * Create a line number component for a text component. This minimum display + * width will be based on 3 digits. + * + * @param component the related text component + */ + public TextLineNumber(JTextComponent component) { + this(component, 3); + } + + /** + * Create a line number component for a text component. + * + * @param component the related text component + * @param minimumDisplayDigits the number of digits used to calculate the + * minimum width of the component + */ + public TextLineNumber(JTextComponent component, int minimumDisplayDigits) { + this.component = component; + + setFont(component.getFont()); + + setBorderGap(10); + //8f908a + setCurrentLineForeground(Color.decode("#f92672")); + setBackground(Color.decode("#171818")); + setLineForeground(Color.decode("#FFFFFFF")); + + setDigitAlignment(CENTER); + setMinimumDisplayDigits(minimumDisplayDigits); + + component.getDocument().addDocumentListener(this); + component.addCaretListener(this); + component.addPropertyChangeListener("font", this); + } + + /** + * Gets the update font property + * + * @return the update font property + */ + public boolean getUpdateFont() { + return updateFont; + } + + public int getCurrentLine() { + return (this.lastLine + 1); + } + + /** + * Set the update font property. Indicates whether this Font should be + * updated automatically when the Font of the related text component is + * changed. + * + * @param updateFont when true update the Font and repaint the line numbers, + * otherwise just repaint the line numbers. + */ + public void setUpdateFont(boolean updateFont) { + this.updateFont = updateFont; + } + + /** + * Gets the border gap + * + * @return the border gap in pixels + */ + public int getBorderGap() { + return borderGap; + } + + /** + * The border gap is used in calculating the left and right insets of the + * border. Default value is 5. + * + * @param borderGap the gap in pixels + */ + public void setBorderGap(int borderGap) { + this.borderGap = borderGap; + Border inner = new EmptyBorder(0, borderGap, 0, borderGap); + setBorder(new CompoundBorder(OUTER, inner)); + lastDigits = 0; + setPreferredWidth(); + } + + /** + * Gets the current line rendering Color + * + * @return the Color used to render the current line number + */ + public Color getCurrentLineForeground() { + return currentLineForeground == null ? getForeground() : currentLineForeground; + } + + /** + * The Color used to render the current line digits. Default is Coolor.RED. + * + * @param currentLineForeground the Color used to render the current line + */ + public void setCurrentLineForeground(Color currentLineForeground) { + this.currentLineForeground = currentLineForeground; + } + public void setBackground(Color background) { + this.background = background; + } + public void setLineForeground(Color LineForeground) { + this.LineForeground = LineForeground; + } + + /** + * Gets the digit alignment + * + * @return the alignment of the painted digits + */ + public float getDigitAlignment() { + return digitAlignment; + } + + /** + * Specify the horizontal alignment of the digits within the component. + * Common values would be: + *
          + *
        • TextLineNumber.LEFT + *
        • TextLineNumber.CENTER + *
        • TextLineNumber.RIGHT (default) + *
        + * + * @param currentLineForeground the Color used to render the current line + */ + public void setDigitAlignment(float digitAlignment) { + this.digitAlignment + = digitAlignment > 1.0f ? 1.0f : digitAlignment < 0.0f ? -1.0f : digitAlignment; + } + + /** + * Gets the minimum display digits + * + * @return the minimum display digits + */ + public int getMinimumDisplayDigits() { + return minimumDisplayDigits; + } + + /** + * Specify the mimimum number of digits used to calculate the preferred + * width of the component. Default is 3. + * + * @param minimumDisplayDigits the number digits used in the preferred width + * calculation + */ + public void setMinimumDisplayDigits(int minimumDisplayDigits) { + this.minimumDisplayDigits = minimumDisplayDigits; + setPreferredWidth(); + } + + /** + * Calculate the width needed to display the maximum line number + */ + private void setPreferredWidth() { + Element root = component.getDocument().getDefaultRootElement(); + int lines = root.getElementCount(); + int digits = Math.max(String.valueOf(lines).length(), minimumDisplayDigits); + + // Update sizes when number of digits in the line number changes + if (lastDigits != digits) { + lastDigits = digits; + FontMetrics fontMetrics = getFontMetrics(getFont()); + int width = fontMetrics.charWidth('0') * digits; + Insets insets = getInsets(); + int preferredWidth = insets.left + insets.right + width; + + Dimension d = getPreferredSize(); + d.setSize(preferredWidth, HEIGHT); + setPreferredSize(d); + setSize(d); + } + } + + /** + * Draw the line numbers + */ + @Override + public void paintComponent(Graphics g) { + super.paintComponent(g); + setBackground(this.background); + + + // Determine the width of the space available to draw the line number + FontMetrics fontMetrics = component.getFontMetrics(component.getFont()); + Insets insets = getInsets(); + int availableWidth = getSize().width - insets.left - insets.right; + + // Determine the rows to draw within the clipped bounds. + Rectangle clip = new Rectangle(); + g.getClipBounds(clip); + + + + int rowStartOffset = component.viewToModel(new Point(0, clip.y)); + + int endOffset = component.viewToModel(new Point(0, clip.y + clip.height)); + + while (rowStartOffset <= endOffset) { + try { + if (isCurrentLine(rowStartOffset)) { + g.setColor(getCurrentLineForeground()); + } else { + g.setColor(this.LineForeground); + } + + // Get the line number as a string and then determine the + // "X" and "Y" offsets for drawing the string. + String lineNumber = getTextLineNumber(rowStartOffset); + int stringWidth = fontMetrics.stringWidth(lineNumber); + int x = getOffsetX(availableWidth, stringWidth) + insets.left; + int y = getOffsetY(rowStartOffset, fontMetrics); + g.drawString(lineNumber, x, y); + + // Move to the next row + + rowStartOffset = Utilities.getRowEnd(component, rowStartOffset) + 1; + + } catch (Exception e) { + break; + } + } + } + + /* + * We need to know if the caret is currently positioned on the line we + * are about to paint so the line number can be highlighted. + */ + private boolean isCurrentLine(int rowStartOffset) { + int caretPosition = component.getCaretPosition(); + Element root = component.getDocument().getDefaultRootElement(); + + if (root.getElementIndex(rowStartOffset) == root.getElementIndex(caretPosition)) { + return true; + } else { + return false; + } + } + + /* + * Get the line number to be drawn. The empty string will be returned + * when a line of text has wrapped. + */ + protected String getTextLineNumber(int rowStartOffset) { + Element root = component.getDocument().getDefaultRootElement(); + int index = root.getElementIndex(rowStartOffset); + Element line = root.getElement(index); + + if (line.getStartOffset() == rowStartOffset) { + return String.valueOf(index + 1); + } else { + return ""; + } + } + + /* + * Determine the X offset to properly align the line number when drawn + */ + private int getOffsetX(int availableWidth, int stringWidth) { + return (int) ((availableWidth - stringWidth) * digitAlignment); + } + + /* + * Determine the Y offset for the current row + */ + private int getOffsetY(int rowStartOffset, FontMetrics fontMetrics) + throws BadLocationException { + // Get the bounding rectangle of the row + + Rectangle r = component.modelToView(rowStartOffset); + int lineHeight = fontMetrics.getHeight(); + int y = r.y + r.height; + int descent = 0; + + // The text needs to be positioned above the bottom of the bounding + // rectangle based on the descent of the font(s) contained on the row. + if (r.height == lineHeight) // default font is being used + { + descent = fontMetrics.getDescent(); + } else // We need to check all the attributes for font changes + { + if (fonts == null) { + fonts = new HashMap(); + } + + Element root = component.getDocument().getDefaultRootElement(); + int index = root.getElementIndex(rowStartOffset); + Element line = root.getElement(index); + + for (int i = 0; i < line.getElementCount(); i++) { + Element child = line.getElement(i); + AttributeSet as = child.getAttributes(); + String fontFamily = (String) as.getAttribute(StyleConstants.FontFamily); + Integer fontSize = (Integer) as.getAttribute(StyleConstants.FontSize); + String key = fontFamily + fontSize; + + FontMetrics fm = fonts.get(key); + + if (fm == null) { + Font font = new Font(fontFamily, Font.PLAIN, fontSize); + fm = component.getFontMetrics(font); + fonts.put(key, fm); + } + + descent = Math.max(descent, fm.getDescent()); + } + } + + return y - descent; + } + +// +// Implement CaretListener interface +// + @Override + public void caretUpdate(CaretEvent e) { + // Get the line the caret is positioned on + + int caretPosition = component.getCaretPosition(); + Element root = component.getDocument().getDefaultRootElement(); + int currentLine = root.getElementIndex(caretPosition); + + // Need to repaint so the correct line number can be highlighted + if (lastLine != currentLine) { + repaint(); + lastLine = currentLine; + } + } + +// +// Implement DocumentListener interface +// + @Override + public void changedUpdate(DocumentEvent e) { + documentChanged(); + } + + @Override + public void insertUpdate(DocumentEvent e) { + documentChanged(); + } + + @Override + public void removeUpdate(DocumentEvent e) { + documentChanged(); + } + + /* + * A document change may affect the number of displayed lines of text. + * Therefore the lines numbers will also change. + */ + private void documentChanged() { + // View of the component has not been updated at the time + // the DocumentEvent is fired + + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + try { + int endPos = component.getDocument().getLength(); + Rectangle rect = component.modelToView(endPos); + + if (rect != null && rect.y != lastHeight) { + setPreferredWidth(); + repaint(); + lastHeight = rect.y; + } + } catch (BadLocationException ex) { /* nothing to do */ } + } + }); + } + +// +// Implement PropertyChangeListener interface +// + @Override + public void propertyChange(PropertyChangeEvent evt) { + if (evt.getNewValue() instanceof Font) { + if (updateFont) { + Font newFont = (Font) evt.getNewValue(); + setFont(newFont); + lastDigits = 0; + setPreferredWidth(); + } else { + repaint(); + } + } + } +} diff --git a/Test/com/classes/editor/UndoAndRedo.java b/Test/com/classes/editor/UndoAndRedo.java new file mode 100644 index 0000000..eb1a1db --- /dev/null +++ b/Test/com/classes/editor/UndoAndRedo.java @@ -0,0 +1,109 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.classes.editor; + + +import static com.forms.Editor.tab; +import java.awt.event.ActionEvent; +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.JMenuItem; +import javax.swing.JTextPane; +import javax.swing.event.UndoableEditEvent; +import javax.swing.event.UndoableEditListener; +import javax.swing.undo.CannotRedoException; +import javax.swing.undo.CannotUndoException; +import javax.swing.undo.UndoManager; + +/** + * + * @author Andrew + */ +public class UndoAndRedo { + + private JTextPane campo = null; + private UndoManager undoManager = new UndoManager(); + private UndoAction undoAction = new UndoAction(); + //private RedoAction redoAction = new RedoAction(); + + public UndoAndRedo(JTextPane c) { + this.campo = c; + + this.campo.getDocument().addUndoableEditListener(new UndoListener()); + + + //jMenuItem7.addActionListener(undoAction); + //jMenuItem8.addActionListener(redoAction); + } + + class UndoListener implements UndoableEditListener { + + @Override + public void undoableEditHappened(UndoableEditEvent e) { + System.out.println("update"); + undoManager.addEdit(e.getEdit()); + //undoAction.update(); + //redoAction.update(); + } + } + + class UndoAction extends JTextPane { + + public void setUndo() { + undoManager.undo(); + //undoAction.update(); + //redoAction.update(); + } + } +} +/* + class UndoAction extends AbstractAction { + + public UndoAction() { + super("Desfazer"); + this.putValue(Action.NAME, undoManager.getUndoPresentationName()); + this.setEnabled(false); + } + + @Override + public void actionPerformed(ActionEvent e) { + System.out.println(this.isEnabled()); + if (this.isEnabled()) { + undoManager.undo(); + undoAction.update(); + redoAction.update(); + } + } + + public void update() { + this.putValue(Action.NAME, undoManager.getUndoPresentationName()); + this.setEnabled(undoManager.canUndo()); + } + } + + class RedoAction extends AbstractAction { + + public RedoAction() { + this.putValue(Action.NAME, undoManager.getRedoPresentationName()); + this.setEnabled(false); + } + + @Override + public void actionPerformed(ActionEvent e) { + if (this.isEnabled()) { + undoManager.redo(); + undoAction.update(); + redoAction.update(); + } + } + + public void update() { + this.putValue(Action.NAME, undoManager.getRedoPresentationName()); + this.setEnabled(undoManager.canRedo()); + } + } + */ + diff --git a/Test/com/test/MoveToText.java b/Test/com/test/MoveToText.java new file mode 100644 index 0000000..6afb857 --- /dev/null +++ b/Test/com/test/MoveToText.java @@ -0,0 +1,153 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package com.test; + +import java.awt.BorderLayout; +import java.awt.EventQueue; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Rectangle; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.FileReader; +import java.io.Reader; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.UIManager; +import javax.swing.UnsupportedLookAndFeelException; +import javax.swing.text.Document; + +/** + * + * @author SIMONETO-2 + */ +public class MoveToText { + + public static void main(String[] args) { + new MoveToText(); + } + + public MoveToText() { + EventQueue.invokeLater(new Runnable() { + @Override + public void run() { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { + } + + JFrame frame = new JFrame("Testing"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setLayout(new BorderLayout()); + frame.add(new FindTextPane()); + frame.setSize(400, 400); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + }); + } + + public class FindTextPane extends JPanel { + + private JTextField findField; + private JButton findButton; + private JTextArea textArea; + private int pos = 0; + + public FindTextPane() { + setLayout(new BorderLayout()); + findButton = new JButton("Next"); + findField = new JTextField("Java", 10); + textArea = new JTextArea(); + textArea.setWrapStyleWord(true); + textArea.setLineWrap(true); + + Reader reader = null; + try { + reader = new FileReader(new File("Java.txt")); + textArea.read(reader, null); + } catch (Exception e) { + e.printStackTrace(); + } finally { + try { + reader.close(); + } catch (Exception e) { + } + } + + JPanel header = new JPanel(new GridBagLayout()); + + GridBagConstraints gbc = new GridBagConstraints(); + gbc.gridx = 0; + gbc.gridy = 0; + gbc.anchor = GridBagConstraints.WEST; + header.add(findField, gbc); + gbc.gridx++; + header.add(findButton, gbc); + + add(header, BorderLayout.NORTH); + add(new JScrollPane(textArea)); + + findButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + // Get the text to find...convert it to lower case for eaiser comparision + String find = findField.getText().toLowerCase(); + // Focus the text area, otherwise the highlighting won't show up + textArea.requestFocusInWindow(); + // Make sure we have a valid search term + if (find != null && find.length() > 0) { + Document document = textArea.getDocument(); + int findLength = find.length(); + try { + boolean found = false; + // Rest the search position if we're at the end of the document + if (pos + findLength > document.getLength()) { + pos = 0; + } + // While we haven't reached the end... + // "<=" Correction + while (pos + findLength <= document.getLength()) { + // Extract the text from teh docuemnt + String match = document.getText(pos, findLength).toLowerCase(); + // Check to see if it matches or request + if (match.equals(find)) { + found = true; + break; + } + pos++; + } + + // Did we find something... + if (found) { + // Get the rectangle of the where the text would be visible... + Rectangle viewRect = textArea.modelToView(pos); + // Scroll to make the rectangle visible + textArea.scrollRectToVisible(viewRect); + // Highlight the text + textArea.setCaretPosition(pos + findLength); + textArea.moveCaretPosition(pos); + // Move the search position beyond the current match + pos += findLength; + } + + } catch (Exception exp) { + exp.printStackTrace(); + } + + } + } + }); + + } + } +} diff --git a/Test/com/test/QuickTerminal.java b/Test/com/test/QuickTerminal.java new file mode 100644 index 0000000..7e8ead9 --- /dev/null +++ b/Test/com/test/QuickTerminal.java @@ -0,0 +1,286 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package com.test; + +/** + * + * @author Andrew + */ +import java.awt.BorderLayout; +import java.awt.EventQueue; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.UnsupportedLookAndFeelException; +import javax.swing.text.BadLocationException; +import org.w3c.dom.ls.LSException; + +public class QuickTerminal { + + public static void main(String[] args) { + new QuickTerminal(); + } + + public QuickTerminal() { + EventQueue.invokeLater(new Runnable() { + @Override + public void run() { + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { + } + + JFrame frame = new JFrame("Testing"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setLayout(new BorderLayout()); + frame.add(new ConsolePane()); + frame.pack(); + frame.setLocationRelativeTo(null); + frame.setVisible(true); + } + + }); + } + + public interface CommandListener { + + public void commandOutput(String text); + + public void commandCompleted(String cmd, int result); + + public void commandFailed(Exception exp); + + } + + public class ConsolePane extends JPanel implements CommandListener { + + private JTextArea textArea; + private int userInputStart = 0; + private Command cmd; + + public ConsolePane() { + + cmd = new Command(this); + + setLayout(new BorderLayout()); + textArea = new JTextArea(20, 30); + add(new JScrollPane(textArea)); + + textArea.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ENTER) { + int range = textArea.getCaretPosition() - userInputStart; + try { + String text = textArea.getText(userInputStart, range).trim(); + System.out.println("[" + text + "]"); + userInputStart += range; + if (!cmd.isRunning()) { + cmd.execute(text); + } else { + } + } catch (BadLocationException ex) { + Logger.getLogger(QuickTerminal.class.getName()).log(Level.SEVERE, null, ex); + } + } else { +// if (!cmd.isRunning()) { +// cmd.send(...); +// } + } + } + + }); + } + + @Override + public void commandOutput(String text) { + SwingUtilities.invokeLater(new AppendTask(textArea, text)); + } + + @Override + public void commandFailed(Exception exp) { + SwingUtilities.invokeLater(new AppendTask(textArea, "Command failed - " + exp.getMessage())); + } + + @Override + public void commandCompleted(String cmd, int result) { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + int pos = textArea.getCaretPosition(); + + System.out.println("pos = " + pos + "; length = " + textArea.getText().length()); + + textArea.setCaretPosition(textArea.getText().length()); + userInputStart = pos; + } + }); + } + + } + + public class AppendTask implements Runnable { + + private JTextArea textArea; + private String text; + + public AppendTask(JTextArea textArea, String text) { + this.textArea = textArea; + this.text = text; + } + + @Override + public void run() { + textArea.append(text); + } + + } + + public class Command { + + private CommandListener listener; + + private ProcessRunner runner; + + public Command(CommandListener listener) { + this.listener = listener; + } + + public boolean isRunning() { + + return runner != null && runner.isAlive(); + + } + + public void execute(String cmd) { + + if (!cmd.trim().isEmpty()) { + + + List values = new ArrayList<>(25); + if (cmd.contains("\"")) { + + while (cmd.contains("\"")) { + + String start = cmd.substring(0, cmd.indexOf("\"")); + cmd = cmd.substring(start.length()); + String quote = cmd.substring(cmd.indexOf("\"") + 1); + cmd = cmd.substring(cmd.indexOf("\"") + 1); + quote = quote.substring(0, cmd.indexOf("\"")); + cmd = cmd.substring(cmd.indexOf("\"") + 1); + + if (!start.trim().isEmpty()) { + String parts[] = start.trim().split(" "); + values.addAll(Arrays.asList(parts)); + } + values.add(quote.trim()); + + } + + if (!cmd.trim().isEmpty()) { + String parts[] = cmd.trim().split(" "); + values.addAll(Arrays.asList(parts)); + } + + for (String value : values) { + System.out.println("[" + value + "]"); + } + + } else { + + if (!cmd.trim().isEmpty()) { + String parts[] = cmd.trim().split(" "); + values.addAll(Arrays.asList(parts)); + } + + } + + runner = new ProcessRunner(listener, values); + + } + + } + + public void send(String cmd) { + // Send user input to the running process... + } + + } + + public class ProcessRunner extends Thread { + + private List cmds; + private CommandListener listener; + + public ProcessRunner(CommandListener listener, List cmds) { + this.cmds = cmds; + this.listener = listener; + start(); + } + + @Override + public void run() { + try { + System.out.println("cmds = " + cmds); + ProcessBuilder pb = new ProcessBuilder(cmds); + pb.redirectErrorStream(); + Process p = pb.start(); + StreamReader reader = new StreamReader(listener, p.getInputStream()); + // Need a stream writer... + + int result = p.waitFor(); + + // Terminate the stream writer + reader.join(); + + listener.commandCompleted(null, result); + } catch (Exception exp) { + exp.printStackTrace(); + } + } + + } + + public class StreamReader extends Thread { + + private InputStream is; + private CommandListener listener; + + public StreamReader(CommandListener listener, InputStream is) { + this.is = is; + this.listener = listener; + start(); + } + + @Override + public void run() { + try { + int value = -1; + while ((value = is.read()) != -1) { + listener.commandOutput(Character.toString((char) value)); + } + } catch (IOException exp) { + exp.printStackTrace(); + } + } + + } + +} \ No newline at end of file diff --git a/Test/com/test/Test1.java b/Test/com/test/Test1.java new file mode 100644 index 0000000..c664084 --- /dev/null +++ b/Test/com/test/Test1.java @@ -0,0 +1,26 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.test; + +/** + * + * @author Andrew + */ +public class Test1 { + + public static int numero = 5; + + public static void main(String args[]) { + + System.out.println(numero); + + Test2 t = new Test2(); + + + + } + +} diff --git a/Test/com/test/Test2.java b/Test/com/test/Test2.java new file mode 100644 index 0000000..18a74c5 --- /dev/null +++ b/Test/com/test/Test2.java @@ -0,0 +1,23 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.test; + +import static com.test.Test1.numero; + +/** + * + * @author Andrew + */ +public class Test2 { + + public Test2() { + + numero = 10; + + System.out.print(numero); + } + +} diff --git a/Test/com/test/Test3.java b/Test/com/test/Test3.java new file mode 100644 index 0000000..d3efa7f --- /dev/null +++ b/Test/com/test/Test3.java @@ -0,0 +1,19 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package com.test; + +/** + * + * @author Andrew + */ +public class Test3 { + + public Test3(){ + + } + +} diff --git a/Test/com/test/Teste.java b/Test/com/test/Teste.java new file mode 100644 index 0000000..7226376 --- /dev/null +++ b/Test/com/test/Teste.java @@ -0,0 +1,92 @@ +package com.test; + +import javax.swing.*; +import java.awt.*; +import javax.swing.text.*; + +public class Teste extends JFrame { + + private int findLastNonWordChar(String text, int index) { + while (--index >= 0) { + if (String.valueOf(text.charAt(index)).matches("\\W")) { + break; + } + } + return index; + } + + private int findFirstNonWordChar(String text, int index) { + while (index < text.length()) { + if (String.valueOf(text.charAt(index)).matches("\\W")) { + break; + } + index++; + } + return index; + } + + public Teste() { + setDefaultCloseOperation(EXIT_ON_CLOSE); + setSize(400, 400); + setLocationRelativeTo(null); + + final StyleContext cont = StyleContext.getDefaultStyleContext(); + final AttributeSet attr = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, Color.RED); + final AttributeSet attrBlack = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, Color.BLACK); + final AttributeSet attrComment = cont.addAttribute(cont.getEmptySet(), StyleConstants.Foreground, Color.GREEN); + + + DefaultStyledDocument doc = new DefaultStyledDocument() { + public void insertString(int offset, String str, AttributeSet a) throws BadLocationException { + super.insertString(offset, str, a); + + String text = getText(0, getLength()); + int before = findLastNonWordChar(text, offset); + if (before < 0) { + before = 0; + } + int after = findFirstNonWordChar(text, offset + str.length()); + int wordL = before; + int wordR = before; + + while (wordR <= after) { + if (wordR == after || String.valueOf(text.charAt(wordR)).matches("\\W")) { + if (text.substring(wordL, wordR).matches("(\\W)*(private|public|protected)")) { + setCharacterAttributes(wordL, wordR - wordL, attr, false); + } else { + setCharacterAttributes(wordL, wordR - wordL, attrBlack, false); + } + wordL = wordR; + } + wordR++; + } + } + + public void remove(int offs, int len) throws BadLocationException { + super.remove(offs, len); + + String text = getText(0, getLength()); + int before = findLastNonWordChar(text, offs); + if (before < 0) { + before = 0; + } + int after = findFirstNonWordChar(text, offs); + + if (text.substring(before, after).matches("(\\W)*(private|public|protected)")) { + setCharacterAttributes(before, after - before, attr, false); + } else { + setCharacterAttributes(before, after - before, attrBlack, false); + } + } + }; + JTextPane txt = new JTextPane(doc); + txt.setText("public class Hi {}"); + add(new JScrollPane(txt)); + setVisible(true); + } + + public static void main(String args[]) { + new Test(); + } + +} diff --git a/Test/com/test/TesteIdentNumber.java b/Test/com/test/TesteIdentNumber.java new file mode 100644 index 0000000..93325af --- /dev/null +++ b/Test/com/test/TesteIdentNumber.java @@ -0,0 +1,114 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package com.test; + +/** + * + * @author SIMONETO-2 + */ +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.text.*; +import javax.swing.text.rtf.*; + +class Test extends JFrame +{ + public Test() + { + JEditorPane edit = new JEditorPane(); + edit.setEditorKit(new MyEditorKit()); + JScrollPane scroll=new JScrollPane(edit); + getContentPane().add(scroll); + setSize(300,300); + setVisible(true); + } + + public static void main(String a[]) + { + new Test(); + } + +} + +class MyEditorKit extends StyledEditorKit +{ + public ViewFactory getViewFactory() + { + return new MyRTFViewFactory(); + } +} + +class MyRTFViewFactory implements ViewFactory +{ + public View create(Element elem) + { + String kind = elem.getName(); + if (kind != null) + if (kind.equals(AbstractDocument.ContentElementName)) { + return new LabelView(elem); + } else if (kind.equals(AbstractDocument.ParagraphElementName)) { +// return new ParagraphView(elem); + return new MyParagraphView(elem); + } else if (kind.equals(AbstractDocument.SectionElementName)) { +// return new BoxView(elem, View.Y_AXIS); + return new MySectionView(elem, View.Y_AXIS); + } else if (kind.equals(StyleConstants.ComponentElementName)) { + return new ComponentView(elem); + } else if (kind.equals(StyleConstants.IconElementName)) { + return new IconView(elem); + } + // default to text display + return new LabelView(elem); + } +} + +class MySectionView extends BoxView { + public MySectionView(Element e, int axis) + { + super(e,axis); + } + + public void paintChild(Graphics g,Rectangle r,int n) { + if (n>0) { + MyParagraphView child=(MyParagraphView)this.getView(n-1); + int shift=child.shift+child.childCount; + + MyParagraphView current=(MyParagraphView)this.getView(n); + current.shift=shift; + } + super.paintChild(g,r,n); + } +} + +class MyParagraphView extends javax.swing.text.ParagraphView +{ + public int childCount; + public int shift=0; + public MyParagraphView(Element e) + { + super(e); + short top=0; + short left=20; + short bottom=0; + short right=0; + this.setInsets(top,left,bottom,right); + + } + + public void paint(Graphics g, Shape a) + { + childCount=this.getViewCount(); + super.paint (g,a); + int rowCountInThisParagraph=this.getViewCount(); //<----- YOU HAVE REAL ROW COUNT FOR ONE PARAGRAPH} + System.err.println(rowCountInThisParagraph); + } + public void paintChild(Graphics g,Rectangle r,int n) { + super.paintChild(g,r,n); + g.drawString(Integer.toString(shift+n+1),r.x-20,r.y+r.height-3); + } +} \ No newline at end of file diff --git a/Test/com/test/UndoEditor.java b/Test/com/test/UndoEditor.java new file mode 100644 index 0000000..d575f4e --- /dev/null +++ b/Test/com/test/UndoEditor.java @@ -0,0 +1,101 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package com.test; + +/** + * + * @author Andrew + */ +import java.awt.BorderLayout; +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JScrollPane; +import javax.swing.JTextPane; +import javax.swing.event.UndoableEditEvent; +import javax.swing.event.UndoableEditListener; +import javax.swing.undo.UndoManager; + +public class UndoEditor extends JFrame { + private UndoManager undoManager = new UndoManager(); + private JMenuBar menuBar = new JMenuBar(); + private JMenu editMenu = new JMenu("Edit"); + private UndoAction undoAction = new UndoAction(); + private RedoAction redoAction = new RedoAction(); + + public UndoEditor() { + setLayout(new BorderLayout()); + this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + JTextPane editor = new JTextPane(); + editor.getDocument().addUndoableEditListener(new UndoListener()); + + menuBar.add(editMenu); + editMenu.add(undoAction); + editMenu.add(redoAction); + this.setJMenuBar(menuBar); + add(new JScrollPane(editor)); + setSize(400, 300); + setVisible(true); + } + + public static void main(String[] args) { + UndoEditor e = new UndoEditor(); + } + + class UndoListener implements UndoableEditListener { + public void undoableEditHappened(UndoableEditEvent e) { + undoManager.addEdit(e.getEdit()); + undoAction.update(); + redoAction.update(); + } + } + + class UndoAction extends AbstractAction { + public UndoAction() { + this.putValue(Action.NAME, undoManager.getUndoPresentationName()); + this.setEnabled(false); + } + + public void actionPerformed(ActionEvent e) { + if (this.isEnabled()) { + undoManager.undo(); + undoAction.update(); + redoAction.update(); + } + } + + public void update() { + this.putValue(Action.NAME, undoManager.getUndoPresentationName()); + this.setEnabled(undoManager.canUndo()); + } + } + + class RedoAction extends AbstractAction { + public RedoAction() { + this.putValue(Action.NAME, undoManager.getRedoPresentationName()); + this.setEnabled(false); + } + + public void actionPerformed(ActionEvent e) { + if (this.isEnabled()) { + undoManager.redo(); + undoAction.update(); + redoAction.update(); + } + } + + public void update() { + this.putValue(Action.NAME, undoManager.getRedoPresentationName()); + this.setEnabled(undoManager.canRedo()); + } + } +} diff --git a/Test/com/test/UndoExample2.java b/Test/com/test/UndoExample2.java new file mode 100644 index 0000000..8f03686 --- /dev/null +++ b/Test/com/test/UndoExample2.java @@ -0,0 +1,341 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package com.test; + +/** + * + * @author Andrew + */ + +/* +Core SWING Advanced Programming +By Kim Topley +ISBN: 0 13 083292 8 +Publisher: Prentice Hall +*/ + + +import java.awt.BorderLayout; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.InputEvent; +import java.awt.event.KeyEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.Hashtable; + +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JTextPane; +import javax.swing.KeyStroke; +import javax.swing.UIManager; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.event.UndoableEditEvent; +import javax.swing.event.UndoableEditListener; +import javax.swing.undo.CannotRedoException; +import javax.swing.undo.CannotUndoException; +import javax.swing.undo.UndoManager; +import javax.swing.undo.UndoableEdit; + +public class UndoExample2 extends JFrame { + public UndoExample2() { + super("Undo/Redo Example 2"); + + pane = new JTextPane(); + pane.setEditable(true); // Editable + getContentPane().add(new JScrollPane(pane), BorderLayout.CENTER); + + // Add a menu bar + menuBar = new JMenuBar(); + setJMenuBar(menuBar); + + // Populate the menu bar + createMenuBar(); + + // Create the undo manager and actions + UndoManager manager = new UndoManager(); + pane.getDocument().addUndoableEditListener(manager); + + Action undoAction = new UndoAction(manager); + Action redoAction = new RedoAction(manager); + + // Add the actions to buttons + JPanel panel = new JPanel(); + JButton undoButton = new JButton("Undo"); + JButton redoButton = new JButton("Redo"); + undoButton.addActionListener(undoAction); + redoButton.addActionListener(redoAction); + panel.add(undoButton); + panel.add(redoButton); + getContentPane().add(panel, BorderLayout.SOUTH); + + // Assign the actions to keys + pane.registerKeyboardAction(undoAction, KeyStroke.getKeyStroke( + KeyEvent.VK_Z, InputEvent.CTRL_MASK), JComponent.WHEN_FOCUSED); + pane.registerKeyboardAction(redoAction, KeyStroke.getKeyStroke( + KeyEvent.VK_Y, InputEvent.CTRL_MASK), JComponent.WHEN_FOCUSED); + } + + public void createMenuBar() { + // Remove the existing menu items + int count = menuBar.getMenuCount(); + for (int i = 0; i < count; i++) { + menuBar.remove(menuBar.getMenu(0)); + } + + // Build the new menu. + Action[] actions = pane.getActions(); + Hashtable actionHash = new Hashtable(); + count = actions.length; + for (int i = 0; i < count; i++) { + actionHash.put(actions[i].getValue(Action.NAME), actions[i]); + } + + // Add the font menu + JMenu menu = MenuBuilder.buildMenu("Font", fontSpec, actionHash); + if (menu != null) { + menuBar.add(menu); + } + + // Add the alignment menu + menu = MenuBuilder.buildMenu("Align", alignSpec, actionHash); + if (menu != null) { + menuBar.add(menu); + } + } + + // The Undo action + public class UndoAction extends AbstractAction { + public UndoAction(UndoManager manager) { + this.manager = manager; + } + + public void actionPerformed(ActionEvent evt) { + try { + manager.undo(); + } catch (CannotUndoException e) { + Toolkit.getDefaultToolkit().beep(); + } + } + + private UndoManager manager; + } + + // The Redo action + public class RedoAction extends AbstractAction { + public RedoAction(UndoManager manager) { + this.manager = manager; + } + + public void actionPerformed(ActionEvent evt) { + try { + manager.redo(); + } catch (CannotRedoException e) { + Toolkit.getDefaultToolkit().beep(); + } + } + + private UndoManager manager; + } + + public static void main(String[] args) { + try { + UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); + } catch (Exception evt) {} + + JFrame f = new UndoExample2(); + f.addWindowListener(new WindowAdapter() { + public void windowClosing(WindowEvent evt) { + System.exit(0); + } + }); + f.setSize(250, 300); + f.setVisible(true); + + // Create and show a frame monitoring undoable edits + JFrame undoMonitor = new JFrame("Undo Monitor"); + final JTextArea textArea = new JTextArea(); + textArea.setEditable(false); + undoMonitor.getContentPane().add(new JScrollPane(textArea)); + undoMonitor.setBounds(f.getLocation().x + f.getSize().width, f + .getLocation().y, 400, 200); + undoMonitor.setVisible(true); + + pane.getDocument().addUndoableEditListener(new UndoableEditListener() { + public void undoableEditHappened(UndoableEditEvent evt) { + UndoableEdit edit = evt.getEdit(); + textArea.append(edit.getPresentationName() + "(" + + edit.toString() + ")\n"); + } + }); + + // Create and show a frame monitoring document edits + JFrame editMonitor = new JFrame("Edit Monitor"); + final JTextArea textArea2 = new JTextArea(); + textArea2.setEditable(false); + editMonitor.getContentPane().add(new JScrollPane(textArea2)); + editMonitor.setBounds(undoMonitor.getLocation().x, undoMonitor + .getLocation().y + + undoMonitor.getSize().height, 400, 200); + editMonitor.setVisible(true); + + pane.getDocument().addDocumentListener(new DocumentListener() { + public void changedUpdate(DocumentEvent evt) { + textArea2.append("Attribute change\n"); + } + + public void insertUpdate(DocumentEvent evt) { + textArea2.append("Text insertion\n"); + } + + public void removeUpdate(DocumentEvent evt) { + textArea2.append("Text removal\n"); + } + }); + } + + private static JTextPane pane; + + private static JMenuBar menuBar; + + private static MenuSpec[] sizeSpec = new MenuSpec[] { + new MenuSpec("Size 8", "font-size-8"), + new MenuSpec("Size 10", "font-size-10"), + new MenuSpec("Size 12", "font-size-12"), + new MenuSpec("Size 14", "font-size-14"), + new MenuSpec("Size 16", "font-size-16"), + new MenuSpec("Size 18", "font-size-18"), + new MenuSpec("Size 24", "font-size-24"), + new MenuSpec("Size 36", "font-size-36"), + new MenuSpec("Size 48", "font-size-48") }; + + private static MenuSpec[] familySpec = new MenuSpec[] { + new MenuSpec("Sans Serif", "font-family-SansSerif"), + new MenuSpec("Monospaced", "font-family-Monospaced"), + new MenuSpec("Serif", "font-family-Serif") }; + + private static MenuSpec[] styleSpec = new MenuSpec[] { + new MenuSpec("Bold", "font-bold"), + new MenuSpec("Italics", "font-italic"), + new MenuSpec("Underline", "font-underline") }; + + // Menu definitions for fonts + private static MenuSpec[] fontSpec = new MenuSpec[] { + new MenuSpec("Size", sizeSpec), new MenuSpec("Family", familySpec), + new MenuSpec("Style", styleSpec) }; + + // Alignment + private static MenuSpec[] alignSpec = new MenuSpec[] { + new MenuSpec("Left", "left-justify"), + new MenuSpec("Center", "center-justify"), + new MenuSpec("Right", "right-justify") }; +} + +class MenuSpec { + public MenuSpec(String name, MenuSpec[] subMenus) { + this.name = name; + this.subMenus = subMenus; + } + + public MenuSpec(String name, String actionName) { + this.name = name; + this.actionName = actionName; + } + + public MenuSpec(String name, Action action) { + this.name = name; + this.action = action; + } + + public boolean isSubMenu() { + return subMenus != null; + } + + public boolean isAction() { + return action != null; + } + + public String getName() { + return name; + } + + public MenuSpec[] getSubMenus() { + return subMenus; + } + + public String getActionName() { + return actionName; + } + + public Action getAction() { + return action; + } + + private String name; + + private String actionName; + + private Action action; + + private MenuSpec[] subMenus; +} + +class MenuBuilder { + public static JMenu buildMenu(String name, MenuSpec[] menuSpecs, + Hashtable actions) { + int count = menuSpecs.length; + + JMenu menu = new JMenu(name); + for (int i = 0; i < count; i++) { + MenuSpec spec = menuSpecs[i]; + if (spec.isSubMenu()) { + // Recurse to handle a sub menu + JMenu subMenu = buildMenu(spec.getName(), spec.getSubMenus(), + actions); + if (subMenu != null) { + menu.add(subMenu); + } + } else if (spec.isAction()) { + // It's an Action - add it directly to the menu + menu.add(spec.getAction()); + } else { + // It's an action name - add it if possible + String actionName = spec.getActionName(); + Action targetAction = (Action) actions.get(actionName); + + // Create the menu item + JMenuItem menuItem = menu.add(spec.getName()); + if (targetAction != null) { + // The editor kit knows the action + menuItem.addActionListener(targetAction); + } else { + // Action not known - disable the menu item + menuItem.setEnabled(false); + } + } + } + + // Return null if nothing was added to the menu. + if (menu.getMenuComponentCount() == 0) { + menu = null; + } + + return menu; + } +} + + diff --git a/Test/com/test/UndoSample.java b/Test/com/test/UndoSample.java new file mode 100644 index 0000000..81e6592 --- /dev/null +++ b/Test/com/test/UndoSample.java @@ -0,0 +1,142 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package com.test; + +/** + * + * @author SIMONETO-2 + */ +/* +Definitive Guide to Swing for Java 2, Second Edition +By John Zukowski +ISBN: 1-893115-78-X +Publisher: APress +*/ + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Container; +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.JFrame; +import javax.swing.JOptionPane; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JToolBar; +import javax.swing.undo.CannotRedoException; +import javax.swing.undo.CannotUndoException; +import javax.swing.undo.UndoManager; + +public class UndoSample { + public static void main(String args[]) { + JFrame frame = new JFrame("Undo Sample"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + JTextArea textArea = new JTextArea(); + JScrollPane scrollPane = new JScrollPane(textArea); + + UndoManager manager = new UndoManager(); + textArea.getDocument().addUndoableEditListener(manager); + + JToolBar toolbar = new JToolBar(); + toolbar.add(UndoManagerHelper.getUndoAction(manager)); + toolbar.add(UndoManagerHelper.getRedoAction(manager)); + + Container content = frame.getContentPane(); + content.add(toolbar, BorderLayout.NORTH); + content.add(scrollPane, BorderLayout.CENTER); + frame.setSize(300, 150); + frame.setVisible(true); + } +} + +class UndoManagerHelper { + + public static Action getUndoAction(UndoManager manager, String label) { + return new UndoAction(manager, label); + } + + public static Action getUndoAction(UndoManager manager) { + return new UndoAction(manager, "Undo"); + } + + public static Action getRedoAction(UndoManager manager, String label) { + return new RedoAction(manager, label); + } + + public static Action getRedoAction(UndoManager manager) { + return new RedoAction(manager, "Redo"); + } + + private abstract static class UndoRedoAction extends AbstractAction { + UndoManager undoManager = new UndoManager(); + + String errorMessage = "Cannot undo"; + + String errorTitle = "Undo Problem"; + + protected UndoRedoAction(UndoManager manager, String name) { + super(name); + undoManager = manager; + } + + public void setErrorMessage(String newValue) { + errorMessage = newValue; + } + + public void setErrorTitle(String newValue) { + errorTitle = newValue; + } + + protected void showMessage(Object source) { + if (source instanceof Component) { + JOptionPane.showMessageDialog((Component) source, errorMessage, + errorTitle, JOptionPane.WARNING_MESSAGE); + } else { + System.err.println(errorMessage); + } + } + } + + public static class UndoAction extends UndoRedoAction { + public UndoAction(UndoManager manager, String name) { + super(manager, name); + setErrorMessage("Cannot undo"); + setErrorTitle("Undo Problem"); + } + + public void actionPerformed(ActionEvent actionEvent) { + try { + undoManager.undo(); + } catch (CannotUndoException cannotUndoException) { + showMessage(actionEvent.getSource()); + } + } + } + + public static class RedoAction extends UndoRedoAction { + String errorMessage = "Cannot redo"; + + String errorTitle = "Redo Problem"; + + public RedoAction(UndoManager manager, String name) { + super(manager, name); + setErrorMessage("Cannot redo"); + setErrorTitle("Redo Problem"); + } + + public void actionPerformed(ActionEvent actionEvent) { + try { + undoManager.redo(); + } catch (CannotRedoException cannotRedoException) { + showMessage(actionEvent.getSource()); + } + } + } + +} diff --git a/Test/com/test/caretDemo.java b/Test/com/test/caretDemo.java new file mode 100644 index 0000000..c0a5285 --- /dev/null +++ b/Test/com/test/caretDemo.java @@ -0,0 +1,78 @@ +package com.test; + +import java.awt.BorderLayout; +import javax.swing.*; +import javax.swing.event.*; + +public class caretDemo extends JFrame { + // Two controls, one is the editor and the other is our little status bar at the bottom. + // When we update the editor, the change in caret will update the status text field. + private JTextArea editor; + private JTextField status; + + // Start of our caretDemo class + public caretDemo() { + setTitle("Caret Demo"); + setSize(500,500); + + // Lets create a border layout to make positioning of items easy and quick. + setLayout(new BorderLayout()); + setDefaultCloseOperation(EXIT_ON_CLOSE); + + editor = new JTextArea(); + + // Add a caretListener to the editor. This is an anonymous class because it is inline and has no specific name. + editor.addCaretListener(new CaretListener() { + // Each time the caret is moved, it will trigger the listener and its method caretUpdate. + // It will then pass the event to the update method including the source of the event (which is our textarea control) + public void caretUpdate(CaretEvent e) { + JTextArea editArea = (JTextArea)e.getSource(); + + // Lets start with some default values for the line and column. + int linenum = 1; + int columnnum = 1; + + // We create a try catch to catch any exceptions. We will simply ignore such an error for our demonstration. + try { + // First we find the position of the caret. This is the number of where the caret is in relation to the start of the JTextArea + // in the upper left corner. We use this position to find offset values (eg what line we are on for the given position as well as + // what position that line starts on. + int caretpos = editArea.getCaretPosition(); + linenum = editArea.getLineOfOffset(caretpos); + + // We subtract the offset of where our line starts from the overall caret position. + // So lets say that we are on line 5 and that line starts at caret position 100, if our caret position is currently 106 + // we know that we must be on column 6 of line 5. + columnnum = caretpos - editArea.getLineStartOffset(linenum); + + // We have to add one here because line numbers start at 0 for getLineOfOffset and we want it to start at 1 for display. + linenum += 1; + } + catch(Exception ex) { } + + // Once we know the position of the line and the column, pass it to a helper function for updating the status bar. + updateStatus(linenum, columnnum); + } + }); + + // Add the fields to the layout, the editor in the middle and the status at the bottom. + add(editor, BorderLayout.CENTER); + + status = new JTextField(); + add(status, BorderLayout.SOUTH); + + // Give the status update value + updateStatus(1,1); + } + + // This helper function updates the status bar with the line number and column number. + private void updateStatus(int linenumber, int columnnumber) { + status.setText("Line: " + linenumber + " Column: " + columnnumber); + } + + // Entry point to the program. It kicks off by creating an instance of our class and making it visible. + public static void main(String args[]) { + caretDemo caretDemoApp = new caretDemo(); + caretDemoApp.setVisible(true); + } +} diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..83af757 --- /dev/null +++ b/build.xml @@ -0,0 +1,104 @@ + + + + + + + + + + + Builds, tests, and runs the project EnginePortugol. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/exemplo/Condicional.alg b/exemplo/Condicional.alg new file mode 100644 index 0000000..d6f6dc9 --- /dev/null +++ b/exemplo/Condicional.alg @@ -0,0 +1,14 @@ +algoritmo "Condicional" + +var entrada : inteiro + +inicio + escreva("Digite um numero: ") + leia(entrada) + + se entrada mod 2 = 0 entao + escreval("Esse numero e par") + senao + escreval("Esse numero e ímpar") + fimse +fimalgoritmo \ No newline at end of file diff --git a/exemplo/Entrada e Saida.alg b/exemplo/Entrada e Saida.alg new file mode 100644 index 0000000..8649dec --- /dev/null +++ b/exemplo/Entrada e Saida.alg @@ -0,0 +1,32 @@ +algoritmo "I/O - Entrada/Sainda" + +var nome : string + sexo : caracter + idade : inteiro + massa : real + +inicio + escreva("Digite seu nome: ") + leia(nome) + + escreva("Digite seu sexo (M OU F): ") + leia(sexo) + + enquanto sexo <> 'M' e sexo <> 'F' faca + escreva("Digite seu sexo (M OU F): ") + leia(sexo) + fimenquanto + + escreva("Digite sua idade: ") + leia(idade) + + escreva("Digite sua massa: ") + leia(massa) + + escreval("Seu perfil: =========================") + escreval("Seu nome: ",nome) + escreval("Seu sexo: ",sexo) + escreval("Seu idade: ",idade) + escreval("Sua massa: ",massa) + +fimalgoritmo \ No newline at end of file diff --git a/exemplo/Loop tipo enquanto.alg b/exemplo/Loop tipo enquanto.alg new file mode 100644 index 0000000..9ea2da0 --- /dev/null +++ b/exemplo/Loop tipo enquanto.alg @@ -0,0 +1,12 @@ +algoritmo "Loop - tipo enquanto" + +var loop : inteiro + +inicio + loop <- 1 + enquanto loop <= 10 faca + escreval(loop) + espere(1000) + loop <- loop + 1 + fimenquanto +fimalgoritmo \ No newline at end of file diff --git a/exemplo/Loop tipo para.alg b/exemplo/Loop tipo para.alg new file mode 100644 index 0000000..5b6f631 --- /dev/null +++ b/exemplo/Loop tipo para.alg @@ -0,0 +1,10 @@ +algoritmo "Loop - tipo para" + +var loop : inteiro + +inicio + para loop de 1 ate 10 faca + escreval(loop) + espere(1000) + fimpara +fimalgoritmo \ No newline at end of file diff --git a/fonts/Ubuntu-B.ttf b/fonts/Ubuntu-B.ttf new file mode 100644 index 0000000..c0142fe Binary files /dev/null and b/fonts/Ubuntu-B.ttf differ diff --git a/fonts/Ubuntu-BI.ttf b/fonts/Ubuntu-BI.ttf new file mode 100644 index 0000000..12e4c7d Binary files /dev/null and b/fonts/Ubuntu-BI.ttf differ diff --git a/fonts/Ubuntu-C.ttf b/fonts/Ubuntu-C.ttf new file mode 100644 index 0000000..8d3e867 Binary files /dev/null and b/fonts/Ubuntu-C.ttf differ diff --git a/fonts/Ubuntu-L.ttf b/fonts/Ubuntu-L.ttf new file mode 100644 index 0000000..7b7ac7d Binary files /dev/null and b/fonts/Ubuntu-L.ttf differ diff --git a/fonts/Ubuntu-LI.ttf b/fonts/Ubuntu-LI.ttf new file mode 100644 index 0000000..e36de45 Binary files /dev/null and b/fonts/Ubuntu-LI.ttf differ diff --git a/fonts/Ubuntu-M.ttf b/fonts/Ubuntu-M.ttf new file mode 100644 index 0000000..443ec8b Binary files /dev/null and b/fonts/Ubuntu-M.ttf differ diff --git a/fonts/Ubuntu-MI.ttf b/fonts/Ubuntu-MI.ttf new file mode 100644 index 0000000..321eccf Binary files /dev/null and b/fonts/Ubuntu-MI.ttf differ diff --git a/fonts/Ubuntu-R.ttf b/fonts/Ubuntu-R.ttf new file mode 100644 index 0000000..45a038b Binary files /dev/null and b/fonts/Ubuntu-R.ttf differ diff --git a/fonts/Ubuntu-RI.ttf b/fonts/Ubuntu-RI.ttf new file mode 100644 index 0000000..6f819f6 Binary files /dev/null and b/fonts/Ubuntu-RI.ttf differ diff --git a/fonts/UbuntuMono-B.ttf b/fonts/UbuntuMono-B.ttf new file mode 100644 index 0000000..7bd6665 Binary files /dev/null and b/fonts/UbuntuMono-B.ttf differ diff --git a/fonts/UbuntuMono-BI.ttf b/fonts/UbuntuMono-BI.ttf new file mode 100644 index 0000000..6c5b8ba Binary files /dev/null and b/fonts/UbuntuMono-BI.ttf differ diff --git a/fonts/UbuntuMono-R.ttf b/fonts/UbuntuMono-R.ttf new file mode 100644 index 0000000..fdd309d Binary files /dev/null and b/fonts/UbuntuMono-R.ttf differ diff --git a/fonts/UbuntuMono-RI.ttf b/fonts/UbuntuMono-RI.ttf new file mode 100644 index 0000000..18f81a2 Binary files /dev/null and b/fonts/UbuntuMono-RI.ttf differ diff --git a/icons/favicon.ico b/icons/favicon.ico new file mode 100644 index 0000000..d693561 Binary files /dev/null and b/icons/favicon.ico differ diff --git a/icons/image.png b/icons/image.png new file mode 100644 index 0000000..21b800e Binary files /dev/null and b/icons/image.png differ diff --git a/icons/pgeditor.ico b/icons/pgeditor.ico new file mode 100644 index 0000000..88b2852 Binary files /dev/null and b/icons/pgeditor.ico differ diff --git a/icons/pgeditor2.ico b/icons/pgeditor2.ico new file mode 100644 index 0000000..cf27725 Binary files /dev/null and b/icons/pgeditor2.ico differ diff --git a/library/Jhrome.jar b/library/Jhrome.jar new file mode 100644 index 0000000..9ca30f9 Binary files /dev/null and b/library/Jhrome.jar differ diff --git a/library/PluginManager.jar b/library/PluginManager.jar new file mode 100644 index 0000000..dcddcb0 Binary files /dev/null and b/library/PluginManager.jar differ diff --git a/library/bsh-2.0b4.jar b/library/bsh-2.0b4.jar new file mode 100644 index 0000000..36fe03d Binary files /dev/null and b/library/bsh-2.0b4.jar differ diff --git a/library/dynamicjava.jar b/library/dynamicjava.jar new file mode 100644 index 0000000..74c1f43 Binary files /dev/null and b/library/dynamicjava.jar differ diff --git a/library/filedrop.jar b/library/filedrop.jar new file mode 100644 index 0000000..36d90ca Binary files /dev/null and b/library/filedrop.jar differ diff --git a/library/java-cup-11a.jar b/library/java-cup-11a.jar new file mode 100644 index 0000000..73ffa0b Binary files /dev/null and b/library/java-cup-11a.jar differ diff --git a/library/jflex-1.5.1.jar b/library/jflex-1.5.1.jar new file mode 100644 index 0000000..4a5649a Binary files /dev/null and b/library/jflex-1.5.1.jar differ diff --git a/library/jide-oss-3.5.5.jar b/library/jide-oss-3.5.5.jar new file mode 100644 index 0000000..2dbdd96 Binary files /dev/null and b/library/jide-oss-3.5.5.jar differ diff --git a/library/jide-oss-3.6.4-sources.jar b/library/jide-oss-3.6.4-sources.jar new file mode 100644 index 0000000..fe6bf04 Binary files /dev/null and b/library/jide-oss-3.6.4-sources.jar differ diff --git a/library/jide-oss-3.6.4.jar b/library/jide-oss-3.6.4.jar new file mode 100644 index 0000000..3002b5d Binary files /dev/null and b/library/jide-oss-3.6.4.jar differ diff --git a/library/jide.jar b/library/jide.jar new file mode 100644 index 0000000..744dd90 Binary files /dev/null and b/library/jide.jar differ diff --git a/library/jsyntaxpane-0.9.5-b29.jar b/library/jsyntaxpane-0.9.5-b29.jar new file mode 100644 index 0000000..8bca1f6 Binary files /dev/null and b/library/jsyntaxpane-0.9.5-b29.jar differ diff --git a/library/jsyntaxpane-1.0.0.jar b/library/jsyntaxpane-1.0.0.jar new file mode 100644 index 0000000..cebd142 Binary files /dev/null and b/library/jsyntaxpane-1.0.0.jar differ diff --git a/library/jydocking.jar b/library/jydocking.jar new file mode 100644 index 0000000..05120b2 Binary files /dev/null and b/library/jydocking.jar differ diff --git a/library/jytable.jar b/library/jytable.jar new file mode 100644 index 0000000..2313a70 Binary files /dev/null and b/library/jytable.jar differ diff --git a/library/jywidgets.jar b/library/jywidgets.jar new file mode 100644 index 0000000..a4f1855 Binary files /dev/null and b/library/jywidgets.jar differ diff --git a/library/laf-plugin-1.1.jar b/library/laf-plugin-1.1.jar new file mode 100644 index 0000000..a1be3ee Binary files /dev/null and b/library/laf-plugin-1.1.jar differ diff --git a/library/laf-widget-7.1.jar b/library/laf-widget-7.1.jar new file mode 100644 index 0000000..580f08a Binary files /dev/null and b/library/laf-widget-7.1.jar differ diff --git a/library/pdfbox-1.8.7.jar b/library/pdfbox-1.8.7.jar new file mode 100644 index 0000000..56af660 Binary files /dev/null and b/library/pdfbox-1.8.7.jar differ diff --git a/library/preflight-app-1.8.7.jar b/library/preflight-app-1.8.7.jar new file mode 100644 index 0000000..40ba6fd Binary files /dev/null and b/library/preflight-app-1.8.7.jar differ diff --git a/library/substance-7.0.jar b/library/substance-7.0.jar new file mode 100644 index 0000000..b5005f6 Binary files /dev/null and b/library/substance-7.0.jar differ diff --git a/library/substance-7.2.1.jar b/library/substance-7.2.1.jar new file mode 100644 index 0000000..20428dd Binary files /dev/null and b/library/substance-7.2.1.jar differ diff --git a/library/swing-worker-1.1.jar b/library/swing-worker-1.1.jar new file mode 100644 index 0000000..3935611 Binary files /dev/null and b/library/swing-worker-1.1.jar differ diff --git a/library/swingx-1.6.5.jar b/library/swingx-1.6.5.jar new file mode 100644 index 0000000..0d95617 Binary files /dev/null and b/library/swingx-1.6.5.jar differ diff --git a/library/syntaxpane-1.1.4-SNAPSHOT.jar b/library/syntaxpane-1.1.4-SNAPSHOT.jar new file mode 100644 index 0000000..3f26027 Binary files /dev/null and b/library/syntaxpane-1.1.4-SNAPSHOT.jar differ diff --git a/library/synthetica.jar b/library/synthetica.jar new file mode 100644 index 0000000..f3011a8 Binary files /dev/null and b/library/synthetica.jar differ diff --git a/library/syntheticaAddons.jar b/library/syntheticaAddons.jar new file mode 100644 index 0000000..12e8153 Binary files /dev/null and b/library/syntheticaAddons.jar differ diff --git a/library/syntheticaAluOxide.jar b/library/syntheticaAluOxide.jar new file mode 100644 index 0000000..8ff5de0 Binary files /dev/null and b/library/syntheticaAluOxide.jar differ diff --git a/library/syntheticaAluOxideAddon.jar b/library/syntheticaAluOxideAddon.jar new file mode 100644 index 0000000..fecc8de Binary files /dev/null and b/library/syntheticaAluOxideAddon.jar differ diff --git a/library/syntheticaBatik.jar b/library/syntheticaBatik.jar new file mode 100644 index 0000000..4f4db1f Binary files /dev/null and b/library/syntheticaBatik.jar differ diff --git a/library/syntheticaBlackEye.jar b/library/syntheticaBlackEye.jar new file mode 100644 index 0000000..c384f4a Binary files /dev/null and b/library/syntheticaBlackEye.jar differ diff --git a/library/syntheticaSkyMetallic.jar b/library/syntheticaSkyMetallic.jar new file mode 100644 index 0000000..6a7c70b Binary files /dev/null and b/library/syntheticaSkyMetallic.jar differ diff --git a/library/syntheticaWhiteVision.jar b/library/syntheticaWhiteVision.jar new file mode 100644 index 0000000..8c317a8 Binary files /dev/null and b/library/syntheticaWhiteVision.jar differ diff --git a/library/trident.jar b/library/trident.jar new file mode 100644 index 0000000..729a771 Binary files /dev/null and b/library/trident.jar differ diff --git a/library/weblaf-complete-1.28.jar b/library/weblaf-complete-1.28.jar new file mode 100644 index 0000000..860d056 Binary files /dev/null and b/library/weblaf-complete-1.28.jar differ diff --git a/nbproject/build-impl.xml b/nbproject/build-impl.xml new file mode 100644 index 0000000..a664cd8 --- /dev/null +++ b/nbproject/build-impl.xml @@ -0,0 +1,1414 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + No tests executed. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + Must select one file in the IDE or set profile.class + This target only works when run from inside the NetBeans IDE. + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + Must select some files in the IDE or set test.includes + + + + + Must select one file in the IDE or set run.class + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + Must select some files in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + Must select one file in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/nbproject/configs/JWS_generated.properties b/nbproject/configs/JWS_generated.properties new file mode 100644 index 0000000..7a873bf --- /dev/null +++ b/nbproject/configs/JWS_generated.properties @@ -0,0 +1,4 @@ +$label=Web Start +$target.debug=jws-debug +$target.run=jws-run +compile.on.save.unsupported.javawebstart=true diff --git a/nbproject/genfiles.properties b/nbproject/genfiles.properties new file mode 100644 index 0000000..fe557f9 --- /dev/null +++ b/nbproject/genfiles.properties @@ -0,0 +1,8 @@ +build.xml.data.CRC32=da2e3cc1 +build.xml.script.CRC32=460c293c +build.xml.stylesheet.CRC32=8064a381@1.68.1.46 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=f216a456 +nbproject/build-impl.xml.script.CRC32=cde8750f +nbproject/build-impl.xml.stylesheet.CRC32=876e7a8f@1.75.1.48 diff --git a/nbproject/jnlp-impl.xml b/nbproject/jnlp-impl.xml new file mode 100644 index 0000000..d0e7703 --- /dev/null +++ b/nbproject/jnlp-impl.xml @@ -0,0 +1,771 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + javaws "${jnlp.file.resolved}" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/nbproject/private/config.properties b/nbproject/private/config.properties new file mode 100644 index 0000000..e69de29 diff --git a/nbproject/private/private.properties b/nbproject/private/private.properties new file mode 100644 index 0000000..bb0452e --- /dev/null +++ b/nbproject/private/private.properties @@ -0,0 +1,10 @@ +compile.on.save=true +do.depend=false +do.jar=true +<<<<<<< HEAD +======= +file.reference.java-cup-11a.jar=C:\\Users\\Andrew\\Documents\\NetBeansProjects\\portugol-projeto\\library\\java-cup-11a.jar +>>>>>>> 2d3fbacdccee3171131820e8448661f94c9a8ff5 +javac.debug=true +javadoc.preview=true +user.properties.file=C:\\Users\\SIMONETO-2\\AppData\\Roaming\\NetBeans\\8.0\\build.properties diff --git a/nbproject/private/private.xml b/nbproject/private/private.xml new file mode 100644 index 0000000..8d2c6ae --- /dev/null +++ b/nbproject/private/private.xml @@ -0,0 +1,10 @@ + + + + + + file:/C:/Users/SIMONETO-2/Documents/NetBeansProjects/portugol-projeto/build.xml + file:/C:/Users/SIMONETO-2/Documents/NetBeansProjects/portugol-projeto/src/com/forms/Editor.java + + + diff --git a/nbproject/private/profiler/configurations.xml b/nbproject/private/profiler/configurations.xml new file mode 100644 index 0000000..21299ea --- /dev/null +++ b/nbproject/private/profiler/configurations.xml @@ -0,0 +1,116 @@ + + + +1000 +false +profiler.simple.filter +false + +64 +true + +10 +false +true +0 +false +true +1 +false +false +false +profiler.simple.filter +32 +false +1 +true +1 +10 +1 +true +Analisar Memória +false +10 +1 +true +10 +0 +profiler.simple.filter +0 +false +true + + +1 +true + + +false +10 +false +true +false +false +32 +Filtro rápido... +false +0 +false +0 + +10 +0 +true +true + +true +10 + +1000 +0 +profiler.simple.filter +false +Analisar Performance + +1 +2 + +0 +false +profiler.simple.filter +Filtro rápido... +true +false +0 +true + +2 +false +32 + +0 +false +Perfil apenas das classes do projeto +0 +0 +profiler.simple.filter +true +1 +10 +false +false +10 +false +true +false +false +Filtro rápido... +0 +false + +128 +Aplicação do Monitor +1000 +true +true + diff --git a/nbproject/project.properties b/nbproject/project.properties new file mode 100644 index 0000000..2feae4c --- /dev/null +++ b/nbproject/project.properties @@ -0,0 +1,110 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=false +annotation.processing.processors.list= +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +ant.customtasks.libs=JWSAntTasks +application.title=EnginePortugol +application.vendor=SIMONETO-2 +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# Os arquivos em build.classes.dir que devem ser exclu\u00eddos do jar de distribui\u00e7\u00e3o +dist.archive.excludes= +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/EnginePortugol.jar +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath=\ + ${java.home}/lib/javaws.jar +excludes= +file.reference.bsh-2.0b4.jar=library/bsh-2.0b4.jar +file.reference.filedrop.jar=library\\filedrop.jar +file.reference.jflex-1.5.1.jar=library/jflex-1.5.1.jar +file.reference.Jhrome.jar=library\\Jhrome.jar +file.reference.jide-oss-3.6.4.jar=library\\jide-oss-3.6.4.jar +file.reference.preflight-app-1.8.7.jar=library\\preflight-app-1.8.7.jar +file.reference.syntaxpane-1.1.4-SNAPSHOT.jar=library\\syntaxpane-1.1.4-SNAPSHOT.jar +file.reference.weblaf-complete-1.28.jar=library\\weblaf-complete-1.28.jar +includes=** +jar.archive.disabled=${jnlp.enabled} +jar.compress=false +jar.index=${jnlp.enabled} +javac.classpath=\ + ${file.reference.bsh-2.0b4.jar}:\ + ${file.reference.jflex-1.5.1.jar}:\ + ${file.reference.filedrop.jar}:\ + ${file.reference.syntaxpane-1.1.4-SNAPSHOT.jar}:\ + ${file.reference.jide-oss-3.6.4.jar}:\ + ${file.reference.preflight-app-1.8.7.jar} +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.processorpath=\ + ${javac.classpath} +javac.source=1.7 +javac.target=1.7 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir}:\ + ${file.reference.Jhrome.jar}:\ + ${file.reference.weblaf-complete-1.28.jar} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +jnlp.codebase.type=user +jnlp.codebase.user=http://127.0.0.1/portugol +jnlp.descriptor=application +jnlp.enabled=true +jnlp.icon=C:\\Users\\SIMONETO-2\\Documents\\NetBeansProjects\\portugol-projeto\\src\\com\\images\\pgeditor.png +jnlp.mixed.code=default +jnlp.offline-allowed=true +jnlp.signed=false +jnlp.signing= +jnlp.signing.alias= +jnlp.signing.keystore= +main.class=com.forms.Editor +# Substitui\u00e7\u00e3o opcional do atributo de manifesto da Base de c\u00f3digo; use para impedir que RIAs sejam adaptados +manifest.custom.codebase= +# Substitui\u00e7\u00e3o opcional do atributo de manifesto de Permiss\u00f5es (valores suportados: sandbox, all-permissions) +manifest.custom.permissions= +manifest.file=manifest.mf +meta.inf.dir=${src.dir}/META-INF +mkdist.disabled=false +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project. +# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value. +# To set system properties for unit tests define test-sys-prop.name=value: +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=src +test.src.dir=test diff --git a/nbproject/project.xml b/nbproject/project.xml new file mode 100644 index 0000000..c36e895 --- /dev/null +++ b/nbproject/project.xml @@ -0,0 +1,21 @@ + + + org.netbeans.modules.java.j2seproject + + + + + + + + + EnginePortugol + + + + + + + + + diff --git a/src/com/classes/util/ButtonTabComponent.java b/src/com/classes/util/ButtonTabComponent.java new file mode 100644 index 0000000..b3820f7 --- /dev/null +++ b/src/com/classes/util/ButtonTabComponent.java @@ -0,0 +1,143 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.classes.util; + +/** + * + * @author SIMONETO-2 + */ +import static com.forms.Editor.enabled_menu; +import static com.forms.Editor.setting_menu; +import static com.forms.Editor.tab; +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.*; +import javax.swing.plaf.basic.BasicButtonUI; + +/** + * Component to be used as tabComponent; Contains a JLabel to show the text and + * a JButton to close the tab it belongs to + */ +public class ButtonTabComponent extends JPanel { + + private final JTabbedPane pane; + + public ButtonTabComponent(final JTabbedPane pane) { + //unset default FlowLayout' gaps + super(new FlowLayout(FlowLayout.LEFT, 0, 0)); + if (pane == null) { + throw new NullPointerException("TabbedPane is null"); + } + this.pane = pane; + setOpaque(false); + + //make JLabel read titles from JTabbedPane + JLabel label = new JLabel() { + @Override + public String getText() { + int i = pane.indexOfTabComponent(ButtonTabComponent.this); + if (i != -1) { + return pane.getTitleAt(i); + } + return null; + } + }; + + add(label); + //add more space between the label and the button + label.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); + //tab button + JButton button = new TabButton(); + add(button); + //add more space to the top of the component + setBorder(BorderFactory.createEmptyBorder(2, 0, 0, 0)); + } + + private class TabButton extends JButton implements ActionListener { + + public TabButton() { + int size = 17; + setPreferredSize(new Dimension(size, size)); + setToolTipText("Fechar"); + //Make the button looks the same for all Laf's + setUI(new BasicButtonUI()); + //Make it transparent + setContentAreaFilled(false); + //No need to be focusable + setFocusable(false); + setBorder(BorderFactory.createEtchedBorder()); + setBorderPainted(false); + //Making nice rollover effect + //we use the same listener for all buttons + addMouseListener(buttonMouseListener); + setRolloverEnabled(true); + //Close the proper tab by clicking the button + addActionListener(this); + } + + @Override + public void actionPerformed(ActionEvent e) { + int i = pane.indexOfTabComponent(ButtonTabComponent.this); + if (i != -1) { + System.out.println("Aba fechada com sucesso. ID:"+tab.getIdTab(i)); + pane.remove(i); + if (tab.getTabCount() == 0) { + //VERIFICANDO SE O MENU ESTA HABILITADO + if (enabled_menu == true) { + enabled_menu = false; + } + setting_menu.setDisabledTop(enabled_menu); + } + } + } + + //we don't want to update UI for this button + @Override + public void updateUI() { + } + + //paint the cross + @Override + protected void paintComponent(Graphics g) { + super.paintComponent(g); + Graphics2D g2 = (Graphics2D) g.create(); + //shift the image for pressed buttons + if (getModel().isPressed()) { + g2.translate(1, 1); + } + g2.setStroke(new BasicStroke(2)); + g2.setColor(Color.BLACK); + if (getModel().isRollover()) { + g2.setColor(Color.decode("#8f908a")); + } + int delta = 6; + g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta - 1); + g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta - 1); + g2.dispose(); + } + } + + private final static MouseListener buttonMouseListener = new MouseAdapter() { + @Override + public void mouseEntered(MouseEvent e) { + Component component = e.getComponent(); + if (component instanceof AbstractButton) { + AbstractButton button = (AbstractButton) component; + button.setBorderPainted(true); + } + } + + @Override + public void mouseExited(MouseEvent e) { + Component component = e.getComponent(); + if (component instanceof AbstractButton) { + AbstractButton button = (AbstractButton) component; + button.setBorderPainted(false); + } + } + }; +} diff --git a/src/com/classes/util/ExportPDF.java b/src/com/classes/util/ExportPDF.java new file mode 100644 index 0000000..7dbe2ea --- /dev/null +++ b/src/com/classes/util/ExportPDF.java @@ -0,0 +1,160 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.classes.util; + +import static com.forms.Editor.msg; +import static com.forms.Editor.tab; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.List; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.JFileChooser; +import javax.swing.JMenuItem; +import javax.swing.JOptionPane; +import javax.swing.filechooser.FileFilter; +import javax.swing.filechooser.FileNameExtensionFilter; +import org.apache.pdfbox.exceptions.COSVisitorException; +import org.apache.pdfbox.pdmodel.PDDocument; +import org.apache.pdfbox.pdmodel.PDPage; +import org.apache.pdfbox.pdmodel.common.PDRectangle; +import org.apache.pdfbox.pdmodel.edit.PDPageContentStream; +import org.apache.pdfbox.pdmodel.font.PDFont; +import org.apache.pdfbox.pdmodel.font.PDType1Font; + +/** + * + * @author SIMONETO-2 + */ +public class ExportPDF { + + private JMenuItem t; + + public ExportPDF(JMenuItem t) { + try { + this.t = t; + export(); + } catch (IOException | COSVisitorException ex) { + Logger.getLogger(ExportPDF.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public void export() throws FileNotFoundException, IOException, COSVisitorException { + //ABRINDO CHOOSE PARA SALVAR ARQUIVO + JFileChooser SavedFile = new JFileChooser(); + SavedFile.setAcceptAllFileFilterUsed(false); + FileFilter ft = new FileNameExtensionFilter("Salvar como arquivo pdf *.pdf", "pdf"); + SavedFile.addChoosableFileFilter(ft); + SavedFile.setDialogTitle("Aonde você deseja salvar o seu algoritmo ?"); + + //VARIAVEL DE RETORNO + int returnVal = SavedFile.showSaveDialog(t); + + //ABRINDO DIALOGO PARA SALVAR ARQUIVO CRIPTOGRAFADO + if (returnVal == JFileChooser.APPROVE_OPTION) { + File salvar_arquivo = SavedFile.getSelectedFile(); + + //VERIFICANDO SE O ARQUIVO EXISTE PARA O REPLACE + if (salvar_arquivo.exists()) { + int result = JOptionPane.showConfirmDialog(null, "O arquivo que você está tentando salvar já existe. \nDeseja substituir esse arquivo?", "Alerta", JOptionPane.YES_NO_CANCEL_OPTION); + if (result == JOptionPane.NO_OPTION) { + export(); + return; + } + } + + //TRATANDO DO NOME + String nome = salvar_arquivo.toString(); + + //VERIFICA SE JA EXISTE O .ALG NO NOME + if (!nome.endsWith(".pdf")) { + nome = nome + ".pdf"; + } + + //MODIFICANDO NOME + salvar_arquivo = new File(nome); + + //APAGAR CONTEU DO ARQUIVO + PrintWriter clean = new PrintWriter(salvar_arquivo); + clean.print(""); + clean.close(); + + generatePDF(salvar_arquivo); + } + } + + public void generatePDF(File file) throws IOException, COSVisitorException { + PDDocument doc = null; + try { + doc = new PDDocument(); + PDPage page = new PDPage(); + doc.addPage(page); + PDPageContentStream contentStream = new PDPageContentStream(doc, page); + + PDFont pdfFont = PDType1Font.HELVETICA; + float fontSize = 15; + float leading = 1.5f * fontSize; + + PDRectangle mediabox = page.findMediaBox(); + float margin = 72; + float width = mediabox.getWidth() - 2 * margin; + float startX = mediabox.getLowerLeftX() + margin; + float startY = mediabox.getUpperRightY() - margin; + + String text[] = tab.getEditorPane().getText().split("\\n"); + + List lines = new ArrayList<>(); + int lastSpace = -1; + + for(int i = 0; i 0) { + int spaceIndex = text[i].indexOf(' ', lastSpace + 1); + if (spaceIndex < 0) { + lines.add(text[i]); + text[i] = ""; + } else { + String subString = text[i].substring(0, spaceIndex); + float size = fontSize * pdfFont.getStringWidth(subString) / 1000; + if (size > width) { + if (lastSpace < 0) // So we have a word longer than the line... draw it anyways + { + lastSpace = spaceIndex; + } + subString = text[i].substring(0, lastSpace); + lines.add(subString); + text[i] = text[i].substring(lastSpace).trim(); + lastSpace = -1; + } else { + lastSpace = spaceIndex; + } + } + } + } + + contentStream.beginText(); + contentStream.setFont(pdfFont, fontSize); + contentStream.moveTextPositionByAmount(startX, startY); + for (String line : lines) { + contentStream.drawString(line); + contentStream.moveTextPositionByAmount(0, -leading); + } + contentStream.endText(); + contentStream.close(); + + doc.save(file); + System.out.println("Algoritmo exportado com sucesso. "+file.getPath()); + msg.write("PDF gerado com sucedo, em: "+file.getPath()); + } finally { + if (doc != null) { + doc.close(); + } + } + } + +} diff --git a/src/com/classes/util/FilesOpens.java b/src/com/classes/util/FilesOpens.java new file mode 100644 index 0000000..7e7e695 --- /dev/null +++ b/src/com/classes/util/FilesOpens.java @@ -0,0 +1,121 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.classes.util; + +import java.util.ArrayList; + +/** + * + * @author Andrew + */ +public class FilesOpens { + + ArrayList ArrayFilesOpens = new ArrayList<>(); + + /* + * TABELA DE INFORMACOES + * 0 - ID + * 1 - TEXT_PANE NAME + * 2 - DIRETORIO + */ + public void addFileOpen(int id, String text_pane_name, String diretory) { + //ARMAZENANDO NA ARRAY TEMPORARIA + String[] tmp = {"" + id, text_pane_name, diretory}; + //ADICINANDO NA ARRAY PRINCIPAIS + ArrayFilesOpens.add(tmp); + + System.out.println("Total de arquivos abertos: " + ArrayFilesOpens.size()); + } + + public String[] getInfo(String jTextPane) { + String[] info = new String[4]; + int position = 0; + + for (String[] FilesOpen : ArrayFilesOpens) { + if (FilesOpen[1].equals(jTextPane)) { + String[] retorno = {FilesOpen[0], FilesOpen[1], FilesOpen[2], "" + position}; + info = retorno; + break; + } + position++; + } + return info; + } + + public int getPositionItem(String diretory) { + int position = 0; + for (String[] FilesOpen : ArrayFilesOpens) { + if (FilesOpen[2].equals(diretory)) { + break; + } + position++; + } + return position; + } + + public int getPositionItem(int id) { + int position = 0; + for (String[] FilesOpen : ArrayFilesOpens) { + if (FilesOpen[0].equals(""+id)) { + break; + } + position++; + } + return position; + } + + public String[] getInfo(int id) { + String[] info = new String[4]; + int position = 0; + + for (String[] FilesOpen : ArrayFilesOpens) { + if (FilesOpen[0].equals("" + id)) { + String[] retorno = {FilesOpen[0], FilesOpen[1], FilesOpen[2], "" + position}; + info = retorno; + break; + } + position++; + } + return info; + } + + public boolean isExisting(String jTextPane) { + boolean response = false; + String[] info = getInfo(jTextPane); + System.out.println(info[1]); + if (!"".equals(info[1])) { + response = true; + } + return response; + } + + public boolean isExistingOpen(String location) { + boolean response = false; + + for (String[] FilesOpen : ArrayFilesOpens) { + if (FilesOpen[2].equals(location)) { + response = true; + break; + } + } + return response; + } + + public void updateDir(String id, String value) { + String[] info = getInfo(id); + + int position = Integer.parseInt(info[3]); + ArrayFilesOpens.get(position)[2] = value; + + } + + public void unistall(int id) { + String[] info = getInfo(id); + + int position = Integer.parseInt(info[3]); + ArrayFilesOpens.remove(position); + } +} diff --git a/src/com/classes/util/JFontChooser.java b/src/com/classes/util/JFontChooser.java new file mode 100644 index 0000000..bd36752 --- /dev/null +++ b/src/com/classes/util/JFontChooser.java @@ -0,0 +1,818 @@ +/************************************************************ + * Copyright 2004-2005,2007-2008 Masahiko SAWAI All Rights Reserved. + ************************************************************/ +package com.classes.util; + +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.Font; +import java.awt.Frame; +import java.awt.GraphicsEnvironment; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.MissingResourceException; +import java.util.ResourceBundle; +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.ActionMap; +import javax.swing.BorderFactory; +import javax.swing.BoxLayout; +import javax.swing.InputMap; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextField; +import javax.swing.KeyStroke; +import javax.swing.ListSelectionModel; +import javax.swing.SwingUtilities; +import javax.swing.border.Border; +import javax.swing.event.DocumentEvent; +import javax.swing.event.DocumentListener; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.ListSelectionListener; +import javax.swing.text.BadLocationException; +import javax.swing.text.Document; +import javax.swing.text.JTextComponent; +import javax.swing.text.Position; + +/** + * The JFontChooser class is a swing component + * for font selection. + * This class has JFileChooser like APIs. + * The following code pops up a font chooser dialog. + *
        + *   JFontChooser fontChooser = new JFontChooser();
        + *   int result = fontChooser.showDialog(parent);
        + *   if (result == JFontChooser.OK_OPTION)
        + *   {
        + *      Font font = fontChooser.getSelectedFont(); 
        + *      System.out.println("Selected Font : " + font); 
        + *   }
        + * 
        + **/
        +public class JFontChooser extends JComponent
        +{
        +    // class variables
        +    /**
        +     * Return value from showDialog().
        +     * @see #showDialog
        +     **/
        +    public static final int OK_OPTION = 0;
        +    /**
        +     * Return value from showDialog().
        +     * @see #showDialog
        +     **/
        +    public static final int CANCEL_OPTION = 1;
        +    /**
        +     * Return value from showDialog().
        +     * @see #showDialog
        +     **/
        +    //new java.awt.Font("Tahoma", 1, 11)
        +    public static final int ERROR_OPTION = -1;
        +    private static final Font DEFAULT_SELECTED_FONT = new Font("Tahoma", Font.PLAIN, 11);
        +    private static final Font DEFAULT_FONT = new Font("Tahoma", Font.PLAIN, 11);
        +    private static final int[] FONT_STYLE_CODES =
        +    {
        +        Font.PLAIN, Font.BOLD, Font.ITALIC, Font.BOLD | Font.ITALIC
        +    };
        +    private static final String[] DEFAULT_FONT_SIZE_STRINGS =
        +    {
        +        "8", "9", "10", "11", "12", "14", "16", "18", "20",
        +        "22", "24", "26", "28", "36", "48", "72",
        +    };
        +
        +    // instance variables
        +    protected int dialogResultValue = ERROR_OPTION;
        +
        +
        +
        +    private String[] fontStyleNames = null;
        +    private String[] fontFamilyNames = null;
        +    private String[] fontSizeStrings = null;
        +    private JTextField fontFamilyTextField = null;
        +    private JTextField fontStyleTextField = null;
        +    private JTextField fontSizeTextField = null;
        +    private JList fontNameList = null;
        +    private JList fontStyleList = null;
        +    private JList fontSizeList = null;
        +    private JPanel fontNamePanel = null;
        +    private JPanel fontStylePanel = null;
        +    private JPanel fontSizePanel = null;
        +    private JPanel samplePanel = null;
        +    private JTextField sampleText = null;
        +
        +    /**
        +     * Constructs a JFontChooser object.
        +     **/
        +    public JFontChooser()
        +    {
        +        this(DEFAULT_FONT_SIZE_STRINGS);
        +    }
        +
        +    /**
        +     * Constructs a JFontChooser object using the given font size array.
        +     * @param fontSizeStrings  the array of font size string.
        +     **/
        +    public JFontChooser(String[] fontSizeStrings)
        +    {
        +        if (fontSizeStrings == null)
        +        {
        +            fontSizeStrings = DEFAULT_FONT_SIZE_STRINGS;
        +        }
        +        this.fontSizeStrings = fontSizeStrings;
        +
        +        JPanel selectPanel = new JPanel();
        +        selectPanel.setLayout(new BoxLayout(selectPanel, BoxLayout.X_AXIS));
        +        selectPanel.add(getFontFamilyPanel());
        +        //selectPanel.add(getFontStylePanel());
        +        selectPanel.add(getFontSizePanel());
        +
        +        JPanel contentsPanel = new JPanel();
        +        contentsPanel.setLayout(new GridLayout(2, 1));
        +        contentsPanel.add(selectPanel, BorderLayout.NORTH);
        +        contentsPanel.add(getSamplePanel(), BorderLayout.CENTER);
        +
        +        this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
        +        this.add(contentsPanel);
        +        this.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        +        this.setSelectedFont(DEFAULT_SELECTED_FONT);
        +    }
        +
        +    public JTextField getFontFamilyTextField()
        +    {
        +        if (fontFamilyTextField == null)
        +        {
        +            fontFamilyTextField = new JTextField();
        +            fontFamilyTextField.addFocusListener(
        +                new TextFieldFocusHandlerForTextSelection(fontFamilyTextField));
        +            fontFamilyTextField.addKeyListener(
        +                new TextFieldKeyHandlerForListSelectionUpDown(getFontFamilyList()));
        +            fontFamilyTextField.getDocument().addDocumentListener(
        +                new ListSearchTextFieldDocumentHandler(getFontFamilyList()));
        +            fontFamilyTextField.setFont(DEFAULT_FONT);
        +
        +        }
        +        return fontFamilyTextField;
        +    }
        +
        +    public JTextField getFontStyleTextField()
        +    {
        +        if (fontStyleTextField == null)
        +        {
        +            fontStyleTextField = new JTextField();
        +            fontStyleTextField.addFocusListener(
        +                new TextFieldFocusHandlerForTextSelection(fontStyleTextField));
        +            fontStyleTextField.addKeyListener(
        +                new TextFieldKeyHandlerForListSelectionUpDown(getFontStyleList()));
        +            fontStyleTextField.getDocument().addDocumentListener(
        +                new ListSearchTextFieldDocumentHandler(getFontStyleList()));
        +            fontStyleTextField.setFont(DEFAULT_FONT);
        +        }
        +        return fontStyleTextField;
        +    }
        +
        +    public JTextField getFontSizeTextField()
        +    {
        +        if (fontSizeTextField == null)
        +        {
        +            fontSizeTextField = new JTextField();
        +            fontSizeTextField.addFocusListener(
        +                new TextFieldFocusHandlerForTextSelection(fontSizeTextField));
        +            fontSizeTextField.addKeyListener(
        +                new TextFieldKeyHandlerForListSelectionUpDown(getFontSizeList()));
        +            fontSizeTextField.getDocument().addDocumentListener(
        +                new ListSearchTextFieldDocumentHandler(getFontSizeList()));
        +            fontSizeTextField.setFont(DEFAULT_FONT);
        +        }
        +        return fontSizeTextField;
        +    }
        +
        +    public JList getFontFamilyList()
        +    {
        +        if (fontNameList == null)
        +        {
        +            fontNameList = new JList(getFontFamilies());
        +            fontNameList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        +            fontNameList.addListSelectionListener(
        +                new ListSelectionHandler(getFontFamilyTextField()));
        +            fontNameList.setSelectedIndex(0);
        +            fontNameList.setFont(DEFAULT_FONT);
        +            fontNameList.setFocusable(false);
        +        }
        +        return fontNameList;
        +    }
        +
        +    public JList getFontStyleList()
        +    {
        +        if (fontStyleList == null)
        +        {
        +            fontStyleList = new JList(getFontStyleNames());
        +            fontStyleList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        +            fontStyleList.addListSelectionListener(
        +                new ListSelectionHandler(getFontStyleTextField()));
        +            fontStyleList.setSelectedIndex(0);
        +            fontStyleList.setFont(DEFAULT_FONT);
        +            fontStyleList.setFocusable(false);
        +        }
        +        return fontStyleList;
        +    }
        +
        +    public JList getFontSizeList()
        +    {
        +        if (fontSizeList == null)
        +        {
        +            fontSizeList = new JList(this.fontSizeStrings);
        +            fontSizeList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        +            fontSizeList.addListSelectionListener(
        +                new ListSelectionHandler(getFontSizeTextField()));
        +            fontSizeList.setSelectedIndex(0);
        +            fontSizeList.setFont(DEFAULT_FONT);
        +            fontSizeList.setFocusable(false);
        +        }
        +        return fontSizeList;
        +    }
        +
        +    /**
        +     * Get the family name of the selected font.
        +     * @return  the font family of the selected font.
        +     *
        +     * @see #setSelectedFontFamily
        +     **/
        +    public String getSelectedFontFamily()
        +    {
        +        String fontName = (String) getFontFamilyList().getSelectedValue();
        +        return fontName;
        +    }
        +
        +    /**
        +     * Get the style of the selected font.
        +     * @return  the style of the selected font.
        +     *          Font.PLAIN, Font.BOLD,
        +     *          Font.ITALIC, Font.BOLD|Font.ITALIC
        +     *
        +     * @see java.awt.Font#PLAIN
        +     * @see java.awt.Font#BOLD
        +     * @see java.awt.Font#ITALIC
        +     * @see #setSelectedFontStyle
        +     **/
        +    public int getSelectedFontStyle()
        +    {
        +        int index = getFontStyleList().getSelectedIndex();
        +        return FONT_STYLE_CODES[index];
        +    }
        +
        +    /**
        +     * Get the size of the selected font.
        +     * @return  the size of the selected font
        +     *
        +     * @see #setSelectedFontSize
        +     **/
        +    public int getSelectedFontSize()
        +    {
        +        int fontSize = 1;
        +        String fontSizeString = getFontSizeTextField().getText();
        +        while (true)
        +        {
        +            try
        +            {
        +                fontSize = Integer.parseInt(fontSizeString);
        +                break;
        +            }
        +            catch (NumberFormatException e)
        +            {
        +                fontSizeString = (String) getFontSizeList().getSelectedValue();
        +                getFontSizeTextField().setText(fontSizeString);
        +            }
        +        }
        +
        +        return fontSize;
        +    }
        +
        +    /**
        +     * Get the selected font.
        +     * @return  the selected font
        +     *
        +     * @see #setSelectedFont
        +     * @see java.awt.Font
        +     **/
        +    public Font getSelectedFont()
        +    {
        +        Font font = new Font(getSelectedFontFamily(),
        +            getSelectedFontStyle(), getSelectedFontSize());
        +        return font;
        +    }
        +
        +    /**
        +     * Set the family name of the selected font.
        +     * @param name  the family name of the selected font. 
        +     *
        +     * @see getSelectedFontFamily
        +     **/
        +    public void setSelectedFontFamily(String name)
        +    {
        +        String[] names = getFontFamilies();
        +        for (int i = 0; i < names.length; i++)
        +        {
        +            if (names[i].toLowerCase().equals(name.toLowerCase()))
        +            {
        +                getFontFamilyList().setSelectedIndex(i);
        +                break;
        +            }
        +        }
        +        updateSampleFont();
        +    }
        +
        +    /**
        +     * Set the style of the selected font.
        +     * @param style  the size of the selected font.
        +     *               Font.PLAIN, Font.BOLD,
        +     *               Font.ITALIC, or
        +     *               Font.BOLD|Font.ITALIC.
        +     *
        +     * @see java.awt.Font#PLAIN
        +     * @see java.awt.Font#BOLD
        +     * @see java.awt.Font#ITALIC
        +     * @see #getSelectedFontStyle
        +     **/
        +    public void setSelectedFontStyle(int style)
        +    {
        +        for (int i = 0; i < FONT_STYLE_CODES.length; i++)
        +        {
        +            if (FONT_STYLE_CODES[i] == style)
        +            {
        +                getFontStyleList().setSelectedIndex(i);
        +                break;
        +            }
        +        }
        +        updateSampleFont();
        +    }
        +
        +    /**
        +     * Set the size of the selected font.
        +     * @param size the size of the selected font
        +     *
        +     * @see #getSelectedFontSize
        +     **/
        +    public void setSelectedFontSize(int size)
        +    {
        +        String sizeString = String.valueOf(size);
        +        for (int i = 0; i < this.fontSizeStrings.length; i++)
        +        {
        +            if (this.fontSizeStrings[i].equals(sizeString))
        +            {
        +                getFontSizeList().setSelectedIndex(i);
        +                break;
        +            }
        +        }
        +        getFontSizeTextField().setText(sizeString);
        +        updateSampleFont();
        +    }
        +
        +    /**
        +     * Set the selected font.
        +     * @param font the selected font
        +     *
        +     * @see #getSelectedFont
        +     * @see java.awt.Font
        +     **/
        +    public void setSelectedFont(Font font)
        +    {
        +        setSelectedFontFamily(font.getFamily());
        +        setSelectedFontStyle(font.getStyle());
        +        setSelectedFontSize(font.getSize());
        +    }
        +
        +    public String getVersionString()
        +    {
        +        return ("Version");
        +    }
        +
        +    /**
        +     *  Show font selection dialog.
        +     *  @param parent Dialog's Parent component.
        +     *  @return OK_OPTION, CANCEL_OPTION or ERROR_OPTION
        +     *
        +     *  @see #OK_OPTION 
        +     *  @see #CANCEL_OPTION
        +     *  @see #ERROR_OPTION
        +     **/
        +    public int showDialog(Component parent)
        +    {
        +        dialogResultValue = ERROR_OPTION;
        +        JDialog dialog = createDialog(parent);
        +        dialog.addWindowListener(new WindowAdapter()
        +        {
        +            public void windowClosing(WindowEvent e)
        +            {
        +                dialogResultValue = CANCEL_OPTION;
        +            }
        +        });
        +
        +        dialog.setVisible(true);
        +        dialog.dispose();
        +        dialog = null;
        +
        +        return dialogResultValue;
        +    }
        +
        +    protected class ListSelectionHandler implements ListSelectionListener
        +    {
        +        private JTextComponent textComponent;
        +
        +        ListSelectionHandler(JTextComponent textComponent)
        +        {
        +            this.textComponent = textComponent;
        +        }
        +
        +        public void valueChanged(ListSelectionEvent e)
        +        {
        +            if (e.getValueIsAdjusting() == false)
        +            {
        +                JList list = (JList) e.getSource();
        +                String selectedValue = (String) list.getSelectedValue();
        +
        +                String oldValue = textComponent.getText();
        +                textComponent.setText(selectedValue);
        +                if (!oldValue.equalsIgnoreCase(selectedValue))
        +                {
        +                    textComponent.selectAll();
        +                    textComponent.requestFocus();
        +                }
        +
        +                updateSampleFont();
        +            }
        +        }
        +    }
        +
        +    protected class TextFieldFocusHandlerForTextSelection extends FocusAdapter
        +    {
        +        private JTextComponent textComponent;
        +
        +        public TextFieldFocusHandlerForTextSelection(JTextComponent textComponent)
        +        {
        +            this.textComponent = textComponent;
        +        }
        +
        +        public void focusGained(FocusEvent e)
        +        {
        +            textComponent.selectAll();
        +        }
        +
        +        public void focusLost(FocusEvent e)
        +        {
        +            textComponent.select(0, 0);
        +            updateSampleFont();
        +        }
        +    }
        +
        +    protected class TextFieldKeyHandlerForListSelectionUpDown extends KeyAdapter
        +    {
        +        private JList targetList;
        +
        +        public TextFieldKeyHandlerForListSelectionUpDown(JList list)
        +        {
        +            this.targetList = list;
        +        }
        +
        +        public void keyPressed(KeyEvent e)
        +        {
        +            int i = targetList.getSelectedIndex();
        +            switch (e.getKeyCode())
        +            {
        +                case KeyEvent.VK_UP:
        +                    i = targetList.getSelectedIndex() - 1;
        +                    if (i < 0)
        +                    {
        +                        i = 0;
        +                    }
        +                    targetList.setSelectedIndex(i);
        +                    break;
        +                case KeyEvent.VK_DOWN:
        +                    int listSize = targetList.getModel().getSize();
        +                    i = targetList.getSelectedIndex() + 1;
        +                    if (i >= listSize)
        +                    {
        +                        i = listSize - 1;
        +                    }
        +                    targetList.setSelectedIndex(i);
        +                    break;
        +                default:
        +                    break;
        +            }
        +        }
        +    }
        +
        +    protected class ListSearchTextFieldDocumentHandler implements DocumentListener
        +    {
        +        JList targetList;
        +
        +        public ListSearchTextFieldDocumentHandler(JList targetList)
        +        {
        +            this.targetList = targetList;
        +        }
        +
        +        public void insertUpdate(DocumentEvent e)
        +        {
        +            update(e);
        +        }
        +
        +        public void removeUpdate(DocumentEvent e)
        +        {
        +            update(e);
        +        }
        +
        +        public void changedUpdate(DocumentEvent e)
        +        {
        +            update(e);
        +        }
        +
        +        private void update(DocumentEvent event)
        +        {
        +            String newValue = "";
        +            try
        +            {
        +                Document doc = event.getDocument();
        +                newValue = doc.getText(0, doc.getLength());
        +            }
        +            catch (BadLocationException e)
        +            {
        +                e.printStackTrace();
        +            }
        +
        +            if (newValue.length() > 0)
        +            {
        +                int index = targetList.getNextMatch(newValue, 0, Position.Bias.Forward);
        +                if (index < 0)
        +                {
        +                    index = 0;
        +                }
        +                targetList.ensureIndexIsVisible(index);
        +
        +                String matchedName = targetList.getModel().getElementAt(index).toString();
        +                if (newValue.equalsIgnoreCase(matchedName))
        +                {
        +                    if (index != targetList.getSelectedIndex())
        +                    {
        +                        SwingUtilities.invokeLater(new ListSelector(index));
        +                    }
        +                }
        +            }
        +        }
        +
        +        public class ListSelector implements Runnable
        +        {
        +            private int index;
        +
        +            public ListSelector(int index)
        +            {
        +                this.index = index;
        +            }
        +
        +            public void run()
        +            {
        +                targetList.setSelectedIndex(this.index);
        +            }
        +        }
        +    }
        +
        +    protected class DialogOKAction extends AbstractAction
        +    {
        +        protected static final String ACTION_NAME = "OK";
        +        private JDialog dialog;
        +
        +        protected DialogOKAction(JDialog dialog)
        +        {
        +            this.dialog = dialog;
        +            putValue(Action.DEFAULT, ACTION_NAME);
        +            putValue(Action.ACTION_COMMAND_KEY, ACTION_NAME);
        +            putValue(Action.NAME, (ACTION_NAME));
        +        }
        +
        +        public void actionPerformed(ActionEvent e)
        +        {
        +            dialogResultValue = OK_OPTION;
        +            dialog.setVisible(false);
        +        }
        +    }
        +
        +    protected class DialogCancelAction extends AbstractAction
        +    {
        +        protected static final String ACTION_NAME = "Cancel";
        +        private JDialog dialog;
        +
        +        protected DialogCancelAction(JDialog dialog)
        +        {
        +            this.dialog = dialog;
        +            putValue(Action.DEFAULT, ACTION_NAME);
        +            putValue(Action.ACTION_COMMAND_KEY, ACTION_NAME);
        +            putValue(Action.NAME, (ACTION_NAME));
        +        }
        +
        +        public void actionPerformed(ActionEvent e)
        +        {
        +            dialogResultValue = CANCEL_OPTION;
        +            dialog.setVisible(false);
        +        }
        +    }
        +
        +    protected JDialog createDialog(Component parent)
        +    {
        +        Frame frame = parent instanceof Frame ? (Frame) parent
        +            : (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent);
        +        JDialog dialog = new JDialog(frame, ("Seletor de fonte"), true);
        +
        +        Action okAction = new DialogOKAction(dialog);
        +        Action cancelAction = new DialogCancelAction(dialog);
        +
        +        JButton okButton = new JButton(okAction);
        +        okButton.setFont(DEFAULT_FONT);
        +        JButton cancelButton = new JButton(cancelAction);
        +        cancelButton.setFont(DEFAULT_FONT);
        +
        +        JPanel buttonsPanel = new JPanel();
        +        buttonsPanel.setLayout(new GridLayout(2, 1));
        +        buttonsPanel.add(okButton);
        +        buttonsPanel.add(cancelButton);
        +        buttonsPanel.setBorder(BorderFactory.createEmptyBorder(25, 0, 10, 10));
        +
        +        ActionMap actionMap = buttonsPanel.getActionMap();
        +        actionMap.put(cancelAction.getValue(Action.DEFAULT), cancelAction);
        +        actionMap.put(okAction.getValue(Action.DEFAULT), okAction);
        +        InputMap inputMap = buttonsPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
        +        inputMap.put(KeyStroke.getKeyStroke("ESCAPE"), cancelAction.getValue(Action.DEFAULT));
        +        inputMap.put(KeyStroke.getKeyStroke("ENTER"), okAction.getValue(Action.DEFAULT));
        +
        +        JPanel dialogEastPanel = new JPanel();
        +        dialogEastPanel.setLayout(new BorderLayout());
        +        dialogEastPanel.add(buttonsPanel, BorderLayout.NORTH);
        +
        +        dialog.getContentPane().add(this, BorderLayout.CENTER);
        +        dialog.getContentPane().add(dialogEastPanel, BorderLayout.EAST);
        +        dialog.pack();
        +        dialog.setLocationRelativeTo(frame);
        +        return dialog;
        +    }
        +
        +    protected void updateSampleFont()
        +    {
        +        Font font = getSelectedFont();
        +        getSampleTextField().setFont(font);
        +    }
        +
        +    protected JPanel getFontFamilyPanel()
        +    {
        +        if (fontNamePanel == null)
        +        {
        +            fontNamePanel = new JPanel();
        +            fontNamePanel.setLayout(new BorderLayout());
        +            fontNamePanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        +            fontNamePanel.setPreferredSize(new Dimension(180, 130));
        +
        +            JScrollPane scrollPane = new JScrollPane(getFontFamilyList());
        +            scrollPane.getVerticalScrollBar().setFocusable(false);
        +            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        +
        +            JPanel p = new JPanel();
        +            p.setLayout(new BorderLayout());
        +            p.add(getFontFamilyTextField(), BorderLayout.NORTH);
        +            p.add(scrollPane, BorderLayout.CENTER);
        +
        +            JLabel label = new JLabel(("Nome da fonte"));
        +            label.setHorizontalAlignment(JLabel.LEFT);
        +            label.setHorizontalTextPosition(JLabel.LEFT);
        +            label.setLabelFor(getFontFamilyTextField());
        +            label.setDisplayedMnemonic('F');
        +
        +            fontNamePanel.add(label, BorderLayout.NORTH);
        +            fontNamePanel.add(p, BorderLayout.CENTER);
        +
        +        }
        +        return fontNamePanel;
        +    }
        +
        +    protected JPanel getFontStylePanel()
        +    {
        +        if (fontStylePanel == null)
        +        {
        +            fontStylePanel = new JPanel();
        +            fontStylePanel.setLayout(new BorderLayout());
        +            fontStylePanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        +            fontStylePanel.setPreferredSize(new Dimension(140, 130));
        +
        +            JScrollPane scrollPane = new JScrollPane(getFontStyleList());
        +            scrollPane.getVerticalScrollBar().setFocusable(false);
        +            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        +
        +            JPanel p = new JPanel();
        +            p.setLayout(new BorderLayout());
        +            p.add(getFontStyleTextField(), BorderLayout.NORTH);
        +            p.add(scrollPane, BorderLayout.CENTER);
        +
        +            JLabel label = new JLabel(("Font Style"));
        +            label.setHorizontalAlignment(JLabel.LEFT);
        +            label.setHorizontalTextPosition(JLabel.LEFT);
        +            label.setLabelFor(getFontStyleTextField());
        +            label.setDisplayedMnemonic('Y');
        +
        +            fontStylePanel.add(label, BorderLayout.NORTH);
        +            fontStylePanel.add(p, BorderLayout.CENTER);
        +        }
        +        return fontStylePanel;
        +    }
        +
        +    protected JPanel getFontSizePanel()
        +    {
        +        if (fontSizePanel == null)
        +        {
        +            fontSizePanel = new JPanel();
        +            fontSizePanel.setLayout(new BorderLayout());
        +            fontSizePanel.setPreferredSize(new Dimension(70, 130));
        +            fontSizePanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        +
        +            JScrollPane scrollPane = new JScrollPane(getFontSizeList());
        +            scrollPane.getVerticalScrollBar().setFocusable(false);
        +            scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        +
        +            JPanel p = new JPanel();
        +            p.setLayout(new BorderLayout());
        +            p.add(getFontSizeTextField(), BorderLayout.NORTH);
        +            p.add(scrollPane, BorderLayout.CENTER);
        +
        +            JLabel label = new JLabel(("Tamanho da fonte"));
        +            label.setHorizontalAlignment(JLabel.LEFT);
        +            label.setHorizontalTextPosition(JLabel.LEFT);
        +            label.setLabelFor(getFontSizeTextField());
        +            label.setDisplayedMnemonic('S');
        +
        +            fontSizePanel.add(label, BorderLayout.NORTH);
        +            fontSizePanel.add(p, BorderLayout.CENTER);
        +        }
        +        return fontSizePanel;
        +    }
        +
        +    protected JPanel getSamplePanel()
        +    {
        +        if (samplePanel == null)
        +        {
        +            Border titledBorder = BorderFactory.createTitledBorder(
        +                BorderFactory.createEtchedBorder(), ("Amostra"));
        +            Border empty = BorderFactory.createEmptyBorder(5, 10, 10, 10);
        +            Border border = BorderFactory.createCompoundBorder(titledBorder, empty);
        +
        +            samplePanel = new JPanel();
        +            samplePanel.setLayout(new BorderLayout());
        +            samplePanel.setBorder(border);
        +
        +            samplePanel.add(getSampleTextField(), BorderLayout.CENTER);
        +        }
        +        return samplePanel;
        +    }
        +
        +    protected JTextField getSampleTextField()
        +    {
        +        if (sampleText == null)
        +        {
        +            Border lowered = BorderFactory.createLoweredBevelBorder();
        +
        +            sampleText = new JTextField(("AaBbYyZz"));
        +            sampleText.setBorder(lowered);
        +            sampleText.setPreferredSize(new Dimension(300, 100));
        +        }
        +        return sampleText;
        +    }
        +
        +    protected String[] getFontFamilies()
        +    {
        +        if (fontFamilyNames == null)
        +        {
        +            GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
        +            fontFamilyNames = env.getAvailableFontFamilyNames();
        +        }
        +        return fontFamilyNames;
        +    }
        +
        +    protected String[] getFontStyleNames()
        +    {
        +        if (fontStyleNames == null)
        +        {
        +            int i = 0;
        +            fontStyleNames = new String[4];
        +            fontStyleNames[i++] = ("Plain");
        +            fontStyleNames[i++] = ("Bold");
        +            fontStyleNames[i++] = ("Italic");
        +            fontStyleNames[i++] = ("BoldItalic");
        +        }
        +        return fontStyleNames;
        +    }
        +}
        \ No newline at end of file
        diff --git a/src/com/classes/util/Menssage.java b/src/com/classes/util/Menssage.java
        new file mode 100644
        index 0000000..db1ce75
        --- /dev/null
        +++ b/src/com/classes/util/Menssage.java
        @@ -0,0 +1,48 @@
        +/*
        + * To change this license header, choose License Headers in Project Properties.
        + * To change this template file, choose Tools | Templates
        + * and open the template in the editor.
        + */
        +package com.classes.util;
        +
        +import java.util.logging.Level;
        +import java.util.logging.Logger;
        +import javax.swing.JLabel;
        +import javax.swing.JPanel;
        +
        +/**
        + *
        + * @author Andrew
        + */
        +public class Menssage extends JPanel {
        +
        +    private JLabel label = null;
        +    
        +    private Thread thread = null;
        +
        +    public Menssage(JLabel label) {
        +        this.label = label;
        +        this.label.setText("");
        +    }
        +
        +    public void write(final String msg) {
        +        thread = new Thread(new Runnable() {
        +            @Override
        +            public void run() {
        +                label.setText(msg);
        +                try {
        +                    Thread.sleep(10000);
        +                } catch (InterruptedException ex) {
        +                    Logger.getLogger(Menssage.class.getName()).log(Level.SEVERE, null, ex);
        +                } finally{
        +                    label.setText("");
        +                }
        +            }
        +        });
        +        if(thread.isAlive()){
        +            thread.interrupt();
        +        }
        +        thread.start();
        +    }
        +
        +}
        diff --git a/src/com/classes/util/MenuSetting.java b/src/com/classes/util/MenuSetting.java
        new file mode 100644
        index 0000000..145f706
        --- /dev/null
        +++ b/src/com/classes/util/MenuSetting.java
        @@ -0,0 +1,104 @@
        +/*
        + * To change this license header, choose License Headers in Project Properties.
        + * To change this template file, choose Tools | Templates
        + * and open the template in the editor.
        + */
        +package com.classes.util;
        +
        +import javax.swing.JMenuItem;
        +import javax.swing.JMenuBar;
        +
        +/**
        + *
        + * @author SIMONETO-2
        + */
        +public class MenuSetting {
        +
        +    //MENU
        +    JMenuBar MENU;
        +
        +    //TAB ARQUIVOS
        +    JMenuItem JMenuItem1;
        +    JMenuItem JMenuItem2;
        +    JMenuItem JMenuItem3;
        +    JMenuItem JMenuItem4;
        +    JMenuItem JMenuItem5;
        +    JMenuItem JMenuItem6;
        +    JMenuItem JMenuItem15;
        +
        +    //TAB EDITAR
        +    JMenuItem JMenuItem7;
        +    JMenuItem JMenuItem8;
        +    JMenuItem JMenuItem9;
        +    JMenuItem JMenuItem10;
        +    JMenuItem JMenuItem11;
        +    JMenuItem JMenuItem12;
        +    JMenuItem JMenuItem13;
        +    JMenuItem JMenuItem14;
        +
        +    //TAB EXIBIR
        +    JMenuItem jMenuItem16;
        +
        +    //TAB ALGORITMO
        +    //JMenuItem jMenuItem17;
        +    //JMenuItem jMenuItem18;
        +    
        +    
        +    //TAB AJUDA
        +    JMenuItem jMenuItem19;
        +
        +    public MenuSetting(JMenuBar menu) {
        +        this.MENU = menu;
        +
        +        JMenuItem1 = MENU.getMenu(0).getItem(0);
        +        JMenuItem2 = MENU.getMenu(0).getItem(1);
        +        JMenuItem3 = MENU.getMenu(0).getItem(3);
        +        JMenuItem4 = MENU.getMenu(0).getItem(4);
        +        JMenuItem5 = MENU.getMenu(0).getItem(10);
        +        JMenuItem6 = MENU.getMenu(0).getItem(8);
        +        JMenuItem15 = MENU.getMenu(0).getItem(6);
        +
        +        //TAB EDITAR
        +        JMenuItem7 = MENU.getMenu(1).getItem(0);
        +        JMenuItem8 = MENU.getMenu(1).getItem(1);
        +        JMenuItem9 = MENU.getMenu(1).getItem(3);
        +        JMenuItem10 = MENU.getMenu(1).getItem(4);
        +        JMenuItem11 = MENU.getMenu(1).getItem(5);
        +        JMenuItem12 = MENU.getMenu(1).getItem(7);
        +        JMenuItem13 = MENU.getMenu(1).getItem(9);
        +        JMenuItem14 = MENU.getMenu(1).getItem(10);
        +
        +        //TAB EXIBIR
        +        jMenuItem16 = MENU.getMenu(2).getItem(0);
        +
        +        //TAB ALGORITMO
        +        //jMenuItem17 = MENU.getMenu(3).getItem(0);
        +        jMenuItem19 = MENU.getMenu(3).getItem(1);
        +    }
        +
        +    public void setDisabledTop(boolean p) {
        +        JMenuItem3.setEnabled(p);
        +        JMenuItem4.setEnabled(p);
        +        JMenuItem6.setEnabled(p);
        +        JMenuItem15.setEnabled(p);
        +        
        +        //MENU.getMenu(1).setEnabled(p);
        +        //MENU.getMenu(2).setEnabled(p);
        +        //MENU.getMenu(3).setEnabled(p);
        +        
        +        JMenuItem7.setEnabled(p);
        +        JMenuItem8.setEnabled(p);
        +        JMenuItem9.setEnabled(p);
        +        JMenuItem10.setEnabled(p);
        +        JMenuItem11.setEnabled(p);
        +        JMenuItem12.setEnabled(p);
        +        JMenuItem13.setEnabled(p);
        +        JMenuItem14.setEnabled(p);
        +        
        +        jMenuItem16.setEnabled(p);
        +
        +        //jMenuItem17.setEnabled(p);
        +        jMenuItem19.setEnabled(p);
        +    }
        +
        +}
        diff --git a/src/com/classes/util/NewTab.java b/src/com/classes/util/NewTab.java
        new file mode 100644
        index 0000000..6f9e3bb
        --- /dev/null
        +++ b/src/com/classes/util/NewTab.java
        @@ -0,0 +1,178 @@
        +/*
        + * To change this license header, choose License Headers in Project Properties.
        + * To change this template file, choose Tools | Templates
        + * and open the template in the editor.
        + */
        +package com.classes.util;
        +
        +import static com.forms.Editor.enabled_menu;
        +import static com.forms.Editor.files_opens;
        +import static com.forms.Editor.line_number;
        +import static com.forms.Editor.linha_coluna_txt;
        +import de.sciss.syntaxpane.DefaultSyntaxKit;
        +import java.awt.Color;
        +import javax.swing.JEditorPane;
        +import javax.swing.JScrollPane;
        +import javax.swing.JTabbedPane;
        +import de.sciss.syntaxpane.actions.CaretMonitor;
        +import de.sciss.syntaxpane.components.LineNumbersRuler;
        +import java.awt.AlphaComposite;
        +import java.awt.Graphics;
        +import java.awt.Graphics2D;
        +import java.awt.Image;
        +import java.awt.Toolkit;
        +import java.net.URL;
        +
        +/**
        + *
        + * @author SIMONETO-2
        + */
        +public class NewTab {
        +
        +    private final JScrollPane[] scrollpane = new JScrollPane[500];
        +    private final JEditorPane[] jtextpane = new JEditorPane[500];
        +
        +    private JTabbedPane tab = null;
        +
        +    public int tabs_criadas = 0;
        +
        +    public NewTab(JTabbedPane jTab) {
        +        //ADICIONANDO O JTAB
        +        this.tab = jTab;
        +    }
        +
        +    public void addTab(String tabname, String diretory, String alg) {
        +        //CRIANDO A SCROLBAR
        +        scrollpane[tabs_criadas] = new javax.swing.JScrollPane();
        +        scrollpane[tabs_criadas].setBorder(null);
        +        scrollpane[tabs_criadas].setBackground(Color.decode("#FFFFFF"));
        +        scrollpane[tabs_criadas].setName("scrollpane_" + tabs_criadas);
        +
        +        //CRIANDO JTEXTPANE
        +        jtextpane[tabs_criadas] = new javax.swing.JEditorPane() {
        +            @Override
        +            public void paintComponent(Graphics g) {
        +                super.paintComponent(g);
        +                
        +                Graphics2D g2d = (Graphics2D) g;
        +                
        +               AlphaComposite alphaChannel = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f);
        +                URL urlicon = NewTab.class.getClassLoader().getResource("com/images/logo.png");
        +                Image icon = Toolkit.getDefaultToolkit().getImage(urlicon);
        +                g2d.setComposite(alphaChannel);
        +                g2d.drawImage(icon, this.getWidth() - 128, this.getHeight() - 128, this);
        +                g2d.dispose();
        +            }
        +        };
        +        jtextpane[tabs_criadas].setBackground(Color.decode("#FFFFFF"));
        +        jtextpane[tabs_criadas].setBorder(null);
        +        //jtextpane[tabs_criadas].setMargin(new java.awt.Insets(5, 5, 5, 5));
        +        jtextpane[tabs_criadas].setToolTipText(null);
        +        jtextpane[tabs_criadas].setName("jtextpane_" + tabs_criadas);
        +        jtextpane[tabs_criadas].setSelectionColor(Color.GRAY);
        +        //SETANDO A SCROLL NO TEXTPANE
        +        scrollpane[tabs_criadas].setViewportView(jtextpane[tabs_criadas]);
        +
        +        //INICIANDO O EDITOR
        +        jtextpane[tabs_criadas].setContentType("text/portugol");
        +        jtextpane[tabs_criadas].setText(alg);
        +        ((de.sciss.syntaxpane.SyntaxDocument) jtextpane[tabs_criadas].getDocument()).clearUndos();
        +
        +        //ADICIOANDO A TAB
        +        //""+tabname+""
        +        tab.addTab("" + tabname + "", scrollpane[tabs_criadas]);
        +        jtextpane[tabs_criadas].setCaretPosition(0);
        +
        +        //SETANDO CARET_MONITOR
        +        CaretMonitor m = new CaretMonitor(jtextpane[tabs_criadas], linha_coluna_txt);
        +        m.setNoSelectionFormat("Linha %d, Coluna %d (Total de caracteres ate o cursor %d)");
        +        m.setSelectionFormat("Linha %d, Coluna %d até Linha %d, Coluna %d (Total de caracteres selecionados %d)");
        +
        +        //VERIFICANDO SE E PARA REMOVER O LINE_NUMBER
        +        if (!line_number) {
        +            DefaultSyntaxKit kit = (DefaultSyntaxKit) jtextpane[tabs_criadas].getEditorKit();
        +            if (kit.isComponentInstalled(jtextpane[tabs_criadas], LineNumbersRuler.class.getName())) {
        +                kit.deinstallComponent(jtextpane[tabs_criadas], LineNumbersRuler.class.getName());
        +            }
        +        }
        +
        +        //PEGANDO A POSICAO DA TAB
        +        int tabIndex = tab.getTabCount() - 1;
        +
        +        //ADICIONANDO NOME A TAB
        +        tab.getComponentAt(tabIndex).setName("" + tabs_criadas);
        +
        +        //CONFIGURANDO A ARRAY DE INFORMACOES DO ARQUIVO
        +        files_opens.addFileOpen(tabs_criadas, "jtextpane_" + tabs_criadas, diretory);
        +
        +        //SELECIONANDO A TAB ABERTA
        +        tab.setSelectedIndex(tabIndex);
        +
        +        //VERIFICANDO SE O MENU ESTA DESABILITADO
        +        if (enabled_menu == false) {
        +            enabled_menu = true;
        +        }
        +        //setting_menu.setDisabledTop(enabled_menu);
        +
        +        //APLICANDO FOCUS NO TEXT
        +        jtextpane[tabs_criadas].requestFocus();
        +
        +        System.out.println("Aba criada com sucesso. ID:" + tabs_criadas);
        +
        +        //INCREMENTANDO CONTATADOR
        +        tabs_criadas++;
        +    }
        +
        +    //RETORNAR TOTAL DE TABS
        +    public int getTabCount() {
        +        return tab.getTabCount();
        +    }
        +
        +    //VAI PARA A TAB SELECIONADA
        +    public void setSelectedIndex(int index) {
        +        tab.setSelectedIndex(index);
        +    }
        +
        +    //FUNCAO PARA RENOMEAR A TAB
        +    public void renameTab(int index, String txt) {
        +        tab.setTitleAt(index, txt);
        +    }
        +
        +    public String getTitleTab(int index) {
        +        return tab.getTitleAt(index);
        +    }
        +
        +    //PEGA A TAB QUE ESTA ABERTA
        +    public int getIndexTab() {
        +        return tab.getSelectedIndex();
        +    }
        +
        +    //DELETAR TAB
        +    public void unistallTab(int id) {
        +        scrollpane[id] = null;
        +        jtextpane[id] = null;
        +        files_opens.unistall(id);
        +    }
        +
        +    //RETORNAR O JTEXTPANE DA TAB ABERTA
        +    public JEditorPane getEditorPane() {
        +        JScrollPane scroll_atual = (JScrollPane) tab.getSelectedComponent();
        +        return (JEditorPane) scroll_atual.getViewport().getComponent(0);
        +    }
        +
        +    //RETORNAR O JTEXTPANE DE QUALQUER TAB
        +    public JEditorPane getJEditorPaneAt(int index) {
        +        JScrollPane scroll_atual = (JScrollPane) tab.getComponentAt(index);
        +        return (JEditorPane) scroll_atual.getViewport().getComponent(0);
        +    }
        +
        +    public int getIdTab() {
        +        String[] Split = getEditorPane().getName().split("_");
        +        return Integer.parseInt(Split[1]);
        +    }
        +
        +    public int getIdTab(int index) {
        +        String[] Split = getJEditorPaneAt(index).getName().split("_");
        +        return Integer.parseInt(Split[1]);
        +    }
        +}
        diff --git a/src/com/classes/util/OpenFile.java b/src/com/classes/util/OpenFile.java
        new file mode 100644
        index 0000000..6fc3bf6
        --- /dev/null
        +++ b/src/com/classes/util/OpenFile.java
        @@ -0,0 +1,90 @@
        +/*
        + * To change this license header, choose License Headers in Project Properties.
        + * To change this template file, choose Tools | Templates
        + * and open the template in the editor.
        + */
        +package com.classes.util;
        +
        +import static com.forms.Editor.files_opens;
        +import static com.forms.Editor.tab;
        +import java.awt.event.ActionEvent;
        +import java.awt.event.ActionListener;
        +import java.io.File;
        +import java.io.FileInputStream;
        +import java.io.IOException;
        +import java.io.InputStreamReader;
        +import java.nio.charset.Charset;
        +import java.nio.file.Files;
        +import java.nio.file.Paths;
        +import java.util.List;
        +import java.util.logging.Level;
        +import java.util.logging.Logger;
        +import javax.swing.JFileChooser;
        +import javax.swing.JMenuItem;
        +import javax.swing.filechooser.FileFilter;
        +import javax.swing.filechooser.FileNameExtensionFilter;
        +
        +/**
        + *
        + * @author SIMONETO-2
        + */
        +public class OpenFile {
        +
        +    private JMenuItem menu = null;
        +
        +    public OpenFile(JMenuItem botao) {
        +        //ARMAZENANDO BOTAO
        +        this.menu = botao;
        +        //ADICIONANDO EVENTO
        +        menu.addActionListener(actions);
        +    }
        +    
        +    //RESPONSAVEL PELA LEITURA DO ARQUIVO
        +    public String readFile(String path, Charset encoding) throws IOException {
        +        /*byte[] encoded = Files.readAllBytes(Paths.get(path));
        +         return new String(encoded, encoding);*/
        +        String retorno = "";
        +        List lines = Files.readAllLines(Paths.get(path), encoding);
        +        for (int i = 0; i < lines.size(); i++) {
        +            if (i == lines.size() - 1) {
        +                retorno += lines.get(i);
        +            } else {
        +                retorno += lines.get(i) + "\n";
        +            }
        +        }
        +        return retorno;
        +    }
        +    
        +    //ACAO DE ABERTURA DO ARQUIVO FILE CHOOSER
        +    private final ActionListener actions = new ActionListener() {
        +        @Override
        +        public void actionPerformed(ActionEvent e) {
        +            if (e.getSource() == menu) {
        +                JFileChooser fc = new JFileChooser();
        +                FileFilter filter = new FileNameExtensionFilter("Arquivo algoritmo *.alg", "alg");
        +                fc.addChoosableFileFilter(filter);
        +                fc.setFileFilter(filter);
        +                int returnVal = fc.showOpenDialog(menu);
        +
        +                if (returnVal == JFileChooser.APPROVE_OPTION) {
        +                    File file = fc.getSelectedFile();
        +                    
        +                    //PARA EVITAR A ABERTURA DE ITENS DUPLICADOS
        +                    if (!files_opens.isExistingOpen(file.getAbsoluteFile().toString())) {
        +                        try {
        +                            InputStreamReader r = new InputStreamReader(new FileInputStream(file));
        +                            /*Charset.defaultCharset()*/
        +                            tab.addTab(file.getName(), file.getAbsoluteFile().toString(), readFile(file.toString(), Charset.forName(r.getEncoding())));
        +                            tab.getEditorPane().setCaretPosition(0);
        +                            System.out.println("Arquivo " + file.getName() + " foi aberto com sucesso. Charset: " + r.getEncoding());
        +                        } catch (IOException ex) {
        +                            Logger.getLogger(OpenFile.class.getName()).log(Level.SEVERE, null, ex);
        +                        }
        +                    } else {
        +                        tab.setSelectedIndex(files_opens.getPositionItem(file.getAbsoluteFile().toString()));
        +                    }
        +                }
        +            }
        +        }
        +    };
        +}
        diff --git a/src/com/classes/util/SaveSaveAs.java b/src/com/classes/util/SaveSaveAs.java
        new file mode 100644
        index 0000000..e17fd9a
        --- /dev/null
        +++ b/src/com/classes/util/SaveSaveAs.java
        @@ -0,0 +1,172 @@
        +/*
        + * To change this license header, choose License Headers in Project Properties.
        + * To change this template file, choose Tools | Templates
        + * and open the template in the editor.
        + */
        +package com.classes.util;
        +
        +import static com.forms.Editor.files_opens;
        +import static com.forms.Editor.msg;
        +import static com.forms.Editor.tab;
        +import java.awt.event.ActionEvent;
        +import java.awt.event.ActionListener;
        +import java.io.BufferedWriter;
        +import java.io.File;
        +import java.io.FileNotFoundException;
        +import java.io.FileWriter;
        +import java.io.IOException;
        +import java.io.PrintWriter;
        +import java.util.logging.Level;
        +import java.util.logging.Logger;
        +import javax.swing.JFileChooser;
        +import javax.swing.JMenuItem;
        +import javax.swing.JOptionPane;
        +import javax.swing.JTextPane;
        +import javax.swing.filechooser.FileFilter;
        +import javax.swing.filechooser.FileNameExtensionFilter;
        +
        +/**
        + *
        + * @author SIMONETO-2
        + */
        +public class SaveSaveAs {
        +
        +    private JMenuItem botao_save = null;
        +    private JMenuItem botao_save_as = null;
        +    private JTextPane editor_txt = null;
        +
        +    public SaveSaveAs(JMenuItem btn_save, JMenuItem btn_saveAs) {
        +        //ARMAZENANDO VARIAVEIS (BOTOES)
        +        this.botao_save = btn_save;
        +        this.botao_save_as = btn_saveAs;
        +
        +        //ADICIONANDO EVENTOS
        +        botao_save_as.addActionListener(action_save_As);
        +        botao_save.addActionListener(action_save);
        +    }
        +
        +    //EVENTO PARA SAVA(AS)
        +    private final ActionListener action_save_As = new ActionListener() {
        +        @Override
        +        public void actionPerformed(ActionEvent e) {
        +            try {
        +                if (e.getSource() == botao_save_as) {
        +                    SaveAs();
        +                }
        +            } catch (IOException ex) {
        +                Logger.getLogger(SaveSaveAs.class.getName()).log(Level.SEVERE, null, ex);
        +            }
        +        }
        +    };
        +
        +    //EVENTO PARA SALVAMENTO PADRAO
        +    private final ActionListener action_save = new ActionListener() {
        +        @Override
        +        public void actionPerformed(ActionEvent e) {
        +
        +            if (e.getSource() == botao_save) {
        +                //VERIFICANDO SE EXISTE UM LOCAL SALVO
        +                                
        +                if (!"".equals(files_opens.getInfo(tab.getEditorPane().getName())[2])) {
        +                    try {
        +                        //SALVA O ARQUIVO
        +                        Save(files_opens.getInfo(tab.getEditorPane().getName())[2]);
        +                        msg.write("Arquivo " + files_opens.getInfo(tab.getEditorPane().getName())[2] + " foi modificado com sucesso.");
        +                        System.out.println("Arquivo " + files_opens.getInfo(tab.getEditorPane().getName())[2] + " foi modificado com sucesso.");
        +                    } catch (IOException ex) {
        +                        JOptionPane.showConfirmDialog(null, "Erro ao salver o arquivo, tente novamente", "Alerta", JOptionPane.ERROR_MESSAGE);                        
        +                        //Logger.getLogger(SaveSaveAs.class.getName()).log(Level.SEVERE, null, ex);
        +                    }
        +                } else {
        +                    try {
        +                        //ABRE JANELA DE SAVE(AS)
        +                        SaveAs();
        +                    } catch (IOException ex) {
        +                        JOptionPane.showConfirmDialog(null, "Erro ao salver o arquivo, tente novamente", "Alerta", JOptionPane.ERROR_MESSAGE);
        +                        //Logger.getLogger(SaveSaveAs.class.getName()).log(Level.SEVERE, null, ex);
        +                    }
        +                }
        +            }
        +        }
        +    };
        +
        +    public void Save(String diretory) throws IOException {
        +        //ARMAZENA VARIAVEIS
        +        String tmp = diretory;
        +        File salvar_arquivo = new File(tmp);
        +
        +        //APAGAR CONTEU DO ARQUIVO
        +        PrintWriter clean = new PrintWriter(salvar_arquivo);
        +        clean.print("");
        +        clean.close();
        +
        +        //PREPARA PARA SALVAR O ARQUIVO
        +        PrintWriter writer = new PrintWriter(diretory);
        +        String[] alg = tab.getEditorPane().getText().split("\n");
        +        for (int i = 0; i < alg.length; i++) {
        +            if (i == alg.length - 1) {
        +                writer.print(alg[i]);
        +            } else {
        +                writer.println(alg[i]);
        +            }
        +        }
        +        writer.close();
        +    }
        +
        +    public void SaveAs() throws FileNotFoundException, IOException {
        +        //ABRINDO CHOOSE PARA SALVAR ARQUIVO
        +        JFileChooser SavedFile = new JFileChooser();
        +        SavedFile.setAcceptAllFileFilterUsed(false);
        +        FileFilter ft = new FileNameExtensionFilter("Salvar como arquivo algoritmo *.alg", "alg");
        +        SavedFile.addChoosableFileFilter(ft);
        +        SavedFile.setDialogTitle("Aonde você deseja salvar o seu algoritmo ?");
        +
        +        //VARIAVEL DE RETORNO
        +        int returnVal = SavedFile.showSaveDialog(botao_save_as);
        +
        +        //ABRINDO DIALOGO PARA SALVAR ARQUIVO CRIPTOGRAFADO
        +        if (returnVal == JFileChooser.APPROVE_OPTION) {
        +            File salvar_arquivo = SavedFile.getSelectedFile();
        +
        +            //VERIFICANDO SE O ARQUIVO EXISTE PARA O REPLACE
        +            if (salvar_arquivo.exists()) {
        +                int result = JOptionPane.showConfirmDialog(null, "O arquivo que você está tentando salvar já existe. \nDeseja substituir esse arquivo?", "Alerta", JOptionPane.YES_NO_CANCEL_OPTION);
        +                if (result == JOptionPane.NO_OPTION) {
        +                    SaveAs();
        +                    return;
        +                }
        +            }
        +
        +            //TRATANDO DO NOME
        +            String nome = salvar_arquivo.toString();
        +
        +            //VERIFICA SE JA EXISTE O .ALG NO NOME
        +            if (!nome.endsWith(".alg")) {
        +                nome = nome + ".alg";
        +            }
        +
        +            //MODIFICANDO NOME
        +            salvar_arquivo = new File(nome);
        +
        +            //SALVANDO O ARQUIVO
        +            Save(salvar_arquivo.toString());
        +
        +            //VERIFICANDO SE O ARQUIVO JA ESTA SALVO
        +            if (!"".equals(files_opens.getInfo(tab.getEditorPane().getName())[2])) {
        +                //PARA O SAVAS_aS
        +                tab.addTab(salvar_arquivo.getName(), nome, tab.getEditorPane().getText());
        +            } else {
        +                //PARA O SAVE
        +                files_opens.updateDir(tab.getEditorPane().getName(), nome);
        +                tab.renameTab(tab.getIndexTab(), salvar_arquivo.getName());
        +            }
        +            
        +            
        +            msg.write("Arquivo " + salvar_arquivo.toString() + " foi salvo com sucesso.");
        +            System.out.println("Arquivo " + salvar_arquivo.toString() + " foi salvo com sucesso.");
        +
        +        }
        +
        +    }
        +
        +}
        diff --git a/src/com/compilador/portugol/.sublf61.tmp b/src/com/compilador/portugol/.sublf61.tmp
        new file mode 100644
        index 0000000..784d04c
        --- /dev/null
        +++ b/src/com/compilador/portugol/.sublf61.tmp
        @@ -0,0 +1,239 @@
        +////////////////////////////////////////////////////////////////////////
        +/*                                                                  ////
        +* ANALIZADOR DE PORTUGOL (GRAMATICA).							    ////
        +* BY: ANDREW NETO                                                   ////
        +* 05/07/2014                                                        ////
        +*/                                                                  ////
        +////////////////////////////////////////////////////////////////////////
        +
        +package com.analizador.portugol;
        +
        +/*import static com.analizador.portugol.parser.error;*/
        +import java_cup.runtime.*;
        +
        +
        +parser code
        +{:
        +
        +	static Compilador util = new Compilador();
        +
        +    public static void main(String args[]) throws Exception{
        +        new parser(new PortugolFlex(System.in)).parse();
        +    }
        +    public void syntax_error(Symbol s){
        +        report_error("Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right)+". Trecho desconhecido: "+s.value,null);
        +        util.setErro();
        +    }
        +:}
        +
        +action code {::}
        +
        +terminal ALGORITMO;
        +terminal VAR;
        +terminal String TIPO_VARIAVEL,TIPO_VARIAVEL_VETOR;
        +
        +terminal INICIO;
        +
        +terminal String OPERADOR,OPERADOR_SOMA,VALOR_LOGICO;
        +terminal ATRIBUIR;
        +terminal ABRIR_PARENTESE, FECHAR_PARENTESE,ABRIR_COLCHETE,FECHAR_COLCHETE,DOIS_PONTOS;
        +
        +terminal SE,ENTAO,SENAO,FIMSE;
        +terminal String CONDICIONAL_NUMERICA,CONDICIONAL_COMPARATIVA;
        +
        +terminal DE,E,OU;
        +
        +terminal FIMALGORITMO;
        +
        +terminal ADD_ATTR_VAR, SEPARADOR;
        +terminal String ID,STRING,NUMERO_INT,NUMERO_FLOAT;
        +
        +
        +non terminal algoritmo;
        +
        +/* ALGORITMO DECLARACAO */
        +non terminal algoritmo_nome, algoritmo_instanciacao;
        +
        +/* VAR DECLARACAO */
        +non terminal var_estrutura, variaveis, var_instanciacao;
        +non terminal String var_listagem;
        +
        +
        +
        +/* TERMINAL PROGRAMA */
        +non terminal programa, corpo_programa;
        +
        +/* FUNCOES */
        +non terminal instanciacao_variaveis,condicional;
        +
        +/* PARA OPERACOES EM GERAL*/
        +non terminal String _operacoes,_condicional,_sub_condicional;
        +
        +
        +/* PRESEDENCIA DE OPERACOES */
        +precedence left OPERADOR,OPERADOR_SOMA;
        +
        +precedence left ABRIR_PARENTESE, FECHAR_PARENTESE;
        +
        +/* PRESEDENCIA DE VARIAVEIS */
        +precedence left SEPARADOR;
        +
        +/* PRECEDENCIAS CONDICIONAIS */
        +precedence left E,OU;
        +precedence left CONDICIONAL_NUMERICA,CONDICIONAL_COMPARATIVA;
        +
        +start with algoritmo;
        +
        +/* ALGORITMO */
        +algoritmo 		::= algoritmo_nome 
        +					var_estrutura 
        +					INICIO {: util.setCode("\n\tpublic static void main(String[] args) {"); :}
        +					programa
        +					FIMALGORITMO {: util.setCode("\t}\n}"); if(util.isErros() == false) util.printCode(); :}
        +					| error {::};
        +
        +
        +
        +
        +/* PARA A DECLARACAO DO NO DO ALGORITMO */
        +algoritmo_nome   		::= algoritmo_instanciacao | error {:  :};
        +algoritmo_instanciacao  ::= ALGORITMO ID:e {: util.setCode("class "+e+" {"); :} | ALGORITMO STRING:e {: util.setCode("class "+e.toString().substring(1, e.toString().length()-1)+" {"); :};
        +
        +
        +
        +
        +
        +/* PARA A DECLARACAO DE VARIAVEIS */
        +var_estrutura		::= VAR variaveis | error {: util.setCode("Detalhe: Erro de estruturacao. Exemplo de estruturacao.: var variavel1,variavel2 : tipo_de_variavel"); :};
        +variaveis 			::= variaveis var_instanciacao | var_instanciacao | error {: :};
        +var_instanciacao 	::= var_listagem:e ADD_ATTR_VAR TIPO_VARIAVEL:x {:
        +							util.addVariavel(e,x); /* Ja estao com toLowerCase */
        +							util.setCode("\t" + util.getTipoVariavel(x) + " " +e+ ";");
        +						:} |
        +						var_listagem:e ADD_ATTR_VAR TIPO_VARIAVEL_VETOR ABRIR_COLCHETE NUMERO_INT:n1 DOIS_PONTOS NUMERO_INT:n2 FECHAR_COLCHETE DE TIPO_VARIAVEL:x {:
        +							util.setBiblioteca("import java.util.List;");
        +							util.addVariavelVetor(e,x,n1,n2); /* Ja estao com toLowerCase */
        +							util.setCode("\tList<"+util.getTipoVariavel(x)+"> "+e+" = new ArrayList<>();");
        +						:};
        +
        +var_listagem      	::= var_listagem:e1 SEPARADOR var_listagem:e2 {: RESULT = e1+","+e2; :} | 
        +						ID:value  {: RESULT = value.toLowerCase(); :};
        +
        +
        +
        +
        +
        +/*PROGRAMA*/
        +programa 	::= programa corpo_programa | corpo_programa | error {::};
        +
        +corpo_programa ::= instanciacao_variaveis | condicional;
        +
        +
        +instanciacao_variaveis   ::=  ID:x ATRIBUIR _operacoes:e {:
        +							  		String tmp = util.setVariavelOperador(x.toLowerCase(),e);
        +							  		switch(tmp){
        +							  			case "error1" : this.parser.report_error("Erro de syntax: Variavel \""+x+"\" não foi declarada", null);util.setErro(); break;
        +							  			case "error2" : this.parser.report_error("Erro de syntax: Variavel \""+x+"\" não suporta esse tipo de valor", null);util.setErro(); break;
        +							  			default: util.setCode(tmp); break;
        +							  		}
        +							  :} | 
        +							  ID:x ABRIR_COLCHETE NUMERO_INT:n FECHAR_COLCHETE ATRIBUIR _operacoes:e {:
        +							  		String tmp = util.setVariavelVetor(x.toLowerCase(),e,n);
        +							  		switch(tmp){
        +							  			case "error1" : this.parser.report_error("Erro de syntax: Variavel \""+x+"\" não foi declarada", null);util.setErro(); break;
        +							  			case "error2" : this.parser.report_error("Erro de syntax: Variavel \""+x+"\" não suporta esse tipo de valor", null);util.setErro(); break;
        +							  			case "error3" : this.parser.report_error("Erro de syntax: Indice do vetor \""+x+"\" esta incorreto", null);util.setErro(); break;
        +							  			default: util.setCode(tmp); break;
        +							  		}
        +							  :} ;
        +
        +
        +condicional 	::= SE _condicional:c ENTAO {:
        +						String tmp = util.setCondicional(c.toLowerCase());
        +						switch(tmp){
        +							case "error1" : this.parser.report_error("Erro de syntax: Comparacao indevida em "+c, null);util.setErro(); break;
        +							default: util.setCode(tmp); break;
        +						}
        +					:} programa FIMSE;
        +
        +
        +
        +/* CONDICINAL GRAMATICA */
        +_condicional 	::= _condicional:c1 E _condicional:c2 {:
        +						RESULT = c1+" && "+c2;
        +						util.setCondicinalETMP(true);
        +					:} |
        +					_condicional:c1 OU _condicional:c2 {:
        +						RESULT = c1+" || "+c2;
        +						util.setCondicionalOuTMP(true);
        +					:} |
        +					ABRIR_PARENTESE _condicional:e FECHAR_PARENTESE	{: RESULT = "("+e+")"; :} |
        +					_sub_condicional:e {: RESULT = e; :};
        +
        +
        +_sub_condicional 	::= _sub_condicional:s1 CONDICIONAL_NUMERICA:c _sub_condicional:s2 {:
        +							RESULT = s1+" "+c+" "+s2;
        +							util.setCondicinalNumericaTMP(true);
        +						:} |
        +						_sub_condicional:s1 CONDICIONAL_COMPARATIVA:c _sub_condicional:s2 {:
        +							RESULT = s1+" "+util.getTipoCondiconal(c)+" "+s2;
        +							util.setCondicionalComparativaTMP(true);
        +						:} |
        +						ABRIR_PARENTESE _sub_condicional:e FECHAR_PARENTESE	{: RESULT = "("+e+")"; :} |
        +						_operacoes:e {: 
        +							RESULT = e;
        +							util.setTiposOperacaoeTMP(util.getTipoOperacao());
        +						:};
        +
        +
        +/* OPERACOES */
        +_operacoes ::= _operacoes:e1 OPERADOR:op _operacoes:e2	{: 
        +					RESULT = e1+" "+util.getOperador(op)+" "+e2; 
        +					util.setOperadorTMP(true);
        +				:} |
        +				_operacoes:e1 OPERADOR_SOMA _operacoes:e2	{: 
        +					RESULT = e1+" + "+e2; 
        +					util.setOperadorSomaTMP(true);
        +				:} |
        +          		ABRIR_PARENTESE _operacoes:e FECHAR_PARENTESE	{: RESULT = "("+e+")"; :} |
        +          		NUMERO_INT:n {: 
        +					RESULT = n;
        +					util.setNumeroIntTMP(true); 
        +				:} |
        +          		NUMERO_FLOAT:n {: 
        +					RESULT = util.getValorRealFloat(n);
        +					util.setNumeroFloatTMP(true); 
        +				:} |
        +          		ID:n {: 
        +					if(util.checkVariavelExiste(n.toLowerCase())) {
        +						String[] tmp = util.getVariavel(n.toLowerCase());
        +						util.setTipoIdTMP(tmp[1]);
        +						RESULT = n.toLowerCase();
        +					}else{
        +						this.parser.report_error("Erro de syntax: Variavel \""+n+"\" não foi declarada", null);
        +						util.setErro();
        +					}
        +				:} |
        +				ID:n ABRIR_COLCHETE NUMERO_INT:i FECHAR_COLCHETE ATRIBUIR {:
        +					String[] tmp = util.getVariavelVetor(n.toLowerCase());
        +					if(tmp[0] != null){
        +						if (i >= tmp[2] && i <= tmp[3]) {
        +							util.setTipoIdTMP(tmp[1]);
        +							RESULT = n.toLowerCase()+".get("+i+")";
        +						}else{
        +							this.parser.report_error("Erro de syntax: Indice do vetor \""+n+"\" esta incorreto", null);
        +							util.setErro();		
        +						}
        +					}else{
        +						this.parser.report_error("Erro de syntax: Variavel \""+n+"\" não foi declarada", null);
        +						util.setErro();	
        +					}
        +				:} |
        +				STRING:s {: 
        +					util.setStringTMP(true);
        +					RESULT = s;
        +				:} |
        +				VALOR_LOGICO:l {:
        +					util.setBooleanTMP(true);
        +					RESULT = util.getValorLogico(l);
        +				:};
        \ No newline at end of file
        diff --git a/src/com/compilador/portugol/Compilador.java b/src/com/compilador/portugol/Compilador.java
        new file mode 100644
        index 0000000..1db9d44
        --- /dev/null
        +++ b/src/com/compilador/portugol/Compilador.java
        @@ -0,0 +1,766 @@
        +/*
        + * To change this license header, choose License Headers in Project Properties.
        + * To change this template file, choose Tools | Templates
        + * and open the template in the editor.
        + */
        +package com.compilador.portugol;
        +
        +import com.forms.Console;
        +import com.forms.Editor;
        +import static com.forms.Editor.tela;
        +import java.awt.Color;
        +import java.util.ArrayList;
        +import java.util.List;
        +import javax.swing.text.SimpleAttributeSet;
        +import javax.swing.text.StyleConstants;
        +
        +/**
        + *
        + * @author SIMONETO-2
        + */
        +public class Compilador {
        +
        +    private final boolean printCode = false;
        +    private final boolean execCode = true;
        +
        +
        +    public ArrayList Variaveis = new ArrayList<>();
        +    /*
        +     *   MENU:
        +     *   0-VARIAVEL NOME
        +     *   1-VARIAVEL TIPO
        +     */
        +    public ArrayList VariaveisVetor = new ArrayList<>();
        +    /*
        +     *   MENU:
        +     *   0-VARIAVEL NOME
        +     *   1-VARIAVEL TIPO
        +     *   2-INDICE A
        +     *   3-INDICE B
        +     */
        +
        +    private String code_name;
        +
        +    private String[] code = {"", "", "", ""}; // 0 - CABECALHO, 1 - VARIAVEIS , 2 - PROGRAMA , 3 - INCLUDES
        +    public String[] code_exec = {"", "", ""};
        +
        +    private int erros = 0;
        +
        +    private final String[] operacoes_portugol = {"+", "-", "*", "/", "^", "mod", "div"};
        +    private final String[] operacoes_java = {"+", "-", "*", "/", "^", "%", "/"};
        +
        +    private final String[] valores_logicos_portugol = {"verdadeiro", "falso"};
        +    private final String[] valores_logicos_java = {"true", "false"};
        +
        +    private final String[] tipos_variaveis_portugol = {"string", "caracter", "inteiro", "real", "logico"};
        +    private final String[] tipos_variaveis_java = {"String", "char", "int", "float", "boolean"};
        +
        +    private final String[] condicionais_portugol = {"=", "<>", "e", "ou"};
        +    private final String[] condicionais_java = {"==", "!=", "&&", "||"};
        +
        +    //para o comando de saida   
        +    private boolean scanner = false;
        +
        +    public void setLeia(boolean n) {
        +        if (this.scanner == false) {
        +            this.scanner = true;
        +            setBiblioteca("import java.util.Scanner;");
        +            setCodeVariables("\t\tScanner scanIn = new Scanner(System.in);");
        +            //setCodeVariablesExec("\t\tScanner scanIn = new Scanner(System.in);");
        +        }
        +    }
        +
        +    public void resetarSaidas() {
        +        code_name = "";
        +
        +        code_exec[0] = "";
        +        code_exec[1] = "";
        +        code_exec[2] = "";
        +
        +        code[0] = "";
        +        code[1] = "";
        +        code[2] = "";
        +        code[3] = "";
        +
        +        scanner = false;
        +        erros = 0;
        +
        +        Variaveis.clear();
        +        VariaveisVetor.clear();
        +    }
        +
        +    /*
        +     * AUXILIAR NAS OPERACOES
        +     */
        +    private boolean operador_tmp = false;
        +    private boolean operador_soma = false;
        +    private boolean numero_float_tmp = false;
        +    private boolean numero_int_tmp = false;
        +    private boolean string_tmp = false;
        +    private boolean char_tmp = false;
        +    private boolean boolean_tmp = false;
        +    List TipoID_tmp = new ArrayList<>();
        +
        +    public void setOperadorTMP(boolean p) {
        +        operador_tmp = p;
        +    }
        +
        +    public void setOperadorSomaTMP(boolean p) {
        +        operador_soma = p;
        +    }
        +
        +    public void setNumeroIntTMP(boolean p) {
        +        numero_int_tmp = p;
        +    }
        +
        +    public void setNumerofloatTMP(boolean p) {
        +        numero_float_tmp = p;
        +    }
        +
        +    public void setStringTMP(boolean p) {
        +        string_tmp = p;
        +    }
        +
        +    public void setCharTMP(boolean p) {
        +        char_tmp = p;
        +    }
        +
        +    public void setBooleanTMP(boolean p) {
        +        boolean_tmp = p;
        +    }
        +
        +    public void setTipoIdTMP(String e) {
        +        TipoID_tmp.add(e);
        +    }
        +
        +    public void resetTMPSOperadores() {
        +        operador_tmp = false;
        +        operador_soma = false;
        +        numero_float_tmp = false;
        +        numero_int_tmp = false;
        +        string_tmp = false;
        +        boolean_tmp = false;
        +        char_tmp = false;
        +        TipoID_tmp.clear();
        +
        +    }
        +
        +    /*
        +     * AXULIAR NAS CONDICIONAIS
        +     */
        +    //para as sub-condicionais
        +    private boolean condicionais_numericas = false;
        +    private boolean condicionais_comparativas = false;
        +    private boolean condicinal_e = false;
        +    private boolean condicinal_ou = false;
        +    List TiposOperacoesTMP = new ArrayList<>();
        +
        +    //para as condicionais 
        +    private boolean condicionais_numericas_permanentes = false;
        +    private boolean condicionais_comparativas_permanentes = false;
        +    List TiposOperacoesTMP_permanentes = new ArrayList<>();
        +
        +    public void setCondicinalNumericaTMP(boolean p) {
        +        condicionais_numericas = p;
        +        condicionais_numericas_permanentes = p; //para as condicionais permanentes
        +    }
        +
        +    public void setCondicionalComparativaTMP(boolean p) {
        +        condicionais_comparativas = p;
        +        condicionais_comparativas_permanentes = p; //para as condicionais permanentes
        +    }
        +
        +    public void setCondicinalETMP(boolean p) {
        +        condicinal_e = p;
        +    }
        +
        +    public void setCondicionalOuTMP(boolean p) {
        +        condicinal_ou = p;
        +    }
        +
        +    public void setTiposOperacaoeTMP(String t) {
        +        TiposOperacoesTMP.add(t);
        +        TiposOperacoesTMP_permanentes.add(t); //para as condicionais permanentes
        +    }
        +
        +    public void resetTMPSSubCondicionais() {
        +        condicionais_numericas = false;
        +        condicionais_comparativas = false;
        +        condicinal_e = false;
        +        condicinal_ou = false;
        +        TiposOperacoesTMP.clear();
        +    }
        +
        +    public void resetTMPSCondicionais() {
        +        condicionais_numericas_permanentes = false;
        +        condicionais_comparativas_permanentes = false;
        +        TiposOperacoesTMP_permanentes.clear();
        +    }
        +
        +
        +    /*
        +     * PARA LISTAGEM
        +     */
        +    public void setCodeName(String name) {
        +        this.code_name = name;
        +    }
        +
        +    public void setInitClass() {
        +        this.code[0] = "\n\tpublic " + this.code_name + "(){";
        +    }
        +
        +    public void setEndClass() {
        +        setCode("\t}\n\n\tpublic static void main(String[] args){\n\t\t" + this.code_name + " programa = new " + this.code_name + "();\n\t}\n}");
        +    }
        +
        +    public void setCode(String code) {
        +        this.code[2] += code + "\n";
        +    }
        +
        +    public void setCodeVariables(String code) {
        +        this.code[1] += code + "\n";
        +    }
        +
        +    public void setBiblioteca(String biblioteca) {
        +        this.code[3] += biblioteca + "\n";
        +    }
        +
        +    public void printCode() {
        +        if (printCode) {
        +            if ("".equals(this.code[3])) {
        +                System.out.print(code[0] + '\n' + code[1] + '\n' + code[2]);
        +            } else {
        +                System.out.print(code[3] + '\n' + code[0] + '\n' + code[1] + '\n' + code[2]);
        +            }
        +        }
        +    }
        +    /*
        +     * PARA EXECUTAR
        +     */
        +
        +    public void setCodeExec(String code) {
        +        this.code_exec[2] += code;
        +    }
        +
        +    public void setCodeExec(String code, int line) {
        +        String _line = "\n";
        +        int cline = line + 1;
        +        
        +        
        +        int total_line = (code_exec[0]+code_exec[1]+code_exec[2]).split("\n").length;
        +        
        +        for (int i = 0; i < (line-(total_line+1)); i++) {
        +            _line += "\n";
        +        }
        +        this.code_exec[2] += _line + code;
        +    }
        +
        +    public void setCodeVariablesExec(String code) {
        +        this.code_exec[1] += code + "\n";
        +    }
        +
        +    public void setCodeLibraryExec(String code) {
        +        this.code_exec[0] += code + "\n";
        +    }
        +    /*
        +    public void execCode() {
        +        if (execCode) {
        +
        +            Threadcode = new Thread(new Runnable() {
        +
        +                @Override
        +                public void run() {
        +                    long startTime = 0;
        +                    long endTime = 0;
        +                    boolean error = false;
        +                    Interpreter i = new Interpreter();
        +                    //System.out.println("#"+code_exec[0] + code_exec[1] + code_exec[2]);
        +                    try {
        +                        startTime = System.currentTimeMillis();
        +                        i.set("ConsoleIO", ConsoleIO);
        +                        i.set("table_variaveis", table_variaveis);
        +                        i.eval(code_exec[0] + code_exec[1] + code_exec[2]);
        +                    } catch (EvalError ex) {
        +                        JOptionPane.showMessageDialog(null, "Erro de syntax:Há algum erro critico de syntax no seu código. Linha:" + (ex.getErrorLineNumber() - 1), "Erro de syntax", JOptionPane.WARNING_MESSAGE);
        +                        error = true;
        +                    } finally {
        +                        endTime = System.currentTimeMillis();
        +                        ConsoleIO.println("");
        +                        ConsoleIO.println("");
        +                        if (!error) {
        +                            ConsoleIO.print("Programa finalizado. Tempo de duração: " + (endTime - startTime) / 1000 + " segundos", AttrColor("codigo_finalizado"));
        +                        } else {
        +                            ConsoleIO.print("Programa finalizado. Tempo de duração: " + (endTime - startTime) / 1000 + " segundos", AttrColor("codigo_finalizado_error"));
        +                        }
        +                        ConsoleIO.finalizacao();
        +
        +                    }
        +                }
        +
        +            });
        +            Threadcode.start();
        +        }
        +    }
        +    */
        +
        +    public void setErro() {
        +        erros++;
        +    }
        +
        +    public boolean isErros() {
        +        boolean retorno = false;
        +        if (erros > 0) {
        +            retorno = true;
        +        }
        +        return retorno;
        +    }
        +
        +    public void codeComplete() {
        +        if (isErros() == false) {
        +            Console console = new Console();
        +            console.setLocation((tela.width - console.getSize().width) / 2, (tela.height - console.getSize().height) / 2);
        +            console.setModal(true);
        +            console.setVisible(true);
        +            /*
        +            //LISTAGEM DE VARIAVEIS
        +            for (String[] Variavei : Variaveis) {
        +                table_variaveis.add(Variavei[0], getTipoVariavelJavaToPt(Variavei[1]), null);
        +            }
        +            
        +            //LISTAGEM DE VARIAVEIS DO TIPO VETOR
        +            for (String[] Variavei : VariaveisVetor) {
        +                for (int i = new Integer(Variavei[2]); i <= new Integer(Variavei[3]); i++) {
        +                    table_variaveis.add(Variavei[0] + "[" + i + "]", getTipoVariavelJavaToPt(Variavei[1]), null);
        +                }
        +            }
        +            */
        +            printCode();
        +            //execCode();
        +        }
        +    }
        +
        +    /*
        +     *   PARA AS VARIAVEIS
        +     */
        +    public String getTipoVariavel(String tipo) { //retornar o operador equivalente java 
        +        int i = 0;
        +        while (i < tipos_variaveis_portugol.length && !tipos_variaveis_portugol[i].equals(tipo)) {
        +            i++;
        +        }
        +        return tipos_variaveis_java[i];
        +    }
        +
        +    public String getTipoVariavelJavaToPt(String tipo) { //retornar o operador equivalente java 
        +        int i = 0;
        +        while (i < tipos_variaveis_java.length && !tipos_variaveis_java[i].equals(tipo)) {
        +            i++;
        +        }
        +        return tipos_variaveis_portugol[i];
        +    }
        +
        +    public String getOperador(String tipo) { // retornar o operador equivalente java
        +        int i = 0;
        +        while (i < operacoes_portugol.length && !operacoes_portugol[i].equals(tipo)) {
        +            i++;
        +        }
        +        return operacoes_java[i];
        +    }
        +
        +    public String getValorLogico(String value) {
        +        int i = 0;
        +        while (i < valores_logicos_portugol.length && !valores_logicos_portugol[i].equals(value)) {
        +            i++;
        +        }
        +        return valores_logicos_java[i];
        +    }
        +    /*
        +     public String getValorRealfloat(String value) {
        +     return value.replace(",", ".");
        +     }
        +     */
        +
        +    public String getValorFloatreal(String value) {
        +        return value.replace(".", ",");
        +    }
        +
        +    public void addVariavel(String nome, String tipo) { //add a variavel na array para controle e seta o codigo
        +        String[] variaveis = nome.split(",");
        +        for (String var : variaveis) {
        +            String[] tmp = {var, getTipoVariavel(tipo)};
        +            Variaveis.add(tmp);
        +        }
        +    }
        +
        +    public void addVariavelVetor(String nome, String tipo, String indice1, String indice2) {
        +        String[] variaveis = nome.split(",");
        +        for (String var : variaveis) {
        +            String[] tmp = {var, getTipoVariavel(tipo), indice1, indice2};
        +            VariaveisVetor.add(tmp);
        +            setCodeVariables("\t" + getTipoVariavel(tipo) + "[] " + var + " = new " + getTipoVariavel(tipo) + "[" + (new Integer(indice2) - new Integer(indice1) + 1) + "];");
        +            setCodeVariablesExec("\t" + getTipoVariavel(tipo) + "[] " + var + " = new " + getTipoVariavel(tipo) + "[" + (new Integer(indice2) - new Integer(indice1) + 1) + "];");
        +        }
        +
        +    }
        +
        +    public String[] getVariavel(String variavel) {
        +        String[] info = new String[2];
        +
        +        for (String[] var : Variaveis) {
        +            if (var[0].equals(variavel)) {
        +                String retorno[] = {var[0], var[1]};
        +                info = retorno;
        +                break;
        +            }
        +        }
        +        return info;
        +    }
        +
        +    public String[] getVariavelVetor(String variavel) {
        +        String[] info = new String[4];
        +
        +        for (String[] var : VariaveisVetor) {
        +            if (var[0].equals(variavel)) {
        +                String retorno[] = {var[0], var[1], var[2], var[3]};
        +                info = retorno;
        +                break;
        +            }
        +        }
        +        return info;
        +    }
        +
        +    public boolean checkVariavelExiste(String variavel) {
        +        boolean tmp = false;
        +        String[] var = getVariavel(variavel);
        +        if (var[1] == null) {
        +            tmp = false;
        +        } else {
        +            tmp = true;
        +        }
        +        return tmp;
        +    }
        +
        +    public String setValorVariavelLogica(String variavel, String value) {
        +        String[] var = getVariavel(variavel);
        +        String retorno = null;
        +
        +        if (var[1] == null) {
        +            retorno = "error1"; //Variavel nao declarada
        +        } else if ("boolean".equals(var[1])) {
        +            retorno = "\t\t" + variavel + " = " + getValorLogico(value) + ";";
        +        } else {
        +            retorno = "error2"; //Variavel nao suporta String
        +        }
        +        return retorno;
        +    }
        +
        +    public String getTipoOperacao() {
        +        String tipo = null;
        +        String[] tmp_tipo = {null, null};
        +
        +        int ids_string = 0;
        +        int ids_char = 0;
        +        int ids_int = 0;
        +        int ids_float = 0;
        +        int ids_boolean = 0;
        +
        +        //caso tenha IDs
        +        if (!TipoID_tmp.isEmpty()) {
        +            for (String tmp : TipoID_tmp) {
        +                if ("String".equals(tmp)) {
        +                    ids_string++;
        +                } else if ("char".equals(tmp)) {
        +                    ids_char++;
        +                } else if ("int".equals(tmp)) {
        +                    ids_int++;
        +                } else if ("float".equals(tmp)) {
        +                    ids_float++;
        +                } else if ("boolean".equals(tmp)) {
        +                    ids_boolean++;
        +                }
        +            }
        +        }
        +        /*
        +         System.out.println("====================");
        +         System.out.println("string="+ids_string);
        +         System.out.println("char="+ids_char);
        +         System.out.println("int="+ids_int);
        +         System.out.println("float="+ids_float);
        +         System.out.println("====================");  
        +         */
        +        /*
        +         System.out.println("====================");
        +         System.out.println("string="+string_tmp);
        +         System.out.println("char="+char_tmp);
        +         System.out.println("int="+numero_int_tmp);
        +         System.out.println("float="+numero_float_tmp);
        +         System.out.println("====================");         
        +         */
        +
        +        //caso int
        +        if ((ids_int > 0 || numero_int_tmp == true) && string_tmp == false && ids_string == 0 && ids_float == 0 && numero_float_tmp == false && boolean_tmp == false && ids_boolean == 0 && ids_char == 0 && char_tmp == false) {
        +            tipo = "int";
        +
        +            //caso float
        +        } else if ((ids_float > 0 || ids_int > 0 || numero_float_tmp == true || numero_int_tmp == true) && string_tmp == false && ids_string == 0 && boolean_tmp == false && ids_boolean == 0 && ids_char == 0 && char_tmp == false) {
        +            tipo = "float";
        +
        +            //caso String
        +        } else if ((ids_string > 0 || string_tmp == true) && ids_int == 0 && ids_float == 0 && operador_tmp == false && numero_float_tmp == false && numero_int_tmp == false && boolean_tmp == false && ids_boolean == 0 && ids_char == 0 && char_tmp == false) {
        +            tipo = "String";
        +
        +            //caso char
        +        } else if ((ids_char > 0 || char_tmp == true) && operador_soma == false && ids_string == 0 && string_tmp == false && ids_int == 0 && ids_float == 0 && operador_tmp == false && numero_float_tmp == false && numero_int_tmp == false && ids_boolean == 0 && boolean_tmp == false) {
        +            tipo = "char";
        +        } //caso logico
        +        else if ((ids_boolean > 0 || boolean_tmp == true) && operador_soma == false && ids_string == 0 && string_tmp == false && ids_int == 0 && ids_float == 0 && operador_tmp == false && numero_float_tmp == false && numero_int_tmp == false && ids_char == 0 && char_tmp == false) {
        +            tipo = "boolean";
        +        }
        +
        +        resetTMPSOperadores();
        +
        +        return tipo;
        +    }
        +
        +    public String setVariavelOperador(String variavel, String value) {
        +        String retorno = null;
        +        String[] var = getVariavel(variavel);
        +
        +        if (var[1] == null) {
        +            retorno = "error1"; //Variavel nao declarada
        +        } else {
        +
        +            String tmp_tipo_operacao = getTipoOperacao();
        +
        +            if (var[1].equals(tmp_tipo_operacao)) {
        +                retorno = "\t\t" + variavel + " = (" + var[1] + ") (" + value + "); /*Variavel do tipo: " + var[1] + ", operacao do tipo: " + tmp_tipo_operacao + "*/";
        +            } else if (("int".equals(tmp_tipo_operacao) || "float".equals(tmp_tipo_operacao)) && ("int".equals(var[1]) || "float".equals(var[1]))) {
        +                retorno = "\t\t" + variavel + " = (" + var[1] + ") (" + value + "); /*Variavel do tipo: " + var[1] + ", operacao do tipo: " + tmp_tipo_operacao + "*/";
        +            } else {
        +                retorno = "error2"; //Variavel nao suporta
        +            }
        +        }
        +        return retorno;
        +    }
        +
        +    public String setVariavelVetor(String variavel, String value, String indice) {
        +        String retorno = null;
        +        String[] var = getVariavelVetor(variavel);
        +
        +        if (var[1] == null) {
        +            retorno = "error1"; //Variavel nao declarada
        +        } else {
        +
        +            String tmp_tipo_operacao = getTipoOperacao();
        +
        +            //int indice_a = new Integer(var[2]);
        +            //int indice_xo = new Integer(indice);
        +            if (var[1].equals(tmp_tipo_operacao)) {
        +                retorno = "\t\t" + variavel + "[" + indice + " - (" + var[2] + ")] = (" + var[1] + ") (" + value + "); /*Variavel do tipo: " + var[1] + ", operacao do tipo: " + tmp_tipo_operacao + "*/";
        +                retorno += "t\ttable_variaveis.update(\"" + variavel + "[\"+" + indice + "+\"]\"," + variavel + "[" + indice + " - (" + var[2] + ")]);";
        +            } else if (("int".equals(tmp_tipo_operacao) || "float".equals(tmp_tipo_operacao)) && ("int".equals(var[1]) || "float".equals(var[1]))) {
        +                retorno = "\t\t" + variavel + "[" + indice + " - (" + var[2] + ")] = (" + var[1] + ") (" + value + "); /*Variavel do tipo: " + var[1] + ", operacao do tipo: " + tmp_tipo_operacao + "*/";
        +                retorno += "t\ttable_variaveis.update(\"" + variavel + "[\"+" + indice + "+\"]\"," + variavel + "[" + indice + " - (" + var[2] + ")]);";
        +            } else {
        +                retorno = "error2"; //Variavel nao suporta
        +            }
        +        }
        +        return retorno;
        +    }
        +
        +    /*
        +     * PARA VALORES LOGICOS
        +     */
        +    public String getTipoCondiconal(String tipo) { //retornar o operador equivalente java 
        +        int i = 0;
        +        while (!condicionais_portugol[i].equals(/*tipo.toLowerCase()*/tipo)) {
        +            i++;
        +        }
        +        return condicionais_java[i];
        +    }
        +
        +    /*
        +     * CONDICINAIS
        +     */
        +    public String setSubCondicional(String condicional) {
        +        String retorno = null;
        +
        +        int op_tipo_int = 0;
        +        int op_tipo_char = 0;
        +        int op_tipo_string = 0;
        +        int op_tipo_float = 0;
        +        int op_tipo_logico = 0;
        +
        +        for (String tmp : TiposOperacoesTMP) {
        +            if ("String".equals(tmp)) {
        +                op_tipo_string++;
        +            } else if ("char".equals(tmp)) {
        +                op_tipo_char++;
        +            } else if ("int".equals(tmp)) {
        +                op_tipo_int++;
        +            } else if ("float".equals(tmp)) {
        +                op_tipo_float++;
        +            } else if ("boolean".equals(tmp)) {
        +                op_tipo_logico++;
        +            } else {
        +                retorno = "error1";
        +            }
        +        }
        +        /*
        +        System.out.println("====================");
        +        System.out.println("op_tipo_int=" + op_tipo_int);
        +        System.out.println("op_tipo_char=" + op_tipo_char);
        +        System.out.println("op_tipo_string=" + op_tipo_string);
        +        System.out.println("op_tipo_float=" + op_tipo_float);
        +        System.out.println("op_tipo_logico=" + op_tipo_logico);
        +        System.out.println("====================");
        +        */
        +        if (!"error1".equals(retorno)) {
        +            //caso int e float (permitido qualquer tipo de comparacao)
        +            if ((op_tipo_int > 0 | op_tipo_float > 0) && op_tipo_string == 0 && op_tipo_logico == 0 && op_tipo_char == 0) {
        +                //caso String (permitido apenas compacao de == e !=)
        +            } else if ((op_tipo_string > 0) && op_tipo_int == 0 && op_tipo_float == 0 && op_tipo_logico == 0 && op_tipo_char == 0 /*COMPARACOES*/ && condicionais_numericas == false) {
        +                retorno = "String";
        +                //caso Logico
        +            } else if ((op_tipo_logico > 0) && op_tipo_int == 0 && op_tipo_float == 0 && op_tipo_string == 0 && op_tipo_char == 0 /*COMPARACOES*/ && condicionais_numericas == false) {
        +                //caso char
        +            } else if ((op_tipo_char > 0) && op_tipo_int == 0 && op_tipo_float == 0 && op_tipo_string == 0 && op_tipo_logico == 0 /*COMPARACOES*/ && condicionais_numericas == false) {
        +                //caso erro
        +            } else {
        +                retorno = condicional;
        +            }
        +        }
        +
        +        resetTMPSSubCondicionais();
        +
        +        return retorno;
        +    }
        +
        +    public String setCondicional(String condicional) {
        +        String retorno = null;
        +
        +        int op_tipo_int = 0;
        +        int op_tipo_char = 0;
        +        int op_tipo_string = 0;
        +        int op_tipo_float = 0;
        +        int op_tipo_logico = 0;
        +
        +        for (String tmp : TiposOperacoesTMP) {
        +            if ("String".equals(tmp)) {
        +                op_tipo_string++;
        +            } else if ("char".equals(tmp)) {
        +                op_tipo_char++;
        +            } else if ("int".equals(tmp)) {
        +                op_tipo_int++;
        +            } else if ("float".equals(tmp)) {
        +                op_tipo_float++;
        +            } else if ("boolean".equals(tmp)) {
        +                op_tipo_logico++;
        +            } else {
        +                retorno = "error1";
        +            }
        +        }
        +
        +        if (!"error1".equals(retorno)) {
        +            // caso exista int ou float sem comparacao
        +            if ((op_tipo_int > 0 || op_tipo_float > 0) && condicionais_numericas_permanentes == false && condicionais_comparativas_permanentes == false) {
        +                retorno = condicional;
        +            } else if (op_tipo_string > 0 && condicionais_comparativas_permanentes == false) {
        +                retorno = condicional;
        +            } else if (op_tipo_char > 0 && condicionais_comparativas_permanentes == false) {
        +                retorno = condicional;
        +            }
        +        }
        +        return retorno;
        +    }
        +
        +    public SimpleAttributeSet AttrColor(String tipe) {
        +        SimpleAttributeSet retorno = new SimpleAttributeSet();
        +
        +        switch (tipe) {
        +            case "error":
        +                retorno.addAttribute(StyleConstants.CharacterConstants.Bold, Boolean.FALSE);
        +                retorno.addAttribute(StyleConstants.CharacterConstants.Foreground, Color.RED);
        +                break;
        +
        +            case "codigo_finalizado":
        +                retorno.addAttribute(StyleConstants.CharacterConstants.Bold, Boolean.TRUE);
        +                retorno.addAttribute(StyleConstants.CharacterConstants.Foreground, Color.decode("#558737"));
        +                break;
        +
        +            case "codigo_finalizado_error":
        +                retorno.addAttribute(StyleConstants.CharacterConstants.Bold, Boolean.TRUE);
        +                retorno.addAttribute(StyleConstants.CharacterConstants.Foreground, Color.decode("#960E0E"));
        +                break;
        +        }
        +
        +        return retorno;
        +    }
        +
        +    public String Erros(String error, String complemento) {
        +        String retorno = null;
        +        switch (error) {
        +            ////////////////////////////
        +            //PARA AS VARIAVEIS NORMAIS
        +            ////////////////////////////
        +            case "VARIAVEL_ERRO1":
        +                retorno = "Erro de syntax: Variável %s não foi declarada.".replace("%s", complemento);
        +                break;
        +            case "VARIAVEL_ERRO2":
        +                retorno = "Erro de syntax: Variável %s não suporta esse tipo de valor.".replace("%s", complemento);
        +                break;
        +            //////////////////
        +            //PARA OS VETORES
        +            //////////////////
        +            case "VARIAVEL_VETOR_ERRO1":
        +                retorno = "Erro de syntax: Vetor %s não foi declarado.".replace("%s", complemento);
        +                break;
        +            case "VARIAVEL_VETOR_ERRO2":
        +                retorno = "Erro de syntax: Vetor %s não suporta esse tipo de valor.".replace("%s", complemento);
        +                break;
        +            case "VARIAVEL_VETOR_ERRO3":
        +                retorno = "Erro de syntax: Índice do vetor %s está incorreto.".replace("%s", complemento);
        +                break;
        +            case "VARIAVEL_VETOR_ERRO4":
        +                retorno = "Erro de syntax: Índice do vetor %s deve ser um valor inteiro.".replace("%s", complemento);
        +                break;
        +            ///////////////////////
        +            //PARA AS CONDICIONAIS
        +            ///////////////////////
        +            case "CONDICIONAL_ERRO1":
        +                retorno = "Erro de syntax: Há uma operacão indevida na condicional.";
        +                break;
        +            case "CONDICIONAL_ERRO2":
        +                retorno = "Erro de syntax: Comparação indevida em: %s.".replace("%s", complemento);
        +                break;
        +
        +            /////////////////////
        +            //ERRO DE OPERACAO///
        +            case "OPERACAO_ERRO1":
        +                retorno = "Erro de syntax: Operação indevida.";
        +                break;
        +
        +            /////////////////////
        +            //ERRO FOR///////////
        +            /////////////////////
        +            case "INDICE_FOR":
        +                retorno = "Erro de syntax: Índice do para não podem ser invertidos.";
        +                break;
        +            case "TIPO_VARIAVEL_FOR":
        +                retorno = "Erro de syntax: Tipo de operação não permitida para o para.";
        +                break;
        +                
        +                
        +            ///////
        +            //ALL//
        +            ///////
        +            case "SOMENTE_INT":
        +                retorno = "Erro de syntax: Não é permitido outro tipo de operação: Somente tipo int.";
        +                break;
        +                
        +            case "SOMENTE_NUMEROS":
        +                retorno = "Erro de syntax: Não é permitido outro tipo de operação: Somente numeros.";
        +                break;
        +        }
        +        return retorno;
        +    }
        +}
        diff --git a/src/com/compilador/portugol/CompilarCUP.bat b/src/com/compilador/portugol/CompilarCUP.bat
        new file mode 100644
        index 0000000..fe362fa
        --- /dev/null
        +++ b/src/com/compilador/portugol/CompilarCUP.bat
        @@ -0,0 +1,3 @@
        +@echo off
        +java -jar java_cup.jar ./Portugol.cup
        +pause
        \ No newline at end of file
        diff --git a/src/com/compilador/portugol/ExecCompilador.java b/src/com/compilador/portugol/ExecCompilador.java
        new file mode 100644
        index 0000000..818cc1c
        --- /dev/null
        +++ b/src/com/compilador/portugol/ExecCompilador.java
        @@ -0,0 +1,35 @@
        +/*
        + * To change this license header, choose License Headers in Project Properties.
        + * To change this template file, choose Tools | Templates
        + * and open the template in the editor.
        + */
        +package com.compilador.portugol;
        +
        +import static com.forms.Editor.tab;
        +import java.io.StringReader;
        +import java.util.logging.Level;
        +import java.util.logging.Logger;
        +
        +/**
        + *
        + * @author SIMONETO-2
        + */
        +public class ExecCompilador extends Compilador {
        +
        +    public ExecCompilador() {
        +        PortugolFlex lexer = new PortugolFlex(new StringReader(tab.getEditorPane().getText()));
        +        
        +        
        +        //Symbol sym;
        +        //for (sym = lexer.next_token(); sym.sym != 0; sym = lexer.next_token()) {
        +        //System.out.println("Token " + sym.sym + ", with value = " + sym.value + "; at line " + sym.left + ", column " + sym.right);
        +        //}
        +        
        +        parser p = new parser(lexer);
        +        try {
        +            p.parse();
        +        } catch (Exception ex) {
        +            Logger.getLogger(ExecCompilador.class.getName()).log(Level.SEVERE, null, ex);
        +        }
        +    }
        +}
        diff --git a/src/com/compilador/portugol/Exemplo.txt b/src/com/compilador/portugol/Exemplo.txt
        new file mode 100644
        index 0000000..7cf7a74
        --- /dev/null
        +++ b/src/com/compilador/portugol/Exemplo.txt
        @@ -0,0 +1,71 @@
        +algoritmo "Algoritmo - Olá mundo"
        +
        +var s : string
        +    c : caracter
        +
        +inicio
        +    c <- 'c'
        +fimalgoritmo
        +
        +
        +
        +
        +
        +/*
        +algoritmo 'teste'
        +
        +var
        +    numero,controle,tmp_espacos,i,n : inteiro
        +    retorno : vetor[1..100] de caracter
        +inicio
        +    escreva("Digite um numero: ")
        +    leia(numero)
        +
        +    controle <- numero
        +    tmp_espacos <- numero
        +
        +    para i de 0 ate (numero-1) faca
        +        retorno[i] <- ""
        +        para n de 0 ate (controle-1) faca
        +            se(tmp_espacos > 1)entao
        +                retorno[i] <- retorno[i] + " "
        +                tmp_espacos <- tmp_espacos - 1
        +            senao
        +                retorno[i] <- retorno[i] + "0"
        +            fimse
        +        fimpara
        +        controle <- controle + 1
        +        tmp_espacos <- numero - (i+1)
        +        escreval(retorno[i])
        +    fimpara
        +
        +fimalgoritmo
        +
        +algoritmo "teste"
        +
        +var nome : caracter
        +
        +inicio
        +    escreva("Digite seu nomes: ")
        +    leia(nome)
        +    escreva("Seu nome e ",nome)
        +fimalgoritmo
        +
        +
        +
        +
        +algoritmo "Algoritmo - Olá mundo"
        +
        +var
        +    nLoop : inteiro
        +    nome : vetor[1..10] de caracter
        +
        +inicio
        +    nLoop <- 1
        +    enquanto nLoop <= 10 faca
        +        leia(nome[nLoop])
        +        nLoop <- nLoop + 1
        +    fimenquanto
        +fimalgoritmo
        +
        +*/
        \ No newline at end of file
        diff --git a/src/com/compilador/portugol/Inicializador.java b/src/com/compilador/portugol/Inicializador.java
        new file mode 100644
        index 0000000..dd6461d
        --- /dev/null
        +++ b/src/com/compilador/portugol/Inicializador.java
        @@ -0,0 +1,40 @@
        +/*
        + * To change this license header, choose License Headers in Project Properties.
        + * To change this template file, choose Tools | Templates
        + * and open the template in the editor.
        + */
        +package com.compilador.portugol;
        +
        +import static com.forms.Editor.tab;
        +import java.io.IOException;
        +import java.io.StringReader;
        +import java.util.Scanner;
        +import java.util.concurrent.locks.ReentrantLock;
        +import java_cup.runtime.Symbol;
        +
        +/**
        + *
        + * @author Andrew
        + */
        +public class Inicializador {
        +
        +    private final ReentrantLock lock = new ReentrantLock();
        +
        +    public static void main(String[] args) throws IOException, Exception {
        +        //Yylex lexer = new Yylex(new StringReader("2+9"));
        +        //PortugolFlex lexer = new PortugolFlex(Inicializador.class.getResourceAsStream("Exemplo.txt"));
        +
        +        //Symbol sym;
        +        //for (sym = lexer.next_token(); sym.sym != 0; sym = lexer.next_token()) {
        +        //System.out.println("Token " + sym.sym + ", with value = " + sym.value + "; at line " + sym.left + ", column " + sym.right);
        +        //}
        +        //parser p = new parser(lexer);
        +        //p.parse();
        +        //p.debug_parse();
        +        //System.out.print(Math.sin(90*Math.PI/180));
        +        if(System.getProperty("os.name").toLowerCase().contains("win")){
        +            System.out.print("windows");
        +        }
        +    }
        +
        +}
        diff --git a/src/com/compilador/portugol/Portugol.cup b/src/com/compilador/portugol/Portugol.cup
        new file mode 100644
        index 0000000..79d9111
        --- /dev/null
        +++ b/src/com/compilador/portugol/Portugol.cup
        @@ -0,0 +1,648 @@
        +////////////////////////////////////////////////////////////////////////
        +/*                                                                  ////
        +* ANALIZADOR DE PORTUGOL (GRAMATICA).							    ////
        +* BY: ANDREW NETO                                                   ////
        +* 05/07/2014                                                        ////
        +*/                                                                  ////
        +////////////////////////////////////////////////////////////////////////
        +
        +package com.compilador.portugol;
        +
        +/*import static com.analizador.portugol.parser.error;*/
        +import java_cup.runtime.*;
        +import javax.swing.JOptionPane;
        +
        +
        +parser code
        +{:
        +
        +	static Compilador util = new Compilador();
        +
        +    public void syntax_error(Symbol s){
        +    	if(s.value != null){
        +	        report_error("Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right+1)+". Trecho desconhecido: "+s.value,null);
        +	        JOptionPane.showMessageDialog(null,"Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right+1)+". Trecho desconhecido: "+s.value,"Erro de syntax",JOptionPane.WARNING_MESSAGE);
        +	    }else{
        +	        report_error("Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right+1),null);
        +	        JOptionPane.showMessageDialog(null,"Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right+1),"Erro de syntax",JOptionPane.WARNING_MESSAGE);
        +	    }
        +        util.setErro();
        +        this.done_parsing();
        +    }
        +    public void syntax_error(int left,int right,String mensagem){
        +		report_error(mensagem + " " + "Linha "+(left+1)+" Coluna "+(right),null);
        +		JOptionPane.showMessageDialog(null,mensagem + " " + "Linha "+(left+1)+" Coluna "+(right+1),"Erro de syntax",JOptionPane.WARNING_MESSAGE);
        +
        +        util.setErro();
        +        this.done_parsing();
        +    }
        +    public void report_fatal_error(String message, Object info){
        +    	this.done_parsing();
        +    }
        +:}
        +
        +
        +init with {:
        +	 util = new Compilador();
        +:};
        +
        +
        +action code {::}
        +
        +terminal ALGORITMO;
        +terminal VAR;
        +terminal String TIPO_VARIAVEL,TIPO_VARIAVEL_VETOR;
        +
        +terminal INICIO;
        +
        +terminal String OPERADOR,OPERADOR_SOMA,VALOR_LOGICO;
        +terminal ATRIBUIR;
        +terminal ABRIR_PARENTESE, FECHAR_PARENTESE,ABRIR_COLCHETE,FECHAR_COLCHETE,DOIS_PONTOS;
        +
        +terminal SE,ENTAO,SENAO,FIMSE;
        +terminal ENQUANTO,PARA,FACA,FIMENQUANTO,FIMPARA;
        +terminal ESCOLHA,CASO,OUTROCASO,FIMESCOLHA;
        +
        +terminal INTERROMPA,ESPERAR,POTENCIA,MODULO,SENO,COSSENO,TANGENTE,RAIZ;
        +terminal PI;
        +
        +terminal FUNCAO,FIMFUNCAO,VOID;
        +terminal String CONDICIONAL_NUMERICA,CONDICIONAL_COMPARATIVA;
        +
        +terminal DE,E,ATE,PASSO,OU,NAO;
        +
        +terminal ESCREVA,ESCREVAL,LEIA;
        +
        +terminal FIMALGORITMO;
        +
        +terminal ADD_ATTR_VAR, SEPARADOR;
        +terminal String ID,STRING,NUMERO_INT,NUMERO_FLOAT,CHAR;
        +
        +
        +non terminal algoritmo;
        +
        +/* ALGORITMO DECLARACAO */
        +non terminal algoritmo_nome, algoritmo_instanciacao;
        +
        +/* VAR DECLARACAO */
        +non terminal var_estrutura, variaveis, var_instanciacao;
        +non terminal String var_listagem;
        +
        +
        +
        +/* TERMINAL PROGRAMA */
        +non terminal programa, corpo_programa;
        +
        +/* FUNCOES */
        +non terminal 	instanciacao_variaveis,
        +
        +				condiciona_estrutura,
        +				condicional_1,
        +				condicional_2,
        +
        +				escreva_funcao,
        +
        +				leia_funcao,
        +
        +				enquanto_funcao,
        +
        +				para_funcao,
        +				para_funcao_1,
        +
        +				escolha_funcao,
        +				escolha_loop,
        +				escolha_casos,
        +				escolha_outrocaso,
        +
        +				funcoes_unitarias,
        +
        +				funcao_estruturacao,
        +				funcao_parametros_loop,
        +				funcao_parametros;
        +
        +/* PARA OPERACOES EM GERAL*/
        +non terminal String _operacoes,_operacoes_indice_vetor;
        +non terminal String _condicional,_sub_condicional;
        +non terminal String _loop_virgula,_loop_virgula_id;
        +non terminal String _para_complementar;
        +
        +
        +/* PRESEDENCIA DE OPERACOES */
        +precedence left OPERADOR,OPERADOR_SOMA;
        +
        +precedence left ABRIR_PARENTESE, FECHAR_PARENTESE;
        +
        +/* PRESEDENCIA DE VARIAVEIS */
        +precedence left SEPARADOR;
        +
        +/* PRECEDENCIAS CONDICIONAIS */
        +precedence left E,OU;
        +precedence left CONDICIONAL_NUMERICA,CONDICIONAL_COMPARATIVA;
        +
        +
        +start with algoritmo;
        +
        +
        +
        +/**********************************************************************************************************************************/
        +/**********************************************************************************************************************************/
        +/**********************************************************************************************************************************/
        +
        +
        +
        +/*************/
        +/* ALGORITMO */
        +/*************/
        +algoritmo 		::= algoritmo_nome 
        +					var_estrutura
        +					INICIO
        +					programa
        +					FIMALGORITMO {: util.setEndClass(); util.codeComplete(); :} 
        +					|;
        +
        +
        +
        +/****************************************/
        +/* PARA A DECLARACAO DO NO DO ALGORITMO */
        +/****************************************/
        +algoritmo_nome   		::= algoritmo_instanciacao {: util.setInitClass(); :};
        +algoritmo_instanciacao  ::= ALGORITMO ID:e {: 
        +								util.setCode("public class "+e+" {"); 
        +								util.setCodeName(e); 
        +							:} | 
        +							ALGORITMO STRING:e {: 
        +								util.setCode("public class "+e.substring(1, e.length()-1)+" {"); 
        +								util.setCodeName(e.substring(1, e.length()-1)); 
        +							:};
        +
        +
        +
        +
        +/**********************************/
        +/* PARA A DECLARACAO DE VARIAVEIS */
        +/**********************************/
        +var_estrutura		::= VAR | VAR variaveis |;
        +variaveis 			::= variaveis var_instanciacao | var_instanciacao;
        +var_instanciacao 	::= var_listagem:e ADD_ATTR_VAR TIPO_VARIAVEL:x {:
        +							util.addVariavel(e,x);
        +							util.setCodeVariables("\t" + util.getTipoVariavel(x) + " " +e+ ";");
        +							util.setCodeVariablesExec("\t" + util.getTipoVariavel(x) + " " +e+ ";");
        +						:} |
        +						var_listagem:e ADD_ATTR_VAR TIPO_VARIAVEL_VETOR ABRIR_COLCHETE NUMERO_INT:n1 DOIS_PONTOS NUMERO_INT:n2 FECHAR_COLCHETE DE TIPO_VARIAVEL:x {:
        +							util.addVariavelVetor(e,x,n1,n2); 
        +						:};
        +
        +var_listagem      	::= var_listagem:e1 SEPARADOR var_listagem:e2 {: RESULT = e1+","+e2; :} | 
        +						ID:value  {: RESULT = value; :};
        +
        +
        +
        +
        +/************/
        +/* PROGRAMA */
        +/************/
        +programa 	::= programa corpo_programa | ;
        +
        +corpo_programa ::= funcoes_unitarias | instanciacao_variaveis | condiciona_estrutura | escreva_funcao | leia_funcao | enquanto_funcao | para_funcao | escolha_funcao;
        +
        +
        +
        +/**********************/
        +/* CRIACAO DE FUNCOES */
        +/**********************/
        +/*
        +funcao_estruturacao 	::= FUNCAO ID:id ABRIR_PARENTESE funcao_parametros_loop FECHAR_PARENTESE DOIS_PONTOS TIPO_VARIAVEL
        +
        +
        +funcao_parametros_loop 	::= funcao_parametros_loop funcao_parametros | ;
        +funcao_parametros 	::= ID:id DOIS_PONTOS TIPO_VARIAVEL:tipo;
        +*/
        +
        +
        +/**********************/
        +/* FUNCOES UNITARIAS  */
        +/**********************/
        +funcoes_unitarias 	::= INTERROMPA:i {:
        +							util.setCode("\t\tbreak;");
        +							util.setCodeExec("\t\tbreak;",ileft);
        +						:} |
        +						ESPERAR:f ABRIR_PARENTESE _operacoes:n FECHAR_PARENTESE {:
        +							String tmp_tipo_operacao = util.getTipoOperacao();
        +							if(tmp_tipo_operacao != "int"){
        +								parser.syntax_error(nleft,nright,util.Erros("SOMENTE_INT",null));
        +							}else{
        +								util.setCode("\t\tThread.sleep("+n+");");
        +								util.setCodeExec("\t\tThread.sleep("+n+");",fleft);
        +							}
        +						:};
        +
        +
        +
        +
        +/*********************************/
        +/* PARA INSTANCIACAO DE VARIAVEIS*/
        +/*********************************/
        +instanciacao_variaveis   ::=  ID:x ATRIBUIR _operacoes:e {:
        +							  		String tmp = util.setVariavelOperador(x,e);
        +							  		switch(tmp){
        +							  			case "error1" : parser.syntax_error(xleft,xright,util.Erros("VARIAVEL_ERRO1",x)); break;
        +							  			case "error2" : parser.syntax_error(xleft,xright,util.Erros("VARIAVEL_ERRO2",x)); break;
        +							  			default: 
        +							  				util.setCode(tmp);
        +							  				util.setCodeExec(tmp + "\ttable_variaveis.update(\""+x+"\","+x+");",xleft);
        +							  			break;
        +							  		}
        +							  :} | 
        +							  ID:x ABRIR_COLCHETE _operacoes_indice_vetor:n FECHAR_COLCHETE ATRIBUIR _operacoes:e {:
        +							  		String tmp = util.setVariavelVetor(x,e,n);
        +							  		switch(tmp){
        +							  			case "error1" : parser.syntax_error(xleft,xright,util.Erros("VARIAVEL_VETOR_ERRO1",x)); break;
        +							  			case "error2" : parser.syntax_error(xleft,xright,util.Erros("VARIAVEL_VETOR_ERRO2",x)); break;
        +							  			case "error3" : parser.syntax_error(xleft,xright,util.Erros("VARIAVEL_VETOR_ERRO3",x)); break;
        +							  			default: 
        +							  				util.setCode(tmp);
        +							  				util.setCodeExec(tmp,xleft);
        +							  			break;
        +							  		}
        +							  :};
        +
        +
        +
        +/****************/
        +/* CONDICIONAIS */
        +/****************/
        +condiciona_estrutura 	::= condicional_1 programa FIMSE:p {:
        +								util.setCode("\t\t}");
        +								util.setCodeExec("\t\t}",pleft);
        +							:}| 
        +							condicional_1 programa condicional_2 programa FIMSE:p3 {:
        +								util.setCode("\t\t}");
        +								util.setCodeExec("\t\t}",p3left);
        +							:};
        +
        +
        +condicional_1 	::= SE _condicional:c ENTAO {:
        +						util.setCode("\t\tif("+c+"){");
        +						util.setCodeExec("\t\tif("+c+"){",cleft);
        +					:};
        +
        +
        +condicional_2 	::= SENAO:p {:
        +						util.setCode("\t\t}else{");
        +						util.setCodeExec("\t\t}else{",pleft);
        +					:};
        +
        +
        +enquanto_funcao 	::= ENQUANTO _condicional:c FACA {:
        +							util.setCode("\t\twhile("+c+"){");
        +							util.setCodeExec("\t\twhile("+c+"){",cleft);
        +						:} programa FIMENQUANTO:p {: util.setCode("\t\t}");util.setCodeExec("\t\t}",pleft);  :};
        +
        +
        +
        +
        +
        +/***************/
        +/* FUNCAO PARA */
        +/***************/
        +para_funcao 	::= para_funcao_1;
        +
        +
        +para_funcao_1 ::= PARA ID:n DE _operacoes:n1 {:
        +						String tmp_tipo_operacao = util.getTipoOperacao();
        +						if(tmp_tipo_operacao != "int"){
        +							parser.syntax_error(n1left,n1right,util.Erros("TIPO_VARIAVEL_FOR",null));
        +						}
        +				:} ATE _operacoes:n2 {:
        +						String tmp_tipo_operacao = util.getTipoOperacao();
        +						if(tmp_tipo_operacao != "int"){
        +							parser.syntax_error(n2left,n2right,util.Erros("TIPO_VARIAVEL_FOR",null));
        +						}
        +				:} _para_complementar:n3 FACA:p {:
        +					String tmp[] = util.getVariavel(n);
        +
        +					if(tmp[1] != null) {
        +						if("int".equals(tmp[1])){
        +							if(n3 != null){
        +								util.setCode("\t\tfor("+n+" = "+n1+";"+n+" <= "+n2+";"+n+"+="+n3+"){");
        +								util.setCodeExec("\t\tfor("+n+" = "+n1+";"+n+" <= "+n2+";"+n+"+="+n3+"){",pleft);
        +							}else{
        +								util.setCode("\t\tfor("+n+" = "+n1+";"+n+" <= "+n2+";"+n+"++){");
        +								util.setCodeExec("\t\tfor("+n+" = "+n1+";"+n+" <= "+n2+";"+n+"++){",pleft);
        +							}
        +							util.setCodeExec("\t\ttable_variaveis.update(\""+n+"\","+n+");");
        +						}else{
        +							parser.syntax_error(nleft,nright,util.Erros("TIPO_VARIAVEL_FOR",null));
        +						}
        +					}else{
        +						parser.syntax_error(nleft,nright,util.Erros("VARIAVEL_ERRO1",n));
        +					}
        +				:} programa FIMPARA:f {: util.setCode("\t\t}");util.setCodeExec("\t\t}",fleft);  :};
        +
        +
        +_para_complementar ::= PASSO _operacoes:n3 {:
        +						String tmp_tipo_operacao = util.getTipoOperacao();
        +						if(tmp_tipo_operacao != "int"){
        +							parser.syntax_error(n3left,n3right,util.Erros("TIPO_VARIAVEL_FOR",null));
        +						}else{
        +							RESULT = n3;
        +						}
        +					:} |;
        +
        +
        +
        +
        +
        +/*****************************/
        +/* FUNCAO ESCREVA E ESCREVAL */
        +/*****************************/
        +escreva_funcao 		::= ESCREVA ABRIR_PARENTESE _loop_virgula:e FECHAR_PARENTESE {: 
        +							util.setCode("\t\tSystem.out.print("+e+");");
        +							util.setCodeExec("\t\tConsoleIO.print("+e+");",eleft); 
        +						:} |
        +						ESCREVAL ABRIR_PARENTESE _loop_virgula:e FECHAR_PARENTESE {: 
        +							util.setCode("\t\tSystem.out.println("+e+");");
        +							util.setCodeExec("\t\tConsoleIO.println("+e+");",eleft); 
        +						:};
        +
        +
        +/***************/
        +/* FUNCAO LEIA */
        +/***************/
        +leia_funcao 		::= LEIA ABRIR_PARENTESE _loop_virgula_id:e FECHAR_PARENTESE {:
        +							util.setLeia(true);
        +
        +							for (String ids : e.split(",")) {
        +								String[] tmp;
        +
        +								if(e.indexOf("[") > 0){
        +									tmp = util.getVariavelVetor(ids.replaceAll("\\[.*\\]",""));
        +									String indice = ids.substring(ids.indexOf("[")+1,ids.indexOf("]"));
        +									ids = ids.substring(0,ids.indexOf("]"))+"-("+tmp[2]+")]";
        +									switch(tmp[1]){
        +										case "int" : util.setCode("\t\t"+ids+" = ConsoleIO.nextInt();");util.setCodeExec("\t\t"+ids+" = ConsoleIO.writeInt();",eleft);break;
        +										case "float" : util.setCode("\t\t"+ids+" = scanIn.nextFloat();");util.setCodeExec("\t\t"+ids+" = ConsoleIO.writeFloat();",eleft);break;
        +										case "String" : util.setCode("\t\t"+ids+" = scanIn.next();");util.setCodeExec("\t\t"+ids+" = ConsoleIO.writeString();",eleft);break;
        +										case "char" : util.setCode("\t\t"+ids+" = scanIn.nextChar();");util.setCodeExec("\t\t"+ids+" = ConsoleIO.writeChar();",eleft);break;
        +									}
        +									util.setCodeExec("\t\ttable_variaveis.update(\""+tmp[0]+"[\"+"+indice+"+\"]\","+ids+");"); 
        +								}else{
        +									tmp = util.getVariavel(ids);
        +									switch(tmp[1]){
        +										case "int" : util.setCode("\t\t"+ids+" = ConsoleIO.nextInt();");util.setCodeExec("\t\t"+ids+" = ConsoleIO.writeInt();",eleft);break;
        +										case "float" : util.setCode("\t\t"+ids+" = scanIn.nextFloat();");util.setCodeExec("\t\t"+ids+" = ConsoleIO.writeFloat();",eleft);break;
        +										case "String" : util.setCode("\t\t"+ids+" = scanIn.next();");util.setCodeExec("\t\t"+ids+" = ConsoleIO.writeString();",eleft);break;
        +										case "char" : util.setCode("\t\t"+ids+" = scanIn.nextChar();");util.setCodeExec("\t\t"+ids+" = ConsoleIO.writeChar();",eleft);break;
        +									}
        +									util.setCodeExec("\t\ttable_variaveis.update(\""+ids+"\","+ids+");");
        +								}
        +							}
        +						:};
        +
        +
        +
        +/******************/
        +/* FUNCAO ESCOLHA */
        +/******************/
        +escolha_funcao 	::= ESCOLHA _operacoes:a {: 
        +						String tmp_tipo_operacao = util.getTipoOperacao(); 
        +						util.setCode("\t\tswitch("+a+"){");
        +						util.setCodeExec("\t\tswitch("+a+"){",aleft); 
        +					:} escolha_loop escolha_outrocaso FIMESCOLHA:f {:
        +						util.setCode("\t\t}");
        +						util.setCodeExec("\t\t}",fleft); 
        +					:};
        +
        +escolha_loop 	::= escolha_loop escolha_casos |;
        +
        +escolha_casos 	::= CASO _operacoes:b {: 
        +						String tmp_tipo_operacao = util.getTipoOperacao(); 
        +						util.setCode("\t\tcase("+b+"):");
        +						util.setCodeExec("\t\tcase("+b+"):",bleft); 
        +					:} programa;
        +
        +escolha_outrocaso 	::= OUTROCASO programa |;
        +
        +
        +
        +
        +
        +
        +/************************************************************************************************************/
        +/************************************************************************************************************/
        +/************************************************************************************************************/
        +
        +
        +/************************/
        +/* CONDICINAL GRAMATICA */
        +/************************/
        +_condicional 	::= _condicional:c1 E _condicional:c2 {:
        +						RESULT = c1+" && "+c2;
        +						util.setCondicinalETMP(true);
        +					:} |
        +					_condicional:c1 OU _condicional:c2 {:
        +						RESULT = c1+" || "+c2;
        +						util.setCondicionalOuTMP(true);
        +					:} |
        +					ABRIR_PARENTESE _condicional:e FECHAR_PARENTESE	{: RESULT = "("+e+")"; :} |
        +					NAO ABRIR_PARENTESE _condicional:e FECHAR_PARENTESE	{: RESULT = "!("+e+")"; :} |
        +					_sub_condicional:e {: 
        +						RESULT = e; 
        +						String tmp = util.setCondicional(RESULT);
        +						if(tmp != null){
        +							switch(tmp){
        +								case "error1" : parser.syntax_error(eleft,eright,util.Erros("CONDICIONAL_ERRO1",null)); break;
        +								default: parser.syntax_error(eleft,eright,util.Erros("CONDICIONAL_ERRO2",tmp)); break;
        +							}
        +						}
        +
        +					:};
        +
        +_sub_condicional 	::= _sub_condicional:s1 CONDICIONAL_NUMERICA:c _sub_condicional:s2 {:
        +							RESULT = s1+" "+c+" "+s2;
        +							util.setCondicinalNumericaTMP(true);
        +
        +							String tmp = util.setSubCondicional(RESULT);
        +							if(tmp != null){
        +								switch(tmp){
        +									case "error1" : parser.syntax_error(s1left,s1right,util.Erros("CONDICIONAL_ERRO1",null)); break;
        +									default: parser.syntax_error(s1left,s1right,util.Erros("CONDICIONAL_ERRO2",tmp)); break;
        +								}
        +							}
        +
        +						:} |
        +						_sub_condicional:s1 CONDICIONAL_COMPARATIVA:c _sub_condicional:s2 {:
        +							
        +							util.setCondicionalComparativaTMP(true);
        +							
        +							RESULT = s1+" "+util.getTipoCondiconal(c)+" "+s2;
        +
        +							String tmp = util.setSubCondicional(RESULT);
        +							
        +							if("String".equals(tmp)){
        +								if("<>".equals(c)){
        +									RESULT = "!"+s1+".equals("+s2+")";
        +								}else{
        +									RESULT = s1+".equals("+s2+")";
        +								}
        +							}
        +							else if(tmp != null){
        +								switch(tmp){
        +									case "error1" : parser.syntax_error(s1left,s1right,util.Erros("CONDICIONAL_ERRO1",null)); break;
        +									default: parser.syntax_error(s1left,s1right,util.Erros("CONDICIONAL_ERRO2",tmp)); break;
        +								}
        +							}
        +
        +						:} |
        +						ABRIR_PARENTESE _sub_condicional:e FECHAR_PARENTESE	{: RESULT = "("+e+")"; :} |
        +						NAO ABRIR_PARENTESE _sub_condicional:e FECHAR_PARENTESE	{: RESULT = "!("+e+")"; :} |
        +						_operacoes:e {: 
        +							RESULT = e;
        +							util.setTiposOperacaoeTMP(util.getTipoOperacao());
        +						:};
        +
        +
        +
        +/********************************************************************************************/
        +/* LOOP COM VIRGULA PARA O ESCREVAL (PERMITIDO STRING IDS VETORES INTEIROS VALORES LOGICOS) */
        +/********************************************************************************************/
        +_loop_virgula 	::= _loop_virgula:e1 SEPARADOR _loop_virgula:e2 {: RESULT = e1 + " + " + e2; :} |
        +					_operacoes:e {: 
        +						RESULT = "("+e+")"; 
        +						String tmp = util.getTipoOperacao(); 
        +						if(tmp == null){
        +							parser.syntax_error(eleft,eright,util.Erros("OPERACAO_ERRO1",null));
        +						}
        +					:};
        +
        +
        +/********************************************************/
        +/* LOOP COM VIRGULA PARA O LEIA (SOMENTE IDS E VETORES) */
        +/********************************************************/
        +_loop_virgula_id ::= _loop_virgula_id:e1 SEPARADOR _loop_virgula_id:e2 {: RESULT = e1 + "," + e2; :} |
        +		          		ID:n {: 
        +							if(util.checkVariavelExiste(n)) {
        +								RESULT = n;
        +							}else{
        +								parser.syntax_error(nleft,nright,util.Erros("VARIAVEL_ERRO1",n));
        +							}
        +						:} |
        +						ID:n ABRIR_COLCHETE _operacoes_indice_vetor:i FECHAR_COLCHETE {:
        +							String[] tmp = util.getVariavelVetor(n);
        +							if(tmp[0] != null){
        +								RESULT = n+"["+i+"]";
        +							}else{
        +								parser.syntax_error(nleft,nright,util.Erros("VARIAVEL_VETOR_ERRO1",n));	
        +							}
        +						:};
        +
        +
        +/*************/
        +/* OPERACOES */
        +/*************/
        +_operacoes ::= _operacoes:e1 OPERADOR:op _operacoes:e2	{: 
        +					RESULT = e1+" "+util.getOperador(op)+" "+e2; 
        +					util.setOperadorTMP(true);
        +				:} |
        +
        +				_operacoes:e1 OPERADOR_SOMA _operacoes:e2	{: 
        +					RESULT = e1+" + "+e2; 
        +					util.setOperadorSomaTMP(true);
        +				:} |
        +
        +				POTENCIA ABRIR_PARENTESE _operacoes:n1 SEPARADOR _operacoes:n2 FECHAR_PARENTESE {:
        +					RESULT = "Math.pow("+n1+","+n2+")";
        +					util.setOperadorTMP(true);
        +				:} |
        +
        +				MODULO ABRIR_PARENTESE _operacoes:n FECHAR_PARENTESE {:
        +					RESULT = "Math.abs("+n+")";
        +					util.setOperadorTMP(true);
        +				:} |
        +
        +				SENO ABRIR_PARENTESE _operacoes:n FECHAR_PARENTESE {:
        +					RESULT = "Math.sin("+n+"*"+(Math.PI)/180+")";
        +					util.setOperadorTMP(true);
        +				:} |
        +
        +				COSSENO ABRIR_PARENTESE _operacoes:n FECHAR_PARENTESE {:
        +					RESULT = "Math.cos("+n+"*"+(Math.PI)/180+")";
        +					util.setOperadorTMP(true);
        +				:} |
        +
        +				TANGENTE ABRIR_PARENTESE _operacoes:n FECHAR_PARENTESE {:
        +					RESULT = "Math.tan("+n+"*"+(Math.PI)/180+")";
        +					util.setOperadorTMP(true);
        +				:} |
        +
        +
        +				RAIZ ABRIR_PARENTESE _operacoes:n FECHAR_PARENTESE {:
        +					RESULT = "Math.sqrt("+n+")";
        +					util.setOperadorTMP(true);
        +				:} |
        +
        +          		ABRIR_PARENTESE _operacoes:e FECHAR_PARENTESE	{: RESULT = "("+e+")"; :} |
        +
        +				ID:n ABRIR_COLCHETE _operacoes_indice_vetor:i FECHAR_COLCHETE {:
        +					String[] tmp = util.getVariavelVetor(n);
        +					if(tmp[0] != null){
        +						util.setTipoIdTMP(tmp[1]);
        +						RESULT = n+"["+i+" - ("+tmp[2]+")]";
        +					}else{
        +						parser.syntax_error(nleft,nright,util.Erros("VARIAVEL_VETOR_ERRO1",n));	
        +					}
        +				:} |
        +          		NUMERO_INT:n {: 
        +					RESULT = n;
        +					util.setNumeroIntTMP(true); 
        +				:} |
        +          		NUMERO_FLOAT:n {: 
        +					RESULT = n;
        +					util.setNumerofloatTMP(true); 
        +				:} |
        +				PI {:
        +					RESULT = ""+Math.PI;
        +					util.setNumerofloatTMP(true); 
        +				:} |
        +          		ID:n {: 
        +					if(util.checkVariavelExiste(n)) {
        +						String[] tmp = util.getVariavel(n);
        +						util.setTipoIdTMP(tmp[1]);
        +						RESULT = n;
        +					}else{
        +						parser.syntax_error(nleft,nright,util.Erros("VARIAVEL_ERRO1",n));	
        +					}
        +				:} |
        +				STRING:s {: 
        +					util.setStringTMP(true);
        +					RESULT = s;
        +				:} |
        +				CHAR:s {:
        +					util.setCharTMP(true);
        +					RESULT = s;
        +				:} |
        +				VALOR_LOGICO:l {:
        +					util.setBooleanTMP(true);
        +					RESULT = util.getValorLogico(l);
        +				:};
        +
        +
        +/********************************/
        +/* OPERAÇÕES DE INCICE VETORIAL */
        +/********************************/
        +_operacoes_indice_vetor ::= _operacoes_indice_vetor:e1 OPERADOR:op _operacoes_indice_vetor:e2	{: RESULT = e1+" "+util.getOperador(op)+" "+e2;  :} |
        +							_operacoes_indice_vetor:e1 OPERADOR_SOMA _operacoes_indice_vetor:e2	{: RESULT = e1+" + "+e2; :} |
        +							ABRIR_PARENTESE _operacoes_indice_vetor:e FECHAR_PARENTESE {: RESULT = e; :} |
        +							NUMERO_INT:n {: RESULT = n; :} |
        +			          		ID:n {:
        +			          			String[] tmp = util.getVariavel(n);
        +								if(tmp[1] != null) {
        +									if("int".equals(tmp[1])){
        +										RESULT = n;
        +									}else{
        +										parser.syntax_error(nleft,nright,util.Erros("VARIAVEL_ERRO1",n));
        +									}
        +								}else{
        +									parser.syntax_error(nleft,nright,util.Erros("VARIAVEL_VETOR_ERRO4",n));	
        +								}
        +							:};
        \ No newline at end of file
        diff --git a/src/com/compilador/portugol/Portugol.flex b/src/com/compilador/portugol/Portugol.flex
        new file mode 100644
        index 0000000..3fdd929
        --- /dev/null
        +++ b/src/com/compilador/portugol/Portugol.flex
        @@ -0,0 +1,233 @@
        +////////////////////////////////////////////////////////////////////////
        +/*                                                                  ////
        +* ANALIZADOR DE PORTUGOL (TOKENS).   							    ////
        +* BY: ANDREW NETO                                                   ////
        +* 05/07/2014                                                        ////
        +*/                                                                  ////
        +////////////////////////////////////////////////////////////////////////
        +
        +package com.compilador.portugol;
        +
        +import java_cup.runtime.*;
        +
        +
        +%%
        +%class PortugolFlex
        +%cup
        +%line
        +%char
        +%column
        +
        +/*%caseless*/
        +/*%ignorecase*/
        +
        +%{
        +
        +    public PortugolFlex() {
        +        super();
        +    }
        +
        +    Symbol newSym(int tokenId) {
        +        return new Symbol(tokenId , yyline, yycolumn);
        +    }
        +
        +    Symbol newSym(int tokenId, Object value) {
        +        return new Symbol(tokenId , yyline, yycolumn, value);
        +    }
        +
        +%}
        +
        +
        +letras          = [A-Za-z]
        +numeros         = [0-9]
        +alphanumeric    = {letras}|{numeros}
        +underline   	= [_]
        +identifier      = {letras}({alphanumeric}|{underline})*
        +
        +inteiro			= {numeros}+|\-{numeros}+
        +fracao			= \.{numeros}*
        +exponent        = (E|e)(\+|\-)?{numeros}*
        +float			= ((({numeros}* {fracao} {exponent}?))|({numeros}+\.)|({numeros}+\.? {exponent})) |
        +				  \-((({numeros}* {fracao} {exponent}?))|({numeros}+\.)|({numeros}+\.? {exponent}))
        +
        +
        +whitespace      = [\n\r\ \t]
        +
        +string_content  = (\\\"|[^\n\r\"]|\\{whitespace}+\\)*
        +string_literal  = {double_qoute}{string_content}{double_qoute}
        +double_qoute    = \"
        +
        +
        +string_content_single  = (\\\'|[^\n\r\']|\\{whitespace}+\\){0,1}
        +string_literal_single  = {double_qoute_single}{string_content_single}{double_qoute_single}
        +double_qoute_single    = \'
        +
        +/*
        +string = {string_literal}
        +char = {string_literal_single}
        +*/
        +
        +string = (\" ( [^\"\n\\] | \\[^\n] )* (\n | \\\n | \")) 
        +char = (\' ( [^\'\n\\] | \\[^\n] ){0,1} (\n | \\\n | \'))
        +
        +
        +newline         = \r|\n|\r\n
        +InputCharacter 	= [^\r\n]
        +
        +Comment 			= {TraditionalComment} | {EndOfLineComment} 
        +TraditionalComment 	= "/*" [^*] ~"*/" | "/*" "*"+ "/"
        +EndOfLineComment 	= "//" {InputCharacter}* {newline}?
        +
        +
        +%%
        +
        +{Comment}					{/* IGNORAR COMENTARIOS */}
        +
        +/*
        +* ALGORITMO NAME
        +*/
        +
        +"algoritmo"					{return newSym(sym.ALGORITMO,yytext()); }
        +
        +
        +/*
        +* VARIAVEIS
        +*/
        +
        +"var"						{return newSym(sym.VAR,yytext()); }
        +"inteiro"					{return newSym(sym.TIPO_VARIAVEL,yytext()); }
        +"real"						{return newSym(sym.TIPO_VARIAVEL,yytext()); }
        +"caracter"					{return newSym(sym.TIPO_VARIAVEL,yytext()); }
        +"string"					{return newSym(sym.TIPO_VARIAVEL,yytext()); }
        +"logico"					{return newSym(sym.TIPO_VARIAVEL,yytext()); }
        +"vetor"						{return newSym(sym.TIPO_VARIAVEL_VETOR,yytext()); }
        +
        +
        +/*
        +* ESTRUTURA
        +*/
        +
        +"inicio"					{return newSym(sym.INICIO,yytext()); }
        +"fimalgoritmo"				{return newSym(sym.FIMALGORITMO,yytext()); }
        +
        +
        +/*
        +* CONDICIONAL
        +*/
        +"se"						{return newSym(sym.SE,yytext()); }
        +"entao"						{return newSym(sym.ENTAO,yytext()); }
        +"senao"						{return newSym(sym.SENAO,yytext()); }
        +"fimse"						{return newSym(sym.FIMSE,yytext()); }
        +
        +/*
        +* FUNCAO REPETICAO
        +*/
        +"enquanto"						{return newSym(sym.ENQUANTO,yytext()); }
        +"faca"							{return newSym(sym.FACA,yytext()); }
        +"fimenquanto"					{return newSym(sym.FIMENQUANTO,yytext()); }
        +
        +"para"							{return newSym(sym.PARA,yytext()); }
        +"fimpara"						{return newSym(sym.FIMPARA,yytext()); }
        +
        +
        +
        +/*
        +* FUNCOES
        +*/
        +"escreva"						{return newSym(sym.ESCREVA,yytext()); }
        +"escreval"						{return newSym(sym.ESCREVAL,yytext()); }
        +"leia"							{return newSym(sym.LEIA,yytext()); }
        +
        +"escolha"						{return newSym(sym.ESCOLHA,yytext()); }
        +"caso"							{return newSym(sym.CASO,yytext()); }
        +"outrocaso"						{return newSym(sym.OUTROCASO,yytext()); }
        +"fimescolha"					{return newSym(sym.FIMESCOLHA,yytext()); }
        +
        +"interrompa"					{return newSym(sym.INTERROMPA,yytext()); }
        +"espere"					{return newSym(sym.ESPERAR,yytext()); }
        +
        +"funcao"						{return newSym(sym.FUNCAO,yytext()); }
        +"fimfuncao"						{return newSym(sym.FIMFUNCAO,yytext()); }
        +"vazio"							{return newSym(sym.VOID,yytext()); }
        +
        +/*
        +* AUXILIARES
        +*/
        +
        +"de"						{return newSym(sym.DE,yytext()); }
        +"e"							{return newSym(sym.E,yytext()); }
        +"ate"						{return newSym(sym.ATE,yytext()); }
        +"passo"						{return newSym(sym.PASSO,yytext()); }
        +"ou"						{return newSym(sym.OU,yytext()); }
        +"nao"						{return newSym(sym.NAO,yytext()); }
        +
        +
        +/*
        +* VARIAVEL LOGICA
        +*/
        +"verdadeiro"				{return newSym(sym.VALOR_LOGICO,yytext());}
        +"falso"						{return newSym(sym.VALOR_LOGICO,yytext());}
        +
        +
        +/*
        +* OPERADORES
        +*/
        +
        +"["							{return newSym(sym.ABRIR_COLCHETE,yytext());}
        +"]"							{return newSym(sym.FECHAR_COLCHETE,yytext());}
        +"("         				{return newSym(sym.ABRIR_PARENTESE,yytext());}
        +")"         				{return newSym(sym.FECHAR_PARENTESE,yytext());}
        +
        +
        +".."						{return newSym(sym.DOIS_PONTOS,yytext());}
        +":"							{return newSym(sym.ADD_ATTR_VAR,yytext());}
        +","							{return newSym(sym.SEPARADOR,yytext());}
        +
        +
        +"+"         				{return newSym(sym.OPERADOR_SOMA,yytext());}
        +"-"         				{return newSym(sym.OPERADOR,yytext());}
        +"*"         				{return newSym(sym.OPERADOR,yytext());}
        +"/"         				{return newSym(sym.OPERADOR,yytext());}
        +"mod"         				{return newSym(sym.OPERADOR,yytext());}
        +"div"         				{return newSym(sym.OPERADOR,yytext());}
        +
        +
        +
        +"pot"						{return newSym(sym.POTENCIA,yytext());}
        +"modulo"					{return newSym(sym.MODULO,yytext());}
        +"sen"						{return newSym(sym.SENO,yytext());}
        +"cos"						{return newSym(sym.COSSENO,yytext());}
        +"tan"						{return newSym(sym.TANGENTE,yytext());}
        +"raiz"						{return newSym(sym.RAIZ,yytext());}
        +
        +"PI"						{return newSym(sym.PI,yytext());}
        +
        +"<"							{return newSym(sym.CONDICIONAL_NUMERICA,yytext());}
        +"<="						{return newSym(sym.CONDICIONAL_NUMERICA,yytext());}
        +">"							{return newSym(sym.CONDICIONAL_NUMERICA,yytext());}
        +">="						{return newSym(sym.CONDICIONAL_NUMERICA,yytext());}
        +
        +"<>"						{return newSym(sym.CONDICIONAL_COMPARATIVA,yytext());}
        +"="         				{return newSym(sym.CONDICIONAL_COMPARATIVA,yytext());}
        +
        +
        +"<-"						{return newSym(sym.ATRIBUIR,yytext());}
        +":="						{return newSym(sym.ATRIBUIR,yytext());}
        +
        +
        +
        +
        +/*
        +* REGIDOS POR REGEXP
        +*/
        +{inteiro}					{return newSym(sym.NUMERO_INT, yytext()); }
        +{float}   					{return newSym(sym.NUMERO_FLOAT, yytext()); }
        +{identifier}				{return newSym(sym.ID,yytext()); }
        +{string}					{return newSym(sym.STRING, yytext()); }
        +{char}                      {return newSym(sym.CHAR, yytext()); }
        +{newline}					{/* IGNORE */}
        +{whitespace}				{/* IGNORE */}
        +
        +
        +<>     				{return newSym(sym.EOF);}
        +.           				{return newSym(sym.error,yytext()); }
        \ No newline at end of file
        diff --git a/src/com/compilador/portugol/PortugolFlex.java b/src/com/compilador/portugol/PortugolFlex.java
        new file mode 100644
        index 0000000..0669019
        --- /dev/null
        +++ b/src/com/compilador/portugol/PortugolFlex.java
        @@ -0,0 +1,1132 @@
        +/* The following code was generated by JFlex 1.5.1 */
        +
        +////////////////////////////////////////////////////////////////////////
        +/*                                                                  ////
        +* ANALIZADOR DE PORTUGOL (TOKENS).   							    ////
        +* BY: ANDREW NETO                                                   ////
        +* 05/07/2014                                                        ////
        +*/                                                                  ////
        +////////////////////////////////////////////////////////////////////////
        +
        +package com.compilador.portugol;
        +
        +import java_cup.runtime.*;
        +
        +
        +
        +/**
        + * This class is a scanner generated by 
        + * JFlex 1.5.1
        + * from the specification file C:/Users/SIMONETO-2/Documents/NetBeansProjects/portugol-projeto/src/com/compilador/portugol/Portugol.flex
        + */
        +class PortugolFlex implements java_cup.runtime.Scanner {
        +
        +  /** This character denotes the end of file */
        +  public static final int YYEOF = -1;
        +
        +  /** initial size of the lookahead buffer */
        +  private static final int ZZ_BUFFERSIZE = 16384;
        +
        +  /** lexical states */
        +  public static final int YYINITIAL = 0;
        +
        +  /**
        +   * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l
        +   * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l
        +   *                  at the beginning of a line
        +   * l is of the form l = 2*k, k a non negative integer
        +   */
        +  private static final int ZZ_LEXSTATE[] = { 
        +     0, 0
        +  };
        +
        +  /** 
        +   * Translates characters to character classes
        +   */
        +  private static final String ZZ_CMAP_PACKED = 
        +    "\11\0\1\11\1\16\1\57\1\57\1\14\22\0\1\11\1\0\1\13"+
        +    "\4\0\1\15\1\46\1\47\1\20\1\10\1\51\1\4\1\5\1\17"+
        +    "\12\2\1\50\1\0\1\54\1\55\1\56\2\0\4\1\1\6\3\1"+
        +    "\1\53\6\1\1\52\12\1\1\44\1\12\1\45\1\0\1\3\1\0"+
        +    "\1\21\1\1\1\33\1\43\1\7\1\35\1\23\1\41\1\26\2\1"+
        +    "\1\22\1\30\1\32\1\24\1\40\1\36\1\25\1\34\1\27\1\37"+
        +    "\1\31\3\1\1\42\12\0\1\57\u1fa2\0\1\57\1\57\udfd6\0";
        +
        +  /** 
        +   * Translates characters to character classes
        +   */
        +  private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);
        +
        +  /** 
        +   * Translates DFA states to action switch labels.
        +   */
        +  private static final int [] ZZ_ACTION = zzUnpackAction();
        +
        +  private static final String ZZ_ACTION_PACKED_0 =
        +    "\1\0\1\1\1\2\1\3\1\4\1\5\1\6\1\7"+
        +    "\1\10\1\1\1\10\1\1\2\4\16\2\1\11\1\12"+
        +    "\1\13\1\14\1\15\1\16\1\2\1\17\1\20\1\17"+
        +    "\2\5\1\21\2\2\2\0\1\22\2\0\1\23\1\24"+
        +    "\1\0\4\2\1\25\12\2\1\26\6\2\1\27\1\2"+
        +    "\1\30\1\31\1\17\1\5\4\2\1\0\2\24\2\0"+
        +    "\1\2\1\32\7\2\1\33\1\4\2\2\1\34\1\2"+
        +    "\1\35\2\2\1\36\1\37\7\2\1\40\1\4\5\2"+
        +    "\1\0\1\2\1\41\2\2\1\42\1\43\7\2\1\44"+
        +    "\3\2\1\45\6\2\1\46\1\2\1\47\14\2\1\50"+
        +    "\1\51\1\2\1\52\1\2\1\53\3\2\1\54\3\2"+
        +    "\1\55\3\2\1\56\2\2\1\57\1\2\1\60\7\2"+
        +    "\1\61\1\2\1\62\1\63\11\2\1\64\1\65\1\66"+
        +    "\10\2\1\67\1\70\4\2\1\71\1\72\1\2\1\73"+
        +    "\1\2\1\74\1\2\1\75";
        +
        +  private static int [] zzUnpackAction() {
        +    int [] result = new int[230];
        +    int offset = 0;
        +    offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result);
        +    return result;
        +  }
        +
        +  private static int zzUnpackAction(String packed, int offset, int [] result) {
        +    int i = 0;       /* index in packed string  */
        +    int j = offset;  /* index in unpacked array */
        +    int l = packed.length();
        +    while (i < l) {
        +      int count = packed.charAt(i++);
        +      int value = packed.charAt(i++);
        +      do result[j++] = value; while (--count > 0);
        +    }
        +    return j;
        +  }
        +
        +
        +  /** 
        +   * Translates a state to a row index in the transition table
        +   */
        +  private static final int [] ZZ_ROWMAP = zzUnpackRowMap();
        +
        +  private static final String ZZ_ROWMAP_PACKED_0 =
        +    "\0\0\0\60\0\140\0\220\0\300\0\360\0\u0120\0\60"+
        +    "\0\60\0\u0150\0\u0180\0\u01b0\0\u01e0\0\60\0\u0210\0\u0240"+
        +    "\0\u0270\0\u02a0\0\u02d0\0\u0300\0\u0330\0\u0360\0\u0390\0\u03c0"+
        +    "\0\u03f0\0\u0420\0\u0450\0\u0480\0\60\0\60\0\60\0\60"+
        +    "\0\u04b0\0\60\0\u04e0\0\u0510\0\60\0\u0540\0\u0570\0\u05a0"+
        +    "\0\60\0\u05d0\0\u0600\0\u0150\0\u0630\0\60\0\u0660\0\u0690"+
        +    "\0\60\0\u06c0\0\u06f0\0\u0720\0\u0750\0\u0780\0\u07b0\0\u07e0"+
        +    "\0\u0810\0\u0840\0\u0870\0\u08a0\0\u08d0\0\u0900\0\u0930\0\u0960"+
        +    "\0\u0990\0\u09c0\0\u09f0\0\u0a20\0\u0a50\0\u0a80\0\u0ab0\0\u0ae0"+
        +    "\0\u0b10\0\140\0\u0b40\0\60\0\140\0\60\0\u0b70\0\u0ba0"+
        +    "\0\u0bd0\0\u0c00\0\u0c30\0\u0c60\0\u0c90\0\60\0\u0cc0\0\u0cf0"+
        +    "\0\u0d20\0\140\0\u0d50\0\u0d80\0\u0db0\0\u0de0\0\u0e10\0\u0e40"+
        +    "\0\u0e70\0\140\0\u0ea0\0\u0ed0\0\u0f00\0\140\0\u0f30\0\140"+
        +    "\0\u0f60\0\u0f90\0\140\0\u0fc0\0\u0ff0\0\u1020\0\u1050\0\u1080"+
        +    "\0\u10b0\0\u10e0\0\u1110\0\140\0\140\0\u1140\0\u1170\0\u11a0"+
        +    "\0\u11d0\0\u1200\0\u1230\0\u1260\0\140\0\u1290\0\u12c0\0\140"+
        +    "\0\140\0\u12f0\0\u1320\0\u1350\0\u1380\0\u13b0\0\u13e0\0\u1410"+
        +    "\0\140\0\u1440\0\u1470\0\u14a0\0\140\0\u14d0\0\u1500\0\u1530"+
        +    "\0\u1560\0\u1590\0\u15c0\0\140\0\u15f0\0\140\0\u1620\0\u1650"+
        +    "\0\u1680\0\u16b0\0\u16e0\0\u1710\0\u1740\0\u1770\0\u17a0\0\u17d0"+
        +    "\0\u1800\0\u1830\0\140\0\140\0\u1860\0\140\0\u1890\0\140"+
        +    "\0\u18c0\0\u18f0\0\u1920\0\140\0\u1950\0\u1980\0\u19b0\0\140"+
        +    "\0\u19e0\0\u1a10\0\u1a40\0\140\0\u1a70\0\u1aa0\0\140\0\u1ad0"+
        +    "\0\140\0\u1b00\0\u1b30\0\u1b60\0\u1b90\0\u1bc0\0\u1bf0\0\u1c20"+
        +    "\0\140\0\u1c50\0\140\0\u1c80\0\u1cb0\0\u1ce0\0\u1d10\0\u1d40"+
        +    "\0\u1d70\0\u1da0\0\u1dd0\0\u1e00\0\u1e30\0\140\0\140\0\140"+
        +    "\0\u1e60\0\u1e90\0\u1ec0\0\u1ef0\0\u1f20\0\u1f50\0\u1f80\0\u1fb0"+
        +    "\0\140\0\140\0\u1fe0\0\u2010\0\u2040\0\u2070\0\140\0\140"+
        +    "\0\u20a0\0\140\0\u20d0\0\140\0\u2100\0\140";
        +
        +  private static int [] zzUnpackRowMap() {
        +    int [] result = new int[230];
        +    int offset = 0;
        +    offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result);
        +    return result;
        +  }
        +
        +  private static int zzUnpackRowMap(String packed, int offset, int [] result) {
        +    int i = 0;  /* index in packed string  */
        +    int j = offset;  /* index in unpacked array */
        +    int l = packed.length();
        +    while (i < l) {
        +      int high = packed.charAt(i++) << 16;
        +      result[j++] = high | packed.charAt(i++);
        +    }
        +    return j;
        +  }
        +
        +  /** 
        +   * The transition table of the DFA
        +   */
        +  private static final int [] ZZ_TRANS = zzUnpackTrans();
        +
        +  private static final String ZZ_TRANS_PACKED_0 =
        +    "\1\2\1\3\1\4\1\2\1\5\1\6\1\3\1\7"+
        +    "\1\10\1\11\1\2\1\12\1\13\1\14\1\11\1\15"+
        +    "\1\16\1\17\1\20\1\3\1\21\1\22\1\23\1\24"+
        +    "\1\25\1\26\1\27\1\30\1\31\1\32\2\3\1\33"+
        +    "\2\3\1\34\1\35\1\36\1\37\1\40\1\41\1\42"+
        +    "\1\43\1\3\1\44\1\45\1\46\62\0\3\3\2\0"+
        +    "\2\3\11\0\23\3\6\0\2\3\6\0\1\4\2\0"+
        +    "\1\47\2\50\52\0\1\4\2\0\1\47\54\0\1\47"+
        +    "\2\0\1\51\2\50\51\0\3\3\2\0\2\3\11\0"+
        +    "\11\3\1\52\1\3\1\53\7\3\6\0\2\3\4\0"+
        +    "\12\54\1\55\1\56\2\54\1\56\41\54\16\0\1\11"+
        +    "\41\0\12\57\1\60\2\57\2\61\41\57\17\0\1\62"+
        +    "\1\63\40\0\3\3\2\0\2\3\11\0\1\3\1\64"+
        +    "\4\3\1\65\14\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\1\3\1\66\11\0\3\3\1\67\17\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\16\3\1\70\4\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\1\3\1\71\11\0"+
        +    "\1\72\22\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\11\3\1\73\11\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\1\74\22\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\3\3\1\75\17\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\1\3\1\76\11\0\1\77"+
        +    "\22\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\1\100\22\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\1\101\2\3\1\102\17\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\1\3\1\103\11\0\6\3\1\104\14\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\1\105"+
        +    "\4\3\1\106\10\3\1\107\4\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\1\110\2\3\1\111\17\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\1\3\1\112\11\0"+
        +    "\5\3\1\113\15\3\6\0\2\3\61\0\1\114\3\0"+
        +    "\3\3\2\0\2\3\11\0\23\3\6\0\1\3\1\115"+
        +    "\10\0\1\114\50\0\1\116\1\45\56\0\1\116\4\0"+
        +    "\1\47\3\0\2\50\52\0\1\117\1\0\1\117\3\0"+
        +    "\1\117\50\0\3\3\2\0\2\3\11\0\6\3\1\120"+
        +    "\6\3\1\121\5\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\12\3\1\122\4\3\1\123\3\3\6\0"+
        +    "\2\3\4\0\16\54\1\56\41\54\12\0\1\124\2\0"+
        +    "\2\61\41\0\16\57\1\61\41\57\14\62\1\125\1\62"+
        +    "\1\126\41\62\20\127\1\130\37\127\1\0\3\3\2\0"+
        +    "\2\3\11\0\2\3\1\131\20\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\1\3\1\132\11\0\23\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\5\3\1\133\15\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\2\3"+
        +    "\1\134\20\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\6\3\1\135\14\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\1\136\22\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\5\3\1\137\15\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\5\3\1\140"+
        +    "\1\141\14\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\11\3\1\142\11\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\22\3\1\143\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\4\3\1\144\1\3\1\145"+
        +    "\14\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\4\3\1\146\14\3\1\147\1\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\3\3\1\150\17\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\4\3\1\151"+
        +    "\6\3\1\152\7\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\13\3\1\153\7\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\11\3\1\154\11\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\4\3\1\155"+
        +    "\16\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\1\3\1\156\10\3\1\157\10\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\7\3\1\160\13\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\11\3\1\161"+
        +    "\11\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\4\3\1\162\6\3\1\163\7\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\6\3\1\164\14\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\10\3\1\165"+
        +    "\12\3\6\0\2\3\6\0\1\117\56\0\3\3\2\0"+
        +    "\2\3\11\0\1\166\22\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\16\3\1\167\4\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\3\3\1\170\1\171"+
        +    "\16\3\6\0\2\3\5\0\3\3\2\0\1\3\1\172"+
        +    "\11\0\23\3\6\0\2\3\22\0\1\61\57\0\1\126"+
        +    "\41\0\20\127\1\173\37\127\17\0\1\126\1\130\40\0"+
        +    "\3\3\2\0\2\3\11\0\3\3\1\174\17\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\1\175\22\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\5\3"+
        +    "\1\176\15\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\4\3\1\177\16\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\1\3\1\200\21\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\21\3\1\201\1\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\12\3"+
        +    "\1\202\10\3\6\0\2\3\5\0\3\3\2\0\1\3"+
        +    "\1\203\11\0\23\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\16\3\1\204\4\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\22\3\1\205\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\3\3\1\206\17\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\5\3"+
        +    "\1\207\15\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\1\210\22\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\3\3\1\211\17\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\1\212\22\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\5\3\1\213\15\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\13\3"+
        +    "\1\214\7\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\1\215\22\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\1\3\1\216\11\0\1\217\12\3\1\220\1\221\2\3"+
        +    "\1\222\3\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\12\3\1\223\10\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\1\224\22\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\13\3\1\225\7\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\3\3\1\226"+
        +    "\17\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\1\227\22\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\1\3\1\230\21\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\1\3\1\231\11\0\23\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\4\3\1\232\16\3\6\0"+
        +    "\2\3\4\0\17\127\1\126\1\173\37\127\1\0\3\3"+
        +    "\2\0\2\3\11\0\4\3\1\233\16\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\12\3\1\234\10\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\3\3"+
        +    "\1\235\17\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\5\3\1\236\15\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\4\3\1\237\1\240\15\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\1\3\1\241"+
        +    "\21\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\1\242\22\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\4\3\1\243\16\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\3\3\1\244\17\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\12\3\1\245\10\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\3\3"+
        +    "\1\246\17\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\11\3\1\247\11\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\3\3\1\250\17\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\11\3\1\251\1\3"+
        +    "\1\252\7\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\1\3\1\253\21\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\1\3\1\254\11\0\23\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\16\3\1\255\4\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\1\256\22\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\1\257"+
        +    "\22\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\3\3\1\260\17\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\11\3\1\261\11\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\20\3\1\262\2\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\10\3\1\263"+
        +    "\12\3\6\0\2\3\5\0\3\3\2\0\1\3\1\264"+
        +    "\11\0\23\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\5\3\1\265\15\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\3\3\1\200\17\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\12\3\1\266\10\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\3\3"+
        +    "\1\267\17\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\4\3\1\270\16\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\4\3\1\234\16\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\3\3\1\271\17\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\22\3"+
        +    "\1\272\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\6\3\1\273\14\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\2\3\1\200\20\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\15\3\1\274\5\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\12\3\1\275"+
        +    "\10\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\2\3\1\276\20\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\11\3\1\277\11\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\4\3\1\300\16\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\3\3\1\301"+
        +    "\17\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\6\3\1\302\14\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\1\303\22\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\1\304\22\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\6\3\1\305\14\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\1\306\22\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\3\3"+
        +    "\1\307\17\3\6\0\2\3\5\0\3\3\2\0\1\3"+
        +    "\1\310\11\0\23\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\1\3\1\311\11\0\23\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\16\3\1\312\4\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\3\3\1\313\17\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\3\3"+
        +    "\1\314\17\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\12\3\1\315\10\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\1\316\22\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\3\3\1\317\17\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\1\3\1\320"+
        +    "\21\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\7\3\1\321\13\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\13\3\1\322\7\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\7\3\1\323\13\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\5\3\1\324"+
        +    "\15\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\4\3\1\200\16\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\1\325\22\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\1\3\1\326\21\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\4\3\1\327\16\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\1\330"+
        +    "\22\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\3\3\1\331\17\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\3\3\1\332\17\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\17\3\1\333\3\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\4\3\1\214"+
        +    "\16\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\11\3\1\334\11\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\20\3\1\335\2\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\5\3\1\336\15\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\3\3\1\337"+
        +    "\17\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\1\340\22\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\6\3\1\341\14\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\1\342\22\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\6\3\1\343\14\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\3\3\1\344"+
        +    "\17\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\7\3\1\345\13\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\3\3\1\346\17\3\6\0\2\3\4\0";
        +
        +  private static int [] zzUnpackTrans() {
        +    int [] result = new int[8496];
        +    int offset = 0;
        +    offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result);
        +    return result;
        +  }
        +
        +  private static int zzUnpackTrans(String packed, int offset, int [] result) {
        +    int i = 0;       /* index in packed string  */
        +    int j = offset;  /* index in unpacked array */
        +    int l = packed.length();
        +    while (i < l) {
        +      int count = packed.charAt(i++);
        +      int value = packed.charAt(i++);
        +      value--;
        +      do result[j++] = value; while (--count > 0);
        +    }
        +    return j;
        +  }
        +
        +
        +  /* error codes */
        +  private static final int ZZ_UNKNOWN_ERROR = 0;
        +  private static final int ZZ_NO_MATCH = 1;
        +  private static final int ZZ_PUSHBACK_2BIG = 2;
        +
        +  /* error messages for the codes above */
        +  private static final String ZZ_ERROR_MSG[] = {
        +    "Unkown internal scanner error",
        +    "Error: could not match input",
        +    "Error: pushback value was too large"
        +  };
        +
        +  /**
        +   * ZZ_ATTRIBUTE[aState] contains the attributes of state aState
        +   */
        +  private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute();
        +
        +  private static final String ZZ_ATTRIBUTE_PACKED_0 =
        +    "\1\0\1\11\5\1\2\11\4\1\1\11\16\1\4\11"+
        +    "\1\1\1\11\2\1\1\11\3\1\1\11\2\1\2\0"+
        +    "\1\11\2\0\1\11\1\1\1\0\30\1\1\11\1\1"+
        +    "\1\11\5\1\1\0\1\1\1\11\2\0\42\1\1\0"+
        +    "\153\1";
        +
        +  private static int [] zzUnpackAttribute() {
        +    int [] result = new int[230];
        +    int offset = 0;
        +    offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result);
        +    return result;
        +  }
        +
        +  private static int zzUnpackAttribute(String packed, int offset, int [] result) {
        +    int i = 0;       /* index in packed string  */
        +    int j = offset;  /* index in unpacked array */
        +    int l = packed.length();
        +    while (i < l) {
        +      int count = packed.charAt(i++);
        +      int value = packed.charAt(i++);
        +      do result[j++] = value; while (--count > 0);
        +    }
        +    return j;
        +  }
        +
        +  /** the input device */
        +  private java.io.Reader zzReader;
        +
        +  /** the current state of the DFA */
        +  private int zzState;
        +
        +  /** the current lexical state */
        +  private int zzLexicalState = YYINITIAL;
        +
        +  /** this buffer contains the current text to be matched and is
        +      the source of the yytext() string */
        +  private char zzBuffer[] = new char[ZZ_BUFFERSIZE];
        +
        +  /** the textposition at the last accepting state */
        +  private int zzMarkedPos;
        +
        +  /** the current text position in the buffer */
        +  private int zzCurrentPos;
        +
        +  /** startRead marks the beginning of the yytext() string in the buffer */
        +  private int zzStartRead;
        +
        +  /** endRead marks the last character in the buffer, that has been read
        +      from input */
        +  private int zzEndRead;
        +
        +  /** number of newlines encountered up to the start of the matched text */
        +  private int yyline;
        +
        +  /** the number of characters up to the start of the matched text */
        +  private int yychar;
        +
        +  /**
        +   * the number of characters from the last newline up to the start of the 
        +   * matched text
        +   */
        +  private int yycolumn;
        +
        +  /** 
        +   * zzAtBOL == true <=> the scanner is currently at the beginning of a line
        +   */
        +  private boolean zzAtBOL = true;
        +
        +  /** zzAtEOF == true <=> the scanner is at the EOF */
        +  private boolean zzAtEOF;
        +
        +  /** denotes if the user-EOF-code has already been executed */
        +  private boolean zzEOFDone;
        +
        +  /* user code: */
        +
        +    public PortugolFlex() {
        +        super();
        +    }
        +
        +    Symbol newSym(int tokenId) {
        +        return new Symbol(tokenId , yyline, yycolumn);
        +    }
        +
        +    Symbol newSym(int tokenId, Object value) {
        +        return new Symbol(tokenId , yyline, yycolumn, value);
        +    }
        +
        +
        +
        +  /**
        +   * Creates a new scanner
        +   * There is also a java.io.InputStream version of this constructor.
        +   *
        +   * @param   in  the java.io.Reader to read input from.
        +   */
        +  PortugolFlex(java.io.Reader in) {
        +    this.zzReader = in;
        +  }
        +
        +  /**
        +   * Creates a new scanner.
        +   * There is also java.io.Reader version of this constructor.
        +   *
        +   * @param   in  the java.io.Inputstream to read input from.
        +   */
        +  PortugolFlex(java.io.InputStream in) {
        +    this(new java.io.InputStreamReader
        +             (in, java.nio.charset.Charset.forName("UTF-8")));
        +  }
        +
        +  /** 
        +   * Unpacks the compressed character translation table.
        +   *
        +   * @param packed   the packed character translation table
        +   * @return         the unpacked character translation table
        +   */
        +  private static char [] zzUnpackCMap(String packed) {
        +    char [] map = new char[0x10000];
        +    int i = 0;  /* index in packed string  */
        +    int j = 0;  /* index in unpacked array */
        +    while (i < 138) {
        +      int  count = packed.charAt(i++);
        +      char value = packed.charAt(i++);
        +      do map[j++] = value; while (--count > 0);
        +    }
        +    return map;
        +  }
        +
        +
        +  /**
        +   * Refills the input buffer.
        +   *
        +   * @return      false, iff there was new input.
        +   * 
        +   * @exception   java.io.IOException  if any I/O-Error occurs
        +   */
        +  private boolean zzRefill() throws java.io.IOException {
        +
        +    /* first: make room (if you can) */
        +    if (zzStartRead > 0) {
        +      System.arraycopy(zzBuffer, zzStartRead,
        +                       zzBuffer, 0,
        +                       zzEndRead-zzStartRead);
        +
        +      /* translate stored positions */
        +      zzEndRead-= zzStartRead;
        +      zzCurrentPos-= zzStartRead;
        +      zzMarkedPos-= zzStartRead;
        +      zzStartRead = 0;
        +    }
        +
        +    /* is the buffer big enough? */
        +    if (zzCurrentPos >= zzBuffer.length) {
        +      /* if not: blow it up */
        +      char newBuffer[] = new char[zzCurrentPos*2];
        +      System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length);
        +      zzBuffer = newBuffer;
        +    }
        +
        +    /* finally: fill the buffer with new input */
        +    int numRead = zzReader.read(zzBuffer, zzEndRead,
        +                                            zzBuffer.length-zzEndRead);
        +
        +    if (numRead > 0) {
        +      zzEndRead+= numRead;
        +      return false;
        +    }
        +    // unlikely but not impossible: read 0 characters, but not at end of stream    
        +    if (numRead == 0) {
        +      int c = zzReader.read();
        +      if (c == -1) {
        +        return true;
        +      } else {
        +        zzBuffer[zzEndRead++] = (char) c;
        +        return false;
        +      }     
        +    }
        +
        +    // numRead < 0
        +    return true;
        +  }
        +
        +    
        +  /**
        +   * Closes the input stream.
        +   */
        +  public final void yyclose() throws java.io.IOException {
        +    zzAtEOF = true;            /* indicate end of file */
        +    zzEndRead = zzStartRead;  /* invalidate buffer    */
        +
        +    if (zzReader != null)
        +      zzReader.close();
        +  }
        +
        +
        +  /**
        +   * Resets the scanner to read from a new input stream.
        +   * Does not close the old reader.
        +   *
        +   * All internal variables are reset, the old input stream 
        +   * cannot be reused (internal buffer is discarded and lost).
        +   * Lexical state is set to ZZ_INITIAL.
        +   *
        +   * Internal scan buffer is resized down to its initial length, if it has grown.
        +   *
        +   * @param reader   the new input stream 
        +   */
        +  public final void yyreset(java.io.Reader reader) {
        +    zzReader = reader;
        +    zzAtBOL  = true;
        +    zzAtEOF  = false;
        +    zzEOFDone = false;
        +    zzEndRead = zzStartRead = 0;
        +    zzCurrentPos = zzMarkedPos = 0;
        +    yyline = yychar = yycolumn = 0;
        +    zzLexicalState = YYINITIAL;
        +    if (zzBuffer.length > ZZ_BUFFERSIZE)
        +      zzBuffer = new char[ZZ_BUFFERSIZE];
        +  }
        +
        +
        +  /**
        +   * Returns the current lexical state.
        +   */
        +  public final int yystate() {
        +    return zzLexicalState;
        +  }
        +
        +
        +  /**
        +   * Enters a new lexical state
        +   *
        +   * @param newState the new lexical state
        +   */
        +  public final void yybegin(int newState) {
        +    zzLexicalState = newState;
        +  }
        +
        +
        +  /**
        +   * Returns the text matched by the current regular expression.
        +   */
        +  public final String yytext() {
        +    return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead );
        +  }
        +
        +
        +  /**
        +   * Returns the character at position pos from the 
        +   * matched text. 
        +   * 
        +   * It is equivalent to yytext().charAt(pos), but faster
        +   *
        +   * @param pos the position of the character to fetch. 
        +   *            A value from 0 to yylength()-1.
        +   *
        +   * @return the character at position pos
        +   */
        +  public final char yycharat(int pos) {
        +    return zzBuffer[zzStartRead+pos];
        +  }
        +
        +
        +  /**
        +   * Returns the length of the matched text region.
        +   */
        +  public final int yylength() {
        +    return zzMarkedPos-zzStartRead;
        +  }
        +
        +
        +  /**
        +   * Reports an error that occured while scanning.
        +   *
        +   * In a wellformed scanner (no or only correct usage of 
        +   * yypushback(int) and a match-all fallback rule) this method 
        +   * will only be called with things that "Can't Possibly Happen".
        +   * If this method is called, something is seriously wrong
        +   * (e.g. a JFlex bug producing a faulty scanner etc.).
        +   *
        +   * Usual syntax/scanner level error handling should be done
        +   * in error fallback rules.
        +   *
        +   * @param   errorCode  the code of the errormessage to display
        +   */
        +  private void zzScanError(int errorCode) {
        +    String message;
        +    try {
        +      message = ZZ_ERROR_MSG[errorCode];
        +    }
        +    catch (ArrayIndexOutOfBoundsException e) {
        +      message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
        +    }
        +
        +    throw new Error(message);
        +  } 
        +
        +
        +  /**
        +   * Pushes the specified amount of characters back into the input stream.
        +   *
        +   * They will be read again by then next call of the scanning method
        +   *
        +   * @param number  the number of characters to be read again.
        +   *                This number must not be greater than yylength()!
        +   */
        +  public void yypushback(int number)  {
        +    if ( number > yylength() )
        +      zzScanError(ZZ_PUSHBACK_2BIG);
        +
        +    zzMarkedPos -= number;
        +  }
        +
        +
        +  /**
        +   * Contains user EOF-code, which will be executed exactly once,
        +   * when the end of file is reached
        +   */
        +  private void zzDoEOF() throws java.io.IOException {
        +    if (!zzEOFDone) {
        +      zzEOFDone = true;
        +      yyclose();
        +    }
        +  }
        +
        +
        +  /**
        +   * Resumes scanning until the next regular expression is matched,
        +   * the end of input is encountered or an I/O-Error occurs.
        +   *
        +   * @return      the next token
        +   * @exception   java.io.IOException  if any I/O-Error occurs
        +   */
        +  public java_cup.runtime.Symbol next_token() throws java.io.IOException {
        +    int zzInput;
        +    int zzAction;
        +
        +    // cached fields:
        +    int zzCurrentPosL;
        +    int zzMarkedPosL;
        +    int zzEndReadL = zzEndRead;
        +    char [] zzBufferL = zzBuffer;
        +    char [] zzCMapL = ZZ_CMAP;
        +
        +    int [] zzTransL = ZZ_TRANS;
        +    int [] zzRowMapL = ZZ_ROWMAP;
        +    int [] zzAttrL = ZZ_ATTRIBUTE;
        +
        +    while (true) {
        +      zzMarkedPosL = zzMarkedPos;
        +
        +      yychar+= zzMarkedPosL-zzStartRead;
        +
        +      boolean zzR = false;
        +      for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL;
        +                                                             zzCurrentPosL++) {
        +        switch (zzBufferL[zzCurrentPosL]) {
        +        case '\u000B':
        +        case '\u000C':
        +        case '\u0085':
        +        case '\u2028':
        +        case '\u2029':
        +          yyline++;
        +          yycolumn = 0;
        +          zzR = false;
        +          break;
        +        case '\r':
        +          yyline++;
        +          yycolumn = 0;
        +          zzR = true;
        +          break;
        +        case '\n':
        +          if (zzR)
        +            zzR = false;
        +          else {
        +            yyline++;
        +            yycolumn = 0;
        +          }
        +          break;
        +        default:
        +          zzR = false;
        +          yycolumn++;
        +        }
        +      }
        +
        +      if (zzR) {
        +        // peek one character ahead if it is \n (if we have counted one line too much)
        +        boolean zzPeek;
        +        if (zzMarkedPosL < zzEndReadL)
        +          zzPeek = zzBufferL[zzMarkedPosL] == '\n';
        +        else if (zzAtEOF)
        +          zzPeek = false;
        +        else {
        +          boolean eof = zzRefill();
        +          zzEndReadL = zzEndRead;
        +          zzMarkedPosL = zzMarkedPos;
        +          zzBufferL = zzBuffer;
        +          if (eof) 
        +            zzPeek = false;
        +          else 
        +            zzPeek = zzBufferL[zzMarkedPosL] == '\n';
        +        }
        +        if (zzPeek) yyline--;
        +      }
        +      zzAction = -1;
        +
        +      zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL;
        +  
        +      zzState = ZZ_LEXSTATE[zzLexicalState];
        +
        +      // set up zzAction for empty match case:
        +      int zzAttributes = zzAttrL[zzState];
        +      if ( (zzAttributes & 1) == 1 ) {
        +        zzAction = zzState;
        +      }
        +
        +
        +      zzForAction: {
        +        while (true) {
        +    
        +          if (zzCurrentPosL < zzEndReadL)
        +            zzInput = zzBufferL[zzCurrentPosL++];
        +          else if (zzAtEOF) {
        +            zzInput = YYEOF;
        +            break zzForAction;
        +          }
        +          else {
        +            // store back cached positions
        +            zzCurrentPos  = zzCurrentPosL;
        +            zzMarkedPos   = zzMarkedPosL;
        +            boolean eof = zzRefill();
        +            // get translated positions and possibly new buffer
        +            zzCurrentPosL  = zzCurrentPos;
        +            zzMarkedPosL   = zzMarkedPos;
        +            zzBufferL      = zzBuffer;
        +            zzEndReadL     = zzEndRead;
        +            if (eof) {
        +              zzInput = YYEOF;
        +              break zzForAction;
        +            }
        +            else {
        +              zzInput = zzBufferL[zzCurrentPosL++];
        +            }
        +          }
        +          int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];
        +          if (zzNext == -1) break zzForAction;
        +          zzState = zzNext;
        +
        +          zzAttributes = zzAttrL[zzState];
        +          if ( (zzAttributes & 1) == 1 ) {
        +            zzAction = zzState;
        +            zzMarkedPosL = zzCurrentPosL;
        +            if ( (zzAttributes & 8) == 8 ) break zzForAction;
        +          }
        +
        +        }
        +      }
        +
        +      // store back cached position
        +      zzMarkedPos = zzMarkedPosL;
        +
        +      switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
        +        case 1: 
        +          { return newSym(sym.error,yytext());
        +          }
        +        case 62: break;
        +        case 2: 
        +          { return newSym(sym.ID,yytext());
        +          }
        +        case 63: break;
        +        case 3: 
        +          { return newSym(sym.NUMERO_INT, yytext());
        +          }
        +        case 64: break;
        +        case 4: 
        +          { return newSym(sym.OPERADOR,yytext());
        +          }
        +        case 65: break;
        +        case 5: 
        +          { return newSym(sym.NUMERO_FLOAT, yytext());
        +          }
        +        case 66: break;
        +        case 6: 
        +          { return newSym(sym.E,yytext());
        +          }
        +        case 67: break;
        +        case 7: 
        +          { return newSym(sym.OPERADOR_SOMA,yytext());
        +          }
        +        case 68: break;
        +        case 8: 
        +          { /* IGNORE */
        +          }
        +        case 69: break;
        +        case 9: 
        +          { return newSym(sym.ABRIR_COLCHETE,yytext());
        +          }
        +        case 70: break;
        +        case 10: 
        +          { return newSym(sym.FECHAR_COLCHETE,yytext());
        +          }
        +        case 71: break;
        +        case 11: 
        +          { return newSym(sym.ABRIR_PARENTESE,yytext());
        +          }
        +        case 72: break;
        +        case 12: 
        +          { return newSym(sym.FECHAR_PARENTESE,yytext());
        +          }
        +        case 73: break;
        +        case 13: 
        +          { return newSym(sym.ADD_ATTR_VAR,yytext());
        +          }
        +        case 74: break;
        +        case 14: 
        +          { return newSym(sym.SEPARADOR,yytext());
        +          }
        +        case 75: break;
        +        case 15: 
        +          { return newSym(sym.CONDICIONAL_NUMERICA,yytext());
        +          }
        +        case 76: break;
        +        case 16: 
        +          { return newSym(sym.CONDICIONAL_COMPARATIVA,yytext());
        +          }
        +        case 77: break;
        +        case 17: 
        +          { return newSym(sym.DOIS_PONTOS,yytext());
        +          }
        +        case 78: break;
        +        case 18: 
        +          { return newSym(sym.STRING, yytext());
        +          }
        +        case 79: break;
        +        case 19: 
        +          { return newSym(sym.CHAR, yytext());
        +          }
        +        case 80: break;
        +        case 20: 
        +          { /* IGNORAR COMENTARIOS */
        +          }
        +        case 81: break;
        +        case 21: 
        +          { return newSym(sym.OU,yytext());
        +          }
        +        case 82: break;
        +        case 22: 
        +          { return newSym(sym.SE,yytext());
        +          }
        +        case 83: break;
        +        case 23: 
        +          { return newSym(sym.DE,yytext());
        +          }
        +        case 84: break;
        +        case 24: 
        +          { return newSym(sym.ATRIBUIR,yytext());
        +          }
        +        case 85: break;
        +        case 25: 
        +          { return newSym(sym.PI,yytext());
        +          }
        +        case 86: break;
        +        case 26: 
        +          { return newSym(sym.ATE,yytext());
        +          }
        +        case 87: break;
        +        case 27: 
        +          { return newSym(sym.TANGENTE,yytext());
        +          }
        +        case 88: break;
        +        case 28: 
        +          { return newSym(sym.VAR,yytext());
        +          }
        +        case 89: break;
        +        case 29: 
        +          { return newSym(sym.NAO,yytext());
        +          }
        +        case 90: break;
        +        case 30: 
        +          { return newSym(sym.COSSENO,yytext());
        +          }
        +        case 91: break;
        +        case 31: 
        +          { return newSym(sym.SENO,yytext());
        +          }
        +        case 92: break;
        +        case 32: 
        +          { return newSym(sym.POTENCIA,yytext());
        +          }
        +        case 93: break;
        +        case 33: 
        +          { return newSym(sym.LEIA,yytext());
        +          }
        +        case 94: break;
        +        case 34: 
        +          { return newSym(sym.TIPO_VARIAVEL,yytext());
        +          }
        +        case 95: break;
        +        case 35: 
        +          { return newSym(sym.RAIZ,yytext());
        +          }
        +        case 96: break;
        +        case 36: 
        +          { return newSym(sym.CASO,yytext());
        +          }
        +        case 97: break;
        +        case 37: 
        +          { return newSym(sym.FACA,yytext());
        +          }
        +        case 98: break;
        +        case 38: 
        +          { return newSym(sym.PARA,yytext());
        +          }
        +        case 99: break;
        +        case 39: 
        +          { return newSym(sym.ENTAO,yytext());
        +          }
        +        case 100: break;
        +        case 40: 
        +          { return newSym(sym.TIPO_VARIAVEL_VETOR,yytext());
        +          }
        +        case 101: break;
        +        case 41: 
        +          { return newSym(sym.VOID,yytext());
        +          }
        +        case 102: break;
        +        case 42: 
        +          { return newSym(sym.SENAO,yytext());
        +          }
        +        case 103: break;
        +        case 43: 
        +          { return newSym(sym.VALOR_LOGICO,yytext());
        +          }
        +        case 104: break;
        +        case 44: 
        +          { return newSym(sym.FIMSE,yytext());
        +          }
        +        case 105: break;
        +        case 45: 
        +          { return newSym(sym.PASSO,yytext());
        +          }
        +        case 106: break;
        +        case 46: 
        +          { return newSym(sym.ESPERAR,yytext());
        +          }
        +        case 107: break;
        +        case 47: 
        +          { return newSym(sym.INICIO,yytext());
        +          }
        +        case 108: break;
        +        case 48: 
        +          { return newSym(sym.MODULO,yytext());
        +          }
        +        case 109: break;
        +        case 49: 
        +          { return newSym(sym.FUNCAO,yytext());
        +          }
        +        case 110: break;
        +        case 50: 
        +          { return newSym(sym.ESCOLHA,yytext());
        +          }
        +        case 111: break;
        +        case 51: 
        +          { return newSym(sym.ESCREVA,yytext());
        +          }
        +        case 112: break;
        +        case 52: 
        +          { return newSym(sym.FIMPARA,yytext());
        +          }
        +        case 113: break;
        +        case 53: 
        +          { return newSym(sym.ENQUANTO,yytext());
        +          }
        +        case 114: break;
        +        case 54: 
        +          { return newSym(sym.ESCREVAL,yytext());
        +          }
        +        case 115: break;
        +        case 55: 
        +          { return newSym(sym.ALGORITMO,yytext());
        +          }
        +        case 116: break;
        +        case 56: 
        +          { return newSym(sym.OUTROCASO,yytext());
        +          }
        +        case 117: break;
        +        case 57: 
        +          { return newSym(sym.FIMFUNCAO,yytext());
        +          }
        +        case 118: break;
        +        case 58: 
        +          { return newSym(sym.INTERROMPA,yytext());
        +          }
        +        case 119: break;
        +        case 59: 
        +          { return newSym(sym.FIMESCOLHA,yytext());
        +          }
        +        case 120: break;
        +        case 60: 
        +          { return newSym(sym.FIMENQUANTO,yytext());
        +          }
        +        case 121: break;
        +        case 61: 
        +          { return newSym(sym.FIMALGORITMO,yytext());
        +          }
        +        case 122: break;
        +        default: 
        +          if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
        +            zzAtEOF = true;
        +            zzDoEOF();
        +              {
        +                return newSym(sym.EOF);
        +              }
        +          } 
        +          else {
        +            zzScanError(ZZ_NO_MATCH);
        +          }
        +      }
        +    }
        +  }
        +
        +
        +}
        diff --git a/src/com/compilador/portugol/PortugolFlex.java~ b/src/com/compilador/portugol/PortugolFlex.java~
        new file mode 100644
        index 0000000..ec90ceb
        --- /dev/null
        +++ b/src/com/compilador/portugol/PortugolFlex.java~
        @@ -0,0 +1,1130 @@
        +/* The following code was generated by JFlex 1.5.1 */
        +
        +////////////////////////////////////////////////////////////////////////
        +/*                                                                  ////
        +* ANALIZADOR DE PORTUGOL (TOKENS).   							    ////
        +* BY: ANDREW NETO                                                   ////
        +* 05/07/2014                                                        ////
        +*/                                                                  ////
        +////////////////////////////////////////////////////////////////////////
        +
        +package com.compilador.portugol;
        +
        +import java_cup.runtime.*;
        +
        +
        +
        +/**
        + * This class is a scanner generated by 
        + * JFlex 1.5.1
        + * from the specification file C:/Users/SIMONETO-2/Documents/NetBeansProjects/portugol-projeto/src/com/compilador/portugol/Portugol.flex
        + */
        +class PortugolFlex implements java_cup.runtime.Scanner {
        +
        +  /** This character denotes the end of file */
        +  public static final int YYEOF = -1;
        +
        +  /** initial size of the lookahead buffer */
        +  private static final int ZZ_BUFFERSIZE = 16384;
        +
        +  /** lexical states */
        +  public static final int YYINITIAL = 0;
        +
        +  /**
        +   * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l
        +   * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l
        +   *                  at the beginning of a line
        +   * l is of the form l = 2*k, k a non negative integer
        +   */
        +  private static final int ZZ_LEXSTATE[] = { 
        +     0, 0
        +  };
        +
        +  /** 
        +   * Translates characters to character classes
        +   */
        +  private static final String ZZ_CMAP_PACKED = 
        +    "\11\0\1\11\1\16\1\57\1\57\1\14\22\0\1\11\1\0\1\13"+
        +    "\4\0\1\15\1\46\1\47\1\20\1\10\1\51\1\4\1\5\1\17"+
        +    "\12\2\1\50\1\0\1\54\1\55\1\56\2\0\4\1\1\6\3\1"+
        +    "\1\53\6\1\1\52\12\1\1\44\1\12\1\45\1\0\1\3\1\0"+
        +    "\1\21\1\1\1\33\1\43\1\7\1\35\1\23\1\41\1\26\2\1"+
        +    "\1\22\1\30\1\32\1\24\1\40\1\36\1\25\1\34\1\27\1\37"+
        +    "\1\31\3\1\1\42\12\0\1\57\u1fa2\0\1\57\1\57\udfd6\0";
        +
        +  /** 
        +   * Translates characters to character classes
        +   */
        +  private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);
        +
        +  /** 
        +   * Translates DFA states to action switch labels.
        +   */
        +  private static final int [] ZZ_ACTION = zzUnpackAction();
        +
        +  private static final String ZZ_ACTION_PACKED_0 =
        +    "\1\0\1\1\1\2\1\3\1\4\1\5\1\6\1\7"+
        +    "\1\10\1\1\1\10\1\1\2\4\16\2\1\11\1\12"+
        +    "\1\13\1\14\1\15\1\16\1\2\1\17\1\20\1\17"+
        +    "\2\5\1\21\2\2\2\0\1\22\2\0\1\23\1\24"+
        +    "\1\0\4\2\1\25\12\2\1\26\6\2\1\27\1\2"+
        +    "\1\30\1\31\1\17\1\5\4\2\1\0\2\24\2\0"+
        +    "\1\2\1\32\7\2\1\33\1\4\2\2\1\34\1\2"+
        +    "\1\35\2\2\1\36\1\37\7\2\1\40\1\4\5\2"+
        +    "\1\0\1\2\1\41\2\2\1\42\1\43\2\2\1\44"+
        +    "\4\2\1\45\3\2\1\46\6\2\1\47\1\2\1\50"+
        +    "\13\2\1\51\1\52\1\2\1\53\1\2\1\54\3\2"+
        +    "\1\55\3\2\1\56\3\2\1\57\2\2\1\60\10\2"+
        +    "\1\61\1\2\1\62\1\63\11\2\1\64\1\65\1\66"+
        +    "\10\2\1\67\1\70\4\2\1\71\1\72\1\2\1\73"+
        +    "\1\2\1\74\1\2\1\75";
        +
        +  private static int [] zzUnpackAction() {
        +    int [] result = new int[228];
        +    int offset = 0;
        +    offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result);
        +    return result;
        +  }
        +
        +  private static int zzUnpackAction(String packed, int offset, int [] result) {
        +    int i = 0;       /* index in packed string  */
        +    int j = offset;  /* index in unpacked array */
        +    int l = packed.length();
        +    while (i < l) {
        +      int count = packed.charAt(i++);
        +      int value = packed.charAt(i++);
        +      do result[j++] = value; while (--count > 0);
        +    }
        +    return j;
        +  }
        +
        +
        +  /** 
        +   * Translates a state to a row index in the transition table
        +   */
        +  private static final int [] ZZ_ROWMAP = zzUnpackRowMap();
        +
        +  private static final String ZZ_ROWMAP_PACKED_0 =
        +    "\0\0\0\60\0\140\0\220\0\300\0\360\0\u0120\0\60"+
        +    "\0\60\0\u0150\0\u0180\0\u01b0\0\u01e0\0\60\0\u0210\0\u0240"+
        +    "\0\u0270\0\u02a0\0\u02d0\0\u0300\0\u0330\0\u0360\0\u0390\0\u03c0"+
        +    "\0\u03f0\0\u0420\0\u0450\0\u0480\0\60\0\60\0\60\0\60"+
        +    "\0\u04b0\0\60\0\u04e0\0\u0510\0\60\0\u0540\0\u0570\0\u05a0"+
        +    "\0\60\0\u05d0\0\u0600\0\u0150\0\u0630\0\60\0\u0660\0\u0690"+
        +    "\0\60\0\u06c0\0\u06f0\0\u0720\0\u0750\0\u0780\0\u07b0\0\u07e0"+
        +    "\0\u0810\0\u0840\0\u0870\0\u08a0\0\u08d0\0\u0900\0\u0930\0\u0960"+
        +    "\0\u0990\0\u09c0\0\u09f0\0\u0a20\0\u0a50\0\u0a80\0\u0ab0\0\u0ae0"+
        +    "\0\u0b10\0\140\0\u0b40\0\60\0\140\0\60\0\u0b70\0\u0ba0"+
        +    "\0\u0bd0\0\u0c00\0\u0c30\0\u0c60\0\u0c90\0\60\0\u0cc0\0\u0cf0"+
        +    "\0\u0d20\0\140\0\u0d50\0\u0d80\0\u0db0\0\u0de0\0\u0e10\0\u0e40"+
        +    "\0\u0e70\0\140\0\u0ea0\0\u0ed0\0\u0f00\0\140\0\u0f30\0\140"+
        +    "\0\u0f60\0\u0f90\0\140\0\u0fc0\0\u0ff0\0\u1020\0\u1050\0\u1080"+
        +    "\0\u10b0\0\u10e0\0\u1110\0\140\0\140\0\u1140\0\u1170\0\u11a0"+
        +    "\0\u11d0\0\u1200\0\u1230\0\u1260\0\140\0\u1290\0\u12c0\0\140"+
        +    "\0\140\0\u12f0\0\u1320\0\140\0\u1350\0\u1380\0\u13b0\0\u13e0"+
        +    "\0\140\0\u1410\0\u1440\0\u1470\0\140\0\u14a0\0\u14d0\0\u1500"+
        +    "\0\u1530\0\u1560\0\u1590\0\140\0\u15c0\0\140\0\u15f0\0\u1620"+
        +    "\0\u1650\0\u1680\0\u16b0\0\u16e0\0\u1710\0\u1740\0\u1770\0\u17a0"+
        +    "\0\u17d0\0\140\0\140\0\u1800\0\140\0\u1830\0\140\0\u1860"+
        +    "\0\u1890\0\u18c0\0\140\0\u18f0\0\u1920\0\u1950\0\140\0\u1980"+
        +    "\0\u19b0\0\u19e0\0\140\0\u1a10\0\u1a40\0\140\0\u1a70\0\u1aa0"+
        +    "\0\u1ad0\0\u1b00\0\u1b30\0\u1b60\0\u1b90\0\u1bc0\0\140\0\u1bf0"+
        +    "\0\140\0\u1c20\0\u1c50\0\u1c80\0\u1cb0\0\u1ce0\0\u1d10\0\u1d40"+
        +    "\0\u1d70\0\u1da0\0\u1dd0\0\140\0\140\0\140\0\u1e00\0\u1e30"+
        +    "\0\u1e60\0\u1e90\0\u1ec0\0\u1ef0\0\u1f20\0\u1f50\0\140\0\140"+
        +    "\0\u1f80\0\u1fb0\0\u1fe0\0\u2010\0\140\0\140\0\u2040\0\140"+
        +    "\0\u2070\0\140\0\u20a0\0\140";
        +
        +  private static int [] zzUnpackRowMap() {
        +    int [] result = new int[228];
        +    int offset = 0;
        +    offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result);
        +    return result;
        +  }
        +
        +  private static int zzUnpackRowMap(String packed, int offset, int [] result) {
        +    int i = 0;  /* index in packed string  */
        +    int j = offset;  /* index in unpacked array */
        +    int l = packed.length();
        +    while (i < l) {
        +      int high = packed.charAt(i++) << 16;
        +      result[j++] = high | packed.charAt(i++);
        +    }
        +    return j;
        +  }
        +
        +  /** 
        +   * The transition table of the DFA
        +   */
        +  private static final int [] ZZ_TRANS = zzUnpackTrans();
        +
        +  private static final String ZZ_TRANS_PACKED_0 =
        +    "\1\2\1\3\1\4\1\2\1\5\1\6\1\3\1\7"+
        +    "\1\10\1\11\1\2\1\12\1\13\1\14\1\11\1\15"+
        +    "\1\16\1\17\1\20\1\3\1\21\1\22\1\23\1\24"+
        +    "\1\25\1\26\1\27\1\30\1\31\1\32\2\3\1\33"+
        +    "\2\3\1\34\1\35\1\36\1\37\1\40\1\41\1\42"+
        +    "\1\43\1\3\1\44\1\45\1\46\62\0\3\3\2\0"+
        +    "\2\3\11\0\23\3\6\0\2\3\6\0\1\4\2\0"+
        +    "\1\47\2\50\52\0\1\4\2\0\1\47\54\0\1\47"+
        +    "\2\0\1\51\2\50\51\0\3\3\2\0\2\3\11\0"+
        +    "\11\3\1\52\1\3\1\53\7\3\6\0\2\3\4\0"+
        +    "\12\54\1\55\1\56\2\54\1\56\41\54\16\0\1\11"+
        +    "\41\0\12\57\1\60\2\57\2\61\41\57\17\0\1\62"+
        +    "\1\63\40\0\3\3\2\0\2\3\11\0\1\3\1\64"+
        +    "\4\3\1\65\14\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\1\3\1\66\11\0\3\3\1\67\17\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\16\3\1\70\4\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\1\3\1\71\11\0"+
        +    "\1\72\22\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\11\3\1\73\11\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\1\74\22\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\3\3\1\75\17\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\1\3\1\76\11\0\1\77"+
        +    "\22\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\1\100\22\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\1\101\2\3\1\102\17\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\1\3\1\103\11\0\6\3\1\104\14\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\1\105"+
        +    "\4\3\1\106\10\3\1\107\4\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\1\110\2\3\1\111\17\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\1\3\1\112\11\0"+
        +    "\5\3\1\113\15\3\6\0\2\3\61\0\1\114\3\0"+
        +    "\3\3\2\0\2\3\11\0\23\3\6\0\1\3\1\115"+
        +    "\10\0\1\114\50\0\1\116\1\45\56\0\1\116\4\0"+
        +    "\1\47\3\0\2\50\52\0\1\117\1\0\1\117\3\0"+
        +    "\1\117\50\0\3\3\2\0\2\3\11\0\6\3\1\120"+
        +    "\6\3\1\121\5\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\12\3\1\122\4\3\1\123\3\3\6\0"+
        +    "\2\3\4\0\16\54\1\56\41\54\12\0\1\124\2\0"+
        +    "\2\61\41\0\16\57\1\61\41\57\14\62\1\125\1\62"+
        +    "\1\126\41\62\20\127\1\130\37\127\1\0\3\3\2\0"+
        +    "\2\3\11\0\2\3\1\131\20\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\1\3\1\132\11\0\23\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\5\3\1\133\15\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\2\3"+
        +    "\1\134\20\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\6\3\1\135\14\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\1\136\22\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\5\3\1\137\15\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\5\3\1\140"+
        +    "\1\141\14\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\11\3\1\142\11\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\22\3\1\143\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\4\3\1\144\1\3\1\145"+
        +    "\14\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\4\3\1\146\14\3\1\147\1\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\3\3\1\150\17\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\4\3\1\151"+
        +    "\6\3\1\152\7\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\13\3\1\153\7\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\11\3\1\154\11\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\4\3\1\155"+
        +    "\16\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\1\3\1\156\10\3\1\157\10\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\7\3\1\160\13\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\11\3\1\161"+
        +    "\11\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\4\3\1\162\6\3\1\163\7\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\6\3\1\164\14\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\10\3\1\165"+
        +    "\12\3\6\0\2\3\6\0\1\117\56\0\3\3\2\0"+
        +    "\2\3\11\0\1\166\22\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\16\3\1\167\4\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\3\3\1\170\1\171"+
        +    "\16\3\6\0\2\3\5\0\3\3\2\0\1\3\1\172"+
        +    "\11\0\23\3\6\0\2\3\22\0\1\61\57\0\1\126"+
        +    "\41\0\20\127\1\173\37\127\17\0\1\126\1\130\40\0"+
        +    "\3\3\2\0\2\3\11\0\3\3\1\174\17\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\1\175\22\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\5\3"+
        +    "\1\176\15\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\4\3\1\177\16\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\1\3\1\200\21\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\21\3\1\201\1\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\12\3"+
        +    "\1\202\10\3\6\0\2\3\5\0\3\3\2\0\1\3"+
        +    "\1\203\11\0\23\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\3\3\1\204\17\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\22\3\1\205\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\3\3\1\206\17\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\5\3"+
        +    "\1\207\15\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\1\210\22\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\3\3\1\211\17\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\1\212\22\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\5\3\1\213\15\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\13\3"+
        +    "\1\214\7\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\1\215\22\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\1\3\1\216\11\0\1\217\12\3\1\220\1\221\2\3"+
        +    "\1\222\3\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\12\3\1\223\10\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\1\224\22\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\13\3\1\225\7\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\3\3\1\226"+
        +    "\17\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\1\227\22\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\1\3\1\230\21\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\1\3\1\231\11\0\23\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\4\3\1\232\16\3\6\0"+
        +    "\2\3\4\0\17\127\1\126\1\173\37\127\1\0\3\3"+
        +    "\2\0\2\3\11\0\4\3\1\233\16\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\12\3\1\234\10\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\3\3"+
        +    "\1\235\17\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\5\3\1\236\15\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\4\3\1\237\1\240\15\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\1\241\22\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\4\3"+
        +    "\1\242\16\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\3\3\1\243\17\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\12\3\1\244\10\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\3\3\1\245\17\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\11\3"+
        +    "\1\246\11\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\3\3\1\247\17\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\11\3\1\250\1\3\1\251\7\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\1\3"+
        +    "\1\252\21\3\6\0\2\3\5\0\3\3\2\0\1\3"+
        +    "\1\253\11\0\23\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\16\3\1\254\4\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\1\255\22\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\1\256\22\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\3\3\1\257"+
        +    "\17\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\11\3\1\260\11\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\20\3\1\261\2\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\10\3\1\262\12\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\1\3\1\263\11\0\23\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\5\3"+
        +    "\1\264\15\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\3\3\1\200\17\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\12\3\1\265\10\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\3\3\1\266\17\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\4\3"+
        +    "\1\267\16\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\4\3\1\234\16\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\22\3\1\270\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\6\3\1\271\14\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\2\3\1\200"+
        +    "\20\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\15\3\1\272\5\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\12\3\1\273\10\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\2\3\1\274\20\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\11\3\1\275"+
        +    "\11\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\4\3\1\276\16\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\3\3\1\277\17\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\6\3\1\300\14\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\1\301\22\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\1\302"+
        +    "\22\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\6\3\1\303\14\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\1\304\22\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\3\3\1\305\17\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\1\3\1\306\11\0\23\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\1\3\1\307\11\0\23\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\16\3"+
        +    "\1\310\4\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\3\3\1\311\17\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\3\3\1\312\17\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\12\3\1\313\10\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\1\314"+
        +    "\22\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\3\3\1\315\17\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\1\3\1\316\21\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\7\3\1\317\13\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\13\3\1\320"+
        +    "\7\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\7\3\1\321\13\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\5\3\1\322\15\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\4\3\1\200\16\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\1\323\22\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\1\3"+
        +    "\1\324\21\3\6\0\2\3\5\0\3\3\2\0\2\3"+
        +    "\11\0\4\3\1\325\16\3\6\0\2\3\5\0\3\3"+
        +    "\2\0\2\3\11\0\1\326\22\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\3\3\1\327\17\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\3\3\1\330"+
        +    "\17\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\17\3\1\331\3\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\4\3\1\214\16\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\11\3\1\332\11\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\20\3\1\333"+
        +    "\2\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\5\3\1\334\15\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\3\3\1\335\17\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\1\336\22\3\6\0\2\3"+
        +    "\5\0\3\3\2\0\2\3\11\0\6\3\1\337\14\3"+
        +    "\6\0\2\3\5\0\3\3\2\0\2\3\11\0\1\340"+
        +    "\22\3\6\0\2\3\5\0\3\3\2\0\2\3\11\0"+
        +    "\6\3\1\341\14\3\6\0\2\3\5\0\3\3\2\0"+
        +    "\2\3\11\0\3\3\1\342\17\3\6\0\2\3\5\0"+
        +    "\3\3\2\0\2\3\11\0\7\3\1\343\13\3\6\0"+
        +    "\2\3\5\0\3\3\2\0\2\3\11\0\3\3\1\344"+
        +    "\17\3\6\0\2\3\4\0";
        +
        +  private static int [] zzUnpackTrans() {
        +    int [] result = new int[8400];
        +    int offset = 0;
        +    offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result);
        +    return result;
        +  }
        +
        +  private static int zzUnpackTrans(String packed, int offset, int [] result) {
        +    int i = 0;       /* index in packed string  */
        +    int j = offset;  /* index in unpacked array */
        +    int l = packed.length();
        +    while (i < l) {
        +      int count = packed.charAt(i++);
        +      int value = packed.charAt(i++);
        +      value--;
        +      do result[j++] = value; while (--count > 0);
        +    }
        +    return j;
        +  }
        +
        +
        +  /* error codes */
        +  private static final int ZZ_UNKNOWN_ERROR = 0;
        +  private static final int ZZ_NO_MATCH = 1;
        +  private static final int ZZ_PUSHBACK_2BIG = 2;
        +
        +  /* error messages for the codes above */
        +  private static final String ZZ_ERROR_MSG[] = {
        +    "Unkown internal scanner error",
        +    "Error: could not match input",
        +    "Error: pushback value was too large"
        +  };
        +
        +  /**
        +   * ZZ_ATTRIBUTE[aState] contains the attributes of state aState
        +   */
        +  private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute();
        +
        +  private static final String ZZ_ATTRIBUTE_PACKED_0 =
        +    "\1\0\1\11\5\1\2\11\4\1\1\11\16\1\4\11"+
        +    "\1\1\1\11\2\1\1\11\3\1\1\11\2\1\2\0"+
        +    "\1\11\2\0\1\11\1\1\1\0\30\1\1\11\1\1"+
        +    "\1\11\5\1\1\0\1\1\1\11\2\0\42\1\1\0"+
        +    "\151\1";
        +
        +  private static int [] zzUnpackAttribute() {
        +    int [] result = new int[228];
        +    int offset = 0;
        +    offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result);
        +    return result;
        +  }
        +
        +  private static int zzUnpackAttribute(String packed, int offset, int [] result) {
        +    int i = 0;       /* index in packed string  */
        +    int j = offset;  /* index in unpacked array */
        +    int l = packed.length();
        +    while (i < l) {
        +      int count = packed.charAt(i++);
        +      int value = packed.charAt(i++);
        +      do result[j++] = value; while (--count > 0);
        +    }
        +    return j;
        +  }
        +
        +  /** the input device */
        +  private java.io.Reader zzReader;
        +
        +  /** the current state of the DFA */
        +  private int zzState;
        +
        +  /** the current lexical state */
        +  private int zzLexicalState = YYINITIAL;
        +
        +  /** this buffer contains the current text to be matched and is
        +      the source of the yytext() string */
        +  private char zzBuffer[] = new char[ZZ_BUFFERSIZE];
        +
        +  /** the textposition at the last accepting state */
        +  private int zzMarkedPos;
        +
        +  /** the current text position in the buffer */
        +  private int zzCurrentPos;
        +
        +  /** startRead marks the beginning of the yytext() string in the buffer */
        +  private int zzStartRead;
        +
        +  /** endRead marks the last character in the buffer, that has been read
        +      from input */
        +  private int zzEndRead;
        +
        +  /** number of newlines encountered up to the start of the matched text */
        +  private int yyline;
        +
        +  /** the number of characters up to the start of the matched text */
        +  private int yychar;
        +
        +  /**
        +   * the number of characters from the last newline up to the start of the 
        +   * matched text
        +   */
        +  private int yycolumn;
        +
        +  /** 
        +   * zzAtBOL == true <=> the scanner is currently at the beginning of a line
        +   */
        +  private boolean zzAtBOL = true;
        +
        +  /** zzAtEOF == true <=> the scanner is at the EOF */
        +  private boolean zzAtEOF;
        +
        +  /** denotes if the user-EOF-code has already been executed */
        +  private boolean zzEOFDone;
        +
        +  /* user code: */
        +
        +    public PortugolFlex() {
        +        super();
        +    }
        +
        +    Symbol newSym(int tokenId) {
        +        return new Symbol(tokenId , yyline, yycolumn);
        +    }
        +
        +    Symbol newSym(int tokenId, Object value) {
        +        return new Symbol(tokenId , yyline, yycolumn, value);
        +    }
        +
        +
        +
        +  /**
        +   * Creates a new scanner
        +   * There is also a java.io.InputStream version of this constructor.
        +   *
        +   * @param   in  the java.io.Reader to read input from.
        +   */
        +  PortugolFlex(java.io.Reader in) {
        +    this.zzReader = in;
        +  }
        +
        +  /**
        +   * Creates a new scanner.
        +   * There is also java.io.Reader version of this constructor.
        +   *
        +   * @param   in  the java.io.Inputstream to read input from.
        +   */
        +  PortugolFlex(java.io.InputStream in) {
        +    this(new java.io.InputStreamReader
        +             (in, java.nio.charset.Charset.forName("UTF-8")));
        +  }
        +
        +  /** 
        +   * Unpacks the compressed character translation table.
        +   *
        +   * @param packed   the packed character translation table
        +   * @return         the unpacked character translation table
        +   */
        +  private static char [] zzUnpackCMap(String packed) {
        +    char [] map = new char[0x10000];
        +    int i = 0;  /* index in packed string  */
        +    int j = 0;  /* index in unpacked array */
        +    while (i < 138) {
        +      int  count = packed.charAt(i++);
        +      char value = packed.charAt(i++);
        +      do map[j++] = value; while (--count > 0);
        +    }
        +    return map;
        +  }
        +
        +
        +  /**
        +   * Refills the input buffer.
        +   *
        +   * @return      false, iff there was new input.
        +   * 
        +   * @exception   java.io.IOException  if any I/O-Error occurs
        +   */
        +  private boolean zzRefill() throws java.io.IOException {
        +
        +    /* first: make room (if you can) */
        +    if (zzStartRead > 0) {
        +      System.arraycopy(zzBuffer, zzStartRead,
        +                       zzBuffer, 0,
        +                       zzEndRead-zzStartRead);
        +
        +      /* translate stored positions */
        +      zzEndRead-= zzStartRead;
        +      zzCurrentPos-= zzStartRead;
        +      zzMarkedPos-= zzStartRead;
        +      zzStartRead = 0;
        +    }
        +
        +    /* is the buffer big enough? */
        +    if (zzCurrentPos >= zzBuffer.length) {
        +      /* if not: blow it up */
        +      char newBuffer[] = new char[zzCurrentPos*2];
        +      System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length);
        +      zzBuffer = newBuffer;
        +    }
        +
        +    /* finally: fill the buffer with new input */
        +    int numRead = zzReader.read(zzBuffer, zzEndRead,
        +                                            zzBuffer.length-zzEndRead);
        +
        +    if (numRead > 0) {
        +      zzEndRead+= numRead;
        +      return false;
        +    }
        +    // unlikely but not impossible: read 0 characters, but not at end of stream    
        +    if (numRead == 0) {
        +      int c = zzReader.read();
        +      if (c == -1) {
        +        return true;
        +      } else {
        +        zzBuffer[zzEndRead++] = (char) c;
        +        return false;
        +      }     
        +    }
        +
        +    // numRead < 0
        +    return true;
        +  }
        +
        +    
        +  /**
        +   * Closes the input stream.
        +   */
        +  public final void yyclose() throws java.io.IOException {
        +    zzAtEOF = true;            /* indicate end of file */
        +    zzEndRead = zzStartRead;  /* invalidate buffer    */
        +
        +    if (zzReader != null)
        +      zzReader.close();
        +  }
        +
        +
        +  /**
        +   * Resets the scanner to read from a new input stream.
        +   * Does not close the old reader.
        +   *
        +   * All internal variables are reset, the old input stream 
        +   * cannot be reused (internal buffer is discarded and lost).
        +   * Lexical state is set to ZZ_INITIAL.
        +   *
        +   * Internal scan buffer is resized down to its initial length, if it has grown.
        +   *
        +   * @param reader   the new input stream 
        +   */
        +  public final void yyreset(java.io.Reader reader) {
        +    zzReader = reader;
        +    zzAtBOL  = true;
        +    zzAtEOF  = false;
        +    zzEOFDone = false;
        +    zzEndRead = zzStartRead = 0;
        +    zzCurrentPos = zzMarkedPos = 0;
        +    yyline = yychar = yycolumn = 0;
        +    zzLexicalState = YYINITIAL;
        +    if (zzBuffer.length > ZZ_BUFFERSIZE)
        +      zzBuffer = new char[ZZ_BUFFERSIZE];
        +  }
        +
        +
        +  /**
        +   * Returns the current lexical state.
        +   */
        +  public final int yystate() {
        +    return zzLexicalState;
        +  }
        +
        +
        +  /**
        +   * Enters a new lexical state
        +   *
        +   * @param newState the new lexical state
        +   */
        +  public final void yybegin(int newState) {
        +    zzLexicalState = newState;
        +  }
        +
        +
        +  /**
        +   * Returns the text matched by the current regular expression.
        +   */
        +  public final String yytext() {
        +    return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead );
        +  }
        +
        +
        +  /**
        +   * Returns the character at position pos from the 
        +   * matched text. 
        +   * 
        +   * It is equivalent to yytext().charAt(pos), but faster
        +   *
        +   * @param pos the position of the character to fetch. 
        +   *            A value from 0 to yylength()-1.
        +   *
        +   * @return the character at position pos
        +   */
        +  public final char yycharat(int pos) {
        +    return zzBuffer[zzStartRead+pos];
        +  }
        +
        +
        +  /**
        +   * Returns the length of the matched text region.
        +   */
        +  public final int yylength() {
        +    return zzMarkedPos-zzStartRead;
        +  }
        +
        +
        +  /**
        +   * Reports an error that occured while scanning.
        +   *
        +   * In a wellformed scanner (no or only correct usage of 
        +   * yypushback(int) and a match-all fallback rule) this method 
        +   * will only be called with things that "Can't Possibly Happen".
        +   * If this method is called, something is seriously wrong
        +   * (e.g. a JFlex bug producing a faulty scanner etc.).
        +   *
        +   * Usual syntax/scanner level error handling should be done
        +   * in error fallback rules.
        +   *
        +   * @param   errorCode  the code of the errormessage to display
        +   */
        +  private void zzScanError(int errorCode) {
        +    String message;
        +    try {
        +      message = ZZ_ERROR_MSG[errorCode];
        +    }
        +    catch (ArrayIndexOutOfBoundsException e) {
        +      message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
        +    }
        +
        +    throw new Error(message);
        +  } 
        +
        +
        +  /**
        +   * Pushes the specified amount of characters back into the input stream.
        +   *
        +   * They will be read again by then next call of the scanning method
        +   *
        +   * @param number  the number of characters to be read again.
        +   *                This number must not be greater than yylength()!
        +   */
        +  public void yypushback(int number)  {
        +    if ( number > yylength() )
        +      zzScanError(ZZ_PUSHBACK_2BIG);
        +
        +    zzMarkedPos -= number;
        +  }
        +
        +
        +  /**
        +   * Contains user EOF-code, which will be executed exactly once,
        +   * when the end of file is reached
        +   */
        +  private void zzDoEOF() throws java.io.IOException {
        +    if (!zzEOFDone) {
        +      zzEOFDone = true;
        +      yyclose();
        +    }
        +  }
        +
        +
        +  /**
        +   * Resumes scanning until the next regular expression is matched,
        +   * the end of input is encountered or an I/O-Error occurs.
        +   *
        +   * @return      the next token
        +   * @exception   java.io.IOException  if any I/O-Error occurs
        +   */
        +  public java_cup.runtime.Symbol next_token() throws java.io.IOException {
        +    int zzInput;
        +    int zzAction;
        +
        +    // cached fields:
        +    int zzCurrentPosL;
        +    int zzMarkedPosL;
        +    int zzEndReadL = zzEndRead;
        +    char [] zzBufferL = zzBuffer;
        +    char [] zzCMapL = ZZ_CMAP;
        +
        +    int [] zzTransL = ZZ_TRANS;
        +    int [] zzRowMapL = ZZ_ROWMAP;
        +    int [] zzAttrL = ZZ_ATTRIBUTE;
        +
        +    while (true) {
        +      zzMarkedPosL = zzMarkedPos;
        +
        +      yychar+= zzMarkedPosL-zzStartRead;
        +
        +      boolean zzR = false;
        +      for (zzCurrentPosL = zzStartRead; zzCurrentPosL < zzMarkedPosL;
        +                                                             zzCurrentPosL++) {
        +        switch (zzBufferL[zzCurrentPosL]) {
        +        case '\u000B':
        +        case '\u000C':
        +        case '\u0085':
        +        case '\u2028':
        +        case '\u2029':
        +          yyline++;
        +          yycolumn = 0;
        +          zzR = false;
        +          break;
        +        case '\r':
        +          yyline++;
        +          yycolumn = 0;
        +          zzR = true;
        +          break;
        +        case '\n':
        +          if (zzR)
        +            zzR = false;
        +          else {
        +            yyline++;
        +            yycolumn = 0;
        +          }
        +          break;
        +        default:
        +          zzR = false;
        +          yycolumn++;
        +        }
        +      }
        +
        +      if (zzR) {
        +        // peek one character ahead if it is \n (if we have counted one line too much)
        +        boolean zzPeek;
        +        if (zzMarkedPosL < zzEndReadL)
        +          zzPeek = zzBufferL[zzMarkedPosL] == '\n';
        +        else if (zzAtEOF)
        +          zzPeek = false;
        +        else {
        +          boolean eof = zzRefill();
        +          zzEndReadL = zzEndRead;
        +          zzMarkedPosL = zzMarkedPos;
        +          zzBufferL = zzBuffer;
        +          if (eof) 
        +            zzPeek = false;
        +          else 
        +            zzPeek = zzBufferL[zzMarkedPosL] == '\n';
        +        }
        +        if (zzPeek) yyline--;
        +      }
        +      zzAction = -1;
        +
        +      zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL;
        +  
        +      zzState = ZZ_LEXSTATE[zzLexicalState];
        +
        +      // set up zzAction for empty match case:
        +      int zzAttributes = zzAttrL[zzState];
        +      if ( (zzAttributes & 1) == 1 ) {
        +        zzAction = zzState;
        +      }
        +
        +
        +      zzForAction: {
        +        while (true) {
        +    
        +          if (zzCurrentPosL < zzEndReadL)
        +            zzInput = zzBufferL[zzCurrentPosL++];
        +          else if (zzAtEOF) {
        +            zzInput = YYEOF;
        +            break zzForAction;
        +          }
        +          else {
        +            // store back cached positions
        +            zzCurrentPos  = zzCurrentPosL;
        +            zzMarkedPos   = zzMarkedPosL;
        +            boolean eof = zzRefill();
        +            // get translated positions and possibly new buffer
        +            zzCurrentPosL  = zzCurrentPos;
        +            zzMarkedPosL   = zzMarkedPos;
        +            zzBufferL      = zzBuffer;
        +            zzEndReadL     = zzEndRead;
        +            if (eof) {
        +              zzInput = YYEOF;
        +              break zzForAction;
        +            }
        +            else {
        +              zzInput = zzBufferL[zzCurrentPosL++];
        +            }
        +          }
        +          int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];
        +          if (zzNext == -1) break zzForAction;
        +          zzState = zzNext;
        +
        +          zzAttributes = zzAttrL[zzState];
        +          if ( (zzAttributes & 1) == 1 ) {
        +            zzAction = zzState;
        +            zzMarkedPosL = zzCurrentPosL;
        +            if ( (zzAttributes & 8) == 8 ) break zzForAction;
        +          }
        +
        +        }
        +      }
        +
        +      // store back cached position
        +      zzMarkedPos = zzMarkedPosL;
        +
        +      switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
        +        case 1: 
        +          { return newSym(sym.error,yytext());
        +          }
        +        case 62: break;
        +        case 2: 
        +          { return newSym(sym.ID,yytext());
        +          }
        +        case 63: break;
        +        case 3: 
        +          { return newSym(sym.NUMERO_INT, yytext());
        +          }
        +        case 64: break;
        +        case 4: 
        +          { return newSym(sym.OPERADOR,yytext());
        +          }
        +        case 65: break;
        +        case 5: 
        +          { return newSym(sym.NUMERO_FLOAT, yytext());
        +          }
        +        case 66: break;
        +        case 6: 
        +          { return newSym(sym.E,yytext());
        +          }
        +        case 67: break;
        +        case 7: 
        +          { return newSym(sym.OPERADOR_SOMA,yytext());
        +          }
        +        case 68: break;
        +        case 8: 
        +          { /* IGNORE */
        +          }
        +        case 69: break;
        +        case 9: 
        +          { return newSym(sym.ABRIR_COLCHETE,yytext());
        +          }
        +        case 70: break;
        +        case 10: 
        +          { return newSym(sym.FECHAR_COLCHETE,yytext());
        +          }
        +        case 71: break;
        +        case 11: 
        +          { return newSym(sym.ABRIR_PARENTESE,yytext());
        +          }
        +        case 72: break;
        +        case 12: 
        +          { return newSym(sym.FECHAR_PARENTESE,yytext());
        +          }
        +        case 73: break;
        +        case 13: 
        +          { return newSym(sym.ADD_ATTR_VAR,yytext());
        +          }
        +        case 74: break;
        +        case 14: 
        +          { return newSym(sym.SEPARADOR,yytext());
        +          }
        +        case 75: break;
        +        case 15: 
        +          { return newSym(sym.CONDICIONAL_NUMERICA,yytext());
        +          }
        +        case 76: break;
        +        case 16: 
        +          { return newSym(sym.CONDICIONAL_COMPARATIVA,yytext());
        +          }
        +        case 77: break;
        +        case 17: 
        +          { return newSym(sym.DOIS_PONTOS,yytext());
        +          }
        +        case 78: break;
        +        case 18: 
        +          { return newSym(sym.STRING, yytext());
        +          }
        +        case 79: break;
        +        case 19: 
        +          { return newSym(sym.CHAR, yytext());
        +          }
        +        case 80: break;
        +        case 20: 
        +          { /* IGNORAR COMENTARIOS */
        +          }
        +        case 81: break;
        +        case 21: 
        +          { return newSym(sym.OU,yytext());
        +          }
        +        case 82: break;
        +        case 22: 
        +          { return newSym(sym.SE,yytext());
        +          }
        +        case 83: break;
        +        case 23: 
        +          { return newSym(sym.DE,yytext());
        +          }
        +        case 84: break;
        +        case 24: 
        +          { return newSym(sym.ATRIBUIR,yytext());
        +          }
        +        case 85: break;
        +        case 25: 
        +          { return newSym(sym.PI,yytext());
        +          }
        +        case 86: break;
        +        case 26: 
        +          { return newSym(sym.ATE,yytext());
        +          }
        +        case 87: break;
        +        case 27: 
        +          { return newSym(sym.TANGENTE,yytext());
        +          }
        +        case 88: break;
        +        case 28: 
        +          { return newSym(sym.VAR,yytext());
        +          }
        +        case 89: break;
        +        case 29: 
        +          { return newSym(sym.NAO,yytext());
        +          }
        +        case 90: break;
        +        case 30: 
        +          { return newSym(sym.COSSENO,yytext());
        +          }
        +        case 91: break;
        +        case 31: 
        +          { return newSym(sym.SENO,yytext());
        +          }
        +        case 92: break;
        +        case 32: 
        +          { return newSym(sym.POTENCIA,yytext());
        +          }
        +        case 93: break;
        +        case 33: 
        +          { return newSym(sym.LEIA,yytext());
        +          }
        +        case 94: break;
        +        case 34: 
        +          { return newSym(sym.TIPO_VARIAVEL,yytext());
        +          }
        +        case 95: break;
        +        case 35: 
        +          { return newSym(sym.RAIZ,yytext());
        +          }
        +        case 96: break;
        +        case 36: 
        +          { return newSym(sym.MODULO,yytext());
        +          }
        +        case 97: break;
        +        case 37: 
        +          { return newSym(sym.CASO,yytext());
        +          }
        +        case 98: break;
        +        case 38: 
        +          { return newSym(sym.FACA,yytext());
        +          }
        +        case 99: break;
        +        case 39: 
        +          { return newSym(sym.PARA,yytext());
        +          }
        +        case 100: break;
        +        case 40: 
        +          { return newSym(sym.ENTAO,yytext());
        +          }
        +        case 101: break;
        +        case 41: 
        +          { return newSym(sym.TIPO_VARIAVEL_VETOR,yytext());
        +          }
        +        case 102: break;
        +        case 42: 
        +          { return newSym(sym.VOID,yytext());
        +          }
        +        case 103: break;
        +        case 43: 
        +          { return newSym(sym.SENAO,yytext());
        +          }
        +        case 104: break;
        +        case 44: 
        +          { return newSym(sym.VALOR_LOGICO,yytext());
        +          }
        +        case 105: break;
        +        case 45: 
        +          { return newSym(sym.FIMSE,yytext());
        +          }
        +        case 106: break;
        +        case 46: 
        +          { return newSym(sym.PASSO,yytext());
        +          }
        +        case 107: break;
        +        case 47: 
        +          { return newSym(sym.ESPERAR,yytext());
        +          }
        +        case 108: break;
        +        case 48: 
        +          { return newSym(sym.INICIO,yytext());
        +          }
        +        case 109: break;
        +        case 49: 
        +          { return newSym(sym.FUNCAO,yytext());
        +          }
        +        case 110: break;
        +        case 50: 
        +          { return newSym(sym.ESCOLHA,yytext());
        +          }
        +        case 111: break;
        +        case 51: 
        +          { return newSym(sym.ESCREVA,yytext());
        +          }
        +        case 112: break;
        +        case 52: 
        +          { return newSym(sym.FIMPARA,yytext());
        +          }
        +        case 113: break;
        +        case 53: 
        +          { return newSym(sym.ENQUANTO,yytext());
        +          }
        +        case 114: break;
        +        case 54: 
        +          { return newSym(sym.ESCREVAL,yytext());
        +          }
        +        case 115: break;
        +        case 55: 
        +          { return newSym(sym.ALGORITMO,yytext());
        +          }
        +        case 116: break;
        +        case 56: 
        +          { return newSym(sym.OUTROCASO,yytext());
        +          }
        +        case 117: break;
        +        case 57: 
        +          { return newSym(sym.FIMFUNCAO,yytext());
        +          }
        +        case 118: break;
        +        case 58: 
        +          { return newSym(sym.INTERROMPA,yytext());
        +          }
        +        case 119: break;
        +        case 59: 
        +          { return newSym(sym.FIMESCOLHA,yytext());
        +          }
        +        case 120: break;
        +        case 60: 
        +          { return newSym(sym.FIMENQUANTO,yytext());
        +          }
        +        case 121: break;
        +        case 61: 
        +          { return newSym(sym.FIMALGORITMO,yytext());
        +          }
        +        case 122: break;
        +        default: 
        +          if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
        +            zzAtEOF = true;
        +            zzDoEOF();
        +              {
        +                return newSym(sym.EOF);
        +              }
        +          } 
        +          else {
        +            zzScanError(ZZ_NO_MATCH);
        +          }
        +      }
        +    }
        +  }
        +
        +
        +}
        diff --git a/src/com/compilador/portugol/java_cup.jar b/src/com/compilador/portugol/java_cup.jar
        new file mode 100644
        index 0000000..73ffa0b
        Binary files /dev/null and b/src/com/compilador/portugol/java_cup.jar differ
        diff --git a/src/com/compilador/portugol/parser.java b/src/com/compilador/portugol/parser.java
        new file mode 100644
        index 0000000..d6e5c90
        --- /dev/null
        +++ b/src/com/compilador/portugol/parser.java
        @@ -0,0 +1,2025 @@
        +
        +//----------------------------------------------------
        +// The following code was generated by CUP v0.11a beta 20060608
        +// Fri Sep 26 15:47:26 BRT 2014
        +//----------------------------------------------------
        +
        +package com.compilador.portugol;
        +
        +import static com.forms.Editor.util;
        +import java_cup.runtime.*;
        +import javax.swing.JOptionPane;
        +
        +/** CUP v0.11a beta 20060608 generated parser.
        +  * @version Fri Sep 26 15:47:26 BRT 2014
        +  */
        +public class parser extends java_cup.runtime.lr_parser {
        +
        +  /** Default constructor. */
        +  public parser() {super();}
        +
        +  /** Constructor which sets the default scanner. */
        +  public parser(java_cup.runtime.Scanner s) {super(s);}
        +
        +  /** Constructor which sets the default scanner. */
        +  public parser(java_cup.runtime.Scanner s, java_cup.runtime.SymbolFactory sf) {super(s,sf);}
        +
        +  /** Production table. */
        +  protected static final short _production_table[][] = 
        +    unpackFromStrings(new String[] {
        +    "\000\132\000\002\002\004\000\002\002\007\000\002\002" +
        +    "\002\000\002\003\003\000\002\004\004\000\002\004\004" +
        +    "\000\002\005\003\000\002\005\004\000\002\005\002\000" +
        +    "\002\006\004\000\002\006\003\000\002\007\005\000\002" +
        +    "\007\014\000\002\010\005\000\002\010\003\000\002\011" +
        +    "\004\000\002\011\002\000\002\012\003\000\002\012\003" +
        +    "\000\002\012\003\000\002\012\003\000\002\012\003\000" +
        +    "\002\012\003\000\002\012\003\000\002\012\003\000\002" +
        +    "\030\003\000\002\030\006\000\002\013\005\000\002\013" +
        +    "\010\000\002\014\005\000\002\014\007\000\002\015\005" +
        +    "\000\002\016\003\000\002\043\002\000\002\021\010\000" +
        +    "\002\022\003\000\002\044\002\000\002\045\002\000\002" +
        +    "\046\002\000\002\023\017\000\002\042\004\000\002\042" +
        +    "\002\000\002\017\006\000\002\017\006\000\002\020\006" +
        +    "\000\002\047\002\000\002\024\010\000\002\025\004\000" +
        +    "\002\025\002\000\002\050\002\000\002\026\006\000\002" +
        +    "\027\004\000\002\027\002\000\002\036\005\000\002\036" +
        +    "\005\000\002\036\005\000\002\036\006\000\002\036\003" +
        +    "\000\002\037\005\000\002\037\005\000\002\037\005\000" +
        +    "\002\037\006\000\002\037\003\000\002\040\005\000\002" +
        +    "\040\003\000\002\041\005\000\002\041\003\000\002\041" +
        +    "\006\000\002\034\005\000\002\034\005\000\002\034\010" +
        +    "\000\002\034\006\000\002\034\006\000\002\034\006\000" +
        +    "\002\034\006\000\002\034\006\000\002\034\005\000\002" +
        +    "\034\006\000\002\034\003\000\002\034\003\000\002\034" +
        +    "\003\000\002\034\003\000\002\034\003\000\002\034\003" +
        +    "\000\002\034\003\000\002\035\005\000\002\035\005\000" +
        +    "\002\035\005\000\002\035\003\000\002\035\003" });
        +
        +  /** Access to production table. */
        +  public short[][] production_table() {return _production_table;}
        +
        +  /** Parse-action table. */
        +  protected static final short[][] _action_table = 
        +    unpackFromStrings(new String[] {
        +    "\000\305\000\006\002\uffff\004\006\001\002\000\006\005" +
        +    "\013\010\ufff9\001\002\000\006\005\ufffe\010\ufffe\001\002" +
        +    "\000\006\071\011\072\012\001\002\000\004\002\010\001" +
        +    "\002\000\004\002\001\001\002\000\006\005\ufffd\010\ufffd" +
        +    "\001\002\000\006\005\ufffc\010\ufffc\001\002\000\006\010" +
        +    "\ufffb\071\267\001\002\000\004\010\015\001\002\000\030" +
        +    "\022\ufff1\026\ufff1\027\ufff1\033\ufff1\037\ufff1\040\ufff1\063" +
        +    "\ufff1\064\ufff1\065\ufff1\066\ufff1\071\ufff1\001\002\000\030" +
        +    "\022\034\026\040\027\024\033\037\037\031\040\044\063" +
        +    "\021\064\030\065\042\066\020\071\026\001\002\000\046" +
        +    "\022\uffef\024\uffef\025\uffef\026\uffef\027\uffef\031\uffef\032" +
        +    "\uffef\033\uffef\034\uffef\035\uffef\036\uffef\037\uffef\040\uffef" +
        +    "\063\uffef\064\uffef\065\uffef\066\uffef\071\uffef\001\002\000" +
        +    "\004\002\000\001\002\000\004\015\264\001\002\000\046" +
        +    "\022\uffec\024\uffec\025\uffec\026\uffec\027\uffec\031\uffec\032" +
        +    "\uffec\033\uffec\034\uffec\035\uffec\036\uffec\037\uffec\040\uffec" +
        +    "\063\uffec\064\uffec\065\uffec\066\uffec\071\uffec\001\002\000" +
        +    "\046\022\ufff0\024\ufff0\025\ufff0\026\ufff0\027\ufff0\031\ufff0" +
        +    "\032\ufff0\033\ufff0\034\ufff0\035\ufff0\036\ufff0\037\ufff0\040" +
        +    "\ufff0\063\ufff0\064\ufff0\065\ufff0\066\ufff0\071\ufff0\001\002" +
        +    "\000\004\071\246\001\002\000\046\022\ufff2\024\ufff2\025" +
        +    "\ufff2\026\ufff2\027\ufff2\031\ufff2\032\ufff2\033\ufff2\034\ufff2" +
        +    "\035\ufff2\036\ufff2\037\ufff2\040\ufff2\063\ufff2\064\ufff2\065" +
        +    "\ufff2\066\ufff2\071\ufff2\001\002\000\006\014\240\017\237" +
        +    "\001\002\000\046\022\uffde\024\uffde\025\uffde\026\uffde\027" +
        +    "\uffde\031\uffde\032\uffde\033\uffde\034\uffde\035\uffde\036\uffde" +
        +    "\037\uffde\040\uffde\063\uffde\064\uffde\065\uffde\066\uffde\071" +
        +    "\uffde\001\002\000\004\015\231\001\002\000\046\022\uffe8" +
        +    "\024\uffe8\025\uffe8\026\uffe8\027\uffe8\031\uffe8\032\uffe8\033" +
        +    "\uffe8\034\uffe8\035\uffe8\036\uffe8\037\uffe8\040\uffe8\063\uffe8" +
        +    "\064\uffe8\065\uffe8\066\uffe8\071\uffe8\001\002\000\032\022" +
        +    "\ufff1\024\ufff1\025\ufff1\026\ufff1\027\ufff1\033\ufff1\037\ufff1" +
        +    "\040\ufff1\063\ufff1\064\ufff1\065\ufff1\071\ufff1\001\002\000" +
        +    "\046\022\uffea\024\uffea\025\uffea\026\uffea\027\uffea\031\uffea" +
        +    "\032\uffea\033\uffea\034\uffea\035\uffea\036\uffea\037\uffea\040" +
        +    "\uffea\063\uffea\064\uffea\065\uffea\066\uffea\071\uffea\001\002" +
        +    "\000\040\013\051\015\146\041\047\042\057\043\061\044" +
        +    "\046\045\060\046\053\047\064\062\150\071\056\072\054" +
        +    "\073\063\074\052\075\062\001\002\000\046\022\uffee\024" +
        +    "\uffee\025\uffee\026\uffee\027\uffee\031\uffee\032\uffee\033\uffee" +
        +    "\034\uffee\035\uffee\036\uffee\037\uffee\040\uffee\063\uffee\064" +
        +    "\uffee\065\uffee\066\uffee\071\uffee\001\002\000\046\022\uffed" +
        +    "\024\uffed\025\uffed\026\uffed\027\uffed\031\uffed\032\uffed\033" +
        +    "\uffed\034\uffed\035\uffed\036\uffed\037\uffed\040\uffed\063\uffed" +
        +    "\064\uffed\065\uffed\066\uffed\071\uffed\001\002\000\036\013" +
        +    "\051\015\050\041\047\042\057\043\061\044\046\045\060" +
        +    "\046\053\047\064\071\056\072\054\073\063\074\052\075" +
        +    "\062\001\002\000\040\013\051\015\146\041\047\042\057" +
        +    "\043\061\044\046\045\060\046\053\047\064\062\150\071" +
        +    "\056\072\054\073\063\074\052\075\062\001\002\000\046" +
        +    "\022\uffe9\024\uffe9\025\uffe9\026\uffe9\027\uffe9\031\uffe9\032" +
        +    "\uffe9\033\uffe9\034\uffe9\035\uffe9\036\uffe9\037\uffe9\040\uffe9" +
        +    "\063\uffe9\064\uffe9\065\uffe9\066\uffe9\071\uffe9\001\002\000" +
        +    "\004\015\134\001\002\000\046\022\uffeb\024\uffeb\025\uffeb" +
        +    "\026\uffeb\027\uffeb\031\uffeb\032\uffeb\033\uffeb\034\uffeb\035" +
        +    "\uffeb\036\uffeb\037\uffeb\040\uffeb\063\uffeb\064\uffeb\065\uffeb" +
        +    "\066\uffeb\071\uffeb\001\002\000\004\015\045\001\002\000" +
        +    "\036\013\051\015\050\041\047\042\057\043\061\044\046" +
        +    "\045\060\046\053\047\064\071\056\072\054\073\063\074" +
        +    "\052\075\062\001\002\000\004\015\131\001\002\000\004" +
        +    "\015\124\001\002\000\036\013\051\015\050\041\047\042" +
        +    "\057\043\061\044\046\045\060\046\053\047\064\071\056" +
        +    "\072\054\073\063\074\052\075\062\001\002\000\076\011" +
        +    "\uffad\012\uffad\016\uffad\022\uffad\023\uffad\024\uffad\025\uffad" +
        +    "\026\uffad\027\uffad\030\uffad\031\uffad\032\uffad\033\uffad\034" +
        +    "\uffad\035\uffad\036\uffad\037\uffad\040\uffad\053\uffad\054\uffad" +
        +    "\056\uffad\057\uffad\060\uffad\061\uffad\063\uffad\064\uffad\065" +
        +    "\uffad\066\uffad\070\uffad\071\uffad\001\002\000\076\011\uffb2" +
        +    "\012\uffb2\016\uffb2\022\uffb2\023\uffb2\024\uffb2\025\uffb2\026" +
        +    "\uffb2\027\uffb2\030\uffb2\031\uffb2\032\uffb2\033\uffb2\034\uffb2" +
        +    "\035\uffb2\036\uffb2\037\uffb2\040\uffb2\053\uffb2\054\uffb2\056" +
        +    "\uffb2\057\uffb2\060\uffb2\061\uffb2\063\uffb2\064\uffb2\065\uffb2" +
        +    "\066\uffb2\070\uffb2\071\uffb2\001\002\000\004\015\117\001" +
        +    "\002\000\076\011\uffaf\012\uffaf\016\uffaf\022\uffaf\023\uffaf" +
        +    "\024\uffaf\025\uffaf\026\uffaf\027\uffaf\030\uffaf\031\uffaf\032" +
        +    "\uffaf\033\uffaf\034\uffaf\035\uffaf\036\uffaf\037\uffaf\040\uffaf" +
        +    "\053\uffaf\054\uffaf\056\uffaf\057\uffaf\060\uffaf\061\uffaf\063" +
        +    "\uffaf\064\uffaf\065\uffaf\066\uffaf\070\uffaf\071\uffaf\001\002" +
        +    "\000\010\011\071\012\067\016\116\001\002\000\100\011" +
        +    "\uffb0\012\uffb0\016\uffb0\017\102\022\uffb0\023\uffb0\024\uffb0" +
        +    "\025\uffb0\026\uffb0\027\uffb0\030\uffb0\031\uffb0\032\uffb0\033" +
        +    "\uffb0\034\uffb0\035\uffb0\036\uffb0\037\uffb0\040\uffb0\053\uffb0" +
        +    "\054\uffb0\056\uffb0\057\uffb0\060\uffb0\061\uffb0\063\uffb0\064" +
        +    "\uffb0\065\uffb0\066\uffb0\070\uffb0\071\uffb0\001\002\000\004" +
        +    "\015\077\001\002\000\004\015\074\001\002\000\004\015" +
        +    "\065\001\002\000\076\011\uffae\012\uffae\016\uffae\022\uffae" +
        +    "\023\uffae\024\uffae\025\uffae\026\uffae\027\uffae\030\uffae\031" +
        +    "\uffae\032\uffae\033\uffae\034\uffae\035\uffae\036\uffae\037\uffae" +
        +    "\040\uffae\053\uffae\054\uffae\056\uffae\057\uffae\060\uffae\061" +
        +    "\uffae\063\uffae\064\uffae\065\uffae\066\uffae\070\uffae\071\uffae" +
        +    "\001\002\000\076\011\uffb3\012\uffb3\016\uffb3\022\uffb3\023" +
        +    "\uffb3\024\uffb3\025\uffb3\026\uffb3\027\uffb3\030\uffb3\031\uffb3" +
        +    "\032\uffb3\033\uffb3\034\uffb3\035\uffb3\036\uffb3\037\uffb3\040" +
        +    "\uffb3\053\uffb3\054\uffb3\056\uffb3\057\uffb3\060\uffb3\061\uffb3" +
        +    "\063\uffb3\064\uffb3\065\uffb3\066\uffb3\070\uffb3\071\uffb3\001" +
        +    "\002\000\076\011\uffb1\012\uffb1\016\uffb1\022\uffb1\023\uffb1" +
        +    "\024\uffb1\025\uffb1\026\uffb1\027\uffb1\030\uffb1\031\uffb1\032" +
        +    "\uffb1\033\uffb1\034\uffb1\035\uffb1\036\uffb1\037\uffb1\040\uffb1" +
        +    "\053\uffb1\054\uffb1\056\uffb1\057\uffb1\060\uffb1\061\uffb1\063" +
        +    "\uffb1\064\uffb1\065\uffb1\066\uffb1\070\uffb1\071\uffb1\001\002" +
        +    "\000\036\013\051\015\050\041\047\042\057\043\061\044" +
        +    "\046\045\060\046\053\047\064\071\056\072\054\073\063" +
        +    "\074\052\075\062\001\002\000\010\011\071\012\067\016" +
        +    "\070\001\002\000\036\013\051\015\050\041\047\042\057" +
        +    "\043\061\044\046\045\060\046\053\047\064\071\056\072" +
        +    "\054\073\063\074\052\075\062\001\002\000\076\011\uffb9" +
        +    "\012\uffb9\016\uffb9\022\uffb9\023\uffb9\024\uffb9\025\uffb9\026" +
        +    "\uffb9\027\uffb9\030\uffb9\031\uffb9\032\uffb9\033\uffb9\034\uffb9" +
        +    "\035\uffb9\036\uffb9\037\uffb9\040\uffb9\053\uffb9\054\uffb9\056" +
        +    "\uffb9\057\uffb9\060\uffb9\061\uffb9\063\uffb9\064\uffb9\065\uffb9" +
        +    "\066\uffb9\070\uffb9\071\uffb9\001\002\000\036\013\051\015" +
        +    "\050\041\047\042\057\043\061\044\046\045\060\046\053" +
        +    "\047\064\071\056\072\054\073\063\074\052\075\062\001" +
        +    "\002\000\076\011\uffbd\012\uffbd\016\uffbd\022\uffbd\023\uffbd" +
        +    "\024\uffbd\025\uffbd\026\uffbd\027\uffbd\030\uffbd\031\uffbd\032" +
        +    "\uffbd\033\uffbd\034\uffbd\035\uffbd\036\uffbd\037\uffbd\040\uffbd" +
        +    "\053\uffbd\054\uffbd\056\uffbd\057\uffbd\060\uffbd\061\uffbd\063" +
        +    "\uffbd\064\uffbd\065\uffbd\066\uffbd\070\uffbd\071\uffbd\001\002" +
        +    "\000\076\011\uffbc\012\uffbc\016\uffbc\022\uffbc\023\uffbc\024" +
        +    "\uffbc\025\uffbc\026\uffbc\027\uffbc\030\uffbc\031\uffbc\032\uffbc" +
        +    "\033\uffbc\034\uffbc\035\uffbc\036\uffbc\037\uffbc\040\uffbc\053" +
        +    "\uffbc\054\uffbc\056\uffbc\057\uffbc\060\uffbc\061\uffbc\063\uffbc" +
        +    "\064\uffbc\065\uffbc\066\uffbc\070\uffbc\071\uffbc\001\002\000" +
        +    "\036\013\051\015\050\041\047\042\057\043\061\044\046" +
        +    "\045\060\046\053\047\064\071\056\072\054\073\063\074" +
        +    "\052\075\062\001\002\000\010\011\071\012\067\016\076" +
        +    "\001\002\000\076\011\uffb7\012\uffb7\016\uffb7\022\uffb7\023" +
        +    "\uffb7\024\uffb7\025\uffb7\026\uffb7\027\uffb7\030\uffb7\031\uffb7" +
        +    "\032\uffb7\033\uffb7\034\uffb7\035\uffb7\036\uffb7\037\uffb7\040" +
        +    "\uffb7\053\uffb7\054\uffb7\056\uffb7\057\uffb7\060\uffb7\061\uffb7" +
        +    "\063\uffb7\064\uffb7\065\uffb7\066\uffb7\070\uffb7\071\uffb7\001" +
        +    "\002\000\036\013\051\015\050\041\047\042\057\043\061" +
        +    "\044\046\045\060\046\053\047\064\071\056\072\054\073" +
        +    "\063\074\052\075\062\001\002\000\010\011\071\012\067" +
        +    "\016\101\001\002\000\076\011\uffba\012\uffba\016\uffba\022" +
        +    "\uffba\023\uffba\024\uffba\025\uffba\026\uffba\027\uffba\030\uffba" +
        +    "\031\uffba\032\uffba\033\uffba\034\uffba\035\uffba\036\uffba\037" +
        +    "\uffba\040\uffba\053\uffba\054\uffba\056\uffba\057\uffba\060\uffba" +
        +    "\061\uffba\063\uffba\064\uffba\065\uffba\066\uffba\070\uffba\071" +
        +    "\uffba\001\002\000\010\015\105\071\103\073\106\001\002" +
        +    "\000\012\011\uffa8\012\uffa8\016\uffa8\020\uffa8\001\002\000" +
        +    "\010\011\112\012\110\020\115\001\002\000\010\015\105" +
        +    "\071\103\073\106\001\002\000\012\011\uffa9\012\uffa9\016" +
        +    "\uffa9\020\uffa9\001\002\000\010\011\112\012\110\016\111" +
        +    "\001\002\000\010\015\105\071\103\073\106\001\002\000" +
        +    "\012\011\uffaa\012\uffaa\016\uffaa\020\uffaa\001\002\000\010" +
        +    "\015\105\071\103\073\106\001\002\000\012\011\uffac\012" +
        +    "\uffac\016\uffac\020\uffac\001\002\000\012\011\uffab\012\uffab" +
        +    "\016\uffab\020\uffab\001\002\000\076\011\uffb4\012\uffb4\016" +
        +    "\uffb4\022\uffb4\023\uffb4\024\uffb4\025\uffb4\026\uffb4\027\uffb4" +
        +    "\030\uffb4\031\uffb4\032\uffb4\033\uffb4\034\uffb4\035\uffb4\036" +
        +    "\uffb4\037\uffb4\040\uffb4\053\uffb4\054\uffb4\056\uffb4\057\uffb4" +
        +    "\060\uffb4\061\uffb4\063\uffb4\064\uffb4\065\uffb4\066\uffb4\070" +
        +    "\uffb4\071\uffb4\001\002\000\046\022\uffe7\024\uffe7\025\uffe7" +
        +    "\026\uffe7\027\uffe7\031\uffe7\032\uffe7\033\uffe7\034\uffe7\035" +
        +    "\uffe7\036\uffe7\037\uffe7\040\uffe7\063\uffe7\064\uffe7\065\uffe7" +
        +    "\066\uffe7\071\uffe7\001\002\000\036\013\051\015\050\041" +
        +    "\047\042\057\043\061\044\046\045\060\046\053\047\064" +
        +    "\071\056\072\054\073\063\074\052\075\062\001\002\000" +
        +    "\010\011\071\012\067\016\121\001\002\000\076\011\uffb6" +
        +    "\012\uffb6\016\uffb6\022\uffb6\023\uffb6\024\uffb6\025\uffb6\026" +
        +    "\uffb6\027\uffb6\030\uffb6\031\uffb6\032\uffb6\033\uffb6\034\uffb6" +
        +    "\035\uffb6\036\uffb6\037\uffb6\040\uffb6\053\uffb6\054\uffb6\056" +
        +    "\uffb6\057\uffb6\060\uffb6\061\uffb6\063\uffb6\064\uffb6\065\uffb6" +
        +    "\066\uffb6\070\uffb6\071\uffb6\001\002\000\010\011\071\012" +
        +    "\067\016\123\001\002\000\076\011\uffb5\012\uffb5\016\uffb5" +
        +    "\022\uffb5\023\uffb5\024\uffb5\025\uffb5\026\uffb5\027\uffb5\030" +
        +    "\uffb5\031\uffb5\032\uffb5\033\uffb5\034\uffb5\035\uffb5\036\uffb5" +
        +    "\037\uffb5\040\uffb5\053\uffb5\054\uffb5\056\uffb5\057\uffb5\060" +
        +    "\uffb5\061\uffb5\063\uffb5\064\uffb5\065\uffb5\066\uffb5\070\uffb5" +
        +    "\071\uffb5\001\002\000\036\013\051\015\050\041\047\042" +
        +    "\057\043\061\044\046\045\060\046\053\047\064\071\056" +
        +    "\072\054\073\063\074\052\075\062\001\002\000\010\011" +
        +    "\071\012\067\070\126\001\002\000\036\013\051\015\050" +
        +    "\041\047\042\057\043\061\044\046\045\060\046\053\047" +
        +    "\064\071\056\072\054\073\063\074\052\075\062\001\002" +
        +    "\000\010\011\071\012\067\016\130\001\002\000\076\011" +
        +    "\uffbb\012\uffbb\016\uffbb\022\uffbb\023\uffbb\024\uffbb\025\uffbb" +
        +    "\026\uffbb\027\uffbb\030\uffbb\031\uffbb\032\uffbb\033\uffbb\034" +
        +    "\uffbb\035\uffbb\036\uffbb\037\uffbb\040\uffbb\053\uffbb\054\uffbb" +
        +    "\056\uffbb\057\uffbb\060\uffbb\061\uffbb\063\uffbb\064\uffbb\065" +
        +    "\uffbb\066\uffbb\070\uffbb\071\uffbb\001\002\000\036\013\051" +
        +    "\015\050\041\047\042\057\043\061\044\046\045\060\046" +
        +    "\053\047\064\071\056\072\054\073\063\074\052\075\062" +
        +    "\001\002\000\010\011\071\012\067\016\133\001\002\000" +
        +    "\076\011\uffb8\012\uffb8\016\uffb8\022\uffb8\023\uffb8\024\uffb8" +
        +    "\025\uffb8\026\uffb8\027\uffb8\030\uffb8\031\uffb8\032\uffb8\033" +
        +    "\uffb8\034\uffb8\035\uffb8\036\uffb8\037\uffb8\040\uffb8\053\uffb8" +
        +    "\054\uffb8\056\uffb8\057\uffb8\060\uffb8\061\uffb8\063\uffb8\064" +
        +    "\uffb8\065\uffb8\066\uffb8\070\uffb8\071\uffb8\001\002\000\004" +
        +    "\071\135\001\002\000\010\016\uffbf\017\142\070\uffbf\001" +
        +    "\002\000\006\016\140\070\137\001\002\000\004\071\135" +
        +    "\001\002\000\046\022\uffd5\024\uffd5\025\uffd5\026\uffd5\027" +
        +    "\uffd5\031\uffd5\032\uffd5\033\uffd5\034\uffd5\035\uffd5\036\uffd5" +
        +    "\037\uffd5\040\uffd5\063\uffd5\064\uffd5\065\uffd5\066\uffd5\071" +
        +    "\uffd5\001\002\000\006\016\uffc0\070\uffc0\001\002\000\010" +
        +    "\015\105\071\103\073\106\001\002\000\010\011\112\012" +
        +    "\110\020\144\001\002\000\006\016\uffbe\070\uffbe\001\002" +
        +    "\000\010\030\201\056\173\061\172\001\002\000\040\013" +
        +    "\051\015\146\041\047\042\057\043\061\044\046\045\060" +
        +    "\046\053\047\064\062\150\071\056\072\054\073\063\074" +
        +    "\052\075\062\001\002\000\024\011\071\012\067\016\uffc3" +
        +    "\023\uffc3\030\uffc3\053\uffc3\054\uffc3\056\uffc3\061\uffc3\001" +
        +    "\002\000\004\015\166\001\002\000\020\016\uffc8\023\uffc8" +
        +    "\030\uffc8\053\152\054\153\056\uffc8\061\uffc8\001\002\000" +
        +    "\040\013\051\015\154\041\047\042\057\043\061\044\046" +
        +    "\045\060\046\053\047\064\062\156\071\056\072\054\073" +
        +    "\063\074\052\075\062\001\002\000\040\013\051\015\154" +
        +    "\041\047\042\057\043\061\044\046\045\060\046\053\047" +
        +    "\064\062\156\071\056\072\054\073\063\074\052\075\062" +
        +    "\001\002\000\040\013\051\015\154\041\047\042\057\043" +
        +    "\061\044\046\045\060\046\053\047\064\062\156\071\056" +
        +    "\072\054\073\063\074\052\075\062\001\002\000\020\016" +
        +    "\uffc6\023\uffc6\030\uffc6\053\uffc6\054\uffc6\056\uffc6\061\uffc6" +
        +    "\001\002\000\004\015\157\001\002\000\040\013\051\015" +
        +    "\154\041\047\042\057\043\061\044\046\045\060\046\053" +
        +    "\047\064\062\156\071\056\072\054\073\063\074\052\075" +
        +    "\062\001\002\000\010\016\161\053\152\054\153\001\002" +
        +    "\000\020\016\uffc4\023\uffc4\030\uffc4\053\uffc4\054\uffc4\056" +
        +    "\uffc4\061\uffc4\001\002\000\010\016\164\053\152\054\153" +
        +    "\001\002\000\020\011\071\012\067\016\123\053\uffc3\054" +
        +    "\uffc3\056\uffc3\061\uffc3\001\002\000\020\016\uffc5\023\uffc5" +
        +    "\030\uffc5\053\uffc5\054\uffc5\056\uffc5\061\uffc5\001\002\000" +
        +    "\020\016\uffc7\023\uffc7\030\uffc7\053\uffc7\054\uffc7\056\uffc7" +
        +    "\061\uffc7\001\002\000\040\013\051\015\146\041\047\042" +
        +    "\057\043\061\044\046\045\060\046\053\047\064\062\150" +
        +    "\071\056\072\054\073\063\074\052\075\062\001\002\000" +
        +    "\010\016\171\056\173\061\172\001\002\000\014\016\161" +
        +    "\053\152\054\153\056\uffc8\061\uffc8\001\002\000\014\016" +
        +    "\uffc9\023\uffc9\030\uffc9\056\uffc9\061\uffc9\001\002\000\040" +
        +    "\013\051\015\146\041\047\042\057\043\061\044\046\045" +
        +    "\060\046\053\047\064\062\150\071\056\072\054\073\063" +
        +    "\074\052\075\062\001\002\000\040\013\051\015\146\041" +
        +    "\047\042\057\043\061\044\046\045\060\046\053\047\064" +
        +    "\062\150\071\056\072\054\073\063\074\052\075\062\001" +
        +    "\002\000\014\016\uffcc\023\uffcc\030\uffcc\056\uffcc\061\uffcc" +
        +    "\001\002\000\014\016\uffcb\023\uffcb\030\uffcb\056\uffcb\061" +
        +    "\uffcb\001\002\000\010\016\200\056\173\061\172\001\002" +
        +    "\000\014\016\164\053\152\054\153\056\uffc8\061\uffc8\001" +
        +    "\002\000\014\016\uffca\023\uffca\030\uffca\056\uffca\061\uffca" +
        +    "\001\002\000\030\022\uffe0\026\uffe0\027\uffe0\031\uffe0\033" +
        +    "\uffe0\037\uffe0\040\uffe0\063\uffe0\064\uffe0\065\uffe0\071\uffe0" +
        +    "\001\002\000\030\022\ufff1\026\ufff1\027\ufff1\031\ufff1\033" +
        +    "\ufff1\037\ufff1\040\ufff1\063\ufff1\064\ufff1\065\ufff1\071\ufff1" +
        +    "\001\002\000\030\022\034\026\040\027\024\031\204\033" +
        +    "\037\037\031\040\044\063\021\064\030\065\042\071\026" +
        +    "\001\002\000\046\022\uffdf\024\uffdf\025\uffdf\026\uffdf\027" +
        +    "\uffdf\031\uffdf\032\uffdf\033\uffdf\034\uffdf\035\uffdf\036\uffdf" +
        +    "\037\uffdf\040\uffdf\063\uffdf\064\uffdf\065\uffdf\066\uffdf\071" +
        +    "\uffdf\001\002\000\014\011\071\012\067\034\uffd4\035\uffd4" +
        +    "\036\uffd4\001\002\000\010\034\uffd1\035\uffd1\036\uffd1\001" +
        +    "\002\000\010\034\213\035\210\036\uffcd\001\002\000\030" +
        +    "\022\ufff1\026\ufff1\027\ufff1\033\ufff1\036\ufff1\037\ufff1\040" +
        +    "\ufff1\063\ufff1\064\ufff1\065\ufff1\071\ufff1\001\002\000\004" +
        +    "\036\217\001\002\000\010\034\uffd2\035\uffd2\036\uffd2\001" +
        +    "\002\000\036\013\051\015\050\041\047\042\057\043\061" +
        +    "\044\046\045\060\046\053\047\064\071\056\072\054\073" +
        +    "\063\074\052\075\062\001\002\000\040\011\071\012\067" +
        +    "\022\uffd0\026\uffd0\027\uffd0\033\uffd0\034\uffd0\035\uffd0\036" +
        +    "\uffd0\037\uffd0\040\uffd0\063\uffd0\064\uffd0\065\uffd0\071\uffd0" +
        +    "\001\002\000\034\022\ufff1\026\ufff1\027\ufff1\033\ufff1\034" +
        +    "\ufff1\035\ufff1\036\ufff1\037\ufff1\040\ufff1\063\ufff1\064\ufff1" +
        +    "\065\ufff1\071\ufff1\001\002\000\034\022\034\026\040\027" +
        +    "\024\033\037\034\uffcf\035\uffcf\036\uffcf\037\031\040\044" +
        +    "\063\021\064\030\065\042\071\026\001\002\000\046\022" +
        +    "\uffd3\024\uffd3\025\uffd3\026\uffd3\027\uffd3\031\uffd3\032\uffd3" +
        +    "\033\uffd3\034\uffd3\035\uffd3\036\uffd3\037\uffd3\040\uffd3\063" +
        +    "\uffd3\064\uffd3\065\uffd3\066\uffd3\071\uffd3\001\002\000\030" +
        +    "\022\034\026\040\027\024\033\037\036\uffce\037\031\040" +
        +    "\044\063\021\064\030\065\042\071\026\001\002\000\010" +
        +    "\023\222\056\173\061\172\001\002\000\032\022\uffe2\024" +
        +    "\uffe2\025\uffe2\026\uffe2\027\uffe2\033\uffe2\037\uffe2\040\uffe2" +
        +    "\063\uffe2\064\uffe2\065\uffe2\071\uffe2\001\002\000\032\022" +
        +    "\034\024\224\025\225\026\040\027\024\033\037\037\031" +
        +    "\040\044\063\021\064\030\065\042\071\026\001\002\000" +
        +    "\030\022\uffe1\025\uffe1\026\uffe1\027\uffe1\033\uffe1\037\uffe1" +
        +    "\040\uffe1\063\uffe1\064\uffe1\065\uffe1\071\uffe1\001\002\000" +
        +    "\046\022\uffe4\024\uffe4\025\uffe4\026\uffe4\027\uffe4\031\uffe4" +
        +    "\032\uffe4\033\uffe4\034\uffe4\035\uffe4\036\uffe4\037\uffe4\040" +
        +    "\uffe4\063\uffe4\064\uffe4\065\uffe4\066\uffe4\071\uffe4\001\002" +
        +    "\000\030\022\ufff1\025\ufff1\026\ufff1\027\ufff1\033\ufff1\037" +
        +    "\ufff1\040\ufff1\063\ufff1\064\ufff1\065\ufff1\071\ufff1\001\002" +
        +    "\000\030\022\034\025\230\026\040\027\024\033\037\037" +
        +    "\031\040\044\063\021\064\030\065\042\071\026\001\002" +
        +    "\000\046\022\uffe3\024\uffe3\025\uffe3\026\uffe3\027\uffe3\031" +
        +    "\uffe3\032\uffe3\033\uffe3\034\uffe3\035\uffe3\036\uffe3\037\uffe3" +
        +    "\040\uffe3\063\uffe3\064\uffe3\065\uffe3\066\uffe3\071\uffe3\001" +
        +    "\002\000\036\013\051\015\050\041\047\042\057\043\061" +
        +    "\044\046\045\060\046\053\047\064\071\056\072\054\073" +
        +    "\063\074\052\075\062\001\002\000\012\011\071\012\067" +
        +    "\016\uffc1\070\uffc1\001\002\000\006\016\235\070\234\001" +
        +    "\002\000\036\013\051\015\050\041\047\042\057\043\061" +
        +    "\044\046\045\060\046\053\047\064\071\056\072\054\073" +
        +    "\063\074\052\075\062\001\002\000\046\022\uffd6\024\uffd6" +
        +    "\025\uffd6\026\uffd6\027\uffd6\031\uffd6\032\uffd6\033\uffd6\034" +
        +    "\uffd6\035\uffd6\036\uffd6\037\uffd6\040\uffd6\063\uffd6\064\uffd6" +
        +    "\065\uffd6\066\uffd6\071\uffd6\001\002\000\006\016\uffc2\070" +
        +    "\uffc2\001\002\000\010\015\105\071\103\073\106\001\002" +
        +    "\000\036\013\051\015\050\041\047\042\057\043\061\044" +
        +    "\046\045\060\046\053\047\064\071\056\072\054\073\063" +
        +    "\074\052\075\062\001\002\000\052\011\071\012\067\022" +
        +    "\uffe6\024\uffe6\025\uffe6\026\uffe6\027\uffe6\031\uffe6\032\uffe6" +
        +    "\033\uffe6\034\uffe6\035\uffe6\036\uffe6\037\uffe6\040\uffe6\063" +
        +    "\uffe6\064\uffe6\065\uffe6\066\uffe6\071\uffe6\001\002\000\010" +
        +    "\011\112\012\110\020\243\001\002\000\004\014\244\001" +
        +    "\002\000\036\013\051\015\050\041\047\042\057\043\061" +
        +    "\044\046\045\060\046\053\047\064\071\056\072\054\073" +
        +    "\063\074\052\075\062\001\002\000\052\011\071\012\067" +
        +    "\022\uffe5\024\uffe5\025\uffe5\026\uffe5\027\uffe5\031\uffe5\032" +
        +    "\uffe5\033\uffe5\034\uffe5\035\uffe5\036\uffe5\037\uffe5\040\uffe5" +
        +    "\063\uffe5\064\uffe5\065\uffe5\066\uffe5\071\uffe5\001\002\000" +
        +    "\004\055\247\001\002\000\036\013\051\015\050\041\047" +
        +    "\042\057\043\061\044\046\045\060\046\053\047\064\071" +
        +    "\056\072\054\073\063\074\052\075\062\001\002\000\010" +
        +    "\011\071\012\067\057\uffdd\001\002\000\004\057\252\001" +
        +    "\002\000\036\013\051\015\050\041\047\042\057\043\061" +
        +    "\044\046\045\060\046\053\047\064\071\056\072\054\073" +
        +    "\063\074\052\075\062\001\002\000\012\011\071\012\067" +
        +    "\030\uffdc\060\uffdc\001\002\000\006\030\uffd8\060\255\001" +
        +    "\002\000\036\013\051\015\050\041\047\042\057\043\061" +
        +    "\044\046\045\060\046\053\047\064\071\056\072\054\073" +
        +    "\063\074\052\075\062\001\002\000\004\030\257\001\002" +
        +    "\000\030\022\uffdb\026\uffdb\027\uffdb\032\uffdb\033\uffdb\037" +
        +    "\uffdb\040\uffdb\063\uffdb\064\uffdb\065\uffdb\071\uffdb\001\002" +
        +    "\000\030\022\ufff1\026\ufff1\027\ufff1\032\ufff1\033\ufff1\037" +
        +    "\ufff1\040\ufff1\063\ufff1\064\ufff1\065\ufff1\071\ufff1\001\002" +
        +    "\000\030\022\034\026\040\027\024\032\262\033\037\037" +
        +    "\031\040\044\063\021\064\030\065\042\071\026\001\002" +
        +    "\000\046\022\uffda\024\uffda\025\uffda\026\uffda\027\uffda\031" +
        +    "\uffda\032\uffda\033\uffda\034\uffda\035\uffda\036\uffda\037\uffda" +
        +    "\040\uffda\063\uffda\064\uffda\065\uffda\066\uffda\071\uffda\001" +
        +    "\002\000\010\011\071\012\067\030\uffd9\001\002\000\036" +
        +    "\013\051\015\050\041\047\042\057\043\061\044\046\045" +
        +    "\060\046\053\047\064\071\056\072\054\073\063\074\052" +
        +    "\075\062\001\002\000\006\016\266\070\234\001\002\000" +
        +    "\046\022\uffd7\024\uffd7\025\uffd7\026\uffd7\027\uffd7\031\uffd7" +
        +    "\032\uffd7\033\uffd7\034\uffd7\035\uffd7\036\uffd7\037\uffd7\040" +
        +    "\uffd7\063\uffd7\064\uffd7\065\uffd7\066\uffd7\071\uffd7\001\002" +
        +    "\000\006\067\ufff3\070\ufff3\001\002\000\006\010\ufffa\071" +
        +    "\267\001\002\000\006\010\ufff7\071\ufff7\001\002\000\006" +
        +    "\067\274\070\273\001\002\000\004\071\267\001\002\000" +
        +    "\006\006\275\007\276\001\002\000\006\010\ufff6\071\ufff6" +
        +    "\001\002\000\004\017\277\001\002\000\004\073\300\001" +
        +    "\002\000\004\021\301\001\002\000\004\073\302\001\002" +
        +    "\000\004\020\303\001\002\000\004\055\304\001\002\000" +
        +    "\004\006\305\001\002\000\006\010\ufff5\071\ufff5\001\002" +
        +    "\000\006\067\ufff4\070\ufff4\001\002\000\006\010\ufff8\071" +
        +    "\ufff8\001\002" });
        +
        +  /** Access to parse-action table. */
        +  public short[][] action_table() {return _action_table;}
        +
        +  /** reduce_goto table. */
        +  protected static final short[][] _reduce_table = 
        +    unpackFromStrings(new String[] {
        +    "\000\305\000\010\002\006\003\003\004\004\001\001\000" +
        +    "\004\005\013\001\001\000\002\001\001\000\002\001\001" +
        +    "\000\002\001\001\000\002\001\001\000\002\001\001\000" +
        +    "\002\001\001\000\010\006\267\007\270\010\271\001\001" +
        +    "\000\002\001\001\000\004\011\015\001\001\000\030\012" +
        +    "\024\013\016\014\034\015\031\017\035\020\021\021\042" +
        +    "\022\032\023\026\024\040\030\022\001\001\000\002\001" +
        +    "\001\000\002\001\001\000\002\001\001\000\002\001\001" +
        +    "\000\002\001\001\000\002\001\001\000\002\001\001\000" +
        +    "\002\001\001\000\002\001\001\000\002\001\001\000\002" +
        +    "\001\001\000\004\011\222\001\001\000\002\001\001\000" +
        +    "\010\034\146\036\220\037\150\001\001\000\002\001\001" +
        +    "\000\002\001\001\000\004\034\204\001\001\000\010\034" +
        +    "\146\036\144\037\150\001\001\000\002\001\001\000\002" +
        +    "\001\001\000\002\001\001\000\002\001\001\000\004\034" +
        +    "\054\001\001\000\002\001\001\000\002\001\001\000\004" +
        +    "\034\121\001\001\000\002\001\001\000\002\001\001\000" +
        +    "\002\001\001\000\002\001\001\000\002\001\001\000\002" +
        +    "\001\001\000\002\001\001\000\002\001\001\000\002\001" +
        +    "\001\000\002\001\001\000\002\001\001\000\002\001\001" +
        +    "\000\004\034\065\001\001\000\002\001\001\000\004\034" +
        +    "\072\001\001\000\002\001\001\000\004\034\071\001\001" +
        +    "\000\002\001\001\000\002\001\001\000\004\034\074\001" +
        +    "\001\000\002\001\001\000\002\001\001\000\004\034\077" +
        +    "\001\001\000\002\001\001\000\002\001\001\000\004\035" +
        +    "\103\001\001\000\002\001\001\000\002\001\001\000\004" +
        +    "\035\106\001\001\000\002\001\001\000\002\001\001\000" +
        +    "\004\035\113\001\001\000\002\001\001\000\004\035\112" +
        +    "\001\001\000\002\001\001\000\002\001\001\000\002\001" +
        +    "\001\000\002\001\001\000\004\034\117\001\001\000\002" +
        +    "\001\001\000\002\001\001\000\002\001\001\000\002\001" +
        +    "\001\000\004\034\124\001\001\000\002\001\001\000\004" +
        +    "\034\126\001\001\000\002\001\001\000\002\001\001\000" +
        +    "\004\034\131\001\001\000\002\001\001\000\002\001\001" +
        +    "\000\004\041\135\001\001\000\002\001\001\000\002\001" +
        +    "\001\000\004\041\140\001\001\000\002\001\001\000\002" +
        +    "\001\001\000\004\035\142\001\001\000\002\001\001\000" +
        +    "\002\001\001\000\002\001\001\000\010\034\162\036\175" +
        +    "\037\176\001\001\000\002\001\001\000\002\001\001\000" +
        +    "\002\001\001\000\006\034\146\037\164\001\001\000\006" +
        +    "\034\146\037\154\001\001\000\006\034\162\037\161\001" +
        +    "\001\000\002\001\001\000\002\001\001\000\006\034\146" +
        +    "\037\157\001\001\000\002\001\001\000\002\001\001\000" +
        +    "\002\001\001\000\002\001\001\000\002\001\001\000\002" +
        +    "\001\001\000\010\034\146\036\166\037\167\001\001\000" +
        +    "\002\001\001\000\002\001\001\000\002\001\001\000\010" +
        +    "\034\146\036\174\037\150\001\001\000\010\034\146\036" +
        +    "\173\037\150\001\001\000\002\001\001\000\002\001\001" +
        +    "\000\002\001\001\000\002\001\001\000\002\001\001\000" +
        +    "\004\043\201\001\001\000\004\011\202\001\001\000\030" +
        +    "\012\024\013\016\014\034\015\031\017\035\020\021\021" +
        +    "\042\022\032\023\026\024\040\030\022\001\001\000\002" +
        +    "\001\001\000\004\047\205\001\001\000\004\025\206\001" +
        +    "\001\000\006\026\211\027\210\001\001\000\004\011\217" +
        +    "\001\001\000\002\001\001\000\002\001\001\000\004\034" +
        +    "\213\001\001\000\004\050\214\001\001\000\004\011\215" +
        +    "\001\001\000\030\012\024\013\016\014\034\015\031\017" +
        +    "\035\020\021\021\042\022\032\023\026\024\040\030\022" +
        +    "\001\001\000\002\001\001\000\030\012\024\013\016\014" +
        +    "\034\015\031\017\035\020\021\021\042\022\032\023\026" +
        +    "\024\040\030\022\001\001\000\002\001\001\000\002\001" +
        +    "\001\000\032\012\024\013\016\014\034\015\031\016\225" +
        +    "\017\035\020\021\021\042\022\032\023\026\024\040\030" +
        +    "\022\001\001\000\002\001\001\000\002\001\001\000\004" +
        +    "\011\226\001\001\000\030\012\024\013\016\014\034\015" +
        +    "\031\017\035\020\021\021\042\022\032\023\026\024\040" +
        +    "\030\022\001\001\000\002\001\001\000\006\034\231\040" +
        +    "\232\001\001\000\002\001\001\000\002\001\001\000\006" +
        +    "\034\231\040\235\001\001\000\002\001\001\000\002\001" +
        +    "\001\000\004\035\241\001\001\000\004\034\240\001\001" +
        +    "\000\002\001\001\000\002\001\001\000\002\001\001\000" +
        +    "\004\034\244\001\001\000\002\001\001\000\002\001\001" +
        +    "\000\004\034\247\001\001\000\004\044\250\001\001\000" +
        +    "\002\001\001\000\004\034\252\001\001\000\004\045\253" +
        +    "\001\001\000\004\042\255\001\001\000\004\034\262\001" +
        +    "\001\000\002\001\001\000\004\046\257\001\001\000\004" +
        +    "\011\260\001\001\000\030\012\024\013\016\014\034\015" +
        +    "\031\017\035\020\021\021\042\022\032\023\026\024\040" +
        +    "\030\022\001\001\000\002\001\001\000\002\001\001\000" +
        +    "\006\034\231\040\264\001\001\000\002\001\001\000\002" +
        +    "\001\001\000\002\001\001\000\006\007\306\010\271\001" +
        +    "\001\000\002\001\001\000\002\001\001\000\004\010\305" +
        +    "\001\001\000\002\001\001\000\002\001\001\000\002\001" +
        +    "\001\000\002\001\001\000\002\001\001\000\002\001\001" +
        +    "\000\002\001\001\000\002\001\001\000\002\001\001\000" +
        +    "\002\001\001\000\002\001\001\000\002\001\001" });
        +
        +  /** Access to reduce_goto table. */
        +  public short[][] reduce_table() {return _reduce_table;}
        +
        +  /** Instance of action encapsulation class. */
        +  protected CUP$parser$actions action_obj;
        +
        +  /** Action encapsulation object initializer. */
        +  protected void init_actions()
        +    {
        +      action_obj = new CUP$parser$actions(this);
        +    }
        +
        +  /** Invoke a user supplied parse action. */
        +  public java_cup.runtime.Symbol do_action(
        +    int                        act_num,
        +    java_cup.runtime.lr_parser parser,
        +    java.util.Stack            stack,
        +    int                        top)
        +    throws java.lang.Exception
        +  {
        +    /* call code in generated class */
        +    return action_obj.CUP$parser$do_action(act_num, parser, stack, top);
        +  }
        +
        +  /** Indicates start state. */
        +  public int start_state() {return 0;}
        +  /** Indicates start production. */
        +  public int start_production() {return 0;}
        +
        +  /** EOF Symbol index. */
        +  public int EOF_sym() {return 0;}
        +
        +  /** error Symbol index. */
        +  public int error_sym() {return 1;}
        +
        +
        +  /** User initialization code. */
        +  public void user_init() throws java.lang.Exception
        +    {
        +
        +	 util = new Compilador();
        +
        +    }
        +
        +
        +    public void syntax_error(Symbol s){
        +    	if(s.value != null){
        +	        report_error("Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right+1)+". Trecho desconhecido: "+s.value,null);
        +	        JOptionPane.showMessageDialog(null,"Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right+1)+". Trecho desconhecido: "+s.value,"Erro de syntax",JOptionPane.WARNING_MESSAGE);
        +	    }else{
        +	        report_error("Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right+1),null);
        +	        JOptionPane.showMessageDialog(null,"Erro de syntax: Linha "+(s.left+1)+" Coluna "+(s.right+1),"Erro de syntax",JOptionPane.WARNING_MESSAGE);
        +	    }
        +        util.setErro();
        +        this.done_parsing();
        +    }
        +    public void syntax_error(int left,int right,String mensagem){
        +		report_error(mensagem + " " + "Linha "+(left+1)+" Coluna "+(right),null);
        +		JOptionPane.showMessageDialog(null,mensagem + " " + "Linha "+(left+1)+" Coluna "+(right+1),"Erro de syntax",JOptionPane.WARNING_MESSAGE);
        +
        +        util.setErro();
        +        this.done_parsing();
        +    }
        +    public void report_fatal_error(String message, Object info){
        +    	this.done_parsing();
        +    }
        +
        +}
        +
        +/** Cup generated class to encapsulate user supplied action code.*/
        +class CUP$parser$actions {
        +
        +
        +  private final parser parser;
        +
        +  /** Constructor */
        +  CUP$parser$actions(parser parser) {
        +    this.parser = parser;
        +  }
        +
        +  /** Method with the actual generated action code. */
        +  public final java_cup.runtime.Symbol CUP$parser$do_action(
        +    int                        CUP$parser$act_num,
        +    java_cup.runtime.lr_parser CUP$parser$parser,
        +    java.util.Stack            CUP$parser$stack,
        +    int                        CUP$parser$top)
        +    throws java.lang.Exception
        +    {
        +      /* Symbol object for return from actions */
        +      java_cup.runtime.Symbol CUP$parser$result;
        +
        +      /* select the action based on the action number */
        +      switch (CUP$parser$act_num)
        +        {
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 89: // _operacoes_indice_vetor ::= ID 
        +            {
        +              String RESULT =null;
        +		int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		
        +			          			String[] tmp = util.getVariavel(n);
        +								if(tmp[1] != null) {
        +									if("int".equals(tmp[1])){
        +										RESULT = n;
        +									}else{
        +										parser.syntax_error(nleft,nright,util.Erros("VARIAVEL_ERRO1",n));
        +									}
        +								}else{
        +									parser.syntax_error(nleft,nright,util.Erros("VARIAVEL_VETOR_ERRO4",n));	
        +								}
        +							
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes_indice_vetor",27, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 88: // _operacoes_indice_vetor ::= NUMERO_INT 
        +            {
        +              String RESULT =null;
        +		int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 RESULT = n; 
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes_indice_vetor",27, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 87: // _operacoes_indice_vetor ::= ABRIR_PARENTESE _operacoes_indice_vetor FECHAR_PARENTESE 
        +            {
        +              String RESULT =null;
        +		int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		 RESULT = e; 
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes_indice_vetor",27, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 86: // _operacoes_indice_vetor ::= _operacoes_indice_vetor OPERADOR_SOMA _operacoes_indice_vetor 
        +            {
        +              String RESULT =null;
        +		int e1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left;
        +		int e1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right;
        +		String e1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value;
        +		int e2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int e2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String e2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 RESULT = e1+" + "+e2; 
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes_indice_vetor",27, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 85: // _operacoes_indice_vetor ::= _operacoes_indice_vetor OPERADOR _operacoes_indice_vetor 
        +            {
        +              String RESULT =null;
        +		int e1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left;
        +		int e1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right;
        +		String e1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value;
        +		int opleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int opright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String op = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		int e2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int e2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String e2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 RESULT = e1+" "+util.getOperador(op)+" "+e2;  
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes_indice_vetor",27, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 84: // _operacoes ::= VALOR_LOGICO 
        +            {
        +              String RESULT =null;
        +		int lleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int lright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String l = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		
        +					util.setBooleanTMP(true);
        +					RESULT = util.getValorLogico(l);
        +				
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes",26, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 83: // _operacoes ::= CHAR 
        +            {
        +              String RESULT =null;
        +		int sleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int sright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String s = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		
        +					util.setCharTMP(true);
        +					RESULT = s;
        +				
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes",26, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 82: // _operacoes ::= STRING 
        +            {
        +              String RESULT =null;
        +		int sleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int sright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String s = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 
        +					util.setStringTMP(true);
        +					RESULT = s;
        +				
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes",26, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 81: // _operacoes ::= ID 
        +            {
        +              String RESULT =null;
        +		int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 
        +					if(util.checkVariavelExiste(n)) {
        +						String[] tmp = util.getVariavel(n);
        +						util.setTipoIdTMP(tmp[1]);
        +						RESULT = n;
        +					}else{
        +						parser.syntax_error(nleft,nright,util.Erros("VARIAVEL_ERRO1",n));	
        +					}
        +				
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes",26, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 80: // _operacoes ::= PI 
        +            {
        +              String RESULT =null;
        +		
        +					RESULT = ""+Math.PI;
        +					util.setNumerofloatTMP(true); 
        +				
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes",26, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 79: // _operacoes ::= NUMERO_FLOAT 
        +            {
        +              String RESULT =null;
        +		int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 
        +					RESULT = n;
        +					util.setNumerofloatTMP(true); 
        +				
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes",26, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 78: // _operacoes ::= NUMERO_INT 
        +            {
        +              String RESULT =null;
        +		int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 
        +					RESULT = n;
        +					util.setNumeroIntTMP(true); 
        +				
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes",26, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 77: // _operacoes ::= ID ABRIR_COLCHETE _operacoes_indice_vetor FECHAR_COLCHETE 
        +            {
        +              String RESULT =null;
        +		int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).left;
        +		int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).right;
        +		String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-3)).value;
        +		int ileft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int iright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String i = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		
        +					String[] tmp = util.getVariavelVetor(n);
        +					if(tmp[0] != null){
        +						util.setTipoIdTMP(tmp[1]);
        +						RESULT = n+"["+i+" - ("+tmp[2]+")]";
        +					}else{
        +						parser.syntax_error(nleft,nright,util.Erros("VARIAVEL_VETOR_ERRO1",n));	
        +					}
        +				
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes",26, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 76: // _operacoes ::= ABRIR_PARENTESE _operacoes FECHAR_PARENTESE 
        +            {
        +              String RESULT =null;
        +		int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		 RESULT = "("+e+")"; 
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes",26, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 75: // _operacoes ::= RAIZ ABRIR_PARENTESE _operacoes FECHAR_PARENTESE 
        +            {
        +              String RESULT =null;
        +		int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		
        +					RESULT = "Math.sqrt("+n+")";
        +					util.setOperadorTMP(true);
        +				
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes",26, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 74: // _operacoes ::= TANGENTE ABRIR_PARENTESE _operacoes FECHAR_PARENTESE 
        +            {
        +              String RESULT =null;
        +		int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		
        +					RESULT = "Math.tan("+n+"*"+(Math.PI)/180+")";
        +					util.setOperadorTMP(true);
        +				
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes",26, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 73: // _operacoes ::= COSSENO ABRIR_PARENTESE _operacoes FECHAR_PARENTESE 
        +            {
        +              String RESULT =null;
        +		int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		
        +					RESULT = "Math.cos("+n+"*"+(Math.PI)/180+")";
        +					util.setOperadorTMP(true);
        +				
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes",26, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 72: // _operacoes ::= SENO ABRIR_PARENTESE _operacoes FECHAR_PARENTESE 
        +            {
        +              String RESULT =null;
        +		int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		
        +					RESULT = "Math.sin("+n+"*"+(Math.PI)/180+")";
        +					util.setOperadorTMP(true);
        +				
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes",26, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 71: // _operacoes ::= MODULO ABRIR_PARENTESE _operacoes FECHAR_PARENTESE 
        +            {
        +              String RESULT =null;
        +		int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		
        +					RESULT = "Math.abs("+n+")";
        +					util.setOperadorTMP(true);
        +				
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes",26, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 70: // _operacoes ::= POTENCIA ABRIR_PARENTESE _operacoes SEPARADOR _operacoes FECHAR_PARENTESE 
        +            {
        +              String RESULT =null;
        +		int n1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).left;
        +		int n1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).right;
        +		String n1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-3)).value;
        +		int n2left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int n2right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String n2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		
        +					RESULT = "Math.pow("+n1+","+n2+")";
        +					util.setOperadorTMP(true);
        +				
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes",26, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-5)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 69: // _operacoes ::= _operacoes OPERADOR_SOMA _operacoes 
        +            {
        +              String RESULT =null;
        +		int e1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left;
        +		int e1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right;
        +		String e1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value;
        +		int e2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int e2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String e2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 
        +					RESULT = e1+" + "+e2; 
        +					util.setOperadorSomaTMP(true);
        +				
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes",26, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 68: // _operacoes ::= _operacoes OPERADOR _operacoes 
        +            {
        +              String RESULT =null;
        +		int e1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left;
        +		int e1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right;
        +		String e1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value;
        +		int opleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int opright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String op = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		int e2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int e2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String e2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 
        +					RESULT = e1+" "+util.getOperador(op)+" "+e2; 
        +					util.setOperadorTMP(true);
        +				
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_operacoes",26, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 67: // _loop_virgula_id ::= ID ABRIR_COLCHETE _operacoes_indice_vetor FECHAR_COLCHETE 
        +            {
        +              String RESULT =null;
        +		int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).left;
        +		int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).right;
        +		String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-3)).value;
        +		int ileft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int iright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String i = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		
        +							String[] tmp = util.getVariavelVetor(n);
        +							if(tmp[0] != null){
        +								RESULT = n+"["+i+"]";
        +							}else{
        +								parser.syntax_error(nleft,nright,util.Erros("VARIAVEL_VETOR_ERRO1",n));	
        +							}
        +						
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_loop_virgula_id",31, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 66: // _loop_virgula_id ::= ID 
        +            {
        +              String RESULT =null;
        +		int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 
        +							if(util.checkVariavelExiste(n)) {
        +								RESULT = n;
        +							}else{
        +								parser.syntax_error(nleft,nright,util.Erros("VARIAVEL_ERRO1",n));
        +							}
        +						
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_loop_virgula_id",31, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 65: // _loop_virgula_id ::= _loop_virgula_id SEPARADOR _loop_virgula_id 
        +            {
        +              String RESULT =null;
        +		int e1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left;
        +		int e1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right;
        +		String e1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value;
        +		int e2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int e2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String e2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 RESULT = e1 + "," + e2; 
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_loop_virgula_id",31, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 64: // _loop_virgula ::= _operacoes 
        +            {
        +              String RESULT =null;
        +		int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 
        +						RESULT = "("+e+")"; 
        +						String tmp = util.getTipoOperacao(); 
        +						if(tmp == null){
        +							parser.syntax_error(eleft,eright,util.Erros("OPERACAO_ERRO1",null));
        +						}
        +					
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_loop_virgula",30, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 63: // _loop_virgula ::= _loop_virgula SEPARADOR _loop_virgula 
        +            {
        +              String RESULT =null;
        +		int e1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left;
        +		int e1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right;
        +		String e1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value;
        +		int e2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int e2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String e2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 RESULT = e1 + " + " + e2; 
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_loop_virgula",30, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 62: // _sub_condicional ::= _operacoes 
        +            {
        +              String RESULT =null;
        +		int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 
        +							RESULT = e;
        +							util.setTiposOperacaoeTMP(util.getTipoOperacao());
        +						
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_sub_condicional",29, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 61: // _sub_condicional ::= NAO ABRIR_PARENTESE _sub_condicional FECHAR_PARENTESE 
        +            {
        +              String RESULT =null;
        +		int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		 RESULT = "!("+e+")"; 
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_sub_condicional",29, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 60: // _sub_condicional ::= ABRIR_PARENTESE _sub_condicional FECHAR_PARENTESE 
        +            {
        +              String RESULT =null;
        +		int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		 RESULT = "("+e+")"; 
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_sub_condicional",29, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 59: // _sub_condicional ::= _sub_condicional CONDICIONAL_COMPARATIVA _sub_condicional 
        +            {
        +              String RESULT =null;
        +		int s1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left;
        +		int s1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right;
        +		String s1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value;
        +		int cleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int cright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String c = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		int s2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int s2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String s2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		
        +							
        +							util.setCondicionalComparativaTMP(true);
        +							
        +							RESULT = s1+" "+util.getTipoCondiconal(c)+" "+s2;
        +
        +							String tmp = util.setSubCondicional(RESULT);
        +							
        +							if("String".equals(tmp)){
        +								if("<>".equals(c)){
        +									RESULT = "!"+s1+".equals("+s2+")";
        +								}else{
        +									RESULT = s1+".equals("+s2+")";
        +								}
        +							}
        +							else if(tmp != null){
        +								switch(tmp){
        +									case "error1" : parser.syntax_error(s1left,s1right,util.Erros("CONDICIONAL_ERRO1",null)); break;
        +									default: parser.syntax_error(s1left,s1right,util.Erros("CONDICIONAL_ERRO2",tmp)); break;
        +								}
        +							}
        +
        +						
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_sub_condicional",29, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 58: // _sub_condicional ::= _sub_condicional CONDICIONAL_NUMERICA _sub_condicional 
        +            {
        +              String RESULT =null;
        +		int s1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left;
        +		int s1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right;
        +		String s1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value;
        +		int cleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int cright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String c = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		int s2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int s2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String s2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		
        +							RESULT = s1+" "+c+" "+s2;
        +							util.setCondicinalNumericaTMP(true);
        +
        +							String tmp = util.setSubCondicional(RESULT);
        +							if(tmp != null){
        +								switch(tmp){
        +									case "error1" : parser.syntax_error(s1left,s1right,util.Erros("CONDICIONAL_ERRO1",null)); break;
        +									default: parser.syntax_error(s1left,s1right,util.Erros("CONDICIONAL_ERRO2",tmp)); break;
        +								}
        +							}
        +
        +						
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_sub_condicional",29, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 57: // _condicional ::= _sub_condicional 
        +            {
        +              String RESULT =null;
        +		int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 
        +						RESULT = e; 
        +						String tmp = util.setCondicional(RESULT);
        +						if(tmp != null){
        +							switch(tmp){
        +								case "error1" : parser.syntax_error(eleft,eright,util.Erros("CONDICIONAL_ERRO1",null)); break;
        +								default: parser.syntax_error(eleft,eright,util.Erros("CONDICIONAL_ERRO2",tmp)); break;
        +							}
        +						}
        +
        +					
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_condicional",28, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 56: // _condicional ::= NAO ABRIR_PARENTESE _condicional FECHAR_PARENTESE 
        +            {
        +              String RESULT =null;
        +		int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		 RESULT = "!("+e+")"; 
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_condicional",28, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 55: // _condicional ::= ABRIR_PARENTESE _condicional FECHAR_PARENTESE 
        +            {
        +              String RESULT =null;
        +		int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		 RESULT = "("+e+")"; 
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_condicional",28, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 54: // _condicional ::= _condicional OU _condicional 
        +            {
        +              String RESULT =null;
        +		int c1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left;
        +		int c1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right;
        +		String c1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value;
        +		int c2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int c2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String c2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		
        +						RESULT = c1+" || "+c2;
        +						util.setCondicionalOuTMP(true);
        +					
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_condicional",28, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 53: // _condicional ::= _condicional E _condicional 
        +            {
        +              String RESULT =null;
        +		int c1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left;
        +		int c1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right;
        +		String c1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value;
        +		int c2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int c2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String c2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		
        +						RESULT = c1+" && "+c2;
        +						util.setCondicinalETMP(true);
        +					
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_condicional",28, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 52: // escolha_outrocaso ::= 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("escolha_outrocaso",21, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 51: // escolha_outrocaso ::= OUTROCASO programa 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("escolha_outrocaso",21, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 50: // escolha_casos ::= CASO _operacoes NT$5 programa 
        +            {
        +              Object RESULT =null;
        +              // propagate RESULT from NT$5
        +                RESULT = (Object) ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		int bleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left;
        +		int bright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right;
        +		String b = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("escolha_casos",20, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 49: // NT$5 ::= 
        +            {
        +              Object RESULT =null;
        +		int bleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int bright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String b = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        + 
        +						String tmp_tipo_operacao = util.getTipoOperacao(); 
        +						util.setCode("\t\tcase("+b+"):");
        +						util.setCodeExec("\t\tcase("+b+"):",bleft); 
        +					
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("NT$5",38, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 48: // escolha_loop ::= 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("escolha_loop",19, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 47: // escolha_loop ::= escolha_loop escolha_casos 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("escolha_loop",19, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 46: // escolha_funcao ::= ESCOLHA _operacoes NT$4 escolha_loop escolha_outrocaso FIMESCOLHA 
        +            {
        +              Object RESULT =null;
        +              // propagate RESULT from NT$4
        +                RESULT = (Object) ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-3)).value;
        +		int aleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-4)).left;
        +		int aright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-4)).right;
        +		String a = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-4)).value;
        +		int fleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int fright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		Object f = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		
        +						util.setCode("\t\t}");
        +						util.setCodeExec("\t\t}",fleft); 
        +					
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("escolha_funcao",18, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-5)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 45: // NT$4 ::= 
        +            {
        +              Object RESULT =null;
        +		int aleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int aright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String a = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        + 
        +						String tmp_tipo_operacao = util.getTipoOperacao(); 
        +						util.setCode("\t\tswitch("+a+"){");
        +						util.setCodeExec("\t\tswitch("+a+"){",aleft); 
        +					
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("NT$4",37, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 44: // leia_funcao ::= LEIA ABRIR_PARENTESE _loop_virgula_id FECHAR_PARENTESE 
        +            {
        +              Object RESULT =null;
        +		int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		
        +							util.setLeia(true);
        +
        +							for (String ids : e.split(",")) {
        +								String[] tmp;
        +
        +								if(e.indexOf("[") > 0){
        +									tmp = util.getVariavelVetor(ids.replaceAll("\\[.*\\]",""));
        +									String indice = ids.substring(ids.indexOf("[")+1,ids.indexOf("]"));
        +									ids = ids.substring(0,ids.indexOf("]"))+"-("+tmp[2]+")]";
        +									switch(tmp[1]){
        +										case "int" : util.setCode("\t\t"+ids+" = ConsoleIO.nextInt();");util.setCodeExec("\t\t"+ids+" = ConsoleIO.writeInt();",eleft);break;
        +										case "float" : util.setCode("\t\t"+ids+" = scanIn.nextFloat();");util.setCodeExec("\t\t"+ids+" = ConsoleIO.writeFloat();",eleft);break;
        +										case "String" : util.setCode("\t\t"+ids+" = scanIn.next();");util.setCodeExec("\t\t"+ids+" = ConsoleIO.writeString();",eleft);break;
        +										case "char" : util.setCode("\t\t"+ids+" = scanIn.nextChar();");util.setCodeExec("\t\t"+ids+" = ConsoleIO.writeChar();",eleft);break;
        +									}
        +									util.setCodeExec("\t\ttable_variaveis.update(\""+tmp[0]+"[\"+"+indice+"+\"]\","+ids+");"); 
        +								}else{
        +									tmp = util.getVariavel(ids);
        +									switch(tmp[1]){
        +										case "int" : util.setCode("\t\t"+ids+" = ConsoleIO.nextInt();");util.setCodeExec("\t\t"+ids+" = ConsoleIO.writeInt();",eleft);break;
        +										case "float" : util.setCode("\t\t"+ids+" = scanIn.nextFloat();");util.setCodeExec("\t\t"+ids+" = ConsoleIO.writeFloat();",eleft);break;
        +										case "String" : util.setCode("\t\t"+ids+" = scanIn.next();");util.setCodeExec("\t\t"+ids+" = ConsoleIO.writeString();",eleft);break;
        +										case "char" : util.setCode("\t\t"+ids+" = scanIn.nextChar();");util.setCodeExec("\t\t"+ids+" = ConsoleIO.writeChar();",eleft);break;
        +									}
        +									util.setCodeExec("\t\ttable_variaveis.update(\""+ids+"\","+ids+");");
        +								}
        +							}
        +						
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("leia_funcao",14, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 43: // escreva_funcao ::= ESCREVAL ABRIR_PARENTESE _loop_virgula FECHAR_PARENTESE 
        +            {
        +              Object RESULT =null;
        +		int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		 
        +							util.setCode("\t\tSystem.out.println("+e+");");
        +							util.setCodeExec("\t\tConsoleIO.println("+e+");",eleft); 
        +						
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("escreva_funcao",13, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 42: // escreva_funcao ::= ESCREVA ABRIR_PARENTESE _loop_virgula FECHAR_PARENTESE 
        +            {
        +              Object RESULT =null;
        +		int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		 
        +							util.setCode("\t\tSystem.out.print("+e+");");
        +							util.setCodeExec("\t\tConsoleIO.print("+e+");",eleft); 
        +						
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("escreva_funcao",13, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 41: // _para_complementar ::= 
        +            {
        +              String RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_para_complementar",32, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 40: // _para_complementar ::= PASSO _operacoes 
        +            {
        +              String RESULT =null;
        +		int n3left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int n3right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String n3 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		
        +						String tmp_tipo_operacao = util.getTipoOperacao();
        +						if(tmp_tipo_operacao != "int"){
        +							parser.syntax_error(n3left,n3right,util.Erros("TIPO_VARIAVEL_FOR",null));
        +						}else{
        +							RESULT = n3;
        +						}
        +					
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("_para_complementar",32, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 39: // para_funcao_1 ::= PARA ID DE _operacoes NT$1 ATE _operacoes NT$2 _para_complementar FACA NT$3 programa FIMPARA 
        +            {
        +              Object RESULT =null;
        +              // propagate RESULT from NT$3
        +                RESULT = (Object) ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value;
        +		int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-11)).left;
        +		int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-11)).right;
        +		String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-11)).value;
        +		int n1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-9)).left;
        +		int n1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-9)).right;
        +		String n1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-9)).value;
        +		int n2left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-6)).left;
        +		int n2right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-6)).right;
        +		String n2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-6)).value;
        +		int n3left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-4)).left;
        +		int n3right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-4)).right;
        +		String n3 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-4)).value;
        +		int pleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).left;
        +		int pright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).right;
        +		Object p = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-3)).value;
        +		int fleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int fright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		Object f = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 util.setCode("\t\t}");util.setCodeExec("\t\t}",fleft);  
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("para_funcao_1",17, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-12)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 38: // NT$3 ::= 
        +            {
        +              Object RESULT =(Object) ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value;
        +		int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-8)).left;
        +		int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-8)).right;
        +		String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-8)).value;
        +		int n1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-6)).left;
        +		int n1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-6)).right;
        +		String n1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-6)).value;
        +		int n2left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).left;
        +		int n2right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).right;
        +		String n2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-3)).value;
        +		int n3left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int n3right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String n3 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		int pleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int pright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		Object p = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +
        +					String tmp[] = util.getVariavel(n);
        +
        +					if(tmp[1] != null) {
        +						if("int".equals(tmp[1])){
        +							if(n3 != null){
        +								util.setCode("\t\tfor("+n+" = "+n1+";"+n+" <= "+n2+";"+n+"+="+n3+"){");
        +								util.setCodeExec("\t\tfor("+n+" = "+n1+";"+n+" <= "+n2+";"+n+"+="+n3+"){",pleft);
        +							}else{
        +								util.setCode("\t\tfor("+n+" = "+n1+";"+n+" <= "+n2+";"+n+"++){");
        +								util.setCodeExec("\t\tfor("+n+" = "+n1+";"+n+" <= "+n2+";"+n+"++){",pleft);
        +							}
        +							util.setCodeExec("\t\ttable_variaveis.update(\""+n+"\","+n+");");
        +						}else{
        +							parser.syntax_error(nleft,nright,util.Erros("TIPO_VARIAVEL_FOR",null));
        +						}
        +					}else{
        +						parser.syntax_error(nleft,nright,util.Erros("VARIAVEL_ERRO1",n));
        +					}
        +				
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("NT$3",36, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 37: // NT$2 ::= 
        +            {
        +              Object RESULT =(Object) ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value;
        +		int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-5)).left;
        +		int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-5)).right;
        +		String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-5)).value;
        +		int n1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).left;
        +		int n1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).right;
        +		String n1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-3)).value;
        +		int n2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int n2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String n2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +
        +						String tmp_tipo_operacao = util.getTipoOperacao();
        +						if(tmp_tipo_operacao != "int"){
        +							parser.syntax_error(n2left,n2right,util.Erros("TIPO_VARIAVEL_FOR",null));
        +						}
        +				
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("NT$2",35, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 36: // NT$1 ::= 
        +            {
        +              Object RESULT =null;
        +		int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left;
        +		int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right;
        +		String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value;
        +		int n1left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int n1right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String n1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +
        +						String tmp_tipo_operacao = util.getTipoOperacao();
        +						if(tmp_tipo_operacao != "int"){
        +							parser.syntax_error(n1left,n1right,util.Erros("TIPO_VARIAVEL_FOR",null));
        +						}
        +				
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("NT$1",34, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 35: // para_funcao ::= para_funcao_1 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("para_funcao",16, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 34: // enquanto_funcao ::= ENQUANTO _condicional FACA NT$0 programa FIMENQUANTO 
        +            {
        +              Object RESULT =null;
        +              // propagate RESULT from NT$0
        +                RESULT = (Object) ((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value;
        +		int cleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-4)).left;
        +		int cright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-4)).right;
        +		String c = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-4)).value;
        +		int pleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int pright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		Object p = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 util.setCode("\t\t}");util.setCodeExec("\t\t}",pleft);  
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("enquanto_funcao",15, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-5)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 33: // NT$0 ::= 
        +            {
        +              Object RESULT =null;
        +		int cleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int cright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String c = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +
        +							util.setCode("\t\twhile("+c+"){");
        +							util.setCodeExec("\t\twhile("+c+"){",cleft);
        +						
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("NT$0",33, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 32: // condicional_2 ::= SENAO 
        +            {
        +              Object RESULT =null;
        +		int pleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int pright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		Object p = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		
        +						util.setCode("\t\t}else{");
        +						util.setCodeExec("\t\t}else{",pleft);
        +					
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("condicional_2",12, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 31: // condicional_1 ::= SE _condicional ENTAO 
        +            {
        +              Object RESULT =null;
        +		int cleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int cright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String c = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		
        +						util.setCode("\t\tif("+c+"){");
        +						util.setCodeExec("\t\tif("+c+"){",cleft);
        +					
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("condicional_1",11, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 30: // condiciona_estrutura ::= condicional_1 programa condicional_2 programa FIMSE 
        +            {
        +              Object RESULT =null;
        +		int p3left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int p3right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		Object p3 = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		
        +								util.setCode("\t\t}");
        +								util.setCodeExec("\t\t}",p3left);
        +							
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("condiciona_estrutura",10, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-4)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 29: // condiciona_estrutura ::= condicional_1 programa FIMSE 
        +            {
        +              Object RESULT =null;
        +		int pleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int pright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		Object p = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		
        +								util.setCode("\t\t}");
        +								util.setCodeExec("\t\t}",pleft);
        +							
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("condiciona_estrutura",10, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 28: // instanciacao_variaveis ::= ID ABRIR_COLCHETE _operacoes_indice_vetor FECHAR_COLCHETE ATRIBUIR _operacoes 
        +            {
        +              Object RESULT =null;
        +		int xleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-5)).left;
        +		int xright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-5)).right;
        +		String x = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-5)).value;
        +		int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).left;
        +		int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).right;
        +		String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-3)).value;
        +		int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		
        +							  		String tmp = util.setVariavelVetor(x,e,n);
        +							  		switch(tmp){
        +							  			case "error1" : parser.syntax_error(xleft,xright,util.Erros("VARIAVEL_VETOR_ERRO1",x)); break;
        +							  			case "error2" : parser.syntax_error(xleft,xright,util.Erros("VARIAVEL_VETOR_ERRO2",x)); break;
        +							  			case "error3" : parser.syntax_error(xleft,xright,util.Erros("VARIAVEL_VETOR_ERRO3",x)); break;
        +							  			default: 
        +							  				util.setCode(tmp);
        +							  				util.setCodeExec(tmp,xleft);
        +							  			break;
        +							  		}
        +							  
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao_variaveis",9, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-5)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 27: // instanciacao_variaveis ::= ID ATRIBUIR _operacoes 
        +            {
        +              Object RESULT =null;
        +		int xleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left;
        +		int xright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right;
        +		String x = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value;
        +		int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		
        +							  		String tmp = util.setVariavelOperador(x,e);
        +							  		switch(tmp){
        +							  			case "error1" : parser.syntax_error(xleft,xright,util.Erros("VARIAVEL_ERRO1",x)); break;
        +							  			case "error2" : parser.syntax_error(xleft,xright,util.Erros("VARIAVEL_ERRO2",x)); break;
        +							  			default: 
        +							  				util.setCode(tmp);
        +							  				util.setCodeExec(tmp + "\ttable_variaveis.update(\""+x+"\","+x+");",xleft);
        +							  			break;
        +							  		}
        +							  
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("instanciacao_variaveis",9, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 26: // funcoes_unitarias ::= ESPERAR ABRIR_PARENTESE _operacoes FECHAR_PARENTESE 
        +            {
        +              Object RESULT =null;
        +		int fleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).left;
        +		int fright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).right;
        +		Object f = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-3)).value;
        +		int nleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int nright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		String n = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		
        +							String tmp_tipo_operacao = util.getTipoOperacao();
        +							if(tmp_tipo_operacao != "int"){
        +								parser.syntax_error(nleft,nright,util.Erros("SOMENTE_INT",null));
        +							}else{
        +								util.setCode("\t\tThread.sleep("+n+");");
        +								util.setCodeExec("\t\tThread.sleep("+n+");",fleft);
        +							}
        +						
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("funcoes_unitarias",22, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 25: // funcoes_unitarias ::= INTERROMPA 
        +            {
        +              Object RESULT =null;
        +		int ileft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int iright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		Object i = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		
        +							util.setCode("\t\tbreak;");
        +							util.setCodeExec("\t\tbreak;",ileft);
        +						
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("funcoes_unitarias",22, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 24: // corpo_programa ::= escolha_funcao 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("corpo_programa",8, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 23: // corpo_programa ::= para_funcao 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("corpo_programa",8, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 22: // corpo_programa ::= enquanto_funcao 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("corpo_programa",8, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 21: // corpo_programa ::= leia_funcao 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("corpo_programa",8, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 20: // corpo_programa ::= escreva_funcao 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("corpo_programa",8, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 19: // corpo_programa ::= condiciona_estrutura 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("corpo_programa",8, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 18: // corpo_programa ::= instanciacao_variaveis 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("corpo_programa",8, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 17: // corpo_programa ::= funcoes_unitarias 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("corpo_programa",8, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 16: // programa ::= 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("programa",7, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 15: // programa ::= programa corpo_programa 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("programa",7, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 14: // var_listagem ::= ID 
        +            {
        +              String RESULT =null;
        +		int valueleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int valueright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String value = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 RESULT = value; 
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("var_listagem",6, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 13: // var_listagem ::= var_listagem SEPARADOR var_listagem 
        +            {
        +              String RESULT =null;
        +		int e1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left;
        +		int e1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right;
        +		String e1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value;
        +		int e2left = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int e2right = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String e2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 RESULT = e1+","+e2; 
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("var_listagem",6, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 12: // var_instanciacao ::= var_listagem ADD_ATTR_VAR TIPO_VARIAVEL_VETOR ABRIR_COLCHETE NUMERO_INT DOIS_PONTOS NUMERO_INT FECHAR_COLCHETE DE TIPO_VARIAVEL 
        +            {
        +              Object RESULT =null;
        +		int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-9)).left;
        +		int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-9)).right;
        +		String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-9)).value;
        +		int n1left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-5)).left;
        +		int n1right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-5)).right;
        +		String n1 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-5)).value;
        +		int n2left = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).left;
        +		int n2right = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-3)).right;
        +		String n2 = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-3)).value;
        +		int xleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int xright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String x = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		
        +							util.addVariavelVetor(e,x,n1,n2); 
        +						
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("var_instanciacao",5, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-9)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 11: // var_instanciacao ::= var_listagem ADD_ATTR_VAR TIPO_VARIAVEL 
        +            {
        +              Object RESULT =null;
        +		int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).left;
        +		int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)).right;
        +		String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-2)).value;
        +		int xleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int xright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String x = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		
        +							util.addVariavel(e,x);
        +							util.setCodeVariables("\t" + util.getTipoVariavel(x) + " " +e+ ";");
        +							util.setCodeVariablesExec("\t" + util.getTipoVariavel(x) + " " +e+ ";");
        +						
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("var_instanciacao",5, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-2)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 10: // variaveis ::= var_instanciacao 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("variaveis",4, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 9: // variaveis ::= variaveis var_instanciacao 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("variaveis",4, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 8: // var_estrutura ::= 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("var_estrutura",3, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 7: // var_estrutura ::= VAR variaveis 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("var_estrutura",3, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 6: // var_estrutura ::= VAR 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("var_estrutura",3, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 5: // algoritmo_instanciacao ::= ALGORITMO STRING 
        +            {
        +              Object RESULT =null;
        +		int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 
        +								util.setCode("public class "+e.substring(1, e.length()-1)+" {"); 
        +								util.setCodeName(e.substring(1, e.length()-1)); 
        +							
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("algoritmo_instanciacao",2, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 4: // algoritmo_instanciacao ::= ALGORITMO ID 
        +            {
        +              Object RESULT =null;
        +		int eleft = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).left;
        +		int eright = ((java_cup.runtime.Symbol)CUP$parser$stack.peek()).right;
        +		String e = (String)((java_cup.runtime.Symbol) CUP$parser$stack.peek()).value;
        +		 
        +								util.setCode("public class "+e+" {"); 
        +								util.setCodeName(e); 
        +							
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("algoritmo_instanciacao",2, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 3: // algoritmo_nome ::= algoritmo_instanciacao 
        +            {
        +              Object RESULT =null;
        +		 util.setInitClass(); 
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("algoritmo_nome",1, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 2: // algoritmo ::= 
        +            {
        +              Object RESULT =null;
        +
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("algoritmo",0, ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 1: // algoritmo ::= algoritmo_nome var_estrutura INICIO programa FIMALGORITMO 
        +            {
        +              Object RESULT =null;
        +		 util.setEndClass(); util.codeComplete(); 
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("algoritmo",0, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-4)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          return CUP$parser$result;
        +
        +          /*. . . . . . . . . . . . . . . . . . . .*/
        +          case 0: // $START ::= algoritmo EOF 
        +            {
        +              Object RESULT =null;
        +		int start_valleft = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).left;
        +		int start_valright = ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)).right;
        +		Object start_val = (Object)((java_cup.runtime.Symbol) CUP$parser$stack.elementAt(CUP$parser$top-1)).value;
        +		RESULT = start_val;
        +              CUP$parser$result = parser.getSymbolFactory().newSymbol("$START",0, ((java_cup.runtime.Symbol)CUP$parser$stack.elementAt(CUP$parser$top-1)), ((java_cup.runtime.Symbol)CUP$parser$stack.peek()), RESULT);
        +            }
        +          /* ACCEPT */
        +          CUP$parser$parser.done_parsing();
        +          return CUP$parser$result;
        +
        +          /* . . . . . .*/
        +          default:
        +            throw new Exception(
        +               "Invalid action number found in internal parse table");
        +
        +        }
        +    }
        +}
        +
        diff --git a/src/com/compilador/portugol/sym.java b/src/com/compilador/portugol/sym.java
        new file mode 100644
        index 0000000..a6a7119
        --- /dev/null
        +++ b/src/com/compilador/portugol/sym.java
        @@ -0,0 +1,73 @@
        +
        +//----------------------------------------------------
        +// The following code was generated by CUP v0.11a beta 20060608
        +// Fri Sep 26 15:47:26 BRT 2014
        +//----------------------------------------------------
        +
        +package com.compilador.portugol;
        +
        +/** CUP generated class containing symbol constants. */
        +public class sym {
        +  /* terminals */
        +  public static final int FIMALGORITMO = 52;
        +  public static final int COSSENO = 34;
        +  public static final int TIPO_VARIAVEL_VETOR = 5;
        +  public static final int FUNCAO = 38;
        +  public static final int CASO = 26;
        +  public static final int DE = 43;
        +  public static final int FIMSE = 19;
        +  public static final int FIMENQUANTO = 23;
        +  public static final int CHAR = 59;
        +  public static final int ESCREVAL = 50;
        +  public static final int ESCOLHA = 25;
        +  public static final int PI = 37;
        +  public static final int CONDICIONAL_NUMERICA = 41;
        +  public static final int SE = 16;
        +  public static final int ATRIBUIR = 10;
        +  public static final int CONDICIONAL_COMPARATIVA = 42;
        +  public static final int SEPARADOR = 54;
        +  public static final int DOIS_PONTOS = 15;
        +  public static final int PASSO = 46;
        +  public static final int E = 44;
        +  public static final int OUTROCASO = 27;
        +  public static final int OPERADOR_SOMA = 8;
        +  public static final int OU = 47;
        +  public static final int ATE = 45;
        +  public static final int RAIZ = 36;
        +  public static final int ENTAO = 17;
        +  public static final int VALOR_LOGICO = 9;
        +  public static final int ALGORITMO = 2;
        +  public static final int ID = 55;
        +  public static final int ADD_ATTR_VAR = 53;
        +  public static final int EOF = 0;
        +  public static final int NUMERO_INT = 57;
        +  public static final int error = 1;
        +  public static final int SENAO = 18;
        +  public static final int ENQUANTO = 20;
        +  public static final int FECHAR_COLCHETE = 14;
        +  public static final int ABRIR_PARENTESE = 11;
        +  public static final int MODULO = 32;
        +  public static final int ESCREVA = 49;
        +  public static final int VOID = 40;
        +  public static final int FIMPARA = 24;
        +  public static final int FACA = 22;
        +  public static final int TIPO_VARIAVEL = 4;
        +  public static final int POTENCIA = 31;
        +  public static final int FECHAR_PARENTESE = 12;
        +  public static final int LEIA = 51;
        +  public static final int TANGENTE = 35;
        +  public static final int OPERADOR = 7;
        +  public static final int INTERROMPA = 29;
        +  public static final int FIMESCOLHA = 28;
        +  public static final int SENO = 33;
        +  public static final int FIMFUNCAO = 39;
        +  public static final int STRING = 56;
        +  public static final int ESPERAR = 30;
        +  public static final int PARA = 21;
        +  public static final int INICIO = 6;
        +  public static final int NAO = 48;
        +  public static final int NUMERO_FLOAT = 58;
        +  public static final int VAR = 3;
        +  public static final int ABRIR_COLCHETE = 13;
        +}
        +
        diff --git a/src/com/editor/flex/Portugol.flex b/src/com/editor/flex/Portugol.flex
        new file mode 100644
        index 0000000..ace08c2
        --- /dev/null
        +++ b/src/com/editor/flex/Portugol.flex
        @@ -0,0 +1,164 @@
        +package com.editor.flex;
        +
        +
        +import jsyntaxpane.Token;
        +import jsyntaxpane.TokenType;
        +import jsyntaxpane.lexers.DefaultJFlexLexer;
        +
        +%%
        +
        +%public
        +%class PortugolFlex
        +%extends DefaultJFlexLexer
        +%final
        +%unicode
        +%char
        +%type Token
        +
        +%caseless
        +%ignorecase
        +
        +%{
        +
        +    public PortugolFlex() {
        +        super();
        +    }
        +
        +    private static final byte PARAN     = 1;
        +    private static final byte BRACKET   = 2;
        +    private static final byte CURLY     = 3;
        +
        +    @Override
        +    public int yychar() {
        +        return yychar;
        +    }
        +%}
        +
        +
        +
        +/* main character classes */
        +LineTerminator = \r|\n|\r\n
        +InputCharacter = [^\r\n]
        +
        +WhiteSpace = {LineTerminator} | [ \t\f]+
        +
        +/* comments */
        +Comment = {TraditionalComment} | {EndOfLineComment} 
        +
        +TraditionalComment = "/*" [^*] ~"*/" | "/*" "*"+ "/"
        +EndOfLineComment = "//" {InputCharacter}* {LineTerminator}?
        +
        +/* identifiers */
        +
        +ConstantIdentifier = {SimpleConstantIdentifier}
        +SimpleConstantIdentifier = [#A-Z0-9_]+
        +
        +Identifier = [:jletter:][:jletterdigit:]*
        +
        +TypeIdentifier = {SimpleTypeIdentifier}
        +SimpleTypeIdentifier = [A-Z][:jletterdigit:]*
        +
        +/* int literals */
        +
        +DecLiteral = 0 | [1-9][0-9]* {IntegerSuffix}
        +
        +HexLiteral    = 0 [xX] 0* {HexDigit}* {IntegerSuffix}
        +HexDigit      = [0-9a-fA-F]
        +
        +OctLiteral    = 0+ {OctDigit}* {IntegerSuffix}
        +OctDigit          = [0-7]
        +
        +IntegerSuffix = [uU]? [lL]? [uU]?
        +
        +/* float literals */
        +
        +FloatLiteral  = ({FLit1}|{FLit2}|{FLit3}|{FLit4}) ([fF]|[dD])?
        +
        +FLit1 = [0-9]+ \. [0-9]* {Exponent}?
        +FLit2 = \. [0-9]+ {Exponent}?
        +FLit3 = [0-9]+ {Exponent}
        +FLit4 = [0-9]+ {Exponent}?
        +
        +Exponent = [eE] [+\-]? [0-9]+
        +
        +%%
        +
        + {
        +
        +  /* keywords */
        +  "algoritmo" | "var"  { return token(TokenType.KEYWORD); }
        +
        +  "escreva" |"escreval" | "leia" | "entao" | "faca" | "e" | "ou" { return token(TokenType.KEYWORD2); }
        +
        +  /* Type */
        +  "inteiro" | "caracter" | "real" { return token(TokenType.TYPE); }
        +
        +
        +  /* literals */
        +  (\" ( [^\"\n\\] | \\[^\n] )* (\n | \\\n | \")) | (\' ( [^\'\n\\] | \\[^\n] )* (\n | \\\n | \'))  { return token(TokenType.STRING); }
        + 
        +
        +
        +  {DecLiteral} | {OctLiteral} | {HexLiteral} | {FloatLiteral} { return token(TokenType.NUMBER); }
        +
        +     
        +
        +
        +
        +  
        +  /* separators */
        +  "("                            { return token(TokenType.OPERATOR,  PARAN); }
        +  ")"                            { return token(TokenType.OPERATOR, -PARAN); }
        +
        +  "{"                            { return token(TokenType.OPERATOR,  CURLY); }
        +  "}"                            { return token(TokenType.OPERATOR, -CURLY); }
        +
        +  "inicio"						 { return token(TokenType.KEYWORD,  CURLY); }
        +  "fimalgoritmo"				 { return token(TokenType.KEYWORD,  -CURLY); }
        +
        +  "se" | "enquanto" | "senao"	 { return token(TokenType.KEYWORD2,  CURLY); }
        +  "fimse" | "fimenquanto"		 { return token(TokenType.KEYWORD2,  -CURLY); }
        +
        +
        +
        +
        +  "["                            { return token(TokenType.OPERATOR,  BRACKET); }
        +  "]"                            { return token(TokenType.OPERATOR, -BRACKET); }
        +
        +
        +
        +  /* operators */
        +  "mod" |
        +  "div" |
        +  "=" |
        +  "," |
        +  ">" |
        +  "<" |
        +  ":" |
        +  "+" |
        +  "-" |
        +  "*" |
        +  "/" |
        +  "^" |
        +  "-" { return token(TokenType.OPERATOR); }
        +
        +
        +
        +  {ConstantIdentifier} |{TypeIdentifier} |  {Identifier}	{ return token(TokenType.IDENTIFIER); }
        +
        +
        +{WhiteSpace}						{/* IGNORAR */}
        +
        +\n 									{/* IGNORAR */}
        +
        +
        +
        +  {Comment}   	{ return token(TokenType.COMMENT); }
        +
        +}
        +
        +
        +
        +/* error fallback */
        +.|\n                             {  }
        +<>                          { return null; }
        \ No newline at end of file
        diff --git a/src/com/editor/flex/PortugolFlex.java b/src/com/editor/flex/PortugolFlex.java
        new file mode 100644
        index 0000000..d448355
        --- /dev/null
        +++ b/src/com/editor/flex/PortugolFlex.java
        @@ -0,0 +1,1021 @@
        +/* The following code was generated by JFlex 1.5.1 */
        +
        +package com.editor.flex;
        +
        +
        +import de.sciss.syntaxpane.Token;
        +import de.sciss.syntaxpane.TokenType;
        +import de.sciss.syntaxpane.lexers.DefaultJFlexLexer;
        +
        +
        +
        +/**
        + * This class is a scanner generated by 
        + * JFlex 1.5.1
        + * from the specification file C:/Users/SIMONETO-2/Documents/NetBeansProjects/portugol-projeto/src/com/editor/flex/Portugol_v2.flex
        + */
        +public final class PortugolFlex extends DefaultJFlexLexer {
        +
        +  /** This character denotes the end of file */
        +  public static final int YYEOF = -1;
        +
        +  /** initial size of the lookahead buffer */
        +  private static final int ZZ_BUFFERSIZE = 16384;
        +
        +  /** lexical states */
        +  public static final int YYINITIAL = 0;
        +  public static final int STRING = 2;
        +  public static final int ML_STRING = 4;
        +
        +  /**
        +   * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l
        +   * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l
        +   *                  at the beginning of a line
        +   * l is of the form l = 2*k, k a non negative integer
        +   */
        +  private static final int ZZ_LEXSTATE[] = { 
        +     0,  0,  1,  1,  1, 1
        +  };
        +
        +  /** 
        +   * Translates characters to character classes
        +   */
        +  private static final String ZZ_CMAP_PACKED = 
        +    "\11\0\1\3\1\2\1\70\1\71\1\1\22\0\1\3\1\0\1\64"+
        +    "\4\0\1\67\1\47\1\50\1\5\1\53\1\62\1\22\1\20\1\4"+
        +    "\1\10\1\16\2\15\4\15\2\11\1\63\1\0\1\57\1\61\1\60"+
        +    "\1\66\1\0\4\14\1\21\1\17\2\6\1\56\1\65\1\6\1\12"+
        +    "\3\6\1\55\7\6\1\13\2\6\1\51\1\23\1\52\1\0\1\7"+
        +    "\1\0\1\24\1\14\1\36\1\42\1\40\1\37\1\26\1\46\1\31"+
        +    "\1\65\1\6\1\25\1\33\1\35\1\27\1\43\1\45\1\30\1\41"+
        +    "\1\32\1\44\1\34\1\6\1\13\1\6\1\54\12\0\1\70\u1fa2\0"+
        +    "\1\70\1\70\udfd6\0";
        +
        +  /** 
        +   * Translates characters to character classes
        +   */
        +  private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);
        +
        +  /** 
        +   * Translates DFA states to action switch labels.
        +   */
        +  private static final int [] ZZ_ACTION = zzUnpackAction();
        +
        +  private static final String ZZ_ACTION_PACKED_0 =
        +    "\2\0\1\1\3\2\2\3\1\4\2\5\1\1\13\4"+
        +    "\1\6\3\4\1\7\1\10\1\11\1\12\1\4\2\3"+
        +    "\1\13\2\1\1\14\1\0\1\15\3\5\1\0\4\5"+
        +    "\1\0\4\4\1\6\20\4\1\16\1\4\1\6\2\4"+
        +    "\1\3\1\0\1\17\1\0\1\17\2\0\2\14\2\0"+
        +    "\4\5\1\0\10\4\1\3\1\20\14\4\1\3\2\4"+
        +    "\1\21\2\0\2\5\3\4\1\22\21\4\1\16\2\5"+
        +    "\10\4\1\5\3\4\1\23\5\4\2\5\2\4\1\24"+
        +    "\11\4\2\5\10\4\1\6\2\5\6\4\2\5\2\4"+
        +    "\2\5\2\4\1\0\1\5\1\4\1\0\1\5\1\25"+
        +    "\1\0\1\5\1\0\1\5\1\0\1\5\1\0\1\5"+
        +    "\1\0\1\5\1\0\5\5";
        +
        +  private static int [] zzUnpackAction() {
        +    int [] result = new int[226];
        +    int offset = 0;
        +    offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result);
        +    return result;
        +  }
        +
        +  private static int zzUnpackAction(String packed, int offset, int [] result) {
        +    int i = 0;       /* index in packed string  */
        +    int j = offset;  /* index in unpacked array */
        +    int l = packed.length();
        +    while (i < l) {
        +      int count = packed.charAt(i++);
        +      int value = packed.charAt(i++);
        +      do result[j++] = value; while (--count > 0);
        +    }
        +    return j;
        +  }
        +
        +
        +  /** 
        +   * Translates a state to a row index in the transition table
        +   */
        +  private static final int [] ZZ_ROWMAP = zzUnpackRowMap();
        +
        +  private static final String ZZ_ROWMAP_PACKED_0 =
        +    "\0\0\0\72\0\164\0\256\0\164\0\350\0\u0122\0\164"+
        +    "\0\u015c\0\u0196\0\u01d0\0\u020a\0\u0244\0\u027e\0\u02b8\0\u02f2"+
        +    "\0\u032c\0\u0366\0\u03a0\0\u03da\0\u0414\0\u044e\0\u0488\0\u04c2"+
        +    "\0\u04fc\0\u0536\0\u0570\0\164\0\164\0\164\0\164\0\u05aa"+
        +    "\0\u05e4\0\u061e\0\u0658\0\u0692\0\u06cc\0\u0706\0\u0740\0\164"+
        +    "\0\u077a\0\u07b4\0\164\0\u07ee\0\u0828\0\u0862\0\u089c\0\u08d6"+
        +    "\0\u0910\0\u094a\0\u0984\0\u09be\0\u09f8\0\u0a32\0\u0a6c\0\u0aa6"+
        +    "\0\u0ae0\0\u0b1a\0\u0b54\0\u0b8e\0\u0bc8\0\u0c02\0\u0c3c\0\u0c76"+
        +    "\0\u0cb0\0\u0cea\0\u0d24\0\u0d5e\0\u0d98\0\u0dd2\0\u0e0c\0\u0e46"+
        +    "\0\u015c\0\u0e80\0\u0eba\0\u015c\0\u06cc\0\164\0\u0ef4\0\u0f2e"+
        +    "\0\u0f68\0\u0fa2\0\u0fdc\0\164\0\u1016\0\u1050\0\u108a\0\u10c4"+
        +    "\0\u10fe\0\u1138\0\u1172\0\u11ac\0\u11e6\0\u1220\0\u125a\0\u1294"+
        +    "\0\u12ce\0\u1308\0\u1342\0\u137c\0\u015c\0\u13b6\0\u13f0\0\u142a"+
        +    "\0\u1464\0\u149e\0\u14d8\0\u1512\0\u154c\0\u1586\0\u15c0\0\u15fa"+
        +    "\0\u1634\0\u154c\0\u166e\0\u16a8\0\164\0\u16e2\0\u171c\0\u1756"+
        +    "\0\u1790\0\u17ca\0\u1804\0\u183e\0\u015c\0\u1878\0\u18b2\0\u18ec"+
        +    "\0\u1926\0\u1960\0\u199a\0\u19d4\0\u1a0e\0\u1a48\0\u1a82\0\u1abc"+
        +    "\0\u1af6\0\u1b30\0\u1b6a\0\u1ba4\0\u1bde\0\u1c18\0\u015c\0\u1c52"+
        +    "\0\u1c8c\0\u1cc6\0\u1d00\0\u1d3a\0\u1d74\0\u1dae\0\u1de8\0\u1e22"+
        +    "\0\u1e5c\0\u015c\0\u1e96\0\u1ed0\0\u1f0a\0\u015c\0\u1f44\0\u1f7e"+
        +    "\0\u1fb8\0\u1ff2\0\u202c\0\u2066\0\u20a0\0\u20da\0\u2114\0\u015c"+
        +    "\0\u214e\0\u2188\0\u21c2\0\u21fc\0\u2236\0\u2270\0\u22aa\0\u22e4"+
        +    "\0\u231e\0\u2358\0\u2392\0\u23cc\0\u2406\0\u2440\0\u247a\0\u24b4"+
        +    "\0\u24ee\0\u2528\0\u2562\0\u259c\0\u25d6\0\u2610\0\u264a\0\u2684"+
        +    "\0\u26be\0\u26f8\0\u2732\0\u276c\0\u27a6\0\u27e0\0\u281a\0\u2854"+
        +    "\0\u288e\0\u28c8\0\u2902\0\u293c\0\u2976\0\u29b0\0\u29ea\0\u2a24"+
        +    "\0\u2a5e\0\u015c\0\u2a98\0\u2ad2\0\u2b0c\0\u2b46\0\u2b80\0\u2bba"+
        +    "\0\u2bf4\0\u2c2e\0\u2c68\0\u2ca2\0\u2cdc\0\u2d16\0\u2d50\0\u2d8a"+
        +    "\0\u2dc4\0\u2dfe";
        +
        +  private static int [] zzUnpackRowMap() {
        +    int [] result = new int[226];
        +    int offset = 0;
        +    offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result);
        +    return result;
        +  }
        +
        +  private static int zzUnpackRowMap(String packed, int offset, int [] result) {
        +    int i = 0;  /* index in packed string  */
        +    int j = offset;  /* index in unpacked array */
        +    int l = packed.length();
        +    while (i < l) {
        +      int high = packed.charAt(i++) << 16;
        +      result[j++] = high | packed.charAt(i++);
        +    }
        +    return j;
        +  }
        +
        +  /** 
        +   * The transition table of the DFA
        +   */
        +  private static final int [] ZZ_TRANS = zzUnpackTrans();
        +
        +  private static final String ZZ_TRANS_PACKED_0 =
        +    "\1\3\1\4\1\5\1\6\1\7\1\10\1\11\1\3"+
        +    "\1\12\1\13\3\11\2\13\1\11\1\14\1\11\1\10"+
        +    "\1\3\1\15\1\16\1\11\1\17\1\20\1\21\1\22"+
        +    "\1\23\1\24\1\25\1\26\1\27\1\30\1\31\1\32"+
        +    "\1\33\3\11\1\34\1\35\1\36\1\37\1\10\1\11"+
        +    "\1\40\1\11\1\41\2\42\1\10\1\42\1\43\1\11"+
        +    "\1\3\1\44\1\0\1\6\1\3\1\0\1\5\61\3"+
        +    "\1\45\2\3\1\44\76\0\1\5\72\0\1\6\65\0"+
        +    "\1\6\4\0\1\46\1\47\72\0\12\11\1\0\1\11"+
        +    "\2\0\23\11\5\0\3\11\6\0\1\11\1\50\13\0"+
        +    "\1\51\1\52\1\53\1\54\1\0\1\55\1\56\1\57"+
        +    "\1\60\1\61\3\0\1\53\11\0\1\57\1\61\41\0"+
        +    "\2\13\1\53\2\0\2\13\1\57\1\60\1\61\3\0"+
        +    "\1\53\11\0\1\57\1\61\41\0\2\60\3\0\2\60"+
        +    "\61\0\12\11\1\0\1\11\2\0\1\11\1\62\4\11"+
        +    "\1\63\14\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\3\11\1\64\10\11\1\65"+
        +    "\6\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\20\11\1\66\2\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\1\67\13\11\1\70\6\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\11\11\1\71"+
        +    "\11\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\1\72\22\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\3\11"+
        +    "\1\73\17\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\1\74\13\11\1\75\6\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\1\76\22\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\1\77\2\11"+
        +    "\1\100\17\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\1\101\4\11\1\102\12\11"+
        +    "\1\103\2\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\11\11\1\104\3\11\1\105"+
        +    "\5\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\6\11\1\106\5\11\1\107\6\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\5\11\1\110\6\11\1\111\6\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\1\112\2\11\1\113\17\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\23\11"+
        +    "\5\0\2\11\1\114\6\0\1\11\1\50\25\0\1\10"+
        +    "\35\0\2\10\71\0\1\10\10\0\2\115\1\116\20\115"+
        +    "\1\117\40\115\1\120\5\115\2\121\1\116\20\121\1\122"+
        +    "\43\121\1\116\2\121\2\115\1\116\20\115\1\117\40\115"+
        +    "\1\116\5\115\1\46\1\123\1\124\67\46\5\125\1\126"+
        +    "\64\125\10\0\1\51\1\52\1\53\2\0\1\55\1\56"+
        +    "\1\57\1\60\1\61\3\0\1\53\11\0\1\57\1\61"+
        +    "\41\0\2\52\3\0\2\52\1\57\1\60\1\61\15\0"+
        +    "\1\57\1\61\41\0\1\127\1\130\2\0\4\130\1\0"+
        +    "\1\130\2\0\1\130\11\0\3\130\1\0\1\130\37\0"+
        +    "\1\131\1\52\1\53\2\0\2\131\1\57\1\60\1\61"+
        +    "\3\0\1\53\11\0\1\57\1\61\41\0\1\55\1\52"+
        +    "\1\53\2\0\2\55\1\57\1\60\1\61\3\0\1\53"+
        +    "\11\0\1\57\1\61\116\0\1\53\14\0\2\60\3\0"+
        +    "\2\60\1\57\1\0\1\61\15\0\1\57\1\61\41\0"+
        +    "\2\132\3\0\2\132\3\0\1\133\30\0\1\133\24\0"+
        +    "\12\11\1\0\1\11\2\0\2\11\1\134\20\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\14\11\1\111\6\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\2\11\1\135"+
        +    "\20\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\5\11\1\136\15\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\6\11\1\137\14\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\5\11\1\140\15\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\1\141\22\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\5\11\1\142"+
        +    "\1\143\14\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\11\11\1\114\11\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\16\11\1\144\4\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\4\11\1\145"+
        +    "\16\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\4\11\1\146\1\11\1\147\14\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\3\11\1\114\17\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\4\11"+
        +    "\1\150\10\11\1\151\5\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\15\11\1\114"+
        +    "\5\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\1\11\1\152\10\11\1\136\10\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\7\11\1\153\13\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\11\11"+
        +    "\1\154\11\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\6\11\1\155\12\11\1\156"+
        +    "\1\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\12\11\1\157\4\11\1\160\3\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\4\11\1\161\16\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\11\11"+
        +    "\1\162\11\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\10\11\1\114\12\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\4\11\1\163\10\11\1\164\5\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\6\11\1\114\14\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\3\0\2\115\1\116\67\115\64\0\1\165\7\0\1\116"+
        +    "\20\0\1\166\43\0\1\116\2\0\2\121\1\116\67\121"+
        +    "\2\0\1\124\67\0\5\125\1\167\64\125\4\0\1\124"+
        +    "\1\126\74\0\1\127\1\130\1\53\1\0\4\130\1\0"+
        +    "\1\130\2\0\1\130\1\53\10\0\3\130\1\0\1\130"+
        +    "\37\0\2\170\1\53\1\0\4\170\1\0\1\170\2\0"+
        +    "\1\170\1\53\10\0\3\170\1\0\1\170\37\0\1\171"+
        +    "\1\52\1\53\2\0\2\171\1\57\1\60\1\61\3\0"+
        +    "\1\53\11\0\1\57\1\61\41\0\2\132\3\0\2\132"+
        +    "\1\57\17\0\1\57\42\0\2\132\3\0\2\132\61\0"+
        +    "\12\11\1\0\1\11\2\0\3\11\1\172\17\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\5\11\1\173\15\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\1\111\22\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\4\11\1\174\16\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\23\11"+
        +    "\5\0\1\114\2\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\1\11\1\175\21\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\12\11\1\176\10\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\14\11\1\177\6\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\20\11\1\200\2\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\16\11"+
        +    "\1\201\4\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\3\11\1\202\17\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\1\203\22\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\3\11\1\111\17\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\15\11\1\204\5\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\1\205"+
        +    "\12\11\1\206\1\207\1\210\1\11\1\211\3\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\12\11\1\155\10\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\1\151\22\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\20\11\1\212\2\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\3\11"+
        +    "\1\213\1\214\16\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\14\11\1\215\6\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\5\11\1\216\15\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\1\217"+
        +    "\22\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\15\11\1\151\5\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\5\0\1\116\67\0\4\125\1\124"+
        +    "\1\167\64\125\10\0\2\220\1\53\1\0\4\220\1\0"+
        +    "\1\220\2\0\1\220\1\53\10\0\3\220\1\0\1\220"+
        +    "\37\0\1\221\1\52\1\53\2\0\2\221\1\57\1\60"+
        +    "\1\61\3\0\1\53\11\0\1\57\1\61\37\0\12\11"+
        +    "\1\0\1\11\2\0\4\11\1\222\16\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\12\11\1\223\10\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\3\11\1\224\17\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\5\11\1\225\15\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\4\11"+
        +    "\1\226\1\227\15\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\1\11\1\76\21\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\1\230\22\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\4\11\1\111"+
        +    "\16\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\12\11\1\231\10\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\3\11\1\232\17\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\1\11\1\233\21\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\20\11\1\103\2\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\11\11"+
        +    "\1\234\3\11\1\235\5\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\14\11\1\236"+
        +    "\6\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\1\237\22\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\1\240"+
        +    "\22\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\1\11\1\241\21\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\14\11\1\242\6\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\4\11\1\63\16\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\11\11\1\243\11\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\13\0\2\244\1\53\1\0\4\244\1\0"+
        +    "\1\244\2\0\1\244\1\53\10\0\3\244\1\0\1\244"+
        +    "\37\0\1\245\1\52\1\53\2\0\2\245\1\57\1\60"+
        +    "\1\61\3\0\1\53\11\0\1\57\1\61\37\0\12\11"+
        +    "\1\0\1\11\2\0\5\11\1\246\15\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\3\11\1\175\17\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\12\11\1\247\10\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\3\11\1\250\17\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\4\11"+
        +    "\1\251\16\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\4\11\1\223\16\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\16\11\1\252\4\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\6\11\1\253"+
        +    "\14\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\2\11\1\254\20\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\21\11\1\255\1\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\12\11\1\256\10\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\4\11\1\257\16\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\11\11"+
        +    "\1\260\11\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\22\11\1\163\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\10\11\1\261\12\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\2\11\1\175\20\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\13\0\2\262\1\53"+
        +    "\1\0\4\262\1\0\1\262\2\0\1\262\1\53\10\0"+
        +    "\3\262\1\0\1\262\37\0\1\263\1\52\1\53\2\0"+
        +    "\2\263\1\57\1\60\1\61\3\0\1\53\11\0\1\57"+
        +    "\1\61\37\0\12\11\1\0\1\11\2\0\6\11\1\264"+
        +    "\14\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\1\164\22\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\3\11"+
        +    "\1\265\17\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\14\11\1\266\6\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\14\11\1\267\6\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\3\11\1\270"+
        +    "\17\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\20\11\1\271\2\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\3\11\1\272\17\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\1\236\22\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\6\11\1\273\14\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\1\274\22\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\13\0\2\275\1\53"+
        +    "\1\0\4\275\1\0\1\275\2\0\1\275\1\53\10\0"+
        +    "\3\275\1\0\1\275\37\0\1\276\1\52\1\53\2\0"+
        +    "\2\276\1\57\1\60\1\61\3\0\1\53\11\0\1\57"+
        +    "\1\61\37\0\12\11\1\0\1\11\2\0\7\11\1\277"+
        +    "\13\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\7\11\1\300\13\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\5\11\1\301\15\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\4\11\1\175\16\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\4\11\1\302\16\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\1\303"+
        +    "\22\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\1\11\1\304\21\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\3\11\1\217\17\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\1\11\1\111\21\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\13\0\2\305\1\53"+
        +    "\1\0\4\305\1\0\1\305\2\0\1\305\1\53\10\0"+
        +    "\3\305\1\0\1\305\37\0\1\306\1\52\1\53\2\0"+
        +    "\2\306\1\57\1\60\1\61\3\0\1\53\11\0\1\57"+
        +    "\1\61\37\0\12\11\1\0\1\11\2\0\3\11\1\145"+
        +    "\17\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\17\11\1\136\3\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\4\11\1\204\16\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\5\11\1\307\15\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\11\11\1\310\11\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\22\11"+
        +    "\1\257\5\0\3\11\6\0\1\11\1\50\13\0\2\311"+
        +    "\1\53\1\0\4\311\1\0\1\311\2\0\1\311\1\53"+
        +    "\10\0\3\311\1\0\1\311\37\0\1\312\1\52\1\53"+
        +    "\2\0\2\312\1\57\1\60\1\61\3\0\1\53\11\0"+
        +    "\1\57\1\61\37\0\12\11\1\0\1\11\2\0\6\11"+
        +    "\1\313\14\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\6\11\1\314\14\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\13\0\2\315\1\53\1\0"+
        +    "\4\315\1\0\1\315\2\0\1\315\1\53\10\0\3\315"+
        +    "\1\0\1\315\37\0\1\316\1\52\1\53\2\0\2\316"+
        +    "\1\57\1\60\1\61\3\0\1\53\11\0\1\57\1\61"+
        +    "\37\0\12\11\1\0\1\11\2\0\7\11\1\317\13\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\3\11\1\236\17\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\13\0\2\320\1\53\1\0\4\320\1\0"+
        +    "\1\320\2\0\1\320\1\53\10\0\3\320\1\0\1\320"+
        +    "\37\0\1\321\1\52\1\53\2\0\2\321\1\57\1\60"+
        +    "\1\61\3\0\1\53\11\0\1\57\1\61\37\0\12\11"+
        +    "\1\0\1\11\2\0\3\11\1\322\17\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\13\0\2\323\1\53\1\0\4\323"+
        +    "\1\0\1\323\2\0\1\323\1\53\10\0\3\323\1\0"+
        +    "\1\323\37\0\1\324\1\52\1\53\2\0\2\324\1\57"+
        +    "\1\60\1\61\3\0\1\53\11\0\1\57\1\61\41\0"+
        +    "\2\325\1\53\1\0\4\325\1\0\1\325\2\0\1\325"+
        +    "\1\53\10\0\3\325\1\0\1\325\37\0\1\326\1\52"+
        +    "\1\53\2\0\2\326\1\57\1\60\1\61\3\0\1\53"+
        +    "\11\0\1\57\1\61\41\0\2\327\1\53\1\0\4\327"+
        +    "\1\0\1\327\2\0\1\327\1\53\10\0\3\327\1\0"+
        +    "\1\327\37\0\1\330\1\52\1\53\2\0\2\330\1\57"+
        +    "\1\60\1\61\3\0\1\53\11\0\1\57\1\61\41\0"+
        +    "\2\331\1\53\1\0\4\331\1\0\1\331\2\0\1\331"+
        +    "\1\53\10\0\3\331\1\0\1\331\37\0\1\332\1\52"+
        +    "\1\53\2\0\2\332\1\57\1\60\1\61\3\0\1\53"+
        +    "\11\0\1\57\1\61\41\0\2\333\1\53\1\0\4\333"+
        +    "\1\0\1\333\2\0\1\333\1\53\10\0\3\333\1\0"+
        +    "\1\333\37\0\1\334\1\52\1\53\2\0\2\334\1\57"+
        +    "\1\60\1\61\3\0\1\53\11\0\1\57\1\61\41\0"+
        +    "\2\335\1\53\1\0\4\335\1\0\1\335\2\0\1\335"+
        +    "\1\53\10\0\3\335\1\0\1\335\37\0\1\336\1\52"+
        +    "\1\53\2\0\2\336\1\57\1\60\1\61\3\0\1\53"+
        +    "\11\0\1\57\1\61\43\0\1\53\12\0\1\53\54\0"+
        +    "\1\337\1\52\1\53\2\0\2\337\1\57\1\60\1\61"+
        +    "\3\0\1\53\11\0\1\57\1\61\41\0\1\340\1\52"+
        +    "\1\53\2\0\2\340\1\57\1\60\1\61\3\0\1\53"+
        +    "\11\0\1\57\1\61\41\0\1\341\1\52\1\53\2\0"+
        +    "\2\341\1\57\1\60\1\61\3\0\1\53\11\0\1\57"+
        +    "\1\61\41\0\1\342\1\52\1\53\2\0\2\342\1\57"+
        +    "\1\60\1\61\3\0\1\53\11\0\1\57\1\61\41\0"+
        +    "\2\52\1\53\2\0\2\52\1\57\1\60\1\61\3\0"+
        +    "\1\53\11\0\1\57\1\61\31\0";
        +
        +  private static int [] zzUnpackTrans() {
        +    int [] result = new int[11832];
        +    int offset = 0;
        +    offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result);
        +    return result;
        +  }
        +
        +  private static int zzUnpackTrans(String packed, int offset, int [] result) {
        +    int i = 0;       /* index in packed string  */
        +    int j = offset;  /* index in unpacked array */
        +    int l = packed.length();
        +    while (i < l) {
        +      int count = packed.charAt(i++);
        +      int value = packed.charAt(i++);
        +      value--;
        +      do result[j++] = value; while (--count > 0);
        +    }
        +    return j;
        +  }
        +
        +
        +  /* error codes */
        +  private static final int ZZ_UNKNOWN_ERROR = 0;
        +  private static final int ZZ_NO_MATCH = 1;
        +  private static final int ZZ_PUSHBACK_2BIG = 2;
        +
        +  /* error messages for the codes above */
        +  private static final String ZZ_ERROR_MSG[] = {
        +    "Unkown internal scanner error",
        +    "Error: could not match input",
        +    "Error: pushback value was too large"
        +  };
        +
        +  /**
        +   * ZZ_ATTRIBUTE[aState] contains the attributes of state aState
        +   */
        +  private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute();
        +
        +  private static final String ZZ_ATTRIBUTE_PACKED_0 =
        +    "\2\0\1\11\1\1\1\11\2\1\1\11\23\1\4\11"+
        +    "\7\1\1\0\1\11\2\1\1\11\1\0\4\1\1\0"+
        +    "\33\1\1\0\1\11\1\0\1\1\2\0\1\1\1\11"+
        +    "\2\0\4\1\1\0\31\1\1\11\2\0\125\1\1\0"+
        +    "\2\1\1\0\2\1\1\0\1\1\1\0\1\1\1\0"+
        +    "\1\1\1\0\1\1\1\0\1\1\1\0\5\1";
        +
        +  private static int [] zzUnpackAttribute() {
        +    int [] result = new int[226];
        +    int offset = 0;
        +    offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result);
        +    return result;
        +  }
        +
        +  private static int zzUnpackAttribute(String packed, int offset, int [] result) {
        +    int i = 0;       /* index in packed string  */
        +    int j = offset;  /* index in unpacked array */
        +    int l = packed.length();
        +    while (i < l) {
        +      int count = packed.charAt(i++);
        +      int value = packed.charAt(i++);
        +      do result[j++] = value; while (--count > 0);
        +    }
        +    return j;
        +  }
        +
        +  /** the input device */
        +  private java.io.Reader zzReader;
        +
        +  /** the current state of the DFA */
        +  private int zzState;
        +
        +  /** the current lexical state */
        +  private int zzLexicalState = YYINITIAL;
        +
        +  /** this buffer contains the current text to be matched and is
        +      the source of the yytext() string */
        +  private char zzBuffer[] = new char[ZZ_BUFFERSIZE];
        +
        +  /** the textposition at the last accepting state */
        +  private int zzMarkedPos;
        +
        +  /** the current text position in the buffer */
        +  private int zzCurrentPos;
        +
        +  /** startRead marks the beginning of the yytext() string in the buffer */
        +  private int zzStartRead;
        +
        +  /** endRead marks the last character in the buffer, that has been read
        +      from input */
        +  private int zzEndRead;
        +
        +  /** number of newlines encountered up to the start of the matched text */
        +  private int yyline;
        +
        +  /** the number of characters up to the start of the matched text */
        +  private int yychar;
        +
        +  /**
        +   * the number of characters from the last newline up to the start of the 
        +   * matched text
        +   */
        +  private int yycolumn;
        +
        +  /** 
        +   * zzAtBOL == true <=> the scanner is currently at the beginning of a line
        +   */
        +  private boolean zzAtBOL = true;
        +
        +  /** zzAtEOF == true <=> the scanner is at the EOF */
        +  private boolean zzAtEOF;
        +
        +  /** denotes if the user-EOF-code has already been executed */
        +  private boolean zzEOFDone;
        +
        +  /* user code: */
        +    /**
        +     * Create an empty lexer, yyrset will be called later to reset and assign
        +     * the reader
        +     */
        +    public PortugolFlex() {
        +        super();
        +    }
        +
        +    @Override
        +    public int yychar() {
        +        return yychar;
        +    }
        +
        +    private static final byte PARAN     = 1;
        +    private static final byte BRACKET   = 2;
        +    private static final byte CURLY     = 3;
        +    private static final byte WORD      = 4;
        +
        +
        +
        +  /**
        +   * Creates a new scanner
        +   * There is also a java.io.InputStream version of this constructor.
        +   *
        +   * @param   in  the java.io.Reader to read input from.
        +   */
        +  public PortugolFlex(java.io.Reader in) {
        +    this.zzReader = in;
        +  }
        +
        +  /**
        +   * Creates a new scanner.
        +   * There is also java.io.Reader version of this constructor.
        +   *
        +   * @param   in  the java.io.Inputstream to read input from.
        +   */
        +  public PortugolFlex(java.io.InputStream in) {
        +    this(new java.io.InputStreamReader
        +             (in, java.nio.charset.Charset.forName("UTF-8")));
        +  }
        +
        +  /** 
        +   * Unpacks the compressed character translation table.
        +   *
        +   * @param packed   the packed character translation table
        +   * @return         the unpacked character translation table
        +   */
        +  private static char [] zzUnpackCMap(String packed) {
        +    char [] map = new char[0x10000];
        +    int i = 0;  /* index in packed string  */
        +    int j = 0;  /* index in unpacked array */
        +    while (i < 166) {
        +      int  count = packed.charAt(i++);
        +      char value = packed.charAt(i++);
        +      do map[j++] = value; while (--count > 0);
        +    }
        +    return map;
        +  }
        +
        +
        +  /**
        +   * Refills the input buffer.
        +   *
        +   * @return      false, iff there was new input.
        +   * 
        +   * @exception   java.io.IOException  if any I/O-Error occurs
        +   */
        +  private boolean zzRefill() throws java.io.IOException {
        +
        +    /* first: make room (if you can) */
        +    if (zzStartRead > 0) {
        +      System.arraycopy(zzBuffer, zzStartRead,
        +                       zzBuffer, 0,
        +                       zzEndRead-zzStartRead);
        +
        +      /* translate stored positions */
        +      zzEndRead-= zzStartRead;
        +      zzCurrentPos-= zzStartRead;
        +      zzMarkedPos-= zzStartRead;
        +      zzStartRead = 0;
        +    }
        +
        +    /* is the buffer big enough? */
        +    if (zzCurrentPos >= zzBuffer.length) {
        +      /* if not: blow it up */
        +      char newBuffer[] = new char[zzCurrentPos*2];
        +      System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length);
        +      zzBuffer = newBuffer;
        +    }
        +
        +    /* finally: fill the buffer with new input */
        +    int numRead = zzReader.read(zzBuffer, zzEndRead,
        +                                            zzBuffer.length-zzEndRead);
        +
        +    if (numRead > 0) {
        +      zzEndRead+= numRead;
        +      return false;
        +    }
        +    // unlikely but not impossible: read 0 characters, but not at end of stream    
        +    if (numRead == 0) {
        +      int c = zzReader.read();
        +      if (c == -1) {
        +        return true;
        +      } else {
        +        zzBuffer[zzEndRead++] = (char) c;
        +        return false;
        +      }     
        +    }
        +
        +    // numRead < 0
        +    return true;
        +  }
        +
        +    
        +  /**
        +   * Closes the input stream.
        +   */
        +  public final void yyclose() throws java.io.IOException {
        +    zzAtEOF = true;            /* indicate end of file */
        +    zzEndRead = zzStartRead;  /* invalidate buffer    */
        +
        +    if (zzReader != null)
        +      zzReader.close();
        +  }
        +
        +
        +  /**
        +   * Resets the scanner to read from a new input stream.
        +   * Does not close the old reader.
        +   *
        +   * All internal variables are reset, the old input stream 
        +   * cannot be reused (internal buffer is discarded and lost).
        +   * Lexical state is set to ZZ_INITIAL.
        +   *
        +   * Internal scan buffer is resized down to its initial length, if it has grown.
        +   *
        +   * @param reader   the new input stream 
        +   */
        +  public final void yyreset(java.io.Reader reader) {
        +    zzReader = reader;
        +    zzAtBOL  = true;
        +    zzAtEOF  = false;
        +    zzEOFDone = false;
        +    zzEndRead = zzStartRead = 0;
        +    zzCurrentPos = zzMarkedPos = 0;
        +    yyline = yychar = yycolumn = 0;
        +    zzLexicalState = YYINITIAL;
        +    if (zzBuffer.length > ZZ_BUFFERSIZE)
        +      zzBuffer = new char[ZZ_BUFFERSIZE];
        +  }
        +
        +
        +  /**
        +   * Returns the current lexical state.
        +   */
        +  public final int yystate() {
        +    return zzLexicalState;
        +  }
        +
        +
        +  /**
        +   * Enters a new lexical state
        +   *
        +   * @param newState the new lexical state
        +   */
        +  public final void yybegin(int newState) {
        +    zzLexicalState = newState;
        +  }
        +
        +
        +  /**
        +   * Returns the text matched by the current regular expression.
        +   */
        +  public final String yytext() {
        +    return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead );
        +  }
        +
        +
        +  /**
        +   * Returns the character at position pos from the 
        +   * matched text. 
        +   * 
        +   * It is equivalent to yytext().charAt(pos), but faster
        +   *
        +   * @param pos the position of the character to fetch. 
        +   *            A value from 0 to yylength()-1.
        +   *
        +   * @return the character at position pos
        +   */
        +  public final char yycharat(int pos) {
        +    return zzBuffer[zzStartRead+pos];
        +  }
        +
        +
        +  /**
        +   * Returns the length of the matched text region.
        +   */
        +  public final int yylength() {
        +    return zzMarkedPos-zzStartRead;
        +  }
        +
        +
        +  /**
        +   * Reports an error that occured while scanning.
        +   *
        +   * In a wellformed scanner (no or only correct usage of 
        +   * yypushback(int) and a match-all fallback rule) this method 
        +   * will only be called with things that "Can't Possibly Happen".
        +   * If this method is called, something is seriously wrong
        +   * (e.g. a JFlex bug producing a faulty scanner etc.).
        +   *
        +   * Usual syntax/scanner level error handling should be done
        +   * in error fallback rules.
        +   *
        +   * @param   errorCode  the code of the errormessage to display
        +   */
        +  private void zzScanError(int errorCode) {
        +    String message;
        +    try {
        +      message = ZZ_ERROR_MSG[errorCode];
        +    }
        +    catch (ArrayIndexOutOfBoundsException e) {
        +      message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
        +    }
        +
        +    throw new Error(message);
        +  } 
        +
        +
        +  /**
        +   * Pushes the specified amount of characters back into the input stream.
        +   *
        +   * They will be read again by then next call of the scanning method
        +   *
        +   * @param number  the number of characters to be read again.
        +   *                This number must not be greater than yylength()!
        +   */
        +  public void yypushback(int number)  {
        +    if ( number > yylength() )
        +      zzScanError(ZZ_PUSHBACK_2BIG);
        +
        +    zzMarkedPos -= number;
        +  }
        +
        +
        +  /**
        +   * Resumes scanning until the next regular expression is matched,
        +   * the end of input is encountered or an I/O-Error occurs.
        +   *
        +   * @return      the next token
        +   * @exception   java.io.IOException  if any I/O-Error occurs
        +   */
        +  public Token yylex() throws java.io.IOException {
        +    int zzInput;
        +    int zzAction;
        +
        +    // cached fields:
        +    int zzCurrentPosL;
        +    int zzMarkedPosL;
        +    int zzEndReadL = zzEndRead;
        +    char [] zzBufferL = zzBuffer;
        +    char [] zzCMapL = ZZ_CMAP;
        +
        +    int [] zzTransL = ZZ_TRANS;
        +    int [] zzRowMapL = ZZ_ROWMAP;
        +    int [] zzAttrL = ZZ_ATTRIBUTE;
        +
        +    while (true) {
        +      zzMarkedPosL = zzMarkedPos;
        +
        +      yychar+= zzMarkedPosL-zzStartRead;
        +
        +      zzAction = -1;
        +
        +      zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL;
        +  
        +      zzState = ZZ_LEXSTATE[zzLexicalState];
        +
        +      // set up zzAction for empty match case:
        +      int zzAttributes = zzAttrL[zzState];
        +      if ( (zzAttributes & 1) == 1 ) {
        +        zzAction = zzState;
        +      }
        +
        +
        +      zzForAction: {
        +        while (true) {
        +    
        +          if (zzCurrentPosL < zzEndReadL)
        +            zzInput = zzBufferL[zzCurrentPosL++];
        +          else if (zzAtEOF) {
        +            zzInput = YYEOF;
        +            break zzForAction;
        +          }
        +          else {
        +            // store back cached positions
        +            zzCurrentPos  = zzCurrentPosL;
        +            zzMarkedPos   = zzMarkedPosL;
        +            boolean eof = zzRefill();
        +            // get translated positions and possibly new buffer
        +            zzCurrentPosL  = zzCurrentPos;
        +            zzMarkedPosL   = zzMarkedPos;
        +            zzBufferL      = zzBuffer;
        +            zzEndReadL     = zzEndRead;
        +            if (eof) {
        +              zzInput = YYEOF;
        +              break zzForAction;
        +            }
        +            else {
        +              zzInput = zzBufferL[zzCurrentPosL++];
        +            }
        +          }
        +          int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];
        +          if (zzNext == -1) break zzForAction;
        +          zzState = zzNext;
        +
        +          zzAttributes = zzAttrL[zzState];
        +          if ( (zzAttributes & 1) == 1 ) {
        +            zzAction = zzState;
        +            zzMarkedPosL = zzCurrentPosL;
        +            if ( (zzAttributes & 8) == 8 ) break zzForAction;
        +          }
        +
        +        }
        +      }
        +
        +      // store back cached position
        +      zzMarkedPos = zzMarkedPosL;
        +
        +      switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
        +        case 1: 
        +          { return token(TokenType.ERROR);
        +          }
        +        case 22: break;
        +        case 2: 
        +          { 
        +          }
        +        case 23: break;
        +        case 3: 
        +          { return token(TokenType.OPERATOR);
        +          }
        +        case 24: break;
        +        case 4: 
        +          { return token(TokenType.IDENTIFIER);
        +          }
        +        case 25: break;
        +        case 5: 
        +          { return token(TokenType.NUMBER);
        +          }
        +        case 26: break;
        +        case 6: 
        +          { return token(TokenType.KEYWORD2);
        +          }
        +        case 27: break;
        +        case 7: 
        +          { return token(TokenType.OPERATOR,  PARAN);
        +          }
        +        case 28: break;
        +        case 8: 
        +          { return token(TokenType.OPERATOR, -PARAN);
        +          }
        +        case 29: break;
        +        case 9: 
        +          { return token(TokenType.OPERATOR,  BRACKET);
        +          }
        +        case 30: break;
        +        case 10: 
        +          { return token(TokenType.OPERATOR, -BRACKET);
        +          }
        +        case 31: break;
        +        case 11: 
        +          { yybegin(STRING);
        +                                    tokenStart = yychar;
        +                                    tokenLength = 1;
        +          }
        +        case 32: break;
        +        case 12: 
        +          { return token(TokenType.COMMENT);
        +          }
        +        case 33: break;
        +        case 13: 
        +          { return token(TokenType.TYPE2);
        +          }
        +        case 34: break;
        +        case 14: 
        +          { return token(TokenType.KEYWORD2,  WORD);
        +          }
        +        case 35: break;
        +        case 15: 
        +          { return token(TokenType.STRING);
        +          }
        +        case 36: break;
        +        case 16: 
        +          { return token(TokenType.KEYWORD);
        +          }
        +        case 37: break;
        +        case 17: 
        +          { yybegin(ML_STRING);
        +                                    tokenStart = yychar;
        +                                    tokenLength = 3;
        +          }
        +        case 38: break;
        +        case 18: 
        +          { return token(TokenType.TYPE);
        +          }
        +        case 39: break;
        +        case 19: 
        +          { return token(TokenType.KEYWORD2, -WORD);
        +          }
        +        case 40: break;
        +        case 20: 
        +          { return token(TokenType.KEYWORD, WORD);
        +          }
        +        case 41: break;
        +        case 21: 
        +          { return token(TokenType.KEYWORD, -WORD);
        +          }
        +        case 42: break;
        +        default: 
        +          if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
        +            zzAtEOF = true;
        +              {
        +                return null;
        +              }
        +          } 
        +          else {
        +            zzScanError(ZZ_NO_MATCH);
        +          }
        +      }
        +    }
        +  }
        +
        +
        +}
        diff --git a/src/com/editor/flex/PortugolFlex.java~ b/src/com/editor/flex/PortugolFlex.java~
        new file mode 100644
        index 0000000..3a1e1b3
        --- /dev/null
        +++ b/src/com/editor/flex/PortugolFlex.java~
        @@ -0,0 +1,1018 @@
        +/* The following code was generated by JFlex 1.5.1 */
        +
        +package com.editor.flex;
        +
        +
        +import jsyntaxpane.Token;
        +import jsyntaxpane.TokenType;
        +import jsyntaxpane.lexers.DefaultJFlexLexer;
        +
        +
        +
        +/**
        + * This class is a scanner generated by 
        + * JFlex 1.5.1
        + * from the specification file C:/Users/SIMONETO-2/Documents/NetBeansProjects/portugol-projeto/src/com/editor/flex/Portugol_v2.flex
        + */
        +public final class PortugolFlex extends DefaultJFlexLexer {
        +
        +  /** This character denotes the end of file */
        +  public static final int YYEOF = -1;
        +
        +  /** initial size of the lookahead buffer */
        +  private static final int ZZ_BUFFERSIZE = 16384;
        +
        +  /** lexical states */
        +  public static final int YYINITIAL = 0;
        +  public static final int STRING = 2;
        +  public static final int ML_STRING = 4;
        +
        +  /**
        +   * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l
        +   * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l
        +   *                  at the beginning of a line
        +   * l is of the form l = 2*k, k a non negative integer
        +   */
        +  private static final int ZZ_LEXSTATE[] = { 
        +     0,  0,  1,  1,  1, 1
        +  };
        +
        +  /** 
        +   * Translates characters to character classes
        +   */
        +  private static final String ZZ_CMAP_PACKED = 
        +    "\11\0\1\3\1\2\1\70\1\71\1\1\22\0\1\3\1\0\1\64"+
        +    "\4\0\1\67\1\47\1\50\1\5\1\53\1\62\1\22\1\20\1\4"+
        +    "\1\10\1\16\2\15\4\15\2\11\1\63\1\0\1\57\1\61\1\60"+
        +    "\1\66\1\0\4\14\1\21\1\17\2\6\1\56\1\65\1\6\1\12"+
        +    "\3\6\1\55\7\6\1\13\2\6\1\51\1\23\1\52\1\0\1\7"+
        +    "\1\0\1\24\1\14\1\36\1\42\1\40\1\37\1\26\1\46\1\31"+
        +    "\1\65\1\6\1\25\1\33\1\35\1\27\1\43\1\45\1\30\1\41"+
        +    "\1\32\1\44\1\34\1\6\1\13\1\6\1\54\12\0\1\70\u1fa2\0"+
        +    "\1\70\1\70\udfd6\0";
        +
        +  /** 
        +   * Translates characters to character classes
        +   */
        +  private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED);
        +
        +  /** 
        +   * Translates DFA states to action switch labels.
        +   */
        +  private static final int [] ZZ_ACTION = zzUnpackAction();
        +
        +  private static final String ZZ_ACTION_PACKED_0 =
        +    "\2\0\1\1\3\2\2\3\1\4\2\5\1\1\13\4"+
        +    "\1\6\3\4\1\7\1\10\1\11\1\12\1\4\2\3"+
        +    "\1\13\2\1\1\14\1\0\1\15\3\5\1\0\4\5"+
        +    "\1\0\4\4\1\6\20\4\1\16\1\4\1\6\2\4"+
        +    "\1\3\1\0\1\17\1\0\1\17\2\0\2\14\2\0"+
        +    "\4\5\1\0\10\4\1\3\1\20\14\4\1\3\2\4"+
        +    "\1\21\2\0\2\5\3\4\1\22\20\4\1\16\2\5"+
        +    "\10\4\1\5\3\4\1\23\5\4\2\5\2\4\1\24"+
        +    "\11\4\2\5\10\4\1\6\2\5\6\4\2\5\2\4"+
        +    "\2\5\2\4\1\0\1\5\1\4\1\0\1\5\1\25"+
        +    "\1\0\1\5\1\0\1\5\1\0\1\5\1\0\1\5"+
        +    "\1\0\1\5\1\0\5\5";
        +
        +  private static int [] zzUnpackAction() {
        +    int [] result = new int[225];
        +    int offset = 0;
        +    offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result);
        +    return result;
        +  }
        +
        +  private static int zzUnpackAction(String packed, int offset, int [] result) {
        +    int i = 0;       /* index in packed string  */
        +    int j = offset;  /* index in unpacked array */
        +    int l = packed.length();
        +    while (i < l) {
        +      int count = packed.charAt(i++);
        +      int value = packed.charAt(i++);
        +      do result[j++] = value; while (--count > 0);
        +    }
        +    return j;
        +  }
        +
        +
        +  /** 
        +   * Translates a state to a row index in the transition table
        +   */
        +  private static final int [] ZZ_ROWMAP = zzUnpackRowMap();
        +
        +  private static final String ZZ_ROWMAP_PACKED_0 =
        +    "\0\0\0\72\0\164\0\256\0\164\0\350\0\u0122\0\164"+
        +    "\0\u015c\0\u0196\0\u01d0\0\u020a\0\u0244\0\u027e\0\u02b8\0\u02f2"+
        +    "\0\u032c\0\u0366\0\u03a0\0\u03da\0\u0414\0\u044e\0\u0488\0\u04c2"+
        +    "\0\u04fc\0\u0536\0\u0570\0\164\0\164\0\164\0\164\0\u05aa"+
        +    "\0\u05e4\0\u061e\0\u0658\0\u0692\0\u06cc\0\u0706\0\u0740\0\164"+
        +    "\0\u077a\0\u07b4\0\164\0\u07ee\0\u0828\0\u0862\0\u089c\0\u08d6"+
        +    "\0\u0910\0\u094a\0\u0984\0\u09be\0\u09f8\0\u0a32\0\u0a6c\0\u0aa6"+
        +    "\0\u0ae0\0\u0b1a\0\u0b54\0\u0b8e\0\u0bc8\0\u0c02\0\u0c3c\0\u0c76"+
        +    "\0\u0cb0\0\u0cea\0\u0d24\0\u0d5e\0\u0d98\0\u0dd2\0\u0e0c\0\u0e46"+
        +    "\0\u015c\0\u0e80\0\u0eba\0\u015c\0\u06cc\0\164\0\u0ef4\0\u0f2e"+
        +    "\0\u0f68\0\u0fa2\0\u0fdc\0\164\0\u1016\0\u1050\0\u108a\0\u10c4"+
        +    "\0\u10fe\0\u1138\0\u1172\0\u11ac\0\u11e6\0\u1220\0\u125a\0\u1294"+
        +    "\0\u12ce\0\u1308\0\u1342\0\u0c02\0\u015c\0\u137c\0\u13b6\0\u13f0"+
        +    "\0\u142a\0\u1464\0\u149e\0\u14d8\0\u1512\0\u154c\0\u1586\0\u15c0"+
        +    "\0\u15fa\0\u1512\0\u1634\0\u166e\0\164\0\u16a8\0\u16e2\0\u171c"+
        +    "\0\u1756\0\u1790\0\u17ca\0\u1804\0\u015c\0\u183e\0\u1878\0\u18b2"+
        +    "\0\u18ec\0\u1926\0\u1960\0\u199a\0\u19d4\0\u1a0e\0\u1a48\0\u1a82"+
        +    "\0\u1abc\0\u1af6\0\u1b30\0\u1b6a\0\u1ba4\0\u015c\0\u1bde\0\u1c18"+
        +    "\0\u1c52\0\u1c8c\0\u1cc6\0\u1d00\0\u1d3a\0\u1d74\0\u1dae\0\u1de8"+
        +    "\0\u015c\0\u1e22\0\u1e5c\0\u1e96\0\u015c\0\u1ed0\0\u1f0a\0\u1f44"+
        +    "\0\u1f7e\0\u1fb8\0\u1ff2\0\u202c\0\u2066\0\u20a0\0\u015c\0\u20da"+
        +    "\0\u2114\0\u214e\0\u2188\0\u21c2\0\u21fc\0\u2236\0\u2270\0\u22aa"+
        +    "\0\u22e4\0\u231e\0\u2358\0\u2392\0\u23cc\0\u2406\0\u2440\0\u247a"+
        +    "\0\u24b4\0\u24ee\0\u2528\0\u2562\0\u259c\0\u25d6\0\u2610\0\u264a"+
        +    "\0\u2684\0\u26be\0\u26f8\0\u2732\0\u276c\0\u27a6\0\u27e0\0\u281a"+
        +    "\0\u2854\0\u288e\0\u28c8\0\u2902\0\u293c\0\u2976\0\u29b0\0\u29ea"+
        +    "\0\u015c\0\u2a24\0\u2a5e\0\u2a98\0\u2ad2\0\u2b0c\0\u2b46\0\u2b80"+
        +    "\0\u2bba\0\u2bf4\0\u2c2e\0\u2c68\0\u2ca2\0\u2cdc\0\u2d16\0\u2d50"+
        +    "\0\u2d8a";
        +
        +  private static int [] zzUnpackRowMap() {
        +    int [] result = new int[225];
        +    int offset = 0;
        +    offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result);
        +    return result;
        +  }
        +
        +  private static int zzUnpackRowMap(String packed, int offset, int [] result) {
        +    int i = 0;  /* index in packed string  */
        +    int j = offset;  /* index in unpacked array */
        +    int l = packed.length();
        +    while (i < l) {
        +      int high = packed.charAt(i++) << 16;
        +      result[j++] = high | packed.charAt(i++);
        +    }
        +    return j;
        +  }
        +
        +  /** 
        +   * The transition table of the DFA
        +   */
        +  private static final int [] ZZ_TRANS = zzUnpackTrans();
        +
        +  private static final String ZZ_TRANS_PACKED_0 =
        +    "\1\3\1\4\1\5\1\6\1\7\1\10\1\11\1\3"+
        +    "\1\12\1\13\3\11\2\13\1\11\1\14\1\11\1\10"+
        +    "\1\3\1\15\1\16\1\11\1\17\1\20\1\21\1\22"+
        +    "\1\23\1\24\1\25\1\26\1\27\1\30\1\31\1\32"+
        +    "\1\33\3\11\1\34\1\35\1\36\1\37\1\10\1\11"+
        +    "\1\40\1\11\1\41\2\42\1\10\1\42\1\43\1\11"+
        +    "\1\3\1\44\1\0\1\6\1\3\1\0\1\5\61\3"+
        +    "\1\45\2\3\1\44\76\0\1\5\72\0\1\6\65\0"+
        +    "\1\6\4\0\1\46\1\47\72\0\12\11\1\0\1\11"+
        +    "\2\0\23\11\5\0\3\11\6\0\1\11\1\50\13\0"+
        +    "\1\51\1\52\1\53\1\54\1\0\1\55\1\56\1\57"+
        +    "\1\60\1\61\3\0\1\53\11\0\1\57\1\61\41\0"+
        +    "\2\13\1\53\2\0\2\13\1\57\1\60\1\61\3\0"+
        +    "\1\53\11\0\1\57\1\61\41\0\2\60\3\0\2\60"+
        +    "\61\0\12\11\1\0\1\11\2\0\1\11\1\62\4\11"+
        +    "\1\63\14\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\3\11\1\64\10\11\1\65"+
        +    "\6\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\20\11\1\66\2\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\1\67\13\11\1\70\6\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\11\11\1\71"+
        +    "\11\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\1\72\22\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\3\11"+
        +    "\1\73\17\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\1\74\13\11\1\75\6\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\1\76\22\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\1\77\2\11"+
        +    "\1\100\17\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\1\101\4\11\1\102\12\11"+
        +    "\1\103\2\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\11\11\1\104\3\11\1\105"+
        +    "\5\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\6\11\1\106\5\11\1\107\6\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\5\11\1\110\6\11\1\111\6\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\1\112\2\11\1\113\17\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\23\11"+
        +    "\5\0\2\11\1\114\6\0\1\11\1\50\25\0\1\10"+
        +    "\35\0\2\10\71\0\1\10\10\0\2\115\1\116\20\115"+
        +    "\1\117\40\115\1\120\5\115\2\121\1\116\20\121\1\122"+
        +    "\43\121\1\116\2\121\2\115\1\116\20\115\1\117\40\115"+
        +    "\1\116\5\115\1\46\1\123\1\124\67\46\5\125\1\126"+
        +    "\64\125\10\0\1\51\1\52\1\53\2\0\1\55\1\56"+
        +    "\1\57\1\60\1\61\3\0\1\53\11\0\1\57\1\61"+
        +    "\41\0\2\52\3\0\2\52\1\57\1\60\1\61\15\0"+
        +    "\1\57\1\61\41\0\1\127\1\130\2\0\4\130\1\0"+
        +    "\1\130\2\0\1\130\11\0\3\130\1\0\1\130\37\0"+
        +    "\1\131\1\52\1\53\2\0\2\131\1\57\1\60\1\61"+
        +    "\3\0\1\53\11\0\1\57\1\61\41\0\1\55\1\52"+
        +    "\1\53\2\0\2\55\1\57\1\60\1\61\3\0\1\53"+
        +    "\11\0\1\57\1\61\116\0\1\53\14\0\2\60\3\0"+
        +    "\2\60\1\57\1\0\1\61\15\0\1\57\1\61\41\0"+
        +    "\2\132\3\0\2\132\3\0\1\133\30\0\1\133\24\0"+
        +    "\12\11\1\0\1\11\2\0\2\11\1\134\20\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\14\11\1\111\6\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\2\11\1\135"+
        +    "\20\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\5\11\1\136\15\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\6\11\1\137\14\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\5\11\1\140\15\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\1\141\22\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\5\11\1\142"+
        +    "\1\143\14\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\11\11\1\114\11\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\16\11\1\144\4\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\4\11\1\145"+
        +    "\16\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\4\11\1\146\1\11\1\147\14\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\3\11\1\114\17\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\4\11"+
        +    "\1\150\10\11\1\151\5\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\15\11\1\114"+
        +    "\5\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\1\11\1\152\10\11\1\136\10\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\7\11\1\153\13\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\11\11"+
        +    "\1\154\11\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\6\11\1\155\12\11\1\156"+
        +    "\1\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\12\11\1\157\4\11\1\160\3\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\4\11\1\161\16\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\11\11"+
        +    "\1\162\11\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\10\11\1\114\12\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\4\11\1\163\10\11\1\164\5\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\6\11\1\114\14\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\3\0\2\115\1\116\67\115\64\0\1\165\7\0\1\116"+
        +    "\20\0\1\166\43\0\1\116\2\0\2\121\1\116\67\121"+
        +    "\2\0\1\124\67\0\5\125\1\167\64\125\4\0\1\124"+
        +    "\1\126\74\0\1\127\1\130\1\53\1\0\4\130\1\0"+
        +    "\1\130\2\0\1\130\1\53\10\0\3\130\1\0\1\130"+
        +    "\37\0\2\170\1\53\1\0\4\170\1\0\1\170\2\0"+
        +    "\1\170\1\53\10\0\3\170\1\0\1\170\37\0\1\171"+
        +    "\1\52\1\53\2\0\2\171\1\57\1\60\1\61\3\0"+
        +    "\1\53\11\0\1\57\1\61\41\0\2\132\3\0\2\132"+
        +    "\1\57\17\0\1\57\42\0\2\132\3\0\2\132\61\0"+
        +    "\12\11\1\0\1\11\2\0\3\11\1\172\17\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\5\11\1\173\15\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\1\111\22\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\4\11\1\174\16\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\23\11"+
        +    "\5\0\1\114\2\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\1\11\1\175\21\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\12\11\1\176\10\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\14\11\1\177\6\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\16\11\1\200\4\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\3\11"+
        +    "\1\201\17\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\1\202\22\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\3\11\1\111\17\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\15\11\1\203\5\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\1\204\12\11\1\205\1\206\1\207\1\11"+
        +    "\1\210\3\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\12\11\1\155\10\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\1\151\22\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\20\11\1\211\2\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\3\11\1\212\1\213\16\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\14\11\1\214\6\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\5\11\1\215\15\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\1\216\22\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\15\11\1\151"+
        +    "\5\11\5\0\3\11\6\0\1\11\1\50\5\0\1\116"+
        +    "\67\0\4\125\1\124\1\167\64\125\10\0\2\217\1\53"+
        +    "\1\0\4\217\1\0\1\217\2\0\1\217\1\53\10\0"+
        +    "\3\217\1\0\1\217\37\0\1\220\1\52\1\53\2\0"+
        +    "\2\220\1\57\1\60\1\61\3\0\1\53\11\0\1\57"+
        +    "\1\61\37\0\12\11\1\0\1\11\2\0\4\11\1\221"+
        +    "\16\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\12\11\1\222\10\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\3\11\1\223\17\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\5\11\1\224\15\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\4\11\1\225\1\226\15\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\1\227\22\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\4\11\1\111\16\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\12\11\1\230\10\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\3\11\1\231"+
        +    "\17\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\1\11\1\232\21\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\20\11\1\103\2\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\11\11\1\233\3\11"+
        +    "\1\234\5\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\14\11\1\235\6\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\1\236\22\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\1\237\22\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\1\11\1\240\21\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\14\11\1\241"+
        +    "\6\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\4\11\1\63\16\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\11\11\1\242\11\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\13\0\2\243\1\53\1\0\4\243\1\0\1\243\2\0"+
        +    "\1\243\1\53\10\0\3\243\1\0\1\243\37\0\1\244"+
        +    "\1\52\1\53\2\0\2\244\1\57\1\60\1\61\3\0"+
        +    "\1\53\11\0\1\57\1\61\37\0\12\11\1\0\1\11"+
        +    "\2\0\5\11\1\245\15\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\3\11\1\175"+
        +    "\17\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\12\11\1\246\10\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\3\11\1\247\17\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\4\11\1\250\16\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\4\11\1\222\16\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\16\11"+
        +    "\1\251\4\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\6\11\1\252\14\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\2\11\1\253\20\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\21\11\1\254"+
        +    "\1\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\12\11\1\255\10\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\4\11\1\256\16\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\11\11\1\257\11\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\22\11\1\163\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\10\11\1\260"+
        +    "\12\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\2\11\1\175\20\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\13\0\2\261\1\53\1\0\4\261"+
        +    "\1\0\1\261\2\0\1\261\1\53\10\0\3\261\1\0"+
        +    "\1\261\37\0\1\262\1\52\1\53\2\0\2\262\1\57"+
        +    "\1\60\1\61\3\0\1\53\11\0\1\57\1\61\37\0"+
        +    "\12\11\1\0\1\11\2\0\6\11\1\263\14\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\1\164\22\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\3\11\1\264\17\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\14\11\1\265\6\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\14\11"+
        +    "\1\266\6\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\3\11\1\267\17\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\20\11\1\270\2\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\3\11\1\271"+
        +    "\17\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\1\235\22\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\11\0\12\11\1\0\1\11\2\0\6\11"+
        +    "\1\272\14\11\5\0\3\11\6\0\1\11\1\50\11\0"+
        +    "\12\11\1\0\1\11\2\0\1\273\22\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\13\0\2\274\1\53\1\0\4\274"+
        +    "\1\0\1\274\2\0\1\274\1\53\10\0\3\274\1\0"+
        +    "\1\274\37\0\1\275\1\52\1\53\2\0\2\275\1\57"+
        +    "\1\60\1\61\3\0\1\53\11\0\1\57\1\61\37\0"+
        +    "\12\11\1\0\1\11\2\0\7\11\1\276\13\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\7\11\1\277\13\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\5\11\1\300"+
        +    "\15\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\4\11\1\175\16\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\4\11\1\301\16\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\1\302\22\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\1\11\1\303\21\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\3\11\1\216"+
        +    "\17\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\1\11\1\111\21\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\13\0\2\304\1\53\1\0\4\304"+
        +    "\1\0\1\304\2\0\1\304\1\53\10\0\3\304\1\0"+
        +    "\1\304\37\0\1\305\1\52\1\53\2\0\2\305\1\57"+
        +    "\1\60\1\61\3\0\1\53\11\0\1\57\1\61\37\0"+
        +    "\12\11\1\0\1\11\2\0\3\11\1\145\17\11\5\0"+
        +    "\3\11\6\0\1\11\1\50\11\0\12\11\1\0\1\11"+
        +    "\2\0\17\11\1\136\3\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\11\0\12\11\1\0\1\11\2\0\4\11\1\203"+
        +    "\16\11\5\0\3\11\6\0\1\11\1\50\11\0\12\11"+
        +    "\1\0\1\11\2\0\5\11\1\306\15\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\11\11\1\307\11\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\11\0\12\11\1\0\1\11\2\0\22\11\1\256\5\0"+
        +    "\3\11\6\0\1\11\1\50\13\0\2\310\1\53\1\0"+
        +    "\4\310\1\0\1\310\2\0\1\310\1\53\10\0\3\310"+
        +    "\1\0\1\310\37\0\1\311\1\52\1\53\2\0\2\311"+
        +    "\1\57\1\60\1\61\3\0\1\53\11\0\1\57\1\61"+
        +    "\37\0\12\11\1\0\1\11\2\0\6\11\1\312\14\11"+
        +    "\5\0\3\11\6\0\1\11\1\50\11\0\12\11\1\0"+
        +    "\1\11\2\0\6\11\1\313\14\11\5\0\3\11\6\0"+
        +    "\1\11\1\50\13\0\2\314\1\53\1\0\4\314\1\0"+
        +    "\1\314\2\0\1\314\1\53\10\0\3\314\1\0\1\314"+
        +    "\37\0\1\315\1\52\1\53\2\0\2\315\1\57\1\60"+
        +    "\1\61\3\0\1\53\11\0\1\57\1\61\37\0\12\11"+
        +    "\1\0\1\11\2\0\7\11\1\316\13\11\5\0\3\11"+
        +    "\6\0\1\11\1\50\11\0\12\11\1\0\1\11\2\0"+
        +    "\3\11\1\235\17\11\5\0\3\11\6\0\1\11\1\50"+
        +    "\13\0\2\317\1\53\1\0\4\317\1\0\1\317\2\0"+
        +    "\1\317\1\53\10\0\3\317\1\0\1\317\37\0\1\320"+
        +    "\1\52\1\53\2\0\2\320\1\57\1\60\1\61\3\0"+
        +    "\1\53\11\0\1\57\1\61\37\0\12\11\1\0\1\11"+
        +    "\2\0\3\11\1\321\17\11\5\0\3\11\6\0\1\11"+
        +    "\1\50\13\0\2\322\1\53\1\0\4\322\1\0\1\322"+
        +    "\2\0\1\322\1\53\10\0\3\322\1\0\1\322\37\0"+
        +    "\1\323\1\52\1\53\2\0\2\323\1\57\1\60\1\61"+
        +    "\3\0\1\53\11\0\1\57\1\61\41\0\2\324\1\53"+
        +    "\1\0\4\324\1\0\1\324\2\0\1\324\1\53\10\0"+
        +    "\3\324\1\0\1\324\37\0\1\325\1\52\1\53\2\0"+
        +    "\2\325\1\57\1\60\1\61\3\0\1\53\11\0\1\57"+
        +    "\1\61\41\0\2\326\1\53\1\0\4\326\1\0\1\326"+
        +    "\2\0\1\326\1\53\10\0\3\326\1\0\1\326\37\0"+
        +    "\1\327\1\52\1\53\2\0\2\327\1\57\1\60\1\61"+
        +    "\3\0\1\53\11\0\1\57\1\61\41\0\2\330\1\53"+
        +    "\1\0\4\330\1\0\1\330\2\0\1\330\1\53\10\0"+
        +    "\3\330\1\0\1\330\37\0\1\331\1\52\1\53\2\0"+
        +    "\2\331\1\57\1\60\1\61\3\0\1\53\11\0\1\57"+
        +    "\1\61\41\0\2\332\1\53\1\0\4\332\1\0\1\332"+
        +    "\2\0\1\332\1\53\10\0\3\332\1\0\1\332\37\0"+
        +    "\1\333\1\52\1\53\2\0\2\333\1\57\1\60\1\61"+
        +    "\3\0\1\53\11\0\1\57\1\61\41\0\2\334\1\53"+
        +    "\1\0\4\334\1\0\1\334\2\0\1\334\1\53\10\0"+
        +    "\3\334\1\0\1\334\37\0\1\335\1\52\1\53\2\0"+
        +    "\2\335\1\57\1\60\1\61\3\0\1\53\11\0\1\57"+
        +    "\1\61\43\0\1\53\12\0\1\53\54\0\1\336\1\52"+
        +    "\1\53\2\0\2\336\1\57\1\60\1\61\3\0\1\53"+
        +    "\11\0\1\57\1\61\41\0\1\337\1\52\1\53\2\0"+
        +    "\2\337\1\57\1\60\1\61\3\0\1\53\11\0\1\57"+
        +    "\1\61\41\0\1\340\1\52\1\53\2\0\2\340\1\57"+
        +    "\1\60\1\61\3\0\1\53\11\0\1\57\1\61\41\0"+
        +    "\1\341\1\52\1\53\2\0\2\341\1\57\1\60\1\61"+
        +    "\3\0\1\53\11\0\1\57\1\61\41\0\2\52\1\53"+
        +    "\2\0\2\52\1\57\1\60\1\61\3\0\1\53\11\0"+
        +    "\1\57\1\61\31\0";
        +
        +  private static int [] zzUnpackTrans() {
        +    int [] result = new int[11716];
        +    int offset = 0;
        +    offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result);
        +    return result;
        +  }
        +
        +  private static int zzUnpackTrans(String packed, int offset, int [] result) {
        +    int i = 0;       /* index in packed string  */
        +    int j = offset;  /* index in unpacked array */
        +    int l = packed.length();
        +    while (i < l) {
        +      int count = packed.charAt(i++);
        +      int value = packed.charAt(i++);
        +      value--;
        +      do result[j++] = value; while (--count > 0);
        +    }
        +    return j;
        +  }
        +
        +
        +  /* error codes */
        +  private static final int ZZ_UNKNOWN_ERROR = 0;
        +  private static final int ZZ_NO_MATCH = 1;
        +  private static final int ZZ_PUSHBACK_2BIG = 2;
        +
        +  /* error messages for the codes above */
        +  private static final String ZZ_ERROR_MSG[] = {
        +    "Unkown internal scanner error",
        +    "Error: could not match input",
        +    "Error: pushback value was too large"
        +  };
        +
        +  /**
        +   * ZZ_ATTRIBUTE[aState] contains the attributes of state aState
        +   */
        +  private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute();
        +
        +  private static final String ZZ_ATTRIBUTE_PACKED_0 =
        +    "\2\0\1\11\1\1\1\11\2\1\1\11\23\1\4\11"+
        +    "\7\1\1\0\1\11\2\1\1\11\1\0\4\1\1\0"+
        +    "\33\1\1\0\1\11\1\0\1\1\2\0\1\1\1\11"+
        +    "\2\0\4\1\1\0\31\1\1\11\2\0\124\1\1\0"+
        +    "\2\1\1\0\2\1\1\0\1\1\1\0\1\1\1\0"+
        +    "\1\1\1\0\1\1\1\0\1\1\1\0\5\1";
        +
        +  private static int [] zzUnpackAttribute() {
        +    int [] result = new int[225];
        +    int offset = 0;
        +    offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result);
        +    return result;
        +  }
        +
        +  private static int zzUnpackAttribute(String packed, int offset, int [] result) {
        +    int i = 0;       /* index in packed string  */
        +    int j = offset;  /* index in unpacked array */
        +    int l = packed.length();
        +    while (i < l) {
        +      int count = packed.charAt(i++);
        +      int value = packed.charAt(i++);
        +      do result[j++] = value; while (--count > 0);
        +    }
        +    return j;
        +  }
        +
        +  /** the input device */
        +  private java.io.Reader zzReader;
        +
        +  /** the current state of the DFA */
        +  private int zzState;
        +
        +  /** the current lexical state */
        +  private int zzLexicalState = YYINITIAL;
        +
        +  /** this buffer contains the current text to be matched and is
        +      the source of the yytext() string */
        +  private char zzBuffer[] = new char[ZZ_BUFFERSIZE];
        +
        +  /** the textposition at the last accepting state */
        +  private int zzMarkedPos;
        +
        +  /** the current text position in the buffer */
        +  private int zzCurrentPos;
        +
        +  /** startRead marks the beginning of the yytext() string in the buffer */
        +  private int zzStartRead;
        +
        +  /** endRead marks the last character in the buffer, that has been read
        +      from input */
        +  private int zzEndRead;
        +
        +  /** number of newlines encountered up to the start of the matched text */
        +  private int yyline;
        +
        +  /** the number of characters up to the start of the matched text */
        +  private int yychar;
        +
        +  /**
        +   * the number of characters from the last newline up to the start of the 
        +   * matched text
        +   */
        +  private int yycolumn;
        +
        +  /** 
        +   * zzAtBOL == true <=> the scanner is currently at the beginning of a line
        +   */
        +  private boolean zzAtBOL = true;
        +
        +  /** zzAtEOF == true <=> the scanner is at the EOF */
        +  private boolean zzAtEOF;
        +
        +  /** denotes if the user-EOF-code has already been executed */
        +  private boolean zzEOFDone;
        +
        +  /* user code: */
        +    /**
        +     * Create an empty lexer, yyrset will be called later to reset and assign
        +     * the reader
        +     */
        +    public PortugolFlex() {
        +        super();
        +    }
        +
        +    @Override
        +    public int yychar() {
        +        return yychar;
        +    }
        +
        +    private static final byte PARAN     = 1;
        +    private static final byte BRACKET   = 2;
        +    private static final byte CURLY     = 3;
        +    private static final byte WORD      = 4;
        +
        +
        +
        +  /**
        +   * Creates a new scanner
        +   * There is also a java.io.InputStream version of this constructor.
        +   *
        +   * @param   in  the java.io.Reader to read input from.
        +   */
        +  public PortugolFlex(java.io.Reader in) {
        +    this.zzReader = in;
        +  }
        +
        +  /**
        +   * Creates a new scanner.
        +   * There is also java.io.Reader version of this constructor.
        +   *
        +   * @param   in  the java.io.Inputstream to read input from.
        +   */
        +  public PortugolFlex(java.io.InputStream in) {
        +    this(new java.io.InputStreamReader
        +             (in, java.nio.charset.Charset.forName("UTF-8")));
        +  }
        +
        +  /** 
        +   * Unpacks the compressed character translation table.
        +   *
        +   * @param packed   the packed character translation table
        +   * @return         the unpacked character translation table
        +   */
        +  private static char [] zzUnpackCMap(String packed) {
        +    char [] map = new char[0x10000];
        +    int i = 0;  /* index in packed string  */
        +    int j = 0;  /* index in unpacked array */
        +    while (i < 166) {
        +      int  count = packed.charAt(i++);
        +      char value = packed.charAt(i++);
        +      do map[j++] = value; while (--count > 0);
        +    }
        +    return map;
        +  }
        +
        +
        +  /**
        +   * Refills the input buffer.
        +   *
        +   * @return      false, iff there was new input.
        +   * 
        +   * @exception   java.io.IOException  if any I/O-Error occurs
        +   */
        +  private boolean zzRefill() throws java.io.IOException {
        +
        +    /* first: make room (if you can) */
        +    if (zzStartRead > 0) {
        +      System.arraycopy(zzBuffer, zzStartRead,
        +                       zzBuffer, 0,
        +                       zzEndRead-zzStartRead);
        +
        +      /* translate stored positions */
        +      zzEndRead-= zzStartRead;
        +      zzCurrentPos-= zzStartRead;
        +      zzMarkedPos-= zzStartRead;
        +      zzStartRead = 0;
        +    }
        +
        +    /* is the buffer big enough? */
        +    if (zzCurrentPos >= zzBuffer.length) {
        +      /* if not: blow it up */
        +      char newBuffer[] = new char[zzCurrentPos*2];
        +      System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length);
        +      zzBuffer = newBuffer;
        +    }
        +
        +    /* finally: fill the buffer with new input */
        +    int numRead = zzReader.read(zzBuffer, zzEndRead,
        +                                            zzBuffer.length-zzEndRead);
        +
        +    if (numRead > 0) {
        +      zzEndRead+= numRead;
        +      return false;
        +    }
        +    // unlikely but not impossible: read 0 characters, but not at end of stream    
        +    if (numRead == 0) {
        +      int c = zzReader.read();
        +      if (c == -1) {
        +        return true;
        +      } else {
        +        zzBuffer[zzEndRead++] = (char) c;
        +        return false;
        +      }     
        +    }
        +
        +    // numRead < 0
        +    return true;
        +  }
        +
        +    
        +  /**
        +   * Closes the input stream.
        +   */
        +  public final void yyclose() throws java.io.IOException {
        +    zzAtEOF = true;            /* indicate end of file */
        +    zzEndRead = zzStartRead;  /* invalidate buffer    */
        +
        +    if (zzReader != null)
        +      zzReader.close();
        +  }
        +
        +
        +  /**
        +   * Resets the scanner to read from a new input stream.
        +   * Does not close the old reader.
        +   *
        +   * All internal variables are reset, the old input stream 
        +   * cannot be reused (internal buffer is discarded and lost).
        +   * Lexical state is set to ZZ_INITIAL.
        +   *
        +   * Internal scan buffer is resized down to its initial length, if it has grown.
        +   *
        +   * @param reader   the new input stream 
        +   */
        +  public final void yyreset(java.io.Reader reader) {
        +    zzReader = reader;
        +    zzAtBOL  = true;
        +    zzAtEOF  = false;
        +    zzEOFDone = false;
        +    zzEndRead = zzStartRead = 0;
        +    zzCurrentPos = zzMarkedPos = 0;
        +    yyline = yychar = yycolumn = 0;
        +    zzLexicalState = YYINITIAL;
        +    if (zzBuffer.length > ZZ_BUFFERSIZE)
        +      zzBuffer = new char[ZZ_BUFFERSIZE];
        +  }
        +
        +
        +  /**
        +   * Returns the current lexical state.
        +   */
        +  public final int yystate() {
        +    return zzLexicalState;
        +  }
        +
        +
        +  /**
        +   * Enters a new lexical state
        +   *
        +   * @param newState the new lexical state
        +   */
        +  public final void yybegin(int newState) {
        +    zzLexicalState = newState;
        +  }
        +
        +
        +  /**
        +   * Returns the text matched by the current regular expression.
        +   */
        +  public final String yytext() {
        +    return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead );
        +  }
        +
        +
        +  /**
        +   * Returns the character at position pos from the 
        +   * matched text. 
        +   * 
        +   * It is equivalent to yytext().charAt(pos), but faster
        +   *
        +   * @param pos the position of the character to fetch. 
        +   *            A value from 0 to yylength()-1.
        +   *
        +   * @return the character at position pos
        +   */
        +  public final char yycharat(int pos) {
        +    return zzBuffer[zzStartRead+pos];
        +  }
        +
        +
        +  /**
        +   * Returns the length of the matched text region.
        +   */
        +  public final int yylength() {
        +    return zzMarkedPos-zzStartRead;
        +  }
        +
        +
        +  /**
        +   * Reports an error that occured while scanning.
        +   *
        +   * In a wellformed scanner (no or only correct usage of 
        +   * yypushback(int) and a match-all fallback rule) this method 
        +   * will only be called with things that "Can't Possibly Happen".
        +   * If this method is called, something is seriously wrong
        +   * (e.g. a JFlex bug producing a faulty scanner etc.).
        +   *
        +   * Usual syntax/scanner level error handling should be done
        +   * in error fallback rules.
        +   *
        +   * @param   errorCode  the code of the errormessage to display
        +   */
        +  private void zzScanError(int errorCode) {
        +    String message;
        +    try {
        +      message = ZZ_ERROR_MSG[errorCode];
        +    }
        +    catch (ArrayIndexOutOfBoundsException e) {
        +      message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR];
        +    }
        +
        +    throw new Error(message);
        +  } 
        +
        +
        +  /**
        +   * Pushes the specified amount of characters back into the input stream.
        +   *
        +   * They will be read again by then next call of the scanning method
        +   *
        +   * @param number  the number of characters to be read again.
        +   *                This number must not be greater than yylength()!
        +   */
        +  public void yypushback(int number)  {
        +    if ( number > yylength() )
        +      zzScanError(ZZ_PUSHBACK_2BIG);
        +
        +    zzMarkedPos -= number;
        +  }
        +
        +
        +  /**
        +   * Resumes scanning until the next regular expression is matched,
        +   * the end of input is encountered or an I/O-Error occurs.
        +   *
        +   * @return      the next token
        +   * @exception   java.io.IOException  if any I/O-Error occurs
        +   */
        +  public Token yylex() throws java.io.IOException {
        +    int zzInput;
        +    int zzAction;
        +
        +    // cached fields:
        +    int zzCurrentPosL;
        +    int zzMarkedPosL;
        +    int zzEndReadL = zzEndRead;
        +    char [] zzBufferL = zzBuffer;
        +    char [] zzCMapL = ZZ_CMAP;
        +
        +    int [] zzTransL = ZZ_TRANS;
        +    int [] zzRowMapL = ZZ_ROWMAP;
        +    int [] zzAttrL = ZZ_ATTRIBUTE;
        +
        +    while (true) {
        +      zzMarkedPosL = zzMarkedPos;
        +
        +      yychar+= zzMarkedPosL-zzStartRead;
        +
        +      zzAction = -1;
        +
        +      zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL;
        +  
        +      zzState = ZZ_LEXSTATE[zzLexicalState];
        +
        +      // set up zzAction for empty match case:
        +      int zzAttributes = zzAttrL[zzState];
        +      if ( (zzAttributes & 1) == 1 ) {
        +        zzAction = zzState;
        +      }
        +
        +
        +      zzForAction: {
        +        while (true) {
        +    
        +          if (zzCurrentPosL < zzEndReadL)
        +            zzInput = zzBufferL[zzCurrentPosL++];
        +          else if (zzAtEOF) {
        +            zzInput = YYEOF;
        +            break zzForAction;
        +          }
        +          else {
        +            // store back cached positions
        +            zzCurrentPos  = zzCurrentPosL;
        +            zzMarkedPos   = zzMarkedPosL;
        +            boolean eof = zzRefill();
        +            // get translated positions and possibly new buffer
        +            zzCurrentPosL  = zzCurrentPos;
        +            zzMarkedPosL   = zzMarkedPos;
        +            zzBufferL      = zzBuffer;
        +            zzEndReadL     = zzEndRead;
        +            if (eof) {
        +              zzInput = YYEOF;
        +              break zzForAction;
        +            }
        +            else {
        +              zzInput = zzBufferL[zzCurrentPosL++];
        +            }
        +          }
        +          int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ];
        +          if (zzNext == -1) break zzForAction;
        +          zzState = zzNext;
        +
        +          zzAttributes = zzAttrL[zzState];
        +          if ( (zzAttributes & 1) == 1 ) {
        +            zzAction = zzState;
        +            zzMarkedPosL = zzCurrentPosL;
        +            if ( (zzAttributes & 8) == 8 ) break zzForAction;
        +          }
        +
        +        }
        +      }
        +
        +      // store back cached position
        +      zzMarkedPos = zzMarkedPosL;
        +
        +      switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) {
        +        case 1: 
        +          { return token(TokenType.ERROR);
        +          }
        +        case 22: break;
        +        case 2: 
        +          { 
        +          }
        +        case 23: break;
        +        case 3: 
        +          { return token(TokenType.OPERATOR);
        +          }
        +        case 24: break;
        +        case 4: 
        +          { return token(TokenType.IDENTIFIER);
        +          }
        +        case 25: break;
        +        case 5: 
        +          { return token(TokenType.NUMBER);
        +          }
        +        case 26: break;
        +        case 6: 
        +          { return token(TokenType.KEYWORD2);
        +          }
        +        case 27: break;
        +        case 7: 
        +          { return token(TokenType.OPERATOR,  PARAN);
        +          }
        +        case 28: break;
        +        case 8: 
        +          { return token(TokenType.OPERATOR, -PARAN);
        +          }
        +        case 29: break;
        +        case 9: 
        +          { return token(TokenType.OPERATOR,  BRACKET);
        +          }
        +        case 30: break;
        +        case 10: 
        +          { return token(TokenType.OPERATOR, -BRACKET);
        +          }
        +        case 31: break;
        +        case 11: 
        +          { yybegin(STRING);
        +                                    tokenStart = yychar;
        +                                    tokenLength = 1;
        +          }
        +        case 32: break;
        +        case 12: 
        +          { return token(TokenType.COMMENT);
        +          }
        +        case 33: break;
        +        case 13: 
        +          { return token(TokenType.TYPE2);
        +          }
        +        case 34: break;
        +        case 14: 
        +          { return token(TokenType.KEYWORD2,  WORD);
        +          }
        +        case 35: break;
        +        case 15: 
        +          { return token(TokenType.STRING);
        +          }
        +        case 36: break;
        +        case 16: 
        +          { return token(TokenType.KEYWORD);
        +          }
        +        case 37: break;
        +        case 17: 
        +          { yybegin(ML_STRING);
        +                                    tokenStart = yychar;
        +                                    tokenLength = 3;
        +          }
        +        case 38: break;
        +        case 18: 
        +          { return token(TokenType.TYPE);
        +          }
        +        case 39: break;
        +        case 19: 
        +          { return token(TokenType.KEYWORD2, -WORD);
        +          }
        +        case 40: break;
        +        case 20: 
        +          { return token(TokenType.KEYWORD, WORD);
        +          }
        +        case 41: break;
        +        case 21: 
        +          { return token(TokenType.KEYWORD, -WORD);
        +          }
        +        case 42: break;
        +        default: 
        +          if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
        +            zzAtEOF = true;
        +              {
        +                return null;
        +              }
        +          } 
        +          else {
        +            zzScanError(ZZ_NO_MATCH);
        +          }
        +      }
        +    }
        +  }
        +
        +
        +}
        diff --git a/src/com/editor/flex/Portugol_v2.flex b/src/com/editor/flex/Portugol_v2.flex
        new file mode 100644
        index 0000000..d824ca5
        --- /dev/null
        +++ b/src/com/editor/flex/Portugol_v2.flex
        @@ -0,0 +1,230 @@
        +package com.editor.flex;
        +
        +
        +import jsyntaxpane.Token;
        +import jsyntaxpane.TokenType;
        +import jsyntaxpane.lexers.DefaultJFlexLexer;
        +
        +
        +%%
        +
        +%public
        +%class PortugolFlex
        +%extends DefaultJFlexLexer
        +%final
        +%unicode
        +%char
        +%type Token
        +
        +/*%caseless*/
        +/*%ignorecase*/
        +
        +%{
        +    /**
        +     * Create an empty lexer, yyrset will be called later to reset and assign
        +     * the reader
        +     */
        +    public PortugolFlex() {
        +        super();
        +    }
        +
        +    @Override
        +    public int yychar() {
        +        return yychar;
        +    }
        +
        +    private static final byte PARAN     = 1;
        +    private static final byte BRACKET   = 2;
        +    private static final byte CURLY     = 3;
        +    private static final byte WORD      = 4;
        +
        +%}
        +
        +/* main character classes */
        +LineTerminator = \r|\n|\r\n
        +InputCharacter = [^\r\n]
        +
        +WhiteSpace = {LineTerminator} | [ \t\f]+
        +
        +/* comments */
        +Comment = {TraditionalComment} | {EndOfLineComment} 
        +
        +TraditionalComment = "/*" [^*] ~"*/" | "/*" "*"+ "/"
        +EndOfLineComment = "//" {InputCharacter}* {LineTerminator}?
        +
        +/* identifiers */
        +Identifier = [a-zA-Z][a-zA-Z0-9_]*
        +
        +/* integer literals */
        +DecIntegerLiteral = 0 | [1-9][0-9]*
        +DecLongLiteral    = {DecIntegerLiteral} [lL]
        +
        +HexIntegerLiteral = 0 [xX] 0* {HexDigit} {1,8}
        +HexLongLiteral    = 0 [xX] 0* {HexDigit} {1,16} [lL]
        +HexDigit          = [0-9a-fA-F]
        +
        +OctIntegerLiteral = 0+ [1-3]? {OctDigit} {1,15}
        +OctLongLiteral    = 0+ 1? {OctDigit} {1,21} [lL]
        +OctDigit          = [0-7]
        +    
        +/* floating point literals */        
        +FloatLiteral  = ({FLit1}|{FLit2}|{FLit3}) {Exponent}? [fF]
        +DoubleLiteral = ({FLit1}|{FLit2}|{FLit3}) {Exponent}?
        +
        +FLit1    = [0-9]+ \. [0-9]* 
        +FLit2    = \. [0-9]+ 
        +FLit3    = [0-9]+ 
        +Exponent = [eE] [+-]? [0-9]+
        +
        +/* string and character literals */
        +StringCharacter = [^\r\n\"\\]
        +
        +%state STRING, ML_STRING
        +
        +%%
        +
        + {
        +  
        +  /* key principais */
        +  "algoritmo"                     |
        +  "var"                           { return token(TokenType.KEYWORD); }
        +  
        +
        +  "inicio"                        { return token(TokenType.KEYWORD, WORD); }
        +  "fimalgoritmo"                  { return token(TokenType.KEYWORD, -WORD); }
        +
        +
        +
        +
        +  /* keys secundarias */
        +  "leia"                          |
        +  "escreva"                       |
        +  "escreval"                      |
        +  "entao"                         |
        +  "vetor"                         |
        +  "de"                            |
        +  "ate"                           |
        +  "passo"                         |
        +  "e"                             |
        +  "ou"                            |
        +  "senao"                         |
        +  "caso"                          |
        +  "outrocaso"                     |
        +  "interrompa"                    |
        +  "funcao"                        |
        +  "fimfuncao"                     |
        +  "espere"                        |
        +  "faca"                          { return token(TokenType.KEYWORD2); }
        +
        +
        +  /* key secundarias com abertura de identacao */
        +  "enquanto"                     |
        +  "escolha"                      |
        +  "para"                         |
        +  "se"                           { return token(TokenType.KEYWORD2,  WORD); }
        +
        +  "fimenquanto"                   |
        +  "fimescolha"                    |
        +  "fimpara"                       |
        +  "fimse"                         { return token(TokenType.KEYWORD2, -WORD); }
        +
        +
        +  "string"                       |
        +  "inteiro"                      |
        +  "caracter"                     |
        +  "logico"                       |
        +  "real"                         {  return token(TokenType.TYPE);  }
        +
        +
        +  
        +  /* operators */
        +
        +  "("                            { return token(TokenType.OPERATOR,  PARAN); }
        +  ")"                            { return token(TokenType.OPERATOR, -PARAN); }
        +  /* "{"                            { return token(TokenType.OPERATOR,  CURLY); } */
        +  /* "}"                            { return token(TokenType.OPERATOR, -CURLY); } */
        +  "["                            { return token(TokenType.OPERATOR,  BRACKET); }
        +  "]"                            { return token(TokenType.OPERATOR, -BRACKET); }
        +  
        +
        +
        +  "+"                            |
        +  "-"                            |
        +  "*"                            |
        +  "/"                            |
        +  "mod"                          |
        +  "div"                          |
        +  "nao"                          |
        +  "pot"                          |
        +  "modulo"                       |
        +  "sen"                          |
        +  "cos"                          |
        +  "tan"                          |
        +  "raiz"                         |
        +  "PI"                           |
        +  "<"                            |
        +  ">"                            |
        +  "<="                           |
        +  ">="                           |
        +  "=="                           |
        +  "<>"                           |
        +  ","                            |
        +  ":"                            |
        +  ":="                           |
        +  "<-"                           |
        +  "="                            { return token(TokenType.OPERATOR); }
        +  
        +
        +  "verdadeiro"|
        +  "falso"     { return token(TokenType.NUMBER); }
        +
        +
        +  /* string literal */
        +  \"{3}                          {
        +                                    yybegin(ML_STRING);
        +                                    tokenStart = yychar;
        +                                    tokenLength = 3;
        +                                 }
        +
        +  \"                             {
        +                                    yybegin(STRING);
        +                                    tokenStart = yychar;
        +                                    tokenLength = 1;
        +                                 }
        +
        +
        +  /* numeric literals */
        +
        +  {DecIntegerLiteral}            |
        +  {DecLongLiteral}               |
        +  
        +  {HexIntegerLiteral}            |
        +  {HexLongLiteral}               |
        + 
        +  {OctIntegerLiteral}            |
        +  {OctLongLiteral}               |
        +
        +  {FloatLiteral}                 |
        +  {DoubleLiteral}                |
        +  {FloatLiteral}[jJ]             { return token(TokenType.NUMBER); }
        +  
        +  /* comments */
        +  {Comment}                      { return token(TokenType.COMMENT); }
        +
        +  /* whitespace */
        +  {WhiteSpace}                   { }
        +
        +
        +  /* identifiers */ 
        +  {Identifier}"?"                { return token(TokenType.TYPE2); }
        +  {Identifier}                   { return token(TokenType.IDENTIFIER); }
        +}
        +
        +  (\" ( [^\"\n\\] | \\[^\n] )* (\n | \\\n | \"))  { return token(TokenType.STRING); }
        +
        +  (\' ( [^\'\n\\] | \\[^\n] ){0,1} (\n | \\\n | \'))  { return token(TokenType.STRING); }
        +
        +/* error fallback */
        +\n                             {  }
        +.								{return token(TokenType.ERROR); }
        +<>                          { return null; }
        diff --git a/src/com/editor/identacao/Portugol.cup b/src/com/editor/identacao/Portugol.cup
        new file mode 100644
        index 0000000..ca8b541
        --- /dev/null
        +++ b/src/com/editor/identacao/Portugol.cup
        @@ -0,0 +1,34 @@
        +////////////////////////////////////////////////////////////////////////
        +/*                                                                  ////
        +* ANALIZADOR DE PORTUGOL (IDENTACAO).							    ////
        +* BY: ANDREW NETO                                                   ////
        +* 29/09/2014                                                        ////
        +*/                                                                  ////
        +////////////////////////////////////////////////////////////////////////
        +
        +package com.compilador.portugol;
        +
        +import java_cup.runtime.*;
        +
        +
        +terminal VAR;
        +
        +terminal INICIO,FIMALGORITMO;
        +
        +
        +terminal SE,SENAO,FIMSE;
        +terminal ENQUANTO,FIMENQUANTO,PARA,FIMPARA;
        +terminal ESCOLHA,CASO,OUTROCASO,FIMESCOLHA;
        +
        +terminal ALL;
        +
        +
        +
        +
        +non terminal identacao;
        +
        +
        +start with identacao;
        +
        +
        +identacao 	::= VAR
        \ No newline at end of file
        diff --git a/src/com/editor/identacao/Portugol.flex b/src/com/editor/identacao/Portugol.flex
        new file mode 100644
        index 0000000..1814ad4
        --- /dev/null
        +++ b/src/com/editor/identacao/Portugol.flex
        @@ -0,0 +1,72 @@
        +////////////////////////////////////////////////////////////////////////
        +/*                                                                  ////
        +* ANALIZADOR DE PORTUGOL (TOKENS).   							    ////
        +* BY: ANDREW NETO                                                   ////
        +* 05/07/2014                                                        ////
        +*/                                                                  ////
        +////////////////////////////////////////////////////////////////////////
        +
        +package com.compilador.portugol;
        +
        +import java_cup.runtime.*;
        +
        +
        +%%
        +%class PortugolFlex
        +%cup
        +%line
        +%char
        +%column
        +
        +
        +%{
        +
        +    public PortugolFlex() {
        +        super();
        +    }
        +
        +    Symbol newSym(int tokenId) {
        +        return new Symbol(tokenId , yyline, yycolumn);
        +    }
        +
        +    Symbol newSym(int tokenId, Object value) {
        +        return new Symbol(tokenId , yyline, yycolumn, value);
        +    }
        +
        +%}
        +
        +
        +newline         = \r|\n|\r\n
        +full            = .*
        +
        +
        +
        +%%
        +
        +
        +"var"						{return newSym(sym.VAR,yytext()); }
        +
        +"inicio"					{return newSym(sym.INICIO,yytext()); }
        +"fimalgoritmo"				{return newSym(sym.FIMALGORITMO,yytext()); }
        +
        +"se"						{return newSym(sym.SE,yytext()); }
        +"senao"						{return newSym(sym.SENAO,yytext()); }
        +"fimse"						{return newSym(sym.FIMSE,yytext()); }
        +
        +"enquanto"					{return newSym(sym.ENQUANTO,yytext()); }
        +"fimenquanto"				{return newSym(sym.FIMENQUANTO,yytext()); }
        +
        +"para"						{return newSym(sym.PARA,yytext()); }
        +"fimpara"					{return newSym(sym.FIMPARA,yytext()); }
        +
        +"escolha"					{return newSym(sym.ESCOLHA,yytext()); }
        +"caso"						{return newSym(sym.CASO,yytext()); }
        +"outrocaso"					{return newSym(sym.OUTROCASO,yytext()); }
        +"fimescolha"				{return newSym(sym.FIMESCOLHA,yytext()); }
        +
        +{newline}					{/* IGNORE */}
        +{whitespace}				{/* IGNORE */}
        +{full}                      {return newSym(sym.ALL,yytext()); }
        +
        +<>     				{return newSym(sym.EOF);}
        +.           				{return newSym(sym.error,yytext()); }
        \ No newline at end of file
        diff --git a/src/com/editor/syntax/PortugolSyntaxKit.java b/src/com/editor/syntax/PortugolSyntaxKit.java
        new file mode 100644
        index 0000000..ba1e77a
        --- /dev/null
        +++ b/src/com/editor/syntax/PortugolSyntaxKit.java
        @@ -0,0 +1,20 @@
        +/*
        + * To change this license header, choose License Headers in Project Properties.
        + * To change this template file, choose Tools | Templates
        + * and open the template in the editor.
        + */
        +
        +package com.editor.syntax;
        +
        +import com.editor.flex.PortugolFlex;
        +import de.sciss.syntaxpane.DefaultSyntaxKit;
        +
        +/**
        + *
        + * @author Andrew
        + */
        +public class PortugolSyntaxKit extends DefaultSyntaxKit {
        +    public PortugolSyntaxKit(){
        +        super(new PortugolFlex());
        +    }
        +}
        diff --git a/src/com/editor/syntax/propriedades/combocompletions.txt b/src/com/editor/syntax/propriedades/combocompletions.txt
        new file mode 100644
        index 0000000..e1ea522
        --- /dev/null
        +++ b/src/com/editor/syntax/propriedades/combocompletions.txt
        @@ -0,0 +1,14 @@
        +algoritmo
        +var
        +caracter
        +inteiro
        +real
        +vetor
        +logico
        +inicio
        +escreva
        +escreval
        +enquanto(condicional) faca\n\t//  \nfimenquanto
        +se(condicional) entao\n\t//  \nfimse
        +para variavel de indice1 ate indice2 faca\n\t//  \nfimpara
        +fimalgoritmo
        \ No newline at end of file
        diff --git a/src/com/editor/syntax/propriedades/config.properties b/src/com/editor/syntax/propriedades/config.properties
        new file mode 100644
        index 0000000..d6a71bd
        --- /dev/null
        +++ b/src/com/editor/syntax/propriedades/config.properties
        @@ -0,0 +1,119 @@
        +Components = de.sciss.syntaxpane.components.PairsMarker, \de.sciss.syntaxpane.components.LineNumbersRuler, \de.sciss.syntaxpane.components.TokenMarker
        +TokenMarker.TokenTypes = IDENTIFIER, TYPE
        +
        +
        +#SingleColorSelect = true
        +#RightMarginColumn = 80
        +#RightMarginColor = 0xdddddd
        +
        +DefaultFont = Monospaced 14
        +CaretColor = 0x000000
        +
        +#TokenMarker.Color = 0x646464
        +#PairMarker.Color = 0x0B0909
        +
        +
        +#LineNumbers.RightMargin = 7
        +#LineNumbers.Foreground = 0x999999
        +#LineNumbers.Background 0x272822
        +#LineNumbers.CurrentBack = 0x272822
        +LineNumbers.RightMargin = 10
        +LineNumbers.Foreground = 0x000000
        +LineNumbers.Background 0xf0f0f0
        +LineNumbers.CurrentBack = 0xFFFFFF
        +LineNumbers.YOFFset = -5
        +#Style.KEYWORD = 0x66d9ef, 0
        +#Style.KEYWORD2 = 0xf92672, 0
        +#Style.STRING = 0xe6db74, 0
        +#Style.COMMENT = 0x8f908a, 2
        +#Style.TYPE = 0xf92672, 0
        +#Style.NUMBER = 0xae81ff, 1
        +
        +#Style.DEFAULT = 0xFFFFFF, 0
        +#Style.IDENTIFIER = 0xFFFFFF, 0
        +#Style.OPERATOR = 0xFFFFFF, 0
        +
        +Style.OPERATOR = 0x000000, 1
        +Style.DELIMITER = 0x000000, 1
        +Style.KEYWORD = 0x000cff, 0
        +Style.KEYWORD2 = 0x000cff, 0
        +Style.TYPE = 0x399028, 1
        +Style.TYPE2 = 0x000000, 1
        +Style.TYPE3 = 0x000000, 3
        +Style.STRING = 0xb75c01, 0
        +Style.STRING2 = 0xb75c01, 1
        +Style.NUMBER = 0x7701b4, 1
        +Style.REGEX = 0xcc6600, 0
        +Style.IDENTIFIER = 0x000000, 0
        +Style.COMMENT = 0x339933, 2
        +Style.COMMENT2 = 0x339933, 3
        +Style.DEFAULT = 0x000000, 0
        +Style.WARNING = 0xCC0000, 0
        +Style.ERROR = 0xCC0000, 3
        +
        +
        +
        +
        +Action.indent.WordRegex=\\w+|\\/(\\*)+
        +
        +############# COMPLETE
        +Action.parenthesis = de.sciss.syntaxpane.actions.PairAction, typed (
        +Action.brackets = de.sciss.syntaxpane.actions.PairAction, typed [
        +Action.quotes = de.sciss.syntaxpane.actions.PairAction, typed '
        +Action.double-quotes = de.sciss.syntaxpane.actions.PairAction, typed "
        +
        +############# COMPLETE
        +Action.combo-completion = de.sciss.syntaxpane.actions.ComboCompletionAction, control SPACE
        +Action.combo-completion.MenuText = Completar
        +Action.combo-completion.ItemsURL=${class_path}/combocompletions.txt
        +
        +############# LISTAGEM DE SAIDA
        +Action.surround-debug = de.sciss.syntaxpane.actions.TemplateAction, control Q
        +Action.surround-debug.MenuText = Comando de saida
        +Action.surround-debug.ToolTip = Comando de saida escreval
        +Action.surround-debug.Template = escreval("O valor de #{selection} = " + (#{selection}))
        +
        +############# LISTAGEM DE CONDICIONAL
        +Action.surround-if = de.sciss.syntaxpane.actions.TemplateAction, control E
        +Action.surround-if.MenuText = Condicional
        +Action.surround-if.ToolTip = Express\u00f5es Conditional
        +Action.surround-if.Template = se(#{p:condition}) entao\n    #{selection}\nfimse
        +
        +############# LISTAGEM DE SE
        +Action.surround-while = de.sciss.syntaxpane.actions.TemplateAction, control R
        +Action.surround-while.MenuText = Enquanto loop
        +Action.surround-while.ToolTip = Selecao de loop enquanto
        +Action.surround-while.Template = enquanto(#{p:condition}) faca\n    #{selection}\nfimenquanto
        +
        +
        +#Action.undo = de.sciss.syntaxpane.actions.UndoAction, menu Z
        +#Action.undo.MenuText = Voltar
        +
        +#Action.redo = de.sciss.syntaxpane.actions.RedoAction, menu Y
        +#Action.redo.MenuText = Refazer
        +#JavaSyntaxKit.Action.TOGGLE_LINES = jsyntaxpane.actions.ToggleComponentAction, control F2
        +Action.find = de.sciss.syntaxpane.actions.FindReplaceAction, control F
        +
        +Action.indent.MenuText = Identar
        +
        +DefaultAction.select-all.MenuText = Selecionar tudo
        +DefaultAction.copy-to-clipboard.MenuText = Copiar
        +DefaultAction.cut-to-clipboard.MenuText = Recortar
        +DefaultAction.paste-from-clipboard.MenuText = Colar
        +DefaultAction.goto-line.MenuText = Ir para linha
        +DefaultAction.goto-line.ToolTip = Ir para linha
        +
        +TextAA = ON
        +
        +DEFAULT_EDIT_MENU= \
        +  cut-to-clipboard     , \
        +  copy-to-clipboard    , \
        +  paste-from-clipboard , \
        +  -                    , \
        +  select-all
        +PopupMenu = \
        +  ${DEFAULT_EDIT_MENU}
        +
        +
        +#GotoLineDialog.title=Ir para linha
        +#GotoLineDialog.jBtnOk.text=Ir
        \ No newline at end of file
        diff --git a/src/com/forms/Console.form b/src/com/forms/Console.form
        new file mode 100644
        index 0000000..68c8d0b
        --- /dev/null
        +++ b/src/com/forms/Console.form
        @@ -0,0 +1,104 @@
        +
        +
        +
        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        +
        + +
        +
        +
        +
        +
        +
        +
        + diff --git a/src/com/forms/Console.java b/src/com/forms/Console.java new file mode 100644 index 0000000..96fa947 --- /dev/null +++ b/src/com/forms/Console.java @@ -0,0 +1,179 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.forms; + +import bsh.EvalError; +import bsh.Interpreter; +import static com.forms.Editor.Threadcode; +import static com.forms.Editor.table_variaveis; +import static com.forms.Editor.util; +import static com.forms.Editor.ConsoleIO; +import com.system.ConsoleIO; +import com.system.TableVariables; +import java.awt.Image; +import java.awt.Toolkit; +import java.net.URL; +import javax.swing.JOptionPane; + +/** + * + * @author Andrew + */ +public class Console extends javax.swing.JDialog { + + + public Console() { + + URL urlicon = Editor.class.getClassLoader().getResource("com/images/pgeditor.png"); + Image icon = Toolkit.getDefaultToolkit().getImage(urlicon); + setIconImage(icon); + + initComponents(); + ConsoleIO = new ConsoleIO(console_txt); + table_variaveis = new TableVariables(jTableVariavel); + + execCode(); + } + + private void execCode() { + + //LISTAGEM DE VARIAVEIS + for (String[] Variavei : util.Variaveis) { + table_variaveis.add(Variavei[0], util.getTipoVariavelJavaToPt(Variavei[1]), null); + } + + //LISTAGEM DE VARIAVEIS DO TIPO VETOR + for (String[] Variavei : util.VariaveisVetor) { + for (int i = new Integer(Variavei[2]); i <= new Integer(Variavei[3]); i++) { + table_variaveis.add(Variavei[0] + "[" + i + "]", util.getTipoVariavelJavaToPt(Variavei[1]), null); + } + } + + Threadcode = new Thread(new Runnable() { + + @Override + public void run() { + + Thread.currentThread().setName("Thread - Interpretador"); + + long startTime = 0; + long endTime = 0; + boolean error = false; + Interpreter i = new Interpreter(); + System.out.println(util.code_exec[0] + util.code_exec[1] + util.code_exec[2]); + try { + startTime = System.currentTimeMillis(); + i.set("ConsoleIO", ConsoleIO); + i.set("table_variaveis", table_variaveis); + i.eval(util.code_exec[0] + util.code_exec[1] + util.code_exec[2]); + } catch (EvalError ex) { + JOptionPane.showMessageDialog(null, "Erro de syntax: Há algum erro critico de syntax no seu código. Linha:" + (ex.getErrorLineNumber() - 1), "Erro de syntax", JOptionPane.WARNING_MESSAGE); + error = true; + } finally { + endTime = System.currentTimeMillis(); + ConsoleIO.println(""); + ConsoleIO.println(""); + if (!error) { + ConsoleIO.print("Programa finalizado. Tempo de duração: " + (endTime - startTime) / 1000 + " segundos", util.AttrColor("codigo_finalizado")); + } else { + ConsoleIO.print("Programa finalizado. Tempo de duração: " + (endTime - startTime) / 1000 + " segundos", util.AttrColor("codigo_finalizado_error")); + } + ConsoleIO.finalizacao(); + + } + } + + }); + Threadcode.start(); + } + + public void close() { + ConsoleIO.interrupt(); + dispose(); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jSplitPane1 = new javax.swing.JSplitPane(); + jScrollPane1 = new javax.swing.JScrollPane(); + console_txt = new javax.swing.JTextPane(); + jScrollPane3 = new javax.swing.JScrollPane(); + jTableVariavel = new javax.swing.JTable(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); + setTitle("Console I/O"); + addWindowListener(new java.awt.event.WindowAdapter() { + public void windowClosing(java.awt.event.WindowEvent evt) { + closeWindow(evt); + } + }); + + jSplitPane1.setDividerLocation(600); + jSplitPane1.setResizeWeight(0.5); + + console_txt.setFont(new java.awt.Font("Monospaced", 0, 14)); // NOI18N + console_txt.setCursor(new java.awt.Cursor(java.awt.Cursor.TEXT_CURSOR)); + console_txt.setDisabledTextColor(new java.awt.Color(0, 0, 0)); + jScrollPane1.setViewportView(console_txt); + + jSplitPane1.setLeftComponent(jScrollPane1); + + jTableVariavel.setModel(new javax.swing.table.DefaultTableModel( + new Object [][] { + + }, + new String [] { + "Variável", "Tipo", "Valor" + } + ) { + boolean[] canEdit = new boolean [] { + false, false, false + }; + + public boolean isCellEditable(int rowIndex, int columnIndex) { + return canEdit [columnIndex]; + } + }); + jTableVariavel.setCellSelectionEnabled(true); + jScrollPane3.setViewportView(jTableVariavel); + + jSplitPane1.setRightComponent(jScrollPane3); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 877, Short.MAX_VALUE) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE) + ); + + pack(); + }// //GEN-END:initComponents + + private void closeWindow(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_closeWindow + // TODO add your handling code here: + close(); + }//GEN-LAST:event_closeWindow + + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JTextPane console_txt; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JScrollPane jScrollPane3; + private javax.swing.JSplitPane jSplitPane1; + private javax.swing.JTable jTableVariavel; + // End of variables declaration//GEN-END:variables +} diff --git a/src/com/forms/Editor.form b/src/com/forms/Editor.form new file mode 100644 index 0000000..73f711a --- /dev/null +++ b/src/com/forms/Editor.form @@ -0,0 +1,407 @@ + + +
        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/com/forms/Editor.java b/src/com/forms/Editor.java new file mode 100644 index 0000000..519d496 --- /dev/null +++ b/src/com/forms/Editor.java @@ -0,0 +1,929 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.forms; + +import com.classes.util.ExportPDF; +import com.classes.util.FilesOpens; +import com.classes.util.Menssage; +import com.classes.util.MenuSetting; +import com.classes.util.NewTab; +import com.classes.util.OpenFile; +import com.classes.util.SaveSaveAs; +import com.compilador.portugol.Compilador; +import com.compilador.portugol.ExecCompilador; +import com.editor.syntax.PortugolSyntaxKit; +import com.jidesoft.swing.JideTabbedPane; +import com.system.ConsoleIO; +import com.system.TableVariables; +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.actions.DocumentSearchData; +import de.sciss.syntaxpane.components.LineNumbersRuler; +import de.sciss.syntaxpane.util.Configuration; +import de.sciss.syntaxpane.util.JarServiceProvider; +import java.awt.AWTKeyStroke; +import java.awt.BorderLayout; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.DisplayMode; +import java.awt.GraphicsDevice; +import java.awt.GraphicsEnvironment; +import java.awt.Image; +import java.awt.KeyboardFocusManager; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.print.PrinterException; +import java.beans.PropertyChangeListener; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.nio.charset.Charset; +import java.util.HashSet; +import java.util.Properties; +import java.util.Set; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.Action; +import javax.swing.Box; +import javax.swing.InputMap; +import javax.swing.JComponent; +import javax.swing.JOptionPane; +import javax.swing.JTabbedPane; +import javax.swing.KeyStroke; +import javax.swing.UIManager; +import javax.swing.UnsupportedLookAndFeelException; +import javax.swing.event.ChangeEvent; +import javax.swing.event.ChangeListener; +import net.iharder.dnd.FileDrop; + +/** + * + * @author SIMONETO-2 + */ +public final class Editor extends javax.swing.JFrame { + + //PEGANDO AS DIMENSOES DA TELA + public static Dimension tela = Toolkit.getDefaultToolkit().getScreenSize(); + + //CLASS PARA ABRIR TABS + public static NewTab tab = null; + + //ORGANIZANDO DE ARQUIVOS + public static FilesOpens files_opens = null; + + //IMPORTE DE CONTROLE DOS MENUS + public static MenuSetting setting_menu = null; + + //ACOES PARA ABRIR ARQUIVOS + private static OpenFile _abrir = null; + + //VARIAVEL PARA CONTROLE DE MENUS ENABLEDS + public static boolean enabled_menu = false; + + //VARIAVEL RESPONSAVEL PELO HIDE/SHOW LINE NUMBER + public static boolean line_number = true; + + //VARIAVEL RESPONSAVEL PELA GRAVACAO DO DISPLAY + private DisplayMode dispModeOld = null; + + //VARIAVEL ESTATICA RESPONSAVEL PELA MESANGEM + public static Menssage msg = null; + + //########################################################################### + //# VARIAVEIS ESTATICAS RESPONSAVEIS PELO FUNCIONAMENTO DO INTERPRETADOR # + //########################################################################### + //VARIAVEL RESPONSAVEL POR CRIAR A CHAMADA DA CLASS COMPILADOR + public static Compilador util; + + //VARIAVEL TO THEREAD DE EXECUCAO DO INTERPRETADOR BSH + public static Thread Threadcode; + + //CRIA O STATIC DO CONSOLE_IO + public static ConsoleIO ConsoleIO; + + //CRIA O STATIC DO TABLE_VARIAVEIS + public static TableVariables table_variaveis; + + //########################################################################### + //########################################################################### + //########################################################################### + //ARQUIVO EXTERNO DE CONFIGURAÇÕES + public static File file_setting = new File(System.getProperty("user.dir") + "\\config.properties"); + + //PRIVATE VARIAVEL DE TABS + private JideTabbedPane jTab; + + //VARIAVEL DE OLA MUNDO + private final String algoritmo_dafault = "algoritmo \"Algoritmo - Olá mundo\"\n" + + "\n" + + "inicio\n" + + " escreval(\"Olá mundo\")\n" + + "fimalgoritmo"; + + public Editor() { + initComponents(); + + URL urlicon = Editor.class.getClassLoader().getResource("com/images/logo_icon.png"); + Image icon = Toolkit.getDefaultToolkit().getImage(urlicon); + setIconImage(icon); + + files_opens = new FilesOpens(); + + jTab = new JideTabbedPane(); + jTab.setShowCloseButton(true); + jTab.setShowCloseButtonOnTab(true); + jTab.setTabShape(JideTabbedPane.SHAPE_DEFAULT); + jTab.setColorTheme(JideTabbedPane.COLOR_THEME_WINXP); + + //AÇÃO DE FECHAMENTO DAS TABS + jTab.setCloseAction(new Action() { + + @Override + public Object getValue(String key) { + return null; + } + + @Override + public void putValue(String key, Object value) { + } + + @Override + public void setEnabled(boolean b) { + } + + @Override + public boolean isEnabled() { + return true; + } + + @Override + public void addPropertyChangeListener(PropertyChangeListener listener) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void removePropertyChangeListener(PropertyChangeListener listener) { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public void actionPerformed(ActionEvent e) { + Component b = (Component) e.getSource(); + int id = new Integer(b.getName()); + int index = files_opens.getPositionItem(id); + tab.unistallTab(id); + jTab.remove(index); + } + }); + + /*jTab.setTabHistoryEnabled(true); + jTab.setCloseButtonStrategy(CloseButtonStrategy.ALL_TABS); + jTab.setTabOverviewEnabled(false); + jTab.setPaintSelectedTabBold(true); + jTab.setTabReorderByDraggingEnabled(false); + + jTab.setTabStyle(JYTabbedPane.TabStyle.SELECTED_TAB_ONLY); + + jTab.getActionMap().put("closeTab", new Tab.CloseTabAction() { + @Override + public void actionPerformed(ActionEvent evt) { + AbstractButton closeButton = (AbstractButton) evt.getSource(); + Tab _tab = (Tab) closeButton.getParent().getParent(); + int tabIndex = _tab.getTabIndex(); + + String id = jTab.getComponentAt(tabIndex).getName(); + tab.unistallTab(new Integer(id)); + + System.out.println("Tab fechada com sucesso. ID:" + id); + super.actionPerformed(evt); + } + }); + */ + jTab.addChangeListener(new ChangeListener() { + @Override + public void stateChanged(ChangeEvent e) { + if (jTab.getTabCount() > 1) { + DefaultSyntaxKit kit = (DefaultSyntaxKit) tab.getEditorPane().getEditorKit(); + if (line_number) { + if (!kit.isComponentInstalled(tab.getEditorPane(), LineNumbersRuler.class.getName())) { + kit.installComponent(tab.getEditorPane(), LineNumbersRuler.class.getName()); + } + } else { + if (kit.isComponentInstalled(tab.getEditorPane(), LineNumbersRuler.class.getName())) { + kit.deinstallComponent(tab.getEditorPane(), LineNumbersRuler.class.getName()); + } + } + } + } + }); + + painelTab.setLayout(new BorderLayout()); + painelTab.add(jTab); + + DefaultSyntaxKit.registerContentType("text/portugol", PortugolSyntaxKit.class.getCanonicalName()); + + Configuration conf = DefaultSyntaxKit.getConfig(PortugolSyntaxKit.class); + + String url = "com/editor/syntax/propriedades/config"; + Properties p = JarServiceProvider.readProperties(url); + conf.putAll(p); + + if (file_setting.exists()) { + InputStream leitura = null; + try { + leitura = new FileInputStream(file_setting); + Properties prop = new Properties(); + prop.load(leitura); + conf.putAll(prop); + } catch (FileNotFoundException ex) { + Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex); + } catch (IOException ex) { + Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex); + } finally { + try { + leitura.close(); + } catch (IOException ex) { + Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex); + } + } + } + + tab = new NewTab(jTab); + setupTabTraversalKeys(jTab); + //setting_menu = new MenuSetting(jMenuBar); + + //JMenuItem2 (ABRIR ARQUIVO) + _abrir = new OpenFile(jMenuItem2); + //jMenuItem4 , jMenuItem3 SAVE E SAVE AS + SaveSaveAs _save = new SaveSaveAs(jMenuItem4, jMenuItem3); + //MENU DESABILITADO + //setting_menu.setDisabledTop(enabled_menu); + + //ABRE A PRIMEIRA TAB + tab.addTab("Olá mundo", "", algoritmo_dafault); + + //DRAG AND DROP DE ARQUIVOS + FileDrop dropScrollPane = new FileDrop(jTab, _drop); + FileDrop dropEditorPane = new FileDrop(tab.getEditorPane(), _drop); + + //INICIA AS MENSAGENS + msg = new Menssage(label_msg); + } + + FileDrop.Listener _drop = new FileDrop.Listener() { + @Override + public void filesDropped(java.io.File[] files) { + for (File file : files) { + String extensao = getFileExtension(file); + if (".alg".equals(extensao) || ".txt".equals(extensao)) { + if (!files_opens.isExistingOpen(file.getAbsoluteFile().toString())) { + try { + tab.addTab(file.getName(), file.getAbsoluteFile().toString(), _abrir.readFile(file.toString(), Charset.defaultCharset())); + tab.getEditorPane().setCaretPosition(0); + System.out.println("Arquivo " + file.getName() + " foi aberto com sucesso."); + } catch (IOException ex) { + Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex); + } + } else { + tab.setSelectedIndex(files_opens.getPositionItem(file.getAbsoluteFile().toString())); + } + } else { + JOptionPane.showMessageDialog(null, "Tipo de arquivo não suportado.", "Alerta", JOptionPane.WARNING_MESSAGE); + } + } + } + }; + + private String getFileExtension(File file) { + String name = file.getName(); + int lastIndexOf = name.lastIndexOf("."); + if (lastIndexOf == -1) { + return ""; // empty extension + } + return name.substring(lastIndexOf); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jPopupMenu_console = new javax.swing.JPopupMenu(); + jMenuItem21 = new javax.swing.JMenuItem(); + jMenuItem18 = new javax.swing.JMenuItem(); + painelTab = new javax.swing.JPanel(); + jSplitPane1 = new javax.swing.JSplitPane(); + linha_coluna_txt = new javax.swing.JLabel(); + label_msg = new javax.swing.JLabel(); + jMenuBar = new javax.swing.JMenuBar(); + jMenu1 = new javax.swing.JMenu(); + jMenuItem1 = new javax.swing.JMenuItem(); + jMenuItem2 = new javax.swing.JMenuItem(); + jSeparator1 = new javax.swing.JPopupMenu.Separator(); + jMenuItem4 = new javax.swing.JMenuItem(); + jMenuItem3 = new javax.swing.JMenuItem(); + jSeparator2 = new javax.swing.JPopupMenu.Separator(); + jMenu6 = new javax.swing.JMenu(); + jMenuItem15 = new javax.swing.JMenuItem(); + jSeparator7 = new javax.swing.JPopupMenu.Separator(); + jMenuItem6 = new javax.swing.JMenuItem(); + jSeparator3 = new javax.swing.JPopupMenu.Separator(); + jMenuItem5 = new javax.swing.JMenuItem(); + jMenu2 = new javax.swing.JMenu(); + jMenuItem7 = new javax.swing.JMenuItem(); + jMenuItem8 = new javax.swing.JMenuItem(); + jSeparator4 = new javax.swing.JPopupMenu.Separator(); + jMenuItem9 = new javax.swing.JMenuItem(); + jMenuItem10 = new javax.swing.JMenuItem(); + jMenuItem11 = new javax.swing.JMenuItem(); + jSeparator5 = new javax.swing.JPopupMenu.Separator(); + jMenuItem12 = new javax.swing.JMenuItem(); + jSeparator6 = new javax.swing.JPopupMenu.Separator(); + jMenuItem13 = new javax.swing.JMenuItem(); + jMenuItem14 = new javax.swing.JMenuItem(); + jMenu3 = new javax.swing.JMenu(); + jMenuItem16 = new javax.swing.JCheckBoxMenuItem(); + jCheckBoxMenuItem1 = new javax.swing.JCheckBoxMenuItem(); + jMenu4 = new javax.swing.JMenu(); + jMenuItem17 = new javax.swing.JMenuItem(); + jMenu7 = new javax.swing.JMenu(); + jMenuItem20 = new javax.swing.JMenuItem(); + jMenu5 = new javax.swing.JMenu(); + jMenuItem19 = new javax.swing.JMenuItem(); + jMenu8 = new javax.swing.JMenu(); + + jMenuItem21.setText("Limpar console"); + jMenuItem21.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + cleanConsole(evt); + } + }); + jPopupMenu_console.add(jMenuItem21); + + jMenuItem18.setText("jMenuItem18"); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + setTitle("Portugol Editor (v1.0.0) @alpha"); + setForeground(java.awt.Color.white); + + javax.swing.GroupLayout painelTabLayout = new javax.swing.GroupLayout(painelTab); + painelTab.setLayout(painelTabLayout); + painelTabLayout.setHorizontalGroup( + painelTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 740, Short.MAX_VALUE) + ); + painelTabLayout.setVerticalGroup( + painelTabLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 455, Short.MAX_VALUE) + ); + + jSplitPane1.setBorder(null); + jSplitPane1.setDividerSize(0); + jSplitPane1.setResizeWeight(0.5); + + linha_coluna_txt.setFont(new java.awt.Font("Arial", 0, 11)); // NOI18N + linha_coluna_txt.setText("-"); + jSplitPane1.setLeftComponent(linha_coluna_txt); + + label_msg.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT); + label_msg.setText("-"); + jSplitPane1.setRightComponent(label_msg); + + jMenu1.setText("Arquivo"); + + jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK)); + jMenuItem1.setText("Novo"); + jMenuItem1.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + NewProject(evt); + } + }); + jMenu1.add(jMenuItem1); + + jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK)); + jMenuItem2.setText("Abrir"); + jMenu1.add(jMenuItem2); + jMenu1.add(jSeparator1); + + jMenuItem4.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK)); + jMenuItem4.setText("Salvar"); + jMenu1.add(jMenuItem4); + + jMenuItem3.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK)); + jMenuItem3.setText("Salvar como"); + jMenu1.add(jMenuItem3); + jMenu1.add(jSeparator2); + + jMenu6.setText("Exportar como"); + + jMenuItem15.setText("PDF"); + jMenuItem15.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + ExportPDF(evt); + } + }); + jMenu6.add(jMenuItem15); + + jMenu1.add(jMenu6); + jMenu1.add(jSeparator7); + + jMenuItem6.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_P, java.awt.event.InputEvent.CTRL_MASK)); + jMenuItem6.setText("Imprimir"); + jMenuItem6.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + ImprirTab(evt); + } + }); + jMenu1.add(jMenuItem6); + jMenu1.add(jSeparator3); + + jMenuItem5.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F4, java.awt.event.InputEvent.ALT_MASK)); + jMenuItem5.setText("Fechar"); + jMenuItem5.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + fechar_program(evt); + } + }); + jMenu1.add(jMenuItem5); + + jMenuBar.add(jMenu1); + + jMenu2.setText("Editar"); + + jMenuItem7.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Z, java.awt.event.InputEvent.CTRL_MASK)); + jMenuItem7.setText("Desfazer"); + jMenuItem7.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + undoAction(evt); + } + }); + jMenu2.add(jMenuItem7); + + jMenuItem8.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Y, java.awt.event.InputEvent.CTRL_MASK)); + jMenuItem8.setText("Refazer"); + jMenuItem8.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + redoAction(evt); + } + }); + jMenu2.add(jMenuItem8); + jMenu2.add(jSeparator4); + + jMenuItem9.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_X, java.awt.event.InputEvent.CTRL_MASK)); + jMenuItem9.setText("Recortar"); + jMenuItem9.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + RecortarAction(evt); + } + }); + jMenu2.add(jMenuItem9); + + jMenuItem10.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.CTRL_MASK)); + jMenuItem10.setText("Copiar"); + jMenuItem10.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + CopiarAction(evt); + } + }); + jMenu2.add(jMenuItem10); + + jMenuItem11.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_V, java.awt.event.InputEvent.CTRL_MASK)); + jMenuItem11.setText("Colar"); + jMenuItem11.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + ColarAction(evt); + } + }); + jMenu2.add(jMenuItem11); + jMenu2.add(jSeparator5); + + jMenuItem12.setText("Aplicar identação"); + jMenuItem12.setEnabled(false); + jMenu2.add(jMenuItem12); + jMenu2.add(jSeparator6); + + jMenuItem13.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.CTRL_MASK)); + jMenuItem13.setText("Selecionar tudo"); + jMenuItem13.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + SelectAll(evt); + } + }); + jMenu2.add(jMenuItem13); + + jMenuItem14.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F, java.awt.event.InputEvent.CTRL_MASK)); + jMenuItem14.setText("Localizar e substituir"); + jMenuItem14.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + LocalizarESubstituir(evt); + } + }); + jMenu2.add(jMenuItem14); + + jMenuBar.add(jMenu2); + + jMenu3.setText("Exibir"); + + jMenuItem16.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F12, 0)); + jMenuItem16.setSelected(true); + jMenuItem16.setText("Numero de linhas"); + jMenuItem16.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + NumberLineAction(evt); + } + }); + jMenu3.add(jMenuItem16); + + jCheckBoxMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F11, 0)); + jCheckBoxMenuItem1.setText("Exibir em tela cheia"); + jCheckBoxMenuItem1.setEnabled(false); + jCheckBoxMenuItem1.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + toggleFullScreen(evt); + } + }); + jMenu3.add(jCheckBoxMenuItem1); + + jMenuBar.add(jMenu3); + + jMenu4.setText("Algoritmo"); + + jMenuItem17.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_F9, 0)); + jMenuItem17.setText("Executar"); + jMenuItem17.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + PlayToCode(evt); + } + }); + jMenu4.add(jMenuItem17); + + jMenuBar.add(jMenu4); + + jMenu7.setText("Ferramentas"); + + jMenuItem20.setText("Opções"); + jMenuItem20.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + showOpcoes(evt); + } + }); + jMenu7.add(jMenuItem20); + + jMenuBar.add(jMenu7); + + jMenu5.setText("Ajuda"); + + jMenuItem19.setText("Sobre"); + jMenuItem19.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + sobre(evt); + } + }); + jMenu5.add(jMenuItem19); + + jMenuBar.add(jMenu5); + + jMenu8.setText("Relatar bug"); + jMenu8.addMouseListener(new java.awt.event.MouseAdapter() { + public void mouseClicked(java.awt.event.MouseEvent evt) { + relatarBug(evt); + } + }); + + jMenuBar.add(Box.createHorizontalGlue()); + + jMenuBar.add(jMenu8); + + setJMenuBar(jMenuBar); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(painelTab, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addContainerGap() + .addComponent(jSplitPane1) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addComponent(painelTab, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jSplitPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap()) + ); + + pack(); + }// //GEN-END:initComponents + + private void NewProject(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NewProject + /* NEW PROJECT */ + String print_name = (tab.tabs_criadas != 0) ? "" + tab.tabs_criadas : ""; + tab.addTab("semnome" + print_name, "", algoritmo_dafault); + }//GEN-LAST:event_NewProject + + private void fechar_program(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fechar_program + // TODO add your handling code here: + System.exit(0); + }//GEN-LAST:event_fechar_program + + private void ImprirTab(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ImprirTab + // TODO add your handling code here: + boolean done; + try { + done = tab.getEditorPane().print(); + } catch (PrinterException ex) { + Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex); + } + }//GEN-LAST:event_ImprirTab + + private void ExportPDF(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ExportPDF + ExportPDF e = new ExportPDF(jMenuItem15); + }//GEN-LAST:event_ExportPDF + + private void undoAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_undoAction + // TODO add your handling code here: + de.sciss.syntaxpane.SyntaxDocument t = ((de.sciss.syntaxpane.SyntaxDocument) tab.getEditorPane().getDocument()); + if (t.canUndo()) { + t.doUndo(); + } + //jMenuItem7.setEnabled(t.canUndo()); + }//GEN-LAST:event_undoAction + + private void redoAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_redoAction + // TODO add your handling code here: + de.sciss.syntaxpane.SyntaxDocument t = ((de.sciss.syntaxpane.SyntaxDocument) tab.getEditorPane().getDocument()); + if (t.canRedo()) { + t.doRedo(); + } + //jMenuItem8.setEnabled(t.canUndo()); + }//GEN-LAST:event_redoAction + + private void RecortarAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RecortarAction + // TODO add your handling code here: + tab.getEditorPane().cut(); + }//GEN-LAST:event_RecortarAction + + private void CopiarAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CopiarAction + // TODO add your handling code here: + tab.getEditorPane().copy(); + }//GEN-LAST:event_CopiarAction + + private void ColarAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ColarAction + // TODO add your handling code here: + tab.getEditorPane().paste(); + }//GEN-LAST:event_ColarAction + + private void SelectAll(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SelectAll + // TODO add your handling code here: + tab.getEditorPane().selectAll(); + }//GEN-LAST:event_SelectAll + + private void LocalizarESubstituir(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_LocalizarESubstituir + // TODO add your handling code here: + DocumentSearchData dsd = DocumentSearchData.getFromEditor(tab.getEditorPane()); + dsd.showReplaceDialog(tab.getEditorPane()); + }//GEN-LAST:event_LocalizarESubstituir + + private void cleanConsole(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cleanConsole + // TODO add your handling code here: + //jconsole.setText(null); + }//GEN-LAST:event_cleanConsole + + + private void NumberLineAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_NumberLineAction + // TODO add your handling code here: + DefaultSyntaxKit kit = (DefaultSyntaxKit) tab.getEditorPane().getEditorKit(); + boolean selected = jMenuItem16.getModel().isSelected(); + + if (selected) { + if (!kit.isComponentInstalled(tab.getEditorPane(), LineNumbersRuler.class.getName())) { + kit.installComponent(tab.getEditorPane(), LineNumbersRuler.class.getName()); + } + line_number = true; + } else { + if (kit.isComponentInstalled(tab.getEditorPane(), LineNumbersRuler.class.getName())) { + kit.deinstallComponent(tab.getEditorPane(), LineNumbersRuler.class.getName()); + } + line_number = false; + } + }//GEN-LAST:event_NumberLineAction + + private void PlayToCode(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_PlayToCode + // TODO add your handling code here: + ExecCompilador compilar = new ExecCompilador(); + }//GEN-LAST:event_PlayToCode + + private void sobre(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sobre + // TODO add your handling code here: + Sobre about = new Sobre(this, true); + about.setLocation((tela.width - about.getSize().width) / 2, (tela.height - about.getSize().height) / 2); + about.setVisible(true); + }//GEN-LAST:event_sobre + + + private void showOpcoes(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showOpcoes + // TODO add your handling code here: + Opcoes setting = new Opcoes(this, true); + setting.setLocation((tela.width - setting.getSize().width) / 2, (tela.height - setting.getSize().height) / 2); + setting.setVisible(true); + }//GEN-LAST:event_showOpcoes + + private void toggleFullScreen(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_toggleFullScreen + // TODO add your handling code here: + boolean selected = jCheckBoxMenuItem1.getModel().isSelected(); + + if (selected) { + setFullscreen(true); + } else { + setFullscreen(false); + } + }//GEN-LAST:event_toggleFullScreen + + private void relatarBug(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_relatarBug + // TODO add your handling code here: + RelatarBug bug = new RelatarBug(this, true); + bug.setLocation((tela.width - bug.getSize().width) / 2, (tela.height - bug.getSize().height) / 2); + bug.setVisible(true); + }//GEN-LAST:event_relatarBug + + /** + * Method allows changing whether this window is displayed in fullscreen or + * windowed mode. + * + * @param fullscreen true = change to fullscreen, false = change to windowed + * http://stackoverflow.com/questions/4462454/java-full-screen-program-swing-tab-alt-f4 + */ + public void setFullscreen(boolean fullscreen) { + //get a reference to the device. + GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); + DisplayMode dispMode = device.getDisplayMode(); + //save the old display mode before changing it. + dispModeOld = device.getDisplayMode(); + + if (!fullscreen) { + //change to windowed mode. + //set the display mode back to the what it was when + //the program was launched. + device.setDisplayMode(dispModeOld); + //hide the frame so we can change it. + setVisible(false); + //remove the frame from being displayable. + dispose(); + //put the borders back on the frame. + setUndecorated(false); + //needed to unset this window as the fullscreen window. + device.setFullScreenWindow(null); + //recenter window + setLocationRelativeTo(null); + setResizable(true); + + //reset the display mode to what it was before + //we changed it. + setVisible(true); + + } else { //change to fullscreen. + //hide everything + setVisible(false); + //remove the frame from being displayable. + dispose(); + //remove borders around the frame + setUndecorated(true); + //make the window fullscreen. + device.setFullScreenWindow(this); + //attempt to change the screen resolution. + device.setDisplayMode(dispMode); + setResizable(false); + setAlwaysOnTop(false); + //show the frame + setVisible(true); + } + //make sure that the screen is refreshed. + repaint(); + } + + + /* + * CHANGE TABS COM O CTRL+TAB + */ + private static void setupTabTraversalKeys(JTabbedPane tabbedPane) { + KeyStroke ctrlTab = KeyStroke.getKeyStroke("ctrl TAB"); + KeyStroke ctrlShiftTab = KeyStroke.getKeyStroke("ctrl shift TAB"); + + // Remove ctrl-tab from normal focus traversal + Set forwardKeys = new HashSet<>(tabbedPane.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS)); + forwardKeys.remove(ctrlTab); + tabbedPane.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, forwardKeys); + + // Remove ctrl-shift-tab from normal focus traversal + Set backwardKeys = new HashSet<>(tabbedPane.getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS)); + backwardKeys.remove(ctrlShiftTab); + tabbedPane.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, backwardKeys); + + // Add keys to the tab's input map + InputMap inputMap = tabbedPane.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT); + inputMap.put(ctrlTab, "navigateNext"); + inputMap.put(ctrlShiftTab, "navigatePrevious"); + } + + public static void main(String arg[]) { + java.awt.EventQueue.invokeLater(new Runnable() { + @Override + public void run() { + + DefaultSyntaxKit.initKit(); + + //try { + //WebLookAndFeel.install(); + //if (System.getProperty("os.name").toLowerCase().contains("win")) { + //UIManager.put("Synthetica.window.decoration", Boolean.FALSE); + //} else { + // UIManager.put("Synthetica.window.decoration", Boolean.FALSE); + //} + //UIManager.put("Synthetica.focus.textComponents.enabled", Boolean.FALSE); + /*try { + UIManager.setLookAndFeel(new SyntheticaWhiteVisionLookAndFeel()); + } catch (ParseException | UnsupportedLookAndFeelException ex) { + Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex); + }*/ + /* UIManager.setLookAndFeel("org.pushingpixels.substance.api.skin.SubstanceNebulaLookAndFeel"); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { + Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex); + }*/ + try { + UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); + //LookAndFeelFactory.installJideExtension(LookAndFeelFactory.XERTO_STYLE); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { + Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex); + } + + //UIManager.put("Synthetica.window.opaque", false); + //UIManager.put("Synthetica.window.shape", ""); + Editor Editor = new Editor(); + Editor.setLocation((tela.width - Editor.getSize().width) / 2, (tela.height - Editor.getSize().height) / 2); + Editor.setExtendedState(Editor.MAXIMIZED_BOTH); + Editor.setVisible(true); + + } + }); + + } + + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JCheckBoxMenuItem jCheckBoxMenuItem1; + private javax.swing.JMenu jMenu1; + private javax.swing.JMenu jMenu2; + private javax.swing.JMenu jMenu3; + private javax.swing.JMenu jMenu4; + private javax.swing.JMenu jMenu5; + private javax.swing.JMenu jMenu6; + private javax.swing.JMenu jMenu7; + private javax.swing.JMenu jMenu8; + private javax.swing.JMenuBar jMenuBar; + private javax.swing.JMenuItem jMenuItem1; + private javax.swing.JMenuItem jMenuItem10; + private javax.swing.JMenuItem jMenuItem11; + private javax.swing.JMenuItem jMenuItem12; + private javax.swing.JMenuItem jMenuItem13; + private javax.swing.JMenuItem jMenuItem14; + private javax.swing.JMenuItem jMenuItem15; + private javax.swing.JCheckBoxMenuItem jMenuItem16; + private javax.swing.JMenuItem jMenuItem17; + private javax.swing.JMenuItem jMenuItem18; + private javax.swing.JMenuItem jMenuItem19; + private javax.swing.JMenuItem jMenuItem2; + private javax.swing.JMenuItem jMenuItem20; + private javax.swing.JMenuItem jMenuItem21; + private javax.swing.JMenuItem jMenuItem3; + private javax.swing.JMenuItem jMenuItem4; + private javax.swing.JMenuItem jMenuItem5; + private javax.swing.JMenuItem jMenuItem6; + private javax.swing.JMenuItem jMenuItem7; + private javax.swing.JMenuItem jMenuItem8; + private javax.swing.JMenuItem jMenuItem9; + private javax.swing.JPopupMenu jPopupMenu_console; + private javax.swing.JPopupMenu.Separator jSeparator1; + private javax.swing.JPopupMenu.Separator jSeparator2; + private javax.swing.JPopupMenu.Separator jSeparator3; + private javax.swing.JPopupMenu.Separator jSeparator4; + private javax.swing.JPopupMenu.Separator jSeparator5; + private javax.swing.JPopupMenu.Separator jSeparator6; + private javax.swing.JPopupMenu.Separator jSeparator7; + private javax.swing.JSplitPane jSplitPane1; + private javax.swing.JLabel label_msg; + public static javax.swing.JLabel linha_coluna_txt; + private javax.swing.JPanel painelTab; + // End of variables declaration//GEN-END:variables +} diff --git a/src/com/forms/LocalizarSubstituir.form b/src/com/forms/LocalizarSubstituir.form new file mode 100644 index 0000000..4e0e780 --- /dev/null +++ b/src/com/forms/LocalizarSubstituir.form @@ -0,0 +1,215 @@ + + +
        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        diff --git a/src/com/forms/LocalizarSubstituir.java b/src/com/forms/LocalizarSubstituir.java new file mode 100644 index 0000000..e553bba --- /dev/null +++ b/src/com/forms/LocalizarSubstituir.java @@ -0,0 +1,358 @@ +package com.forms; + +import static com.forms.Editor.tab; +import java.awt.HeadlessException; +import java.awt.Rectangle; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.swing.JOptionPane; +import javax.swing.text.BadLocationException; +import javax.swing.text.Document; + +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +/** + * + * @author SIMONETO-2 + */ +public class LocalizarSubstituir extends javax.swing.JFrame { + + private int pos = 0; + private int pos_reg = 0; + private String tmp_search = ""; + private boolean search = false; + private boolean replaceAllResult = true; + + /** + * Creates new form LocalizarSubstituir + */ + public LocalizarSubstituir() { + initComponents(); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jPanel1 = new javax.swing.JPanel(); + jLabel1 = new javax.swing.JLabel(); + jScrollPane1 = new javax.swing.JScrollPane(); + find_txt = new javax.swing.JTextArea(); + jLabel2 = new javax.swing.JLabel(); + jScrollPane2 = new javax.swing.JScrollPane(); + replace_txt = new javax.swing.JTextArea(); + btn_buscar = new javax.swing.JButton(); + btn_replace = new javax.swing.JButton(); + btn_replaceAll = new javax.swing.JButton(); + jLabel3 = new javax.swing.JLabel(); + jCheckBox1 = new javax.swing.JCheckBox(); + jCheckBox2 = new javax.swing.JCheckBox(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + setTitle("Localizar e substituir"); + setResizable(false); + + jLabel1.setText("Encontrar:"); + + find_txt.setColumns(20); + find_txt.setRows(2); + find_txt.addKeyListener(new java.awt.event.KeyAdapter() { + public void keyPressed(java.awt.event.KeyEvent evt) { + TabFocus1(evt); + } + }); + jScrollPane1.setViewportView(find_txt); + + jLabel2.setText("Substituir:"); + + replace_txt.setColumns(20); + replace_txt.setRows(2); + replace_txt.addKeyListener(new java.awt.event.KeyAdapter() { + public void keyPressed(java.awt.event.KeyEvent evt) { + TabFocus2(evt); + } + }); + jScrollPane2.setViewportView(replace_txt); + + btn_buscar.setText("Buscar"); + btn_buscar.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + FindAction(evt); + } + }); + + btn_replace.setText("Substituir"); + btn_replace.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + ReplaceAction(evt); + } + }); + + btn_replaceAll.setText("Substituir todos"); + btn_replaceAll.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + replaceAllAction(evt); + } + }); + + jLabel3.setText("Opções:"); + + jCheckBox1.setSelected(true); + jCheckBox1.setText("Usar expressão regular"); + + jCheckBox2.setText("Diferenciar maiuscula de minuscula"); + + javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); + jPanel1.setLayout(jPanel1Layout); + jPanel1Layout.setHorizontalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel1) + .addComponent(jLabel2) + .addComponent(jLabel3)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addComponent(jCheckBox2) + .addGap(0, 0, Short.MAX_VALUE)) + .addGroup(jPanel1Layout.createSequentialGroup() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addComponent(jCheckBox1) + .addGap(0, 0, Short.MAX_VALUE)) + .addGroup(jPanel1Layout.createSequentialGroup() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE) + .addComponent(jScrollPane2)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(btn_replaceAll, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE) + .addComponent(btn_replace, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(btn_buscar, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))) + .addContainerGap()))) + ); + jPanel1Layout.setVerticalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addGroup(jPanel1Layout.createSequentialGroup() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel1) + .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jLabel2))) + .addGroup(jPanel1Layout.createSequentialGroup() + .addComponent(btn_buscar) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(btn_replace) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(btn_replaceAll))) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jCheckBox1) + .addComponent(jLabel3)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jCheckBox2) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + pack(); + }// //GEN-END:initComponents + + private void TabFocus1(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_TabFocus1 + // TODO add your handling code here: + if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_TAB) { + replace_txt.requestFocus(); + evt.consume(); + } + }//GEN-LAST:event_TabFocus1 + + private void TabFocus2(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_TabFocus2 + // TODO add your handling code here: + if (evt.getKeyCode() == java.awt.event.KeyEvent.VK_TAB) { + btn_buscar.requestFocus(); + evt.consume(); + } + }//GEN-LAST:event_TabFocus2 + + private void FindAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_FindAction + // TODO add your handling code here: + find_text(find_txt.getText()); + }//GEN-LAST:event_FindAction + + private void ReplaceAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ReplaceAction + // TODO add your handling code here: + if (search == false) { + find_text(find_txt.getText()); + } + replace_text(replace_txt.getText()); + }//GEN-LAST:event_ReplaceAction + + private void replaceAllAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_replaceAllAction + // TODO add your handling code here: + while(replaceAllResult){ + if (search == false) { + find_text(find_txt.getText()); + } + replace_text(replace_txt.getText()); + } + }//GEN-LAST:event_replaceAllAction + + public void replace_text(String replace) { + if (replace != null && replace.length() > 0) { + if (search != false) { + System.out.println("[Sistema~] > Texto \"" + find_txt.getText() + "\" foi substituído por \"" + replace + "\"."); + tab.getEditorPane().replaceSelection(replace); + search = false; + } + } + } + + public void find_text(String find) { + + search = false; + + String texto = find; + + if (jCheckBox2.isSelected() == false) { + texto = texto.toLowerCase(); + } + + if (texto != null && texto.length() > 0) { + Document document = tab.getEditorPane().getDocument(); + int findLength = texto.length(); + + if (!tmp_search.equals(texto)) { + pos = 0; + tmp_search = ""; + } + + try { + boolean found = false; + // Rest the search position if we're at the end of the document + tmp_search = texto; + + if (!jCheckBox1.isSelected()) { + if (pos + findLength > document.getLength()) { + pos = 0; + } + // While we haven't reached the end... + // "<=" Correction + while (pos + findLength <= document.getLength()) { + // Extract the text from teh docuemnt + String match = null; + if (jCheckBox2.isSelected() == false) { + match = document.getText(pos, findLength).toLowerCase(); + + } else { + match = document.getText(pos, findLength); + } + + // Check to see if it matches or request + if (match.equals(texto)) { + found = true; + break; + } + pos++; + } + } else { + + String match = document.getText(0, document.getLength()); + + Pattern p = null; + if (!jCheckBox2.isSelected()) { + p = Pattern.compile(find, Pattern.CASE_INSENSITIVE); + } else { + p = Pattern.compile(find); + } + + Matcher m = p.matcher(match); + + int count = 0; + while (m.find()) { + count++; + } + + if (pos_reg >= count) { + pos = 0; + pos_reg = 0; + } + + if (m.find(pos)) { + pos = m.start(0); + findLength = m.group(0).length(); + pos_reg++; + found = true; + } + } + + // Did we find something... + if (found) { + // Get the rectangle of the where the text would be visible... + Rectangle viewRect = tab.getEditorPane().modelToView(pos); + // Scroll to make the rectangle visible + tab.getEditorPane().scrollRectToVisible(viewRect); + // Highlight the text + tab.getEditorPane().setCaretPosition(pos + findLength); + tab.getEditorPane().moveCaretPosition(pos); + // Move the search position beyond the current match + + pos += findLength; + + search = true; + } else { + //JOptionPane.showMessageDialog(null, "Nenhuma ocorrência foi encontrada", "Alerta", JOptionPane.WARNING_MESSAGE); + replaceAllResult = false; + } + + } catch (BadLocationException | HeadlessException exp) { + } + } + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton btn_buscar; + private javax.swing.JButton btn_replace; + private javax.swing.JButton btn_replaceAll; + private javax.swing.JTextArea find_txt; + private javax.swing.JCheckBox jCheckBox1; + private javax.swing.JCheckBox jCheckBox2; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel3; + private javax.swing.JPanel jPanel1; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JScrollPane jScrollPane2; + private javax.swing.JTextArea replace_txt; + // End of variables declaration//GEN-END:variables +} diff --git a/src/com/forms/Opcoes.form b/src/com/forms/Opcoes.form new file mode 100644 index 0000000..98e85d7 --- /dev/null +++ b/src/com/forms/Opcoes.form @@ -0,0 +1,296 @@ + + +
        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/com/forms/Opcoes.java b/src/com/forms/Opcoes.java new file mode 100644 index 0000000..2aa073b --- /dev/null +++ b/src/com/forms/Opcoes.java @@ -0,0 +1,817 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.forms; + +import com.classes.util.JFontChooser; +import com.editor.syntax.PortugolSyntaxKit; +import static com.forms.Editor.file_setting; +import static com.forms.Editor.tab; +import de.sciss.syntaxpane.DefaultSyntaxKit; +import de.sciss.syntaxpane.components.LineNumbersRuler; +import de.sciss.syntaxpane.util.Configuration; +import de.sciss.syntaxpane.util.JarServiceProvider; +import java.awt.Color; +import java.awt.Font; +import java.awt.event.ActionEvent; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintWriter; +import java.lang.reflect.Array; +import java.lang.reflect.Field; +import java.util.ArrayList; +import java.util.Properties; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.JColorChooser; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JSlider; +import javax.swing.JSpinner; +import javax.swing.colorchooser.AbstractColorChooserPanel; + +/** + * + * @author SIMONETO-2 + */ +public class Opcoes extends javax.swing.JDialog { + + //CRIANDO A CLASS PARA LEITURA DO KIT + private PortugolSyntaxKit kit = null; + + //ESTANCIANDO OS CHOOSER + private final JFontChooser fc = new JFontChooser(); + private final JColorChooser cc = new JColorChooser(); + + //ARRAY COM AS KEYS DE CORES + private final String key[] = {"Style.IDENTIFIER", "Style.KEYWORD", "Style.KEYWORD2", "Style.TYPE", "Style.STRING", "Style.NUMBER", "Style.OPERATOR"}; + + //ONDE SERA ARMAZENADO AS CONFIGURACOES JA PRE-CARREGADAS + private final ArrayList configuracoes_originais = new ArrayList<>(); + + //ONDE SERA ARMAZENADO AS CONFIGURACOES DA CLASSE INTERNA + private final ArrayList configuracoes_originais_internas = new ArrayList<>(); + + //CRIADO NO QUAL SERA ARMAZENADO AS MODIFICACOES + private final ArrayList modificacoes = new ArrayList<>(); + + //PARA A CONFIGURACAO DA FONTE + private Font fonte_padrao = null; + private boolean font_editada = false; + + //ALGORITMO DE EXEMPLO + private final String txt_amostra = "/*\n" + + "* ALGORITMO DE AMOSTRA\n" + + "*/\n" + + "algoritmo \"Loop - tipo enquanto\"\n" + + "\n" + + "var loop : inteiro\n" + + "\n" + + "inicio\n" + + " loop <- 1\n" + + " enquanto loop <= 10 faca\n" + + " escreval(loop)\n" + + " espere(1000)\n" + + " loop <- loop + 1\n" + + " fimenquanto\n" + + "fimalgoritmo"; + + /** + * Creates new form Opcoes + * + * @param parent + * @param modal + */ + public Opcoes(java.awt.Frame parent, boolean modal) { + super(parent, modal); + + initComponents(); + + //PEGANDO AS CONFIGURACOES DA CLASS INTERNA + String url = "com/editor/syntax/propriedades/config"; + Properties p = JarServiceProvider.readProperties(url); + for (String retorno : key) { + configuracoes_originais_internas.add(retorno.replaceAll("\\s+", "") + "," + p.getProperty(retorno).replaceAll("\\s+", "")); + } + + //SETANDO ESTILO DO EDITOR + editor_amostra.setContentType("text/portugol"); + + //PEGANDO OS ESTILOS PRE-CARREGADOS + kit = (PortugolSyntaxKit) editor_amostra.getEditorKit(); + kit.deinstallComponent(editor_amostra, LineNumbersRuler.class.getName()); + + //SETANDO O ALGORITMO DE EXEMPLO + editor_amostra.setText(txt_amostra); + + //LENDO CONFIGURACOES DO KIT + getDataKit(); + + /* + * FONT LOAD + */ + getDataFontKit(); + + //DANDO O REQUEST FOCUS NA LISTAGEM DE CORES PARA EVITAR O BUG DE SELECAO DE COLERES SEM A LISTAGEM ESTAR SELECIONADA + list_categoria.requestFocus(); + //SELECIONANDO O PRIMEIRO + list_categoria.setSelectedIndex(0); + } + + private void getDataKit() { + System.out.println("Configuracoes padrão:"); + int i = 0; + for (String retorno : key) { + configuracoes_originais.add(retorno.replaceAll("\\s+", "") + "," + kit.getProperty(retorno).replaceAll("\\s+", "")); + System.out.println("Indice (" + i + "): " + retorno + "," + kit.getProperty(retorno)); + i++; + } + } + + private void getDataFontKit() { + //PEGANDO AS CONFIGURACOES LIDAS + String font[] = kit.getProperty("DefaultFont").split("\\s"); + //SETANDO NO TEXTO DE FONTE + font_txt.setText(font[0] + ", " + font[1]); + //CRIANDO A FONTE + Font t = new Font(font[0], 0, new Integer(font[1])); + fonte_padrao = t; + //DEIXANDO A FONTE SELECIONADA NO CHOOSER + fc.setSelectedFont(t); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jTabbedPane1 = new javax.swing.JTabbedPane(); + jPanel2 = new javax.swing.JPanel(); + jLabel1 = new javax.swing.JLabel(); + font_txt = new javax.swing.JTextField(); + jButton2 = new javax.swing.JButton(); + jLabel2 = new javax.swing.JLabel(); + jScrollPane2 = new javax.swing.JScrollPane(); + list_categoria = new javax.swing.JList(); + btn_chooserColor = new javax.swing.JButton(); + panel_cor = new javax.swing.JPanel(); + jCheckBox1 = new javax.swing.JCheckBox(); + jCheckBox2 = new javax.swing.JCheckBox(); + jLabel3 = new javax.swing.JLabel(); + jScrollPane3 = new javax.swing.JScrollPane(); + editor_amostra = new javax.swing.JEditorPane(); + jButton3 = new javax.swing.JButton(); + btn_ok = new javax.swing.JButton(); + btn_aplicar = new javax.swing.JButton(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE); + setTitle("Opções"); + setResizable(false); + addWindowListener(new java.awt.event.WindowAdapter() { + public void windowClosing(java.awt.event.WindowEvent evt) { + windowsClosing(evt); + } + }); + + jLabel1.setText("Fonte do editor:"); + + font_txt.setDisabledTextColor(new java.awt.Color(51, 51, 51)); + font_txt.setEnabled(false); + + jButton2.setText("..."); + jButton2.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + openFontChooser(evt); + } + }); + + jLabel2.setText("Categoria:"); + + list_categoria.setModel(new javax.swing.AbstractListModel() { + String[] strings = { "Padrão", "Palavra-chave 1 (estrutural)", "Palavra-chave 2 (funções)", "Declaração de variáveis", "String e caracteres", "Numeros", "Operações" }; + public int getSize() { return strings.length; } + public Object getElementAt(int i) { return strings[i]; } + }); + list_categoria.addListSelectionListener(new javax.swing.event.ListSelectionListener() { + public void valueChanged(javax.swing.event.ListSelectionEvent evt) { + actionSelect(evt); + } + }); + jScrollPane2.setViewportView(list_categoria); + + btn_chooserColor.setText("Redefinir cor"); + btn_chooserColor.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + colorChooser(evt); + } + }); + + javax.swing.GroupLayout panel_corLayout = new javax.swing.GroupLayout(panel_cor); + panel_cor.setLayout(panel_corLayout); + panel_corLayout.setHorizontalGroup( + panel_corLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 172, Short.MAX_VALUE) + ); + panel_corLayout.setVerticalGroup( + panel_corLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGap(0, 0, Short.MAX_VALUE) + ); + + jCheckBox1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N + jCheckBox1.setText("Negrito"); + jCheckBox1.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + updateBold(evt); + } + }); + + jCheckBox2.setFont(new java.awt.Font("Tahoma", 2, 11)); // NOI18N + jCheckBox2.setText("Itáilico"); + jCheckBox2.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + updateItalic(evt); + } + }); + + jLabel3.setText("Amostra:"); + + editor_amostra.setEditable(false); + jScrollPane3.setViewportView(editor_amostra); + + jButton3.setText("Cancelar"); + jButton3.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + cancelAction(evt); + } + }); + + btn_ok.setText("Ok"); + btn_ok.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + brn_okAction(evt); + } + }); + + btn_aplicar.setText("Aplicar"); + btn_aplicar.setEnabled(false); + btn_aplicar.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + aplicarAcao(evt); + } + }); + + javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); + jPanel2.setLayout(jPanel2Layout); + jPanel2Layout.setHorizontalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jCheckBox2) + .addComponent(jCheckBox1) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) + .addGroup(jPanel2Layout.createSequentialGroup() + .addComponent(panel_cor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(btn_chooserColor)) + .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel2Layout.createSequentialGroup() + .addComponent(font_txt, javax.swing.GroupLayout.PREFERRED_SIZE, 220, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jButton2)) + .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING))) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addComponent(jLabel3) + .addGap(0, 0, Short.MAX_VALUE)) + .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE))) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() + .addGap(0, 0, Short.MAX_VALUE) + .addComponent(btn_ok) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(btn_aplicar) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jButton3))) + .addContainerGap()) + ); + jPanel2Layout.setVerticalGroup( + jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jLabel1) + .addComponent(jLabel3)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel2Layout.createSequentialGroup() + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(font_txt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addComponent(jButton2)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(jLabel2) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addComponent(btn_chooserColor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addComponent(panel_cor, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jCheckBox1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) + .addComponent(jCheckBox2) + .addGap(0, 20, Short.MAX_VALUE)) + .addComponent(jScrollPane3)) + .addGap(44, 44, 44)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) + .addComponent(jButton3) + .addComponent(btn_aplicar) + .addComponent(btn_ok)) + .addContainerGap()) + ); + + jTabbedPane1.addTab("Editor", jPanel2); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jTabbedPane1) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jTabbedPane1) + ); + + pack(); + }// //GEN-END:initComponents + + //ABRINDO O FONTE CHOOSER + private void openFontChooser(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openFontChooser + // TODO add your handling code here: + int result = fc.showDialog(null); + if (result == JFontChooser.OK_OPTION) { + Font font = fc.getSelectedFont(); + + font_txt.setText(font.getName() + ", " + font.getSize()); + kit.setProperty("DefaultFont", font.getName() + " " + font.getSize()); + editor_amostra.setFont(font); + System.out.println("Fonte alterada: " + fonte_padrao.getName() + " " + fonte_padrao.getSize() + " -> (" + font.getName() + " " + font.getSize() + ")"); + + if (!fonte_padrao.getName().equals(font.getName()) || fonte_padrao.getSize() != font.getSize()) { + font_editada = true; + } else { + font_editada = false; + } + } + //PARA ATUALIZAR O BOTAO DE APLICAR + checkBtnAplicar(); + }//GEN-LAST:event_openFontChooser + + //ABRINDO O COLOR CHOOSER + private void colorChooser(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_colorChooser + // TODO add your handling code here: + String tmp[] = formatPropertiesColors(kit.getProperty(key[list_categoria.getSelectedIndex()])); + Color color_tmp = Color.decode(tmp[0]); + + cc.setColor(color_tmp); + final AbstractColorChooserPanel[] panels = cc.getChooserPanels(); + for (final AbstractColorChooserPanel accp : panels) { + if (!accp.getDisplayName().equals("RGB")) { + cc.removeChooserPanel(accp); + } + } + + try { + removeTransparencySlider(cc); + } catch (Exception ex) { + Logger.getLogger(Opcoes.class.getName()).log(Level.SEVERE, null, ex); + } + + Action setColorAction = new AbstractAction() { + @Override + public void actionPerformed(ActionEvent evt) { + panel_cor.setOpaque(true); + panel_cor.setBackground(cc.getColor()); + updateProperties(key[list_categoria.getSelectedIndex()], "0x" + String.format("%06x", cc.getColor().getRGB() & 0x00FFFFFF), getCheckbox()); + } + }; + + JColorChooser.createDialog(null, "Redefinição de cor", true, cc, setColorAction, null).setVisible(true); + }//GEN-LAST:event_colorChooser + + //PINTANDO O PAINEL DA COR ESPECIFICA DA TOKEN + private void actionSelect(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_actionSelect + // TODO add your handling code here: + /* + * COLOR KEYS + */ + + String tmp[] = formatPropertiesColors(kit.getProperty(key[list_categoria.getSelectedIndex()])); + panel_cor.setOpaque(true); + Color color_tmp = Color.decode(tmp[0]); + panel_cor.setBackground(color_tmp); + + jCheckBox1.setSelected(false); + jCheckBox2.setSelected(false); + + switch (tmp[1]) { + case "1": + jCheckBox1.setSelected(true); + break; + case "2": + jCheckBox2.setSelected(true); + break; + case "3": + jCheckBox1.setSelected(true); + jCheckBox2.setSelected(true); + break; + } + }//GEN-LAST:event_actionSelect + + //UPDATE FONT AO CLICAR NO CHECKBOX + private void updateBold(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateBold + // TODO add your handling code here: + String color = formatPropertiesColors(kit.getProperty(key[list_categoria.getSelectedIndex()]))[0]; + updateProperties(key[list_categoria.getSelectedIndex()], color, getCheckbox()); + }//GEN-LAST:event_updateBold + + //UPDATE FONT AO CLICAR NO CHECKBOX + private void updateItalic(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateItalic + // TODO add your handling code here: + String color = formatPropertiesColors(kit.getProperty(key[list_categoria.getSelectedIndex()]))[0]; + updateProperties(key[list_categoria.getSelectedIndex()], color, getCheckbox()); + }//GEN-LAST:event_updateItalic + + //BOTAO DE CANCELAR AS ACOES + private void cancelAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelAction + // TODO add your handling code here: + closed(); + }//GEN-LAST:event_cancelAction + + //CLOSE WINDOWS + private void windowsClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_windowsClosing + // TODO add your handling code here: + closed(); + }//GEN-LAST:event_windowsClosing + + //ACAO DO BOTAO APLICAR + private void aplicarAcao(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aplicarAcao + // TODO add your handling code here: + aplicar(); + }//GEN-LAST:event_aplicarAcao + + //ACAO DO BOTAO OK + private void brn_okAction(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_brn_okAction + if(btn_aplicar.isEnabled()){ + aplicar(); + } + dispose(); + }//GEN-LAST:event_brn_okAction + + //PEGAR UM ESTILO JA MODIFICADO NA ARRAY + // FORMATO [KEY,COLOR,FONTSTYLE] + private String[] getConfiguracaoOriginal(String key) { + String r[] = null; + int i = 0; + if (!configuracoes_originais.isEmpty()) { + while (i < configuracoes_originais.size() && !configuracoes_originais.get(i).split(",")[0].equals(key)) { + i++; + } + r = configuracoes_originais.get(i).split(","); + } + return r; + } + + //FUNCAO RESPONSAVEL POR ATUALIZAR A ARRAY MODIFICACOES + private void updateProperties(String key, String color, String font) { + //PEGANDO A COR E O ESTILO DE FONTE E ARMAZENANDO NA ARRAY + String comparacao[] = getConfiguracaoOriginal(key); + + //FAZ O UPDATE NAS PROPRIEDADES + kit.setProperty(key, color + "," + font); + + //FAZ O UPDATE NA ARRAY MODIFICACOES + updateArrayModificacoes(key, color, font); + + System.out.println("Modifição em " + key + " : " + comparacao[1] + " , " + comparacao[2] + " -> (" + color + " , " + font + ")"); + editor_amostra.updateUI(); + editor_amostra.revalidate(); + editor_amostra.validate(); + + if (comparacao[1].equals(color) && comparacao[2].equals(font)) { + //VERIFICANDO SE A ARRAY NAO ESTA VAZIA + for (int i = 0; i < modificacoes.size(); i++) { + if (modificacoes.get(i).split(",")[0].equals(key)) { + modificacoes.remove(i); + break; + } + } + } + //PARA ATUALIZAR O BOTAO DE APLICAR + checkBtnAplicar(); + + } + + //RESPONSAVEL POR FORMATAR A SETRING E RETORNAR O VALOR SEPARADO + // FORMATO [COLOR,FONTSTYLE] + private String[] formatPropertiesColors(String key) { + String retorno[] = null; + String pattern = "(.*)\\,[ \\t]*(.*)"; + Pattern r = Pattern.compile(pattern); + Matcher m = r.matcher(key); + while (m.find()) { + String add[] = {m.group(1).replaceAll("\\s+", ""), m.group(2).replaceAll("\\s+", "")}; + retorno = add; + } + return retorno; + } + + //REPONSAVEL POR ATUALIZAR A ARRAY MODIFICACOES COMPARADO OS VALOR PRE EXISTENTES + private void updateArrayModificacoes(String key, String color, String font) { + if (!modificacoes.isEmpty()) { + int i = 0; + while (i < modificacoes.size() && !modificacoes.get(i).split(",")[0].equals(key)) { + i++; + } + if (i < modificacoes.size()) { + modificacoes.set(i, key + "," + color + "," + font); + } else { + modificacoes.add(key + "," + color + "," + font); + } + } else { + modificacoes.add(key + "," + color + "," + font); + } + } + + //VERIFICANDO OS CHECKBOX + private String getCheckbox() { + String r = null; + boolean strong = jCheckBox1.isSelected(); + boolean italic = jCheckBox2.isSelected(); + + if (strong && italic) { + r = "3"; + } else if (strong && !italic) { + r = "1"; + } else if (!strong && italic) { + r = "2"; + } else { + r = "0"; + } + return r; + } + + //ACAO PARA FECHAMENTO + private void closed() { + if (!modificacoes.isEmpty() || font_editada == true) { + int result = JOptionPane.showConfirmDialog(null, "Deseja salvar as configurações modificadas ?", "Alerta", JOptionPane.YES_NO_OPTION); + if (result == JOptionPane.YES_OPTION) { + aplicar(); + } else { + //RESETA AS CONFIGURACOES (PARTE INTERNA) + Configuration conf = DefaultSyntaxKit.getConfig(PortugolSyntaxKit.class); + String url = "com/editor/syntax/propriedades/config"; + Properties p = JarServiceProvider.readProperties(url); + conf.putAll(p); + + // INCLUI AS CONFIGURACOES (PARTE EXTERNA) + if (file_setting.exists()) { + InputStream leitura = null; + try { + leitura = new FileInputStream(file_setting); + Properties prop = new Properties(); + prop.load(leitura); + conf.putAll(prop); + } catch (FileNotFoundException ex) { + Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex); + } catch (IOException ex) { + Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex); + } finally { + try { + leitura.close(); + } catch (IOException ex) { + Logger.getLogger(Editor.class.getName()).log(Level.SEVERE, null, ex); + } + } + } + } + } + dispose(); + } + + //BRN APLICAR (SETAGEM DE ENABLE E DISABLE) + private void checkBtnAplicar() { + if (!modificacoes.isEmpty() || font_editada == true) { + btn_aplicar.setEnabled(true); + } else { + btn_aplicar.setEnabled(false); + } + } + + private void aplicar() { + ArrayList write = new ArrayList<>(); + + if (font_editada == true) { + write.add(kit.getProperty("DefaultFont")); + } + + if (!modificacoes.isEmpty()) { + boolean controlWrite = true; + for (String retorno : modificacoes) { + String tmp[] = retorno.split(","); + + //VERIFICANDO SE EXISTE NAS CONFIGURACOES ORIGINIAS INTERNAS + for (String original : configuracoes_originais_internas) { + String comparacao[] = original.split(","); + + if (comparacao[0].equals(tmp[0]) && comparacao[1].equals(tmp[1]) && comparacao[2].equals(tmp[2])) { + controlWrite = false; + break; + } else { + controlWrite = true; + } + } + + if (controlWrite) { + write.add(tmp[0] + "=" + tmp[1] + "," + tmp[2]); + } + } + } + + if (!file_setting.delete()) { + //APAGAR CONTEU DO ARQUIVO + PrintWriter clean = null; + try { + clean = new PrintWriter(file_setting); + clean.print(""); + + } catch (FileNotFoundException ex) { + Logger.getLogger(Opcoes.class.getName()).log(Level.SEVERE, null, ex); + } finally { + clean.close(); + } + } + + if (!write.isEmpty()) { + //PREPARA PARA SALVAR O ARQUIVO + PrintWriter print = null; + try { + print = new PrintWriter(file_setting); + + for (String line : write) { + print.println(line); + } + + } catch (FileNotFoundException ex) { + Logger.getLogger(Opcoes.class.getName()).log(Level.SEVERE, null, ex); + } finally { + print.close(); + } + } + + modificacoes.clear(); + configuracoes_originais.clear(); + + getDataKit(); + getDataFontKit(); + + font_editada = false; + btn_aplicar.setEnabled(false); + + //FAZ O UPDATE NO EDITOR + updateStyleText(); + + System.out.println("Modificações aplicadas com sucesso."); + } + + public void updateStyleText() { + for(int i = 0 ; i < tab.getTabCount();i++){ + tab.getJEditorPaneAt(i).updateUI(); + tab.getJEditorPaneAt(i).revalidate(); + tab.getJEditorPaneAt(i).validate(); + } + } + + //REMOVER ALGUMAS CONFIGURACOES DO COLOR CHOOSER + private static void removeTransparencySlider(JColorChooser jc) throws Exception { + + final AbstractColorChooserPanel[] colorPanels = jc.getChooserPanels(); + final AbstractColorChooserPanel cp = colorPanels[0]; + + Field f = null; + try { + f = cp.getClass().getDeclaredField("panel"); + } catch (NoSuchFieldException | SecurityException e) { + } + f.setAccessible(true); + + Object colorPanel = null; + try { + colorPanel = f.get(cp); + } catch (IllegalArgumentException | IllegalAccessException e) { + } + + Field f2 = null; + try { + f2 = colorPanel.getClass().getDeclaredField("spinners"); + } catch (NoSuchFieldException | SecurityException e4) { + } + f2.setAccessible(true); + Object rows = null; + try { + rows = f2.get(colorPanel); + } catch (IllegalArgumentException | IllegalAccessException e3) { + } + + final Object transpSlispinner = Array.get(rows, 3); + Field f3 = null; + try { + f3 = transpSlispinner.getClass().getDeclaredField("slider"); + } catch (NoSuchFieldException | SecurityException e) { + } + f3.setAccessible(true); + JSlider slider = null; + try { + slider = (JSlider) f3.get(transpSlispinner); + } catch (IllegalArgumentException | IllegalAccessException e2) { + } + slider.setVisible(false); + Field f4 = null; + try { + f4 = transpSlispinner.getClass().getDeclaredField("spinner"); + } catch (NoSuchFieldException | SecurityException e1) { + } + f4.setAccessible(true); + JSpinner spinner = null; + try { + spinner = (JSpinner) f4.get(transpSlispinner); + } catch (IllegalArgumentException | IllegalAccessException e) { + } + spinner.setVisible(false); + Field f5 = null; + try { + f5 = transpSlispinner.getClass().getDeclaredField("label"); + } catch (NoSuchFieldException | SecurityException e1) { + } + f5.setAccessible(true); + JLabel label = null; + try { + label = (JLabel) f5.get(transpSlispinner); + } catch (IllegalArgumentException | IllegalAccessException e) { + } + label.setVisible(false); + + Field f6 = null; + try { + f6 = transpSlispinner.getClass().getDeclaredField("value"); + } catch (NoSuchFieldException | SecurityException e1) { + } + f6.setAccessible(true); + float value = 0; + try { + value = (float) f6.get(transpSlispinner); + } catch (IllegalArgumentException | IllegalAccessException e) { + } + + } + + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JButton btn_aplicar; + private javax.swing.JButton btn_chooserColor; + private javax.swing.JButton btn_ok; + private javax.swing.JEditorPane editor_amostra; + private javax.swing.JTextField font_txt; + private javax.swing.JButton jButton2; + private javax.swing.JButton jButton3; + private javax.swing.JCheckBox jCheckBox1; + private javax.swing.JCheckBox jCheckBox2; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel3; + private javax.swing.JPanel jPanel2; + private javax.swing.JScrollPane jScrollPane2; + private javax.swing.JScrollPane jScrollPane3; + private javax.swing.JTabbedPane jTabbedPane1; + private javax.swing.JList list_categoria; + private javax.swing.JPanel panel_cor; + // End of variables declaration//GEN-END:variables +} diff --git a/src/com/forms/RelatarBug.form b/src/com/forms/RelatarBug.form new file mode 100644 index 0000000..b2c7c09 --- /dev/null +++ b/src/com/forms/RelatarBug.form @@ -0,0 +1,129 @@ + + +
        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        diff --git a/src/com/forms/RelatarBug.java b/src/com/forms/RelatarBug.java new file mode 100644 index 0000000..43936bc --- /dev/null +++ b/src/com/forms/RelatarBug.java @@ -0,0 +1,184 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.forms; + +import java.awt.Cursor; +import java.io.BufferedReader; +import java.io.DataOutputStream; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import javax.swing.JOptionPane; + +/** + * + * @author Andrew + */ +public class RelatarBug extends javax.swing.JDialog { + + private final String USER_AGENT = "Mozilla/5.0"; + + /** + * Creates new form RelatarBug + */ + public RelatarBug(java.awt.Frame parent, boolean modal) { + super(parent, modal); + initComponents(); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jPanel1 = new javax.swing.JPanel(); + jLabel1 = new javax.swing.JLabel(); + categoria = new javax.swing.JComboBox(); + jLabel2 = new javax.swing.JLabel(); + jScrollPane1 = new javax.swing.JScrollPane(); + detalhe_bug = new javax.swing.JTextPane(); + jButton1 = new javax.swing.JButton(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + setTitle("Relatar bug"); + setResizable(false); + + jLabel1.setText("Local de ocorrencia:"); + + categoria.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Editor", "Configurações do editor", "Menu de ações", "Interpretador", "Console", "Outros" })); + + jLabel2.setText("Detalhes do bug:"); + + jScrollPane1.setViewportView(detalhe_bug); + + jButton1.setText("Enviar"); + jButton1.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + sendPost(evt); + } + }); + + javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); + jPanel1.setLayout(jPanel1Layout); + jPanel1Layout.setHorizontalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING) + .addComponent(categoria, 0, 288, Short.MAX_VALUE) + .addGroup(jPanel1Layout.createSequentialGroup() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel1) + .addComponent(jLabel2)) + .addGap(0, 0, Short.MAX_VALUE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() + .addGap(0, 0, Short.MAX_VALUE) + .addComponent(jButton1))) + .addContainerGap()) + ); + jPanel1Layout.setVerticalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addComponent(jLabel1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(categoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jLabel2) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jButton1) + .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) + ); + + pack(); + }// //GEN-END:initComponents + + private void sendPost(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sendPost + int length = detalhe_bug.getDocument().getLength(); + if (length != 0) { + try { + sendPost(); + } catch (Exception ex) { + JOptionPane.showMessageDialog(null, "Houve algum problema na comunicação com o servidor.", "Alerta", JOptionPane.ERROR_MESSAGE); + } + } else { + JOptionPane.showMessageDialog(null, "Favor preencher o detalhe do bug que está acontecendo.", "Alerta", JOptionPane.WARNING_MESSAGE); + } + }//GEN-LAST:event_sendPost + +// HTTP POST request + private void sendPost() throws Exception { + setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + + String url = "http://pgeditor.com.br/Relatar-bug"; + URL obj = new URL(url); + HttpURLConnection con = (HttpURLConnection) obj.openConnection(); + + //add reuqest header + con.setRequestMethod("POST"); + con.setRequestProperty("User-Agent", USER_AGENT); + con.setRequestProperty("Accept-Language", "pt-BR,en;q=0.5"); + + String urlParameters = "categoria=" + categoria.getSelectedIndex() + "&detalhe=" + URLEncoder.encode(detalhe_bug.getText(), "UTF-8"); + + // Send post request + con.setDoOutput(true); + try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) { + wr.writeBytes(urlParameters); + wr.flush(); + } + + int responseCode = con.getResponseCode(); + System.out.println("\nSending 'POST' request to URL : " + url); + System.out.println("Post parameters : " + urlParameters); + System.out.println("Response Code : " + responseCode); + + StringBuilder response; + try (BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()))) { + String inputLine; + response = new StringBuilder(); + while ((inputLine = in.readLine()) != null) { + response.append(inputLine); + } + } + + //print result + JOptionPane.showMessageDialog(null, response.toString(), "Alerta", JOptionPane.WARNING_MESSAGE); + + categoria.setSelectedIndex(0); + detalhe_bug.setText(""); + setCursor(Cursor.getDefaultCursor()); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JComboBox categoria; + private javax.swing.JTextPane detalhe_bug; + private javax.swing.JButton jButton1; + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel2; + private javax.swing.JPanel jPanel1; + private javax.swing.JScrollPane jScrollPane1; + // End of variables declaration//GEN-END:variables +} diff --git a/src/com/forms/Sobre.form b/src/com/forms/Sobre.form new file mode 100644 index 0000000..b8435c1 --- /dev/null +++ b/src/com/forms/Sobre.form @@ -0,0 +1,159 @@ + + +
        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        diff --git a/src/com/forms/Sobre.java b/src/com/forms/Sobre.java new file mode 100644 index 0000000..3ff3b3b --- /dev/null +++ b/src/com/forms/Sobre.java @@ -0,0 +1,181 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.forms; + +import java.awt.Desktop; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * + * @author SIMONETO-2 + */ +public class Sobre extends javax.swing.JDialog { + + /** + * Creates new form Sobre + * + * @param parent + * @param modal + */ + public Sobre(java.awt.Frame parent, boolean modal) { + super(parent, modal); + initComponents(); + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jPanel1 = new javax.swing.JPanel(); + jLabel1 = new javax.swing.JLabel(); + jLabel2 = new javax.swing.JLabel(); + jLabel3 = new javax.swing.JLabel(); + jScrollPane1 = new javax.swing.JScrollPane(); + jTextPane1 = new javax.swing.JTextPane(); + jLabel4 = new javax.swing.JLabel(); + jLabel5 = new javax.swing.JLabel(); + + setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); + setTitle("Sobre"); + setResizable(false); + + jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/images/logo.png"))); // NOI18N + + jLabel2.setText("Portugol Editor (1.0.0) ALPHA"); + + jLabel3.setText("Desenvolvido por Andrew Neto"); + + jTextPane1.setEditable(false); + jTextPane1.setBackground(new java.awt.Color(240, 240, 240)); + jTextPane1.setText("Editor e interpretador de Portugol. Produzido com o intuito de facilitar e otimizar a introdução de novos programadores."); + jScrollPane1.setViewportView(jTextPane1); + + jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/images/facebook.png"))); // NOI18N + jLabel4.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); + jLabel4.addMouseListener(new java.awt.event.MouseAdapter() { + public void mouseReleased(java.awt.event.MouseEvent evt) { + openFacebook(evt); + } + }); + + jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/images/email.png"))); // NOI18N + jLabel5.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); + jLabel5.addMouseListener(new java.awt.event.MouseAdapter() { + public void mouseReleased(java.awt.event.MouseEvent evt) { + openMail(evt); + } + }); + + javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); + jPanel1.setLayout(jPanel1Layout); + jPanel1Layout.setHorizontalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addComponent(jLabel1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) + .addGroup(jPanel1Layout.createSequentialGroup() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel2) + .addComponent(jLabel3)) + .addGap(0, 37, Short.MAX_VALUE)) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup() + .addGap(0, 0, Short.MAX_VALUE) + .addComponent(jLabel4) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jLabel5))) + .addContainerGap()) + ); + jPanel1Layout.setVerticalGroup( + jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(jPanel1Layout.createSequentialGroup() + .addContainerGap() + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) + .addGroup(jPanel1Layout.createSequentialGroup() + .addComponent(jLabel2) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jScrollPane1) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jLabel3)) + .addComponent(jLabel1)) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jLabel5) + .addComponent(jLabel4)) + .addGap(0, 0, Short.MAX_VALUE)) + ); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() + .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) + .addContainerGap()) + ); + + pack(); + }// //GEN-END:initComponents + + private void openFacebook(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_openFacebook + try { + openWebpage(new URL("https://www.facebook.com/endroca")); + } catch (MalformedURLException ex) { + Logger.getLogger(Sobre.class.getName()).log(Level.SEVERE, null, ex); + } + }//GEN-LAST:event_openFacebook + + private void openMail(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_openMail + try { + openWebpage(new URL("http://andrewneto.com/contato")); + } catch (MalformedURLException ex) { + Logger.getLogger(Sobre.class.getName()).log(Level.SEVERE, null, ex); + } + }//GEN-LAST:event_openMail + public static void openWebpage(URI uri) { + Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null; + if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) { + try { + desktop.browse(uri); + } catch (Exception e) { + } + } + } + + public static void openWebpage(URL url) { + try { + openWebpage(url.toURI()); + } catch (URISyntaxException e) { + } + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JLabel jLabel1; + private javax.swing.JLabel jLabel2; + private javax.swing.JLabel jLabel3; + private javax.swing.JLabel jLabel4; + private javax.swing.JLabel jLabel5; + private javax.swing.JPanel jPanel1; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JTextPane jTextPane1; + // End of variables declaration//GEN-END:variables +} diff --git a/src/com/images/Thumbs.db b/src/com/images/Thumbs.db new file mode 100644 index 0000000..7a5e91c Binary files /dev/null and b/src/com/images/Thumbs.db differ diff --git a/src/com/images/email.png b/src/com/images/email.png new file mode 100644 index 0000000..c103b7d Binary files /dev/null and b/src/com/images/email.png differ diff --git a/src/com/images/facebook.png b/src/com/images/facebook.png new file mode 100644 index 0000000..c31accc Binary files /dev/null and b/src/com/images/facebook.png differ diff --git a/src/com/images/logo.png b/src/com/images/logo.png new file mode 100644 index 0000000..d008bad Binary files /dev/null and b/src/com/images/logo.png differ diff --git a/src/com/images/logo_editor.png b/src/com/images/logo_editor.png new file mode 100644 index 0000000..291d243 Binary files /dev/null and b/src/com/images/logo_editor.png differ diff --git a/src/com/images/logo_icon.png b/src/com/images/logo_icon.png new file mode 100644 index 0000000..2da323b Binary files /dev/null and b/src/com/images/logo_icon.png differ diff --git a/src/com/images/pgeditor.png b/src/com/images/pgeditor.png new file mode 100644 index 0000000..392bc7a Binary files /dev/null and b/src/com/images/pgeditor.png differ diff --git a/src/com/system/CaretConsole.java b/src/com/system/CaretConsole.java new file mode 100644 index 0000000..3ed929a --- /dev/null +++ b/src/com/system/CaretConsole.java @@ -0,0 +1,89 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.system; + +/** + * + * @author SIMONETO-2 + */ +// CornerCaret.java +// A custom caret class. +// +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Rectangle; +import java.awt.event.MouseEvent; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultCaret; +import javax.swing.text.JTextComponent; + +public class CaretConsole extends DefaultCaret { + + private JTextComponent comp; + + //private String mark = "<"; + public CaretConsole() { + setBlinkRate(500); + } + + @Override + protected synchronized void damage(Rectangle r) { + if (r == null) { + return; + } + + comp = getComponent(); + FontMetrics fm = comp.getFontMetrics(comp.getFont()); + int textWidth = fm.stringWidth(">"); + int textHeight = fm.getHeight(); + x = r.x; + y = r.y; + width = textWidth; + height = textHeight; + repaint(); // calls getComponent().repaint(x, y, width, height) + } + + @Override + public void paint(Graphics g) { + JTextComponent comp = getComponent(); + if (comp == null) { + return; + } + + int dot = getDot(); + Rectangle r = null; + try { + r = comp.modelToView(dot); + } catch (BadLocationException e) { + return; + } + if (r == null) { + return; + } + + if ((x != r.x) || (y != r.y)) { + repaint(); // erase previous location of caret + damage(r); + } + + if (isVisible()) { + g.setColor(comp.getCaretColor()); + g.fillRect(r.x, r.y, 8, r.height); + } + } + + @Override + public void mousePressed(MouseEvent evt) { + comp.requestFocus(); + evt.consume(); + } + + @Override + public void mouseDragged(MouseEvent e) { + e.consume(); + } + +} diff --git a/src/com/system/ConsoleIO.java b/src/com/system/ConsoleIO.java new file mode 100644 index 0000000..08cb090 --- /dev/null +++ b/src/com/system/ConsoleIO.java @@ -0,0 +1,311 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.system; + +import static com.forms.Editor.Threadcode; +import java.awt.Color; +import java.awt.Toolkit; +import java.awt.event.KeyEvent; +import static java.awt.event.KeyEvent.VK_BACK_SPACE; +import static java.awt.event.KeyEvent.VK_DOWN; +import static java.awt.event.KeyEvent.VK_LEFT; +import static java.awt.event.KeyEvent.VK_UP; +import java.awt.event.KeyListener; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.JTextPane; +import javax.swing.text.BadLocationException; +import javax.swing.text.Document; +import javax.swing.text.SimpleAttributeSet; + +/** + * + * @author SIMONETO-2 + */ +public class ConsoleIO implements KeyListener { + + private String retorno_string = ""; + private JTextPane console; + private Document doc; + + private boolean isInterrupt = false; + + private int caret_min_position = -1; + + private boolean key_enter = true; + private boolean block = true; + private boolean write = false; + private boolean write_tipo_int = false; + private boolean write_tipo_float = false; + private boolean write_tipo_char = false; + + public ConsoleIO(JTextPane console) { + this.console = console; + doc = this.console.getDocument(); + console.addKeyListener(this); + console.setCaretColor(Color.decode("#999999")); + console.setCaret(new CaretConsole()); + } + + private int textLength() { + return doc.getLength(); + } + + public void print(int position, Object t, SimpleAttributeSet style) { + try { + doc.insertString(position, "" + t, style); + console.setCaretPosition(textLength()); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + } + + public void print(Object t) { + print(textLength(), t, null); + } + + public void print(Object t, SimpleAttributeSet style) { + print(textLength(), t + "\n", style); + } + + public void println(Object t) { + print(textLength(), t + "\n", null); + } + + public void println(Object t, SimpleAttributeSet style) { + print(textLength(), t + "\n", style); + } + + public String writeString() { + + write(); + + lock(); + + try { + retorno_string = doc.getText(caret_min_position, textLength() - caret_min_position); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + + write = false; + print("\n"); + + return retorno_string; + } + + public int writeInt() { + + write(); + + write_tipo_int = true; + int retorno = 0; + + lock(); + + try { + retorno_string = doc.getText(caret_min_position, textLength() - caret_min_position); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + + retorno = new Integer(retorno_string); + + write = false; + write_tipo_int = false; + print("\n"); + + return retorno; + } + + public float writeFloat() { + + write(); + + write_tipo_float = true; + float retorno = 0; + + lock(); + + try { + retorno_string = doc.getText(caret_min_position, textLength() - caret_min_position); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + + retorno = new Float(retorno_string); + + write = false; + write_tipo_float = false; + print("\n"); + + return retorno; + } + + public char writeChar() { + + write(); + + write_tipo_char = true; + char retorno; + + lock(); + + try { + retorno_string = doc.getText(caret_min_position, textLength() - caret_min_position); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + + retorno = retorno_string.charAt(0); + + write = false; + write_tipo_char = false; + print("\n"); + + return retorno; + } + + private void write() { + write = true; + console.requestFocus(); + int tmp_length = textLength(); + console.setCaretPosition(tmp_length); + caret_min_position = tmp_length; + + } + + public void finalizacao() { + console.setCaretPosition(textLength()); + } + + public synchronized void lock() { + while (block) { + try { + wait(); + } catch (InterruptedException ex) { + //Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + //System.out.println("Error de interrupção::::"); + } + } + block = true; + interrupt_code(); + } + + public synchronized void unlock() { + block = false; + notify(); + } + + public synchronized void interrupt() { + if (write) { + isInterrupt = true; + unlock(); + } else { + isInterrupt = true; + interrupt_code(); + } + + } + + private void interrupt_code() { + if (isInterrupt) { + if (Threadcode.isAlive()) { + Threadcode.interrupt(); + } + } + } + + @Override + public void keyTyped(KeyEvent e) { + if (write) { + type(e); + } else { + e.consume(); + } + } + + @Override + public void keyPressed(KeyEvent e) { + if (write) { + type(e); + key_enter = false; + } else { + e.consume(); + } + } + + @Override + public void keyReleased(KeyEvent e) { + if (write) { + key_enter = true; + type(e); + } else { + e.consume(); + } + } + + private synchronized void type(KeyEvent e) { + switch (e.getKeyCode()) { + case (KeyEvent.VK_ENTER): + if (e.getID() == KeyEvent.KEY_PRESSED) { + if (key_enter) { + int r = 0; + try { + r = doc.getText(caret_min_position, textLength() - caret_min_position).length(); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + + if (r != 0) { + unlock(); + } + + e.consume(); + console.repaint(); + } + } + break; + case (VK_DOWN): + case (VK_UP): + break; + case (VK_LEFT): + case (VK_BACK_SPACE): + if (caret_min_position == console.getCaretPosition()) { + e.consume(); + Toolkit.getDefaultToolkit().beep(); + } + break; + default: + char key = e.getKeyChar(); + + if (write_tipo_int) { + String caracteres = "-0123456789"; + if (!caracteres.contains(key + "")) { + e.consume(); + } + } else if (write_tipo_float) { + String caracteres = "-0123456789."; + if (!caracteres.contains(key + "")) { + e.consume(); + } + } else if (write_tipo_char) { + int r = 0; + try { + r = doc.getText(caret_min_position, textLength() - caret_min_position).length(); + } catch (BadLocationException ex) { + Logger.getLogger(ConsoleIO.class.getName()).log(Level.SEVERE, null, ex); + } + + if (r > 0) { + e.consume(); + } + + } + break; + } + } +} diff --git a/src/com/system/LinePainter.java b/src/com/system/LinePainter.java new file mode 100644 index 0000000..ef34e91 --- /dev/null +++ b/src/com/system/LinePainter.java @@ -0,0 +1,124 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.system; + +/** + * + * @author SIMONETO-2 + */ +import java.awt.*; +import java.awt.event.*; +import javax.swing.*; +import javax.swing.event.*; +import javax.swing.text.*; +import de.sciss.syntaxpane.actions.ActionUtils; + +/* + * Track the movement of the Caret by painting a background line at the + * current caret position. + */ +public class LinePainter implements Highlighter.HighlightPainter { + + private JTextComponent component; + + private Color color; + + private Rectangle lastView; + + /* + * The line color will be calculated automatically by attempting + * to make the current selection lighter by a factor of 1.2. + * + * @param component text component that requires background line painting + */ + public LinePainter(JTextComponent component) { + this(component, null); + setLighter(component.getSelectionColor()); + } + + /* + * Manually control the line color + * + * @param component text component that requires background line painting + * @param color the color of the background line + */ + public LinePainter(JTextComponent component, Color color) { + this.component = component; + setColor(color); + + // Turn highlighting on by adding a dummy highlight + try { + component.getHighlighter().addHighlight(0, 0, this); + } catch (BadLocationException ble) { + } + } + + public void marker(int line) { + setLineNumber(line); + //resetHighlight(); + } + + public void setColor(Color color) { + this.color = color; + } + + public void setLighter(Color color) { + int red = Math.min(255, (int) (color.getRed() * 1.2)); + int green = Math.min(255, (int) (color.getGreen() * 1.2)); + int blue = Math.min(255, (int) (color.getBlue() * 1.2)); + setColor(new Color(red, green, blue)); + } + + private void setLineNumber(int line) { + Element map = component.getDocument().getDefaultRootElement(); + if (line < 0) { + } else if (line >= map.getElementCount()) { + } else { + Element lineElem = map.getElement(line); + component.setCaretPosition(lineElem.getStartOffset()); + } + } + + @Override + public void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent c) { + try { + Rectangle r = c.modelToView(c.getCaretPosition()); + g.setColor(color); + g.fillRect(0, r.y, c.getWidth(), r.height); + + if (lastView == null) { + lastView = r; + } + } catch (BadLocationException ble) { + System.out.println(ble); + } + } + + /* + * Caret position has changed, remove the highlight + */ + private void resetHighlight() { + // Use invokeLater to make sure updates to the Document are completed, + // otherwise Undo processing causes the modelToView method to loop. + + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + try { + int offset = component.getCaretPosition(); + Rectangle currentView = component.modelToView(offset); + + // Remove the highlighting from the previously highlighted line + if (lastView.y != currentView.y) { + component.repaint(0, lastView.y, component.getWidth(), lastView.height); + lastView = currentView; + } + } catch (BadLocationException ble) { + } + } + }); + } +} diff --git a/src/com/system/ResourceWaitQueue.java b/src/com/system/ResourceWaitQueue.java new file mode 100644 index 0000000..7204a61 --- /dev/null +++ b/src/com/system/ResourceWaitQueue.java @@ -0,0 +1,62 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.system; + +import java.util.concurrent.locks.Condition; +import java.util.concurrent.locks.ReentrantLock; +import java.util.logging.Level; +import java.util.logging.Logger; + + +public class ResourceWaitQueue { + + private final ReentrantLock lock = new ReentrantLock(true); // use a FIFO lock. + + private final Condition goodtogo = lock.newCondition(); + private int releasecount = 0; // how many threads should be released. + + public final void await() throws InterruptedException { + lock.lock(); + try { + while (releasecount == 0) { + goodtogo.await(); + } + // releasecount > 0 and we were signalled. + if (--releasecount > 0) { + // reduce the releasdecount, but there's still another + // thread that should be released. + goodtogo.signal(); + // when that other thread releases, if there's still more + // to be released, it can do that for us. + }; + } finally { + lock.unlock(); + } + } + + public final void release() { + lock.lock(); + try { + // indicate there is work to do + releasecount++; + // signal the condition is true.... (only signal, not signalAll()) + goodtogo.signal(); + } finally { + lock.unlock(); + } + } + + + public void interrupt(){ + try { + lock.lockInterruptibly(); + } catch (InterruptedException ex) { + Logger.getLogger(ResourceWaitQueue.class.getName()).log(Level.SEVERE, null, ex); + } + } + + +} \ No newline at end of file diff --git a/src/com/system/TableVariables.java b/src/com/system/TableVariables.java new file mode 100644 index 0000000..7faae98 --- /dev/null +++ b/src/com/system/TableVariables.java @@ -0,0 +1,38 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package com.system; + +import javax.swing.JTable; +import javax.swing.table.DefaultTableModel; + +/** + * + * @author SIMONETO-2 + */ +public class TableVariables { + + private JTable table = null; + private DefaultTableModel model; + + public TableVariables(JTable t) { + table = t; + model = (DefaultTableModel) table.getModel(); + } + + public void add(Object name, Object type, Object value) { + Object[] rowData = {name, type, value}; + model.addRow(rowData); + } + + public void update(Object name, Object value) { + for (int i = 0; i < model.getRowCount(); i++) { + if (model.getValueAt(i, 0).equals(name)) { + model.setValueAt(value, i, 2); + } + } + } + +} diff --git a/src/com/system/Teste.form b/src/com/system/Teste.form new file mode 100644 index 0000000..fd64ca9 --- /dev/null +++ b/src/com/system/Teste.form @@ -0,0 +1,72 @@ + + +
        + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
        diff --git a/src/com/system/Teste.java b/src/com/system/Teste.java new file mode 100644 index 0000000..a03eb6a --- /dev/null +++ b/src/com/system/Teste.java @@ -0,0 +1,135 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +package com.system; + +import java.awt.Rectangle; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.swing.text.BadLocationException; +import javax.swing.text.Utilities; + +/** + * + * @author SIMONETO-2 + */ +public class Teste extends javax.swing.JFrame { + LinePainter line_painter; + /** + * Creates new form Teste + */ + public Teste() { + initComponents(); + line_painter = new LinePainter(jEditorPane1); + + + + } + + /** + * This method is called from within the constructor to initialize the form. + * WARNING: Do NOT modify this code. The content of this method is always + * regenerated by the Form Editor. + */ + @SuppressWarnings("unchecked") + // //GEN-BEGIN:initComponents + private void initComponents() { + + jScrollPane1 = new javax.swing.JScrollPane(); + jEditorPane1 = new javax.swing.JEditorPane(); + jToggleButton1 = new javax.swing.JToggleButton(); + + setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); + + jEditorPane1.addKeyListener(new java.awt.event.KeyAdapter() { + public void keyPressed(java.awt.event.KeyEvent evt) { + teste(evt); + } + }); + jScrollPane1.setViewportView(jEditorPane1); + + jToggleButton1.setText("jToggleButton1"); + jToggleButton1.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent evt) { + jToggleButton1ActionPerformed(evt); + } + }); + + javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); + getContentPane().setLayout(layout); + layout.setHorizontalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 380, Short.MAX_VALUE) + .addComponent(jToggleButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) + .addContainerGap()) + ); + layout.setVerticalGroup( + layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) + .addGroup(layout.createSequentialGroup() + .addContainerGap() + .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 365, Short.MAX_VALUE) + .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) + .addComponent(jToggleButton1) + .addContainerGap()) + ); + + pack(); + }// //GEN-END:initComponents + + private void teste(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_teste + + + }//GEN-LAST:event_teste + + private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jToggleButton1ActionPerformed + // TODO add your handling code here: + line_painter.marker(3); + }//GEN-LAST:event_jToggleButton1ActionPerformed + + /** + * @param args the command line arguments + */ + public static void main(String args[]) { + /* Set the Nimbus look and feel */ + // + /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. + * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html + */ + try { + for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { + if ("Nimbus".equals(info.getName())) { + javax.swing.UIManager.setLookAndFeel(info.getClassName()); + break; + } + } + } catch (ClassNotFoundException ex) { + java.util.logging.Logger.getLogger(Teste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (InstantiationException ex) { + java.util.logging.Logger.getLogger(Teste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (IllegalAccessException ex) { + java.util.logging.Logger.getLogger(Teste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } catch (javax.swing.UnsupportedLookAndFeelException ex) { + java.util.logging.Logger.getLogger(Teste.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); + } + // + + /* Create and display the form */ + java.awt.EventQueue.invokeLater(new Runnable() { + public void run() { + new Teste().setVisible(true); + } + }); + } + + // Variables declaration - do not modify//GEN-BEGIN:variables + private javax.swing.JEditorPane jEditorPane1; + private javax.swing.JScrollPane jScrollPane1; + private javax.swing.JToggleButton jToggleButton1; + // End of variables declaration//GEN-END:variables +}