Syntax Highlighting and Undo Problem

Hello Guys. I am working ona very simple type of Java Code Editor with syntax highlighting feature. It works fine as far as the syntax highlighting, cut, copy, paste etc are concerned but when I added Undo, Redo feature, it was not working as Undo Redo should. The UndoManager first removes the text attributes and finally the main Undo job. For example if I paste word public , the UndoManager will first remove the attributes and after about third or fouth click on the Undo button removes the pasted word.
Please Help.

Here's the complete demo code.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.text.rtf.*;
import javax.swing.undo.*;
class ColorTextInTextPane extends JFrame implements UndoableEditListener
     private Hashtable keywords,impclasses;
     JEditorPane edit;
     UndoManager undo;
     JButton undoIt, redoIt;
     JPanel southButtonPanel;
     MyDocument doc = new MyDocument();
     public ColorTextInTextPane()
          super("ColorTextInTextPane");
          this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          edit = new JEditorPane();
          edit.setEditorKit(new StyledEditorKit());
          edit.setEditable(true);
          doc.addUndoableEditListener(this);
          edit.setDocument(doc);
          JScrollPane scroll=new JScrollPane(edit);
          undo = new UndoManager();
          undoIt = new JButton("Undo");
          undoIt.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent ae)
                undoAction(ae);
          redoIt = new JButton("Redo");
          redoIt.addActionListener(new ActionListener()
            public void actionPerformed(ActionEvent ae)
                redoAction(ae);
          southButtonPanel = new JPanel();
          southButtonPanel.add(undoIt);
          southButtonPanel.add(redoIt);
          getContentPane().add(scroll);
          getContentPane().add(southButtonPanel, BorderLayout.SOUTH);
          setSize(300,300);
          setVisible(true);
          Object dummyObject = new Object();
          keywords = new Hashtable();
          keywords.put( "abstract", dummyObject );
          keywords.put( "boolean", dummyObject );
          keywords.put( "break", dummyObject );
          keywords.put( "byte", dummyObject );
          keywords.put( "byvalue", dummyObject );
          keywords.put( "case", dummyObject );
          keywords.put( "cast", dummyObject );
          keywords.put( "catch", dummyObject );
          keywords.put( "char", dummyObject );
          keywords.put( "class", dummyObject );
          keywords.put( "const", dummyObject );
          keywords.put( "continue", dummyObject );
          keywords.put( "default", dummyObject );
          keywords.put( "do", dummyObject );
          keywords.put( "double", dummyObject );
          keywords.put( "else", dummyObject );
          keywords.put( "extends", dummyObject );
          keywords.put( "false", dummyObject );
          keywords.put( "final", dummyObject );
          keywords.put( "finally", dummyObject );
          keywords.put( "float", dummyObject );
          keywords.put( "for", dummyObject );
          keywords.put( "future", dummyObject );
          keywords.put( "generic", dummyObject );
          keywords.put( "goto", dummyObject );
          keywords.put( "if", dummyObject );
          keywords.put( "implements", dummyObject );
          keywords.put( "import", dummyObject );
          keywords.put( "inner", dummyObject );
          keywords.put( "instanceof", dummyObject );
          keywords.put( "int", dummyObject );
          keywords.put( "interface", dummyObject );
          keywords.put( "long", dummyObject );
          keywords.put( "native", dummyObject );
          keywords.put( "new", dummyObject );
          keywords.put( "null", dummyObject );
          keywords.put( "operator", dummyObject );
          keywords.put( "outer", dummyObject );
          keywords.put( "package", dummyObject );
          keywords.put( "private", dummyObject );
          keywords.put( "protected", dummyObject );
          keywords.put( "public", dummyObject );
          keywords.put( "rest", dummyObject );
          keywords.put( "return", dummyObject );
          keywords.put( "short", dummyObject );
          keywords.put( "static", dummyObject );
          keywords.put( "super", dummyObject );
          keywords.put( "switch", dummyObject );
          keywords.put( "synchronized", dummyObject );
          keywords.put( "this", dummyObject );
          keywords.put( "throw", dummyObject );
          keywords.put( "throws", dummyObject );
          keywords.put( "transient", dummyObject );
          keywords.put( "true", dummyObject );
          keywords.put( "try", dummyObject );
          keywords.put( "var", dummyObject );
          keywords.put( "void", dummyObject );
          keywords.put( "volatile", dummyObject );
          keywords.put( "while", dummyObject );
          Object dummyObject1 = new Object();
          impclasses = new Hashtable();
          impclasses.put( "JFrame", dummyObject1);
          impclasses.put( "Applet", dummyObject1);
                impclasses.put( "JApplet", dummyObject1);
                impclasses.put( "JTextField", dummyObject1);
                impclasses.put( "JLabel", dummyObject1);
                impclasses.put( "JPanel", dummyObject1);
                impclasses.put( "JButton", dummyObject1);
     public void undoableEditHappened(UndoableEditEvent ev) {
    undo.addEdit(ev.getEdit());
    updateMenu();
  void undoAction(ActionEvent e) {
    try {
      if (undo.canUndo())
        undo.undo();
      updateMenu();
    catch (CannotRedoException cre) {
  void redoAction(ActionEvent e)
    try {
      if (undo.canRedo())
        undo.redo();
      updateMenu();
    catch (CannotRedoException cre) {
  public void updateMenu()
    undoIt.setEnabled(undo.canUndo());
    redoIt.setEnabled(undo.canRedo());
     public static void main(String a[])
          new ColorTextInTextPane();
     class MyDocument extends DefaultStyledDocument
          DefaultStyledDocument doc;
          MutableAttributeSet normal;
          MutableAttributeSet keyword;
          MutableAttributeSet comment;
          MutableAttributeSet quote;
          MutableAttributeSet impclasses1;
          public MyDocument()
               doc = this;
               putProperty( DefaultEditorKit.EndOfLineStringProperty, "\n" );
               normal = new SimpleAttributeSet();
               StyleConstants.setForeground(normal, Color.black);
               comment = new SimpleAttributeSet();
               StyleConstants.setForeground(comment, Color.green);
               StyleConstants.setItalic(comment, true);
               keyword = new SimpleAttributeSet();
               StyleConstants.setForeground(keyword, Color.blue);
               StyleConstants.setBold(keyword, true);
               quote = new SimpleAttributeSet();
               StyleConstants.setForeground(quote, Color.red);
               StyleConstants.setBold(quote, true);
               impclasses1 = new SimpleAttributeSet();
               StyleConstants.setForeground(impclasses1, Color.magenta);
               StyleConstants.setBold(impclasses1, true);
          public void insertString(int offset, String str, AttributeSet a) throws BadLocationException
               super.insertString(offset, str, a);
               processChangedLines(offset, str.length());
          public void remove(int offset, int length) throws BadLocationException
               super.remove(offset, length);
               processChangedLines(offset, 0);
          public void processChangedLines(int offset, int length) throws BadLocationException
               String content = doc.getText(0, doc.getLength());
               Element root = doc.getDefaultRootElement();
               int startLine = root.getElementIndex( offset );
               int endLine = root.getElementIndex( offset + length );
               for (int i = startLine; i <= endLine; i++)
                    int startOffset = root.getElement( i ).getStartOffset();
                    int endOffset = root.getElement( i ).getEndOffset();
                    applyHighlighting(content, startOffset, endOffset - 1);
          public void applyHighlighting(String content, int startOffset, int endOffset)
               throws BadLocationException
               int index;
               int lineLength = endOffset - startOffset;
               int contentLength = content.length();
               if (endOffset >= contentLength)
                    endOffset = contentLength - 1;
               //  set normal attributes for the line
               doc.setCharacterAttributes(startOffset, lineLength, normal, true);
               //  check for multi line comment
               String multiLineStartDelimiter = "/*";
               String multiLineEndDelimiter = "*/";
               index = content.lastIndexOf( multiLineStartDelimiter, endOffset );
               if (index > -1)
                    int index2 = content.indexOf( multiLineEndDelimiter, index );
                    if ( (index2 == -1) || (index2 > endOffset) )
                         doc.setCharacterAttributes(index, endOffset - index + 1, comment, false);
                         return;
                    else
                    if (index2 >= startOffset)
                         doc.setCharacterAttributes(index, index2 + 2 - index, comment, false);
                         return;
               //  check for single line comment
               String singleLineDelimiter = "//";
               index = content.indexOf( singleLineDelimiter, startOffset );
               if ( (index > -1) && (index < endOffset) )
                    doc.setCharacterAttributes(index, endOffset - index + 1, comment, false);
                    endOffset = index - 1;
               //  check for tokens
               checkForTokens(content, startOffset, endOffset);
          private void checkForTokens(String content, int startOffset, int endOffset)
               while (startOffset <= endOffset)
                    //  find the start of a new token
                    while ( isDelimiter( content.substring(startOffset, startOffset + 1) ) )
                         if (startOffset < endOffset)
                              startOffset++;
                         else
                              return;
                    if ( isQuoteDelimiter( content.substring(startOffset, startOffset + 1) ) )
                         startOffset = getQuoteToken(content, startOffset, endOffset);
                    else
                         startOffset = getOtherToken(content, startOffset, endOffset);
          private boolean isDelimiter(String character)
               String operands = ";:{}()[]+-/%<=>!&|^~*";
             if (Character.isWhitespace( character.charAt(0) ) ||
                  operands.indexOf(character) != -1 )
                  return true;
             else
                  return false;
          private boolean isQuoteDelimiter(String character)
               String quoteDelimiters = "\"'";
               if (quoteDelimiters.indexOf(character) == -1)
                  return false;
             else
                  return true;
          private boolean isKeyword(String token)
               Object o = keywords.get( token );
               return o == null ? false : true;
          private boolean isimpclasses1(String token)
               Object o = impclasses.get( token );
               return o == null ? false : true;
          private int getQuoteToken(String content, int startOffset, int endOffset)
               String quoteDelimiter = content.substring(startOffset, startOffset + 1);
               String escapedDelimiter = "\\" + quoteDelimiter;
               int index;
               int endOfQuote = startOffset;
               //  skip over the escaped quotes in this quote
               index = content.indexOf(escapedDelimiter, endOfQuote + 1);
               while ( (index > -1) && (index < endOffset) )
                    endOfQuote = index + 1;
                    index = content.indexOf(escapedDelimiter, endOfQuote);
               // now find the matching delimiter
               index = content.indexOf(quoteDelimiter, endOfQuote + 1);
               if ( (index == -1) || (index > endOffset) )
                    endOfQuote = endOffset;
               else
                    endOfQuote = index;
               doc.setCharacterAttributes(startOffset, endOfQuote - startOffset + 1, quote, false);
                        //String token = content.substring(startOffset, endOfQuote + 1);
                        //System.out.println( "quote: " + token );
               return endOfQuote + 1;
          private int getOtherToken(String content, int startOffset, int endOffset)
             int endOfToken = startOffset + 1;
               while ( endOfToken <= endOffset )
                    if ( isDelimiter( content.substring(endOfToken, endOfToken + 1) ) )
                         break;
                    endOfToken++;
               String token = content.substring(startOffset, endOfToken);
                        //System.out.println( "found: " + token );
               if ( isKeyword( token ) )
                    doc.setCharacterAttributes(startOffset, endOfToken - startOffset, keyword, false);
               if(isimpclasses1 ( token) )
                    doc.setCharacterAttributes(startOffset, endOfToken - startOffset, impclasses1, false);
               return endOfToken + 1;
}

Similar Messages

  • HTML editor with syntax highlighting and UTF-8 support

    In an ongoing effort to move our lives into the cloud and into our pockets (and as a part of an article series for a tech blog), me and a friend are trying to completely replace the need for computers with our iPhones.
    In some ways, it is going splendidly (Documents to Go Premium + foldable bluetooth keyboard = all my writing needs as a journalist solved). In others, concessions have to be made (as a practicing musician, my options are a bit limited, but with the help of Xewton Music Studio, Multitrack DAW/NanoStudio, etc, I can at least lay down some basic tracks, create basic MIDI compositions, etc).
    However, there is one area in where we’ve made no headway at all. My friend has the great misfortune of being blessed with logic , and therefore, unlike me, does honest programming and web app designing work. And as far as we know, there is not a single HTML/script editor with more than just the bare, basic functions in the app store.
    What we need is this:
    * Syntax highlighting
    * Support for UTF-8
    A built-in FTP editor would be a nice bonus, but is not essential.
    We found one for the iPad, but when we contacted the company behind the app, they revealed no immediate plans for an iPhone version. (They felt coding on the iPhone was, at best, impractical, but they did concede the fact that if there are indeed users who have that need, the existence of an iOS HTML editor would be justified, and possible lucrative, regardless of their feelings on the matter. On that ground, they promised to examine the possibilities to port their iPad app in the future, but so far, no signs.)
    Does anyone know of such an app? Rest assured your assistance will be mentioned in the article series should you point us in the right direction

    Unfortunately, my friend has offered his iPhone an ultimatum. No syntax highlighting, no computer replacement. It is strange that such as standardized feature has not found its way into any known HTML editor for iOS.
    But FTPOntheGo seems to be a great app in general, so thanks!

  • Highlight and Shadows Problem

    I use a 2GB Imac Intel 2 Ghz If i set Highlights and Shadows in the RAW window to anything above 0.0 when i use the loupe to view close up the loupe isnt as responsive its like the adjustments are eating up all the CPU time, the loupe usually has fluid movement around the image, but not if i enable Highlights and Shadows?
    Any ideas?
    Cheers

    yup. the hilites/shadows settings eat a lot of processing power.
    Cheers,
    Karl

  • Syntax highlighted program code in keynote?

    Is there any easy way insert programming code (in my case Ruby code) into a slide so it shows up with syntax highlighting and formating suitable for the code?
    I.E. so it looks like the highlighted code in Textmate or other gui editors?

    TextWrangler (and thus presumably BBEdit) do preserve their syntax colouring when PDFed, as does Taco HTML Edit. My guess is that this is capability is an app-by-app feature.
    If you were desperate for a PDF output to Keynote, you could always copy the text from Textmate and paste it into the freeware TextWrangler. You would likely have to adjust the default syntax colouring to match Textmate, but that would be relatively straightforward.

  • Syntax highlighting not working on PL/SQL developer tool

    Hello,
    Syntax highlighting is not working on PL/SQL developer tool using the beautifier. When I go set Syntax highlighting parameters (from  EDIT>PL/SQL Developer Beautifier Options > User Interface> Editor> Syntax Highlighting ) and click apply, the changes are not reflected in SQL code in the SQL window. Other feautures in the beautifier such as Fonts, Window types are working fine.
    Please help me with this issue.
    Thanks!!
    Shreejit

    As this is not an Oracle related question (let alone Oracle SQL or PL/SQL), and as you've been given a link to the relevant website... I'll now lock this thread.

  • Dreamweaver CC syntax highlight for  Less

    How to Make Dreamweaver CC syntax highlight , default  syntax highlight have some problem。Thanks。

    Thanks lnayal.
    I  edit Less Code Coloring .
    But Syntax highlight Like Before .
    I want to Make  Syntax highlight Like the left pic.
    Like This .
    http://www.dmxzone.com/go/21528/dmxzone-less-css-compiler

  • Best strategy for creating a Code Editor (w/ syntax highlighting) in flash

    I'm looking into creating a javascript code editor in flash. I would light to include syntax highlighting and am eliciting suggestings on how best to approach it.
    Here are my thoughts so far:
    I don't see anything pre-built, so I'll have to do it myself, am I wrong here?
    I have seen as3syntaxhighlihgt which will take code and turn it into a highlighted HTML file, but not sure whether or not I could find a way to combine that with a text editor that could support html???
    Thanks for any input that can help guide me.
    David

    After more research I've answered this one myself. For anyone else comming across this thread here is what I found:
    as3syntaxhighlight is a good option for code highlighting in flash, see the demo at:
    http://anirudhs.chaosnet.org/blog/2009.01.12.html
    It embeds very easily and quickly.
    Other options exist for editors built in JS that could potentially be ported:
    http://en.wikipedia.org/wiki/Comparison_of_Javascript-based_source_code_editors

  • Syntax highlighting, autotabbing in Eclipse?

    Pardon, is there a way to make Eclipse do syntax highlighting and autoindentation a la Vi? I need to use Eclipse because I've got homework involving Java, and features beyond those of a basic text editor could come in handy, methinks.
    (I know the options should be in some obvious location, but I've managed to miss them somehow... :? )

    Er, it does that automatically from a default setup.
    Are you saying that you have no highlighting at all?
    How did you install Eclipse, via pacman or download it yourself from the website? I ask because a couple of years ago when Eclipse was starting to become popular, I downloaded the Eclipse platform, only to find that I got the base system, without any Java IDE features. You see, the language support is in the form of additional plugins. That's why Eclipse can in fact be a Java, Python or C++ IDE, etc, providing someone has written the plugings to make it so.
    Nowadays, the default download (Eclipse SDK) is bundled with the Java dev stuff. For me, it has always worked fine, out of the box. No need to enable highlighting or indenting.

  • I have upgraded Apple Aperture from version 2 to version 3 and I'm having a problem with the "Highlights and Shadows" adjustment. According to the user's manual, I should have access to an advanced disclosure triangle which would allow me to adjust mid co

    I have upgraded Apple Aperture from version 2 to version 3 and I'm having a problem with the "Highlights and Shadows" adjustment. According to the user's manual, I should have access to an advanced disclosure triangle which would allow me to adjust mid contrast, colour, radius, high tonal width and low tonal width.
    If anyone has any suggestions as to how to access this advanced section, I'd be most grateful.

    Hi David-
    The advanced adjustments in the Highlights & Shadows tool were combined into the "Mid Contrast" slider in Aperture 3.3 and later. If you have any images in your library that were processed in a version of Aperture before 3.3, there will be an Upgrade button in the Highlights & Shadows tool in the upper right, and the controls you asked about under the Advanced section. Clicking the Upgrade button will re-render the photo using the new version of Highlights & Shadows, and the Advanced section will be replaced with the new Mid Contrast slider. With the new version from 3.3 you probably don't need the Advanced slider, but if you want to use the older version you can download it from this page:
    http://www.apertureexpert.com/tips/2012/6/12/reclaim-the-legacy-highlights-shado ws-adjustment-in-aperture.html

  • Where can I get an Html error report of all the syntax and tag problems?

    Where can I get an Html error report of all the syntax and tag problems?

    Thank you for your answer.
    Where is the DW validation for me?
    My files are in my computer so I don’t have an external URL.
    File > validation > as xml = closes DW... Maybe because it is not a correct command for HTML,
    And
    Window > results > validation = gives a partial mistakes (e.g. shows an open tag without closing tag, but doesn’t show a closing tag without an open tag).
    Thank you.

  • Aperture to export photos either TIFF or JPEG files, highlight and shadow transition has obvious faults, this problem solved!?

    Aperture to export photos either TIFF or JPEG files, highlight and shadow transition has obvious faults, this problem solved!?

    What problem?
    You will have to be _a lot_ more specific if you'd like responsible feedback.
    I export thousands of TIFF and JPG files a week with no obvious faults.
    (Sent from my magic glass.) 

  • Resetting my iPad didn't solve my problem with Bible  1 being kicked out when I tried opening the App. I was told to delete the App and re-install it, but won't that delete EVERYTHING I've done within the App?  Like the highlights and the Notes?

    The problem I'm having with my Bible +1 App wasn't solved by resetting my iPad.  I was told to then delete the App and re-install it, but if I do that, won't that delete EVERYTHING within the App, like all the highlighting and Notes?  And I'm sorry to say, I'm extremely technologically inept - only had this iPad since mid-April and the first piece of computer ANYTHING in well over 15 years with my son - and we never had the InterNet. The reason I'm telling this is, I'm not even sure HOW to re-install an App.  Sorry.

    If the app continually fails to run the delete and renown load might help. But yes, you will lose everything that you have done with the app unless there is some way to back up the info to your computer or another device.
    You might also contact the developer of the app to see if they are aware of the problem and are working on fixing it. The developer info can normally be found in the information on the app provided in the App Store.

  • Since installing Yosemite on my Air, I can no longer select a message in my inbox and manually highlight it in color by clicking on a color. Is this a known and fixable problem?

    Since installing Yosemite on my Air, I can no longer select a message in my inbox and manually highlight it in color. Is this a known and fixable problem?

    I no longer recall how it was accomplished in Lion, but the only way I know of to assign a color to a Mail message is to apply a Rule to it.

  • Syntax Highlighting for MATRIXx MathScript and TPL

    There have been some questions about text editors for MATRIXx, so I wanted to let everyone know about an application note that we just posted. It describes how to configure a syntax highlighter for use with MathScript and Template Programming Language (TPL). There is also an example of how Crimson Editor can be configured. I choose Crimson Editor because it was free, but the same thing can be done in other syntax highlighters. Using a syntax highlighter makes MATRIXx code a lot easier to read.
    http://zone.ni.com/devzone/conceptd.nsf/webmain/C43375149CB01C3186256E530081EAA5
    While I am at it, I am going to point out some other resources. The application note is located on Developer Zone section of our website, where
    you can find other MATRIXx examples and tutorials:
    http://zone.ni.com/devzone/devzone.nsf/webcategories/A92DB8BA2DE149F486256CBC00655A0C?opendocument
    If you have code or examples that you want to share with other users you can submit the example to the Example Code Library:
    http://www.ni.com/devzone/dev_exchange/ex_search.htm
    Suggestions and feedback can be submitted from Product Feedback section of Contact NI:
    http://sine.ni.com/apps/we/nicc.call_me?p_action=country&p_lang_id=US
    And of course the main MATRIXx page is:
    http://www.ni.com/matrixx
    Carl L
    National Instruments

    I found another editor with syntax highlighting capabilities for MATRIXx. The editor is VIM which is based on the Unix VI editor, and is available on both Solaris and Windows.
    www.vim.org
    Carl L
    National Instruments
    www.ni.com/matrixx

  • Syntax Colors and highlighting plsql code

    I need some help for something I cannot figure out. I just downloaded SQL Developer and tried it out. So far it looks really good and does pretty much everything I need.
    I'm using JDK1.6_13 on Windows Vista.
    However, I can't figure out how the syntax highlighting works. First of all, our package sources are stored on the filesystem with extensions .pck and .bdy. We take these source files and then compile them to the database.
    The first thing I've noticed is that if I launch SQL Developer and then open a .bdy file right away, it displays in black and white. No coloring of any sort...No shading of the comments and words like function, procedure, varchar2 are not colored. Actually, any subsequent file I open .bdy, .pck will not have any syntax highlighting either. However, if I open a compiled package from the database, it will open and have the proper highlighting for the comments and the words I mentioned previously. I thought that was weird how it could properly highlight compiled packages but not files on the filesystem.
    After much playing around, I noticed that if I launch SQL Developer and then open a compiled package from the database right away, any .bdy or .pck file I open from the filesystem will now have syntax highlighting. That's weird.
    Why is this?
    My test scenarios are:
    Scenario 1.
    1. Launch Sql Developer
    2. Open mypackage.bdy from filesystem.
    Result: No Syntax Highlighting.
    Scenario 2.
    1. Launch sql developer
    2. Open mypackage from database. Noticed that there is syntax highlighting.
    3. Open mypackage.bdy from filesystem.
    Result: Syntax Hightlighting
    Scenario 3.
    1. Launch sql developer
    2. Open mypackage.bdy from filesystem. Noticed no syntax highlighting.
    3. Open anotherpackage from database. Noticed syntax highlighting.
    4. Close mypackage.bdy
    5. ReOpen mypackage.bdy from filesystem. NOW THERE IS SYNTAX HIGHLIGHTING!!! WTF???
    Result: MAXIMUM WEIRDNESS!!!
    Am I missing something in the setup or something???
    Thanks.

    user647679 wrote:
    Here's the version information:
    CVS Version     Internal to Oracle SQL Developer (client-only)
    Java(TM) Platform     1.6.0_13
    Oracle IDE     1.5.4.59.40
    Versioning Support     1.5.4.59.40
    Unfortunately to et the patch level, yuu have to go into the Extensions tab and look at the version of SQL Developer Patch. For example I have 11.1.1.59.59
    >
    Thanks. I hope they get this fixed soon.
    I also noticed that the code folding feature does not work with packages that exceed 10,000 lines or thereabouts.I've seen this reported before, but on the other hand 10000 lines is pretty long. This might be a memory issue. If you run SQLDeveloper from <sqldev>\sqldeveloper\bin\sqlldeveloper.exe it leaves a console open which may show errors.

Maybe you are looking for