Only Undo/Redo Editing but No Syntax Highlighting

I have a JTextPane with styled content, when I apply undo/redo I don't want the different Color Highlighting to be added to Undo/Redo queue of UndoManager. How can I? My Undo Listener and Actions looks like below:
protected class RulesUndoableEditListener implements UndoableEditListener {
          RuleExpressionUndo undoAction;
          RedoRuleExpression redoAction;
          UndoManager undoMgr;
          public RulesUndoableEditListener(RuleExpressionUndo undoAction,
                    RedoRuleExpression redoAction, UndoManager undoMgr)
               this.undoAction = undoAction;
               this.redoAction = redoAction;
               this.undoMgr = undoMgr;
          public void undoableEditHappened(UndoableEditEvent e) {
                    undoMgr.addEdit(e.getEdit());
                    undoAction.updateUndoState();
                    redoAction.updateRedoState();
class RuleExpressionUndo extends AbstractAction {
          RedoRuleExpression redoAction;
          UndoManager undo;
        public RuleExpressionUndo(UndoManager undo) {
            super("Undo");
            this.undo = undo;
            setEnabled(false);
        public void actionPerformed(ActionEvent e) {
            try {
                undo.undo();
            } catch (CannotUndoException ex) {
                System.out.println("Unable to undo: " + ex);
                ex.printStackTrace();
            updateUndoState();
            redoAction.updateRedoState();
        protected void updateUndoState() {
            if (undo.canUndo()) {
                setEnabled(true);
                putValue(Action.NAME, undo.getUndoPresentationName());
            } else {
                setEnabled(false);
                putValue(Action.NAME, "Undo");
           * @param redoAction the redoAction to set
          public void setRedoAction(RedoRuleExpression redoAction)
               this.redoAction = redoAction;
    class RedoRuleExpression extends AbstractAction {
         RuleExpressionUndo undoAction;
         UndoManager undo;
        public RedoRuleExpression(UndoManager undo) {
            super("Redo");
            this.undo = undo;
            setEnabled(false);
        public void actionPerformed(ActionEvent e) {
            try {
                undo.redo();
            } catch (CannotRedoException ex) {
                System.out.println("Unable to redo: " + ex);
                ex.printStackTrace();
            updateRedoState();
            undoAction.updateUndoState();
        protected void updateRedoState() {
            if (undo.canRedo()) {
                setEnabled(true);
                putValue(Action.NAME, undo.getRedoPresentationName());
            } else {
                setEnabled(false);
                putValue(Action.NAME, "Redo");
           * @param undoAction the undoAction to set
          public void setUndoAction(RuleExpressionUndo undoAction)
               this.undoAction = undoAction;
    }

I believe that in the undoableEditHappened() method you can add code like thefollowing:
AbstractDocument.DefaultDocumentEvent event =
     (AbstractDocument.DefaultDocumentEvent)e.getEdit();
if  (event.getType().equals(DocumentEvent.EventType.CHANGE))
     // attribute change  - do nothing
else
     undoMgr.addEdit(e.getEdit());
     undoAction.updateUndoState();
     redoAction.updateRedoState();
}

Similar Messages

  • 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;
    }

  • When recently synchronising my iphone it suggested to uograde to latest software. Now none of my sounds can be changed. Have gone to setting and tried to edit but the only sound I get is Marimba despite a different ringtone being selected?

    When recently synchronising my iphone it suggested to uograde to latest software. Now none of my sounds can be changed. Have gone to setting and tried to edit but the only sound I get is Marimba despite a different ringtone being selected?

    I also lost my ringtones.  I have spent about $100 dollars on ringtones to apply different songs to different callers...and now i can't find them.

  • Help! Installed CS4 student edition, but only Illustrator appeared!

    Hi! I recently installed the CS4 student edition, but only Illustrator appears in 'Applications.' A lot of the files associated with Photoshop and In Design are on the computer, but not the programs themselves. I wonder if this has to do with the fact I downloaded trial versions of Photoshop and In Design, but deleted them when I was ready to install CS4. They are no longer in trash.
    Thank you.

    If you deleted them by simply dragging them to the trash, then yes, that
    would explain it. Those application need to be uninstalled, not trashed.
    Bob

  • Is it possible to make only some nodes of a tree editable but not others???

    I am trying a simple java program in which I need only leaf nodes to be editable but not non-leaf nodes. So please if anyone has any idea of that then I need help.

    You could write conditionals because getTreeCellEditorComponent() method of a TreeCellEditor should have boolean leaf argument.

  • [Solved] Vim: Can only undo most recent change

    Howdy-ha, folks.  So I've been (very) gradually making the transition from Geany to Vim over several months, mostly without issue.  However, I've been reluctant to use Vim for anything other than quick, simple operations for one reason: The "u" key will only undo the most recent change, as though there aren't any other changes in the history.  Hitting "u" a second time reverses the "undo" command, so that repeatedly hitting it will just remove and add the same small change over and over again.  No matter how much time I spend looking into this it seems I'm the only person who's ever had this problem, and it occurs regardless of whether /etc/vimrc and ~/.vimrc exist.  As a result, I can't do any complex editing for fear of botching something and needing to spend hours backtracing my mistakes.  Any help on this is appreciated.
    Last edited by ANOKNUSA (2012-05-18 15:22:06)

    skanky wrote:It should do. There's a comment in /etc/vimrc recommending against changing, so it's worth looking into. There are other settings there that could affect some behaviour, apparently.
    That would likely be the issue: I overwrote the default with my own config file, without including runtime! archlinux.vim in my own config.  As far as I can tell, things are working as both user and root.  I suppose I should have paid more attention, but then again, there's no mention in the Arch wiki entry about not altering/deleting any of those files:
    Arch Wiki Vim Entry wrote:
    Vim's personal configuration file is located in the home directory: ~/.vimrc. Advanced users tend to keep a well-tailored ~/.vimrc. The global configuration file is located at /etc/vimrc. The fall-back $VIM variable is defined as /usr/share/vim/. For example, to create a global colorscheme the *.vim colorscheme file should be stored in /usr/share/vim/vimfiles/.
    Currently, the vim global configuration in Arch Linux is very basic and differs from many other distributions' default vim configuration file. To get some commonly expected behaviors (like syntax highlighting, return to the line of the last edit...), consider using vim's example configuration file:
    cp /etc/vimrc /etc/vimrc.bak
    cp /usr/share/vim/vim73/vimrc_example.vim /etc/vimrc
    It seems the comment in /usr/share/vim/vimfiles/archlinux.vim is all new users have to go on, and it's not usually the first place anyone looks.

  • Lazy Notification and Command Undo/Redo

    I have a two-part CS3 plug-in (model and UI).<br /><br />When I click on one of the checkboxes in the UI, it causes a command to be executed that highlights certain fields in the document and sets a persistent boolean indicating the state of the higlighting.<br /><br />I want to be able to uncheck the checkbox when an Edit > Undo is done using lazy notification, but I've been working on this for a few days now and I can't get it to work.<br /><br />I've made the following changes to the model plug-in code:<br /><br />1. In the .fr file, I added this:<br />AddIn<br />{<br />     kDocWorkspaceBoss,<br />     kInvalidClass,<br />     {<br />          // Interface to the persistent prefs implementation<br />          IID_IVIPREFERENCES, kVIPrefsImpl,<br />               <br />          // Interface to the Toggle Highlighting command<br />          IID_IVIHIGHLIGHTCHANGE, kVISetHighlightDisplayedCmdImpl,<br />     }<br />},<br /><br />2. In the command's DoNotify method, I do a ModelChange call with an 'interestedIn' parameter of IID_IVIHIGHLIGHTCHANGE. I've tried invoking this method on various subjects, e.g., document subject, document workspace subject, document preferences subject (i.e., getting my persistent interface on the workspace and then getting an ISubject interface on it), all to no apparent avail.<br /><br />I've made the following changes to the UI plug-in code:<br /><br />1. In the .fr file, I added this:<br /><br />AddIn<br />{<br />     kDocWorkspaceBoss,<br />     kInvalidClass,<br />     {<br />          // Interface to the preference change observer<br />          IID_IPREFSOBSERVER, kVIPUIPrefsObserverImpl,<br />     }<br />},<br /><br />2. In the preference change observer's AutoAttach method, I do the following (with error checking removed here for clarity). I've tried various subjects besides the document workspace subject here as well...<br /><br />InterfacePtr<IActiveContext><br />    ac(gSession->GetActiveContext(), UseDefaultIID());<br />IDocument *doc = ac->GetContextDocument();<br />InterfacePtr<ISubject> subject(doc->GetDocWorkSpace(), UseDefaultIID());<br /><br />if (!subject->IsAttached(ISubject::kLazyAttachment, this,<br />    IID_IVIHIGHLIGHTCHANGE, IID_IPREFSOBSERVER)<br />) {<br />    subject->AttachObserver(ISubject::kLazyAttachment, this,<br />        IID_IVIHIGHLIGHTCHANGE, IID_IPREFSOBSERVER);<br />}<br /><br />I've implemented a LazyUpdate method in the preference change observer, but it never gets called -- not when the checkbox is checked, and not when an Undo or Redo is done. I've verified that the observer's AutoAttach method is getting called, and that the ModelChange method inside the command's DoNotify method is being called.<br /><br />Has anyone gotten lazy notification on command undo/redo to work? If so, can you tell me what I might be doing wrong?

    Don't post the same question repeatedly. I've removed the thread you started 4 days after this one with the identical same question.
    db

  • Keybindings for undo/redo buttons.

    I thought I knew how to do this, and I do seem to have this working fine for cut/copy/paste/select all keybindings CTRL X/C/V/A respectively.
    However I tried to do this for CTRL X and Y undo/redo and it's not working as I intended. Can anyone see what I'm doing wrong?
    I created a SSCCE based off the original example I was following from: [http://www.java2s.com/Code/Java/Swing-JFC/Undoredotextarea.htm]
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.KeyStroke;
    import javax.swing.event.UndoableEditEvent;
    import javax.swing.event.UndoableEditListener;
    import javax.swing.undo.CannotRedoException;
    import javax.swing.undo.UndoManager;
    public class UndoRedoTextArea extends JFrame implements KeyListener{
        private static final long serialVersionUID = 1L;
        protected JTextArea textArea = new JTextArea();
        protected UndoManager undoManager = new UndoManager();
        protected JButton undoButton = new JButton("Undo");
        protected JButton redoButton = new JButton("Redo");
        public UndoRedoTextArea() {
            super("Undo/Redo Demo");
            undoButton.setEnabled(false);
            redoButton.setEnabled(false);
            JPanel buttonPanel = new JPanel(new GridLayout());
            buttonPanel.add(undoButton);
            buttonPanel.add(redoButton);
            JScrollPane scroller = new JScrollPane(textArea);
            getContentPane().add(buttonPanel, BorderLayout.NORTH);
            getContentPane().add(scroller, BorderLayout.CENTER);
            textArea.getDocument().addUndoableEditListener(
                new UndoableEditListener() {
                    public void undoableEditHappened(UndoableEditEvent e) {
                        undoManager.addEdit(e.getEdit());
                        updateButtons();
            undoButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    try {
                        undoManager.undo();
                    } catch (CannotRedoException cre) {
                        cre.printStackTrace();
                    updateButtons();
            undoButton.addKeyListener(this);
            redoButton.addKeyListener(this);
            redoButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    try {
                        undoManager.redo();
                    } catch (CannotRedoException cre)  {
                        cre.printStackTrace();
                    updateButtons();
            setSize(400, 300);
            setVisible(true);
        public void updateButtons() {
            undoButton.setText(undoManager.getUndoPresentationName());
            redoButton.setText(undoManager.getRedoPresentationName());
            undoButton.setEnabled(undoManager.canUndo());
            redoButton.setEnabled(undoManager.canRedo());
        public static void main(String argv[]) {
            new UndoRedoTextArea();
        public void keyPressed(KeyEvent e){
            if (e.equals(KeyStroke.getKeyStroke
                (KeyEvent.VK_Z, InputEvent.CTRL_DOWN_MASK))){
                // undo
                try {
                    undoManager.undo();
                } catch (CannotRedoException cre)  {
                    cre.printStackTrace();
                updateButtons();
            else if (e.equals(KeyStroke.getKeyStroke
                    (KeyEvent.VK_Y, InputEvent.CTRL_DOWN_MASK))){
                // redo
                try  {
                    undoManager.redo();
                } catch (CannotRedoException cre) {
                    cre.printStackTrace();
                updateButtons();
        public void keyTyped(KeyEvent e){}
        public void keyReleased(KeyEvent e){}
    }Edited by: G-Unit on Oct 24, 2010 5:30 AM

    camickr wrote:
    So the way I posted in the second lump of code OK (3rd post) or did you mean something different? Why did you set the key bindings? Did I not state they would be created automatically? I think you need to reread my suggestion (and the tutorial).Because I don't get it, it says only Menu items can contain accelerators and buttons only get mnemonics. I'm not using menu items here, I only have a text pane and 2 buttons. So I set the actions for the InputMap in TextPane. For the buttons, I pretty much used the small bit of code using undoManager.
    I tried to set KEYSTROKE constructor for the action and simply add them to the buttons that way, but this didn't seem to have any response.
    Also I don't get how this could happen anyway if the TextPane has the focus.
    Not like the example using MNEMONICS.
        Action leftAction = new LeftAction(); //LeftAction code is shown later
        button = new JButton(leftAction)
        menuItem = new JMenuItem(leftAction);
    To create an Action object, you generally create a subclass of AbstractAction and then instantiate it. In your subclass, you must implement the actionPerformed method to react appropriately when the action event occurs. Here's an example of creating and instantiating an AbstractAction subclass:
        leftAction = new LeftAction("Go left", anIcon,
                     "This is the left button.",
                     new Integer(KeyEvent.VK_L));
        class LeftAction extends AbstractAction {
            public LeftAction(String text, ImageIcon icon,
                              String desc, Integer mnemonic) {
                super(text, icon);
                putValue(SHORT_DESCRIPTION, desc);
                putValue(MNEMONIC_KEY, mnemonic);
            public void actionPerformed(ActionEvent e) {
                displayResult("Action for first button/menu item", e);
        }This is what I attempted. No errors... It just doesn't work.
    public JPanel p()
        undoButton.addActionListener(new UndoAction(KeyStroke.getKeyStroke(KeyEvent.VK_Z, Event.CTRL_MASK)));
        panel.add(undoButton);
        return panel;
    private class UndoAction extends AbstractAction
         public UndoAction(KeyStroke keyStroke)
              putValue(ACCELERATOR_KEY, keyStroke);
         private static final long serialVersionUID = 1L;
         public void actionPerformed(ActionEvent e)
              try
                   if (undoManager.canUndo())
                        undoManager.undo();
              catch (CannotRedoException cre)
                   cre.printStackTrace();
              updateButtons();
    }Edited by: G-Unit on Oct 25, 2010 8:32 AM

  • [SOLVED] VIM: different syntax highlighting for new vs existing file

    I've had this minor nagging issue for a while that I've been trying to figure out, but I just don't know where to look.
    It is most obvious with LaTeX files (*.tex).  When I create a new file with "vim file.tex" it is recognized as a latex file and I get syntax highlighting, but it seems odd, or off.  When I close then reopen the same file, it gets "propper" syntax highlighting.
    I gather that this must be because of the two different mechanisms for matching the syntax type: filename versus content.  When the file is new, vim only uses the extension.  Once there is a latex comand (e.g., "\documentclass{article}") it recognizes it as something else and the highlighting style is different.
    It turns out just by actually elaborating exactly what the problem was, I was able to find the solution.  I looked for how vim recognizes the files, and found two relevant lines in /usr/share/vim/vim73/filetype.vim on lines 2093 and 2094.  Apparently the .tex filetype is not the same as .latex and others.  I changed it so it was, and I got the desired behavior.
    I thought about just not posting this - but it may be useful for others.

    You're right about it being overridden.  This change should be able to be placed in ~/.vimrc though.
    Well  that was foolish - I should have read the comments right below in that file.  It says exactly how to set it in vimrc.  I've now added the following to my ~/.vimrc and this is completely solved without modifying the /usr/... file.
    let g:tex_flavor = "tex"
    Last edited by Trilby (2013-03-29 16:11:26)

  • Undoing insignoficant edits

    Hi,
    I'm working with the undo/redo manager, and i've got an issue with significant edits.
    Basically, if I:
    1) do say 10 edits.
    2) hit undo 5 times.
    3) create an insignificant edit (basically right now I'm using a text editor, so any changes to the cursor creates an insignificant edit).
    Now I loose the forward history in the undoable edit, and I can't execute a redo command. This is obviously wrong behaviour, so I'm guessing I'm not the first person who's come across this issue. Is there a standard way of implementing this? Should I be not using insignificant edits at all?
    any help much appreciated,
    Justin

    sorry, an insignificant edit as in an edit that returns false from the method UndoableEdit.isSignificant()
    so in order to restore the position of the caret in my text editor after a user clicks undo, I fire a "CaretMovedEdit" event everytime the caret position changes. But - when an event is fired to the undo manager, the manager clears all edits after that particular edit was added.
    I'm only using moving the caret as an example. the application i'm working on is a little more involved than just having a caret state, but its the same general principal.
    thanks,
    J

  • [SOLVED] syntax highlighting in vim

    Hi,
    How do you guys set syntax highlighting in your vimrc?  For example, I have a bunch of mutt config files saved as something like alias.muttrc, colors.muttc, etc... and I want them all to use the muttrc syntax.
    Currently, I have this in my vimrc:
    au BufNewFile,BufRead *.muttrc setf muttrc
    This works unless my first line is a comment (or first non-blank line).   Which is annoying because I want to begin with a comment sometimes!
    Also, I noticed that if my main config file--muttrc--is set correctly whether or not it begins with a comment.   (This file is already matched to muttrc syntax without my intervention).
    Does anyone have a better/different way of setting the syntax?
    Last edited by miggy (2009-05-27 16:15:44)

    Thanks for the suggestion but I'm experiencing the same behavior.  Something weird's going on.   Can someone confirm this same behavior?
    file1.muttrc
    color normal white default
    file2.muttrc
    # Comment
    color normal white default
    file3.muttrc
    color normal white default
    # Comment
    As I'm writing these, they all are good, but when I go to edit them, only file1.muttrc has the correct highlighting.  The others can get it if I say :set syntax=muttrc. 
    It's especially weird that the comments are highlighted but nothing else is.  If I'm not using any sort of file detecting then not even the comments are highlighted

  • Nano syntax highlighting: catch-all syntax for configuration files

    After years of using nano, I only recently learned that it supports syntax coloring... (Why would they turn that off by default? ) Well, I thought I'll make up for it by making extra good use of it from now on...
    Unfortunately it didn't ship a highlighting syntax for the the kind of files that I use nano the most for: system configuration files.
    So I wrote my own, and after tweaking a bit here and there whenever I encountered a config file for which the highlighting wasn't satisfactory at first, I think the result is now good enough (screenshots below) that it's worth sharing with my fellow Arch users:
    Code & Instructions:
    Here is the syntax definition:
    # config file highlighting
    syntax "conf" "(\.(conf|config|cfg|cnf|rc|lst|list|defs|ini|desktop|mime|types|preset|cache|seat|service|htaccess)$|(^|/)(\w*crontab|mirrorlist|group|hosts|passwd|rpc|netconfig|shadow|fstab|inittab|inputrc|protocols|sudoers)$|conf.d/|.config/)"
    # default text
    color magenta "^.*$"
    # special values
    icolor brightblue "(^|\s|=)(default|true|false|on|off|yes|no)(\s|$)"
    # keys
    icolor cyan "^\s*(set\s+)?[A-Z0-9_\/\.\%\@+-]+\s*([:]|\>)"
    # commands
    color blue "^\s*set\s+\<"
    # punctuation
    color blue "[.]"
    # numbers
    color red "(^|\s|[[/:|<>(){}=,]|\])[-+]?[0-9](\.?[0-9])*%?($|\>)"
    # keys
    icolor cyan "^\s*(\$if )?([A-Z0-9_\/\.\%\@+-]|\s)+="
    # punctuation
    color blue "/"
    color brightwhite "(\]|[()<>[{},;:=])"
    color brightwhite "(^|\[|\{|\:)\s*-(\s|$)"
    # section headings
    icolor brightyellow "^\s*(\[([A-Z0-9_\.-]|\s)+\])+\s*$"
    color brightcyan "^\s*((Sub)?Section\s*(=|\>)|End(Sub)?Section\s*$)"
    color brightcyan "^\s*\$(end)?if(\s|$)"
    # URLs
    icolor green "\b(([A-Z]+://|www[.])[A-Z0-9/:#?&$=_\.\-]+)(\b|$| )"
    # XML-like tags
    icolor brightcyan "</?\w+((\s*\w+\s*=)?\s*("[^"]*"|'[^']*'|!?[A-Z0-9_:/]))*(\s*/)?>"
    # strings
    color yellow "\"(\\.|[^"])*\"" "'(\\.|[^'])*'"
    # comments
    color white "#.*$"
    color blue "^\s*##.*$"
    color white "^;.*$"
    color white start="<!--" end="-->"
    To install, save the above above code snippet as a file called conf.nanorc in the folder /usr/share/nano/ (or /usr/local/share/nano/ or similar if you feel strongly about the /usr <--> /usr/local separation), and then add the following to the end of the file /etc/nanorc:
    ## Configuration files (catch-all syntax)
    include "/usr/share/nano/conf.nanorc"
    Hints:
    The colors I chose look good (imo) with the terminal background and color settings that I use, but might not look good, or even readable, with yours, so simply change the color names in the code snippet to whatever you prefer - valid color names are:
    If you use a console with white background, you'll have to change at least the white color I chose for comments and punctuation.
    The first code line in the snippet includes a regular expression that defines for which file names this syntax highlighting should be used. Whenever you encounter a config file that is not matched by this, but you would still like to open it with syntax highlighting, you can manually select this syntax with nano's -Y switch, like so:
    nano -Y conf myConfigFile
    Technical Note:
    It's implemented as a single catch-all syntax, since nano chooses which syntax to apply based on the filename, and in the case of config files usually not much can be learned about the content format from the file name extension (.conf can by anything from flat key/value tuples to XML, .ini can be the official INI format or something else, etc...).
    This means that some compromises have been made, so with this highlighting syntax probably no config file looks 100% as good as a highlighting syntax that would be specifically optimized for one kind of config format, but all in all the vast majority of config files should look pretty good.
    Screenshots:
    /etc/rc.conf,  /etc/hosts:
    /etc/pacman.conf,  /etc/group:
    xorg.conf,  some .desktop file:
    httpd.conf (Apache config),  php.ini:
    More screenshots:
    /etc/fonts/fonts.conf (uses XML)
    /etc/inittab
    /etc/fstab
    /etc/inputrc
    /etc/mime.types
    /etc/protocols
    /etc/xinetd.conf
    See Also:
    nano syntax highlighting: GNU makefiles
    Update [2012-01-28]: Made some more improvements to the syntax definition (see post)
    Last edited by sas (2012-02-01 15:26:43)

    doug piston wrote:I deal with alot of .mk files and would love to see it there.
    You mean GNU makefiles?
    I'm afraid they might be out of scope for this generic config-file syntax.
    Logically they're not system config files, and technically they're a pretty specialized and complex format (different "types" of rules, rules spanning multiple lines, rules containing arbitrary Bash code, etc.).
    This is how an .mk file currently looks with this highlighting syntax:
    $ nano -Y conf /usr/lib/httpd/build/rules.mk
    And apart from highlighting variables of the form $$abc or $(abc), I'm not sure how much can be improved here without breaking the highlighting for more conventional config files.
    It would probably be better to create a specialized highlighting syntax just for .mk files.
    EDIT: I sat down and did just that, here's the result: nano syntax highlighting: GNU makefiles, and here is how the above makefile snipped looks with it:
    Last edited by sas (2012-02-01 15:18:52)

  • Undo/Redo Deleting of Playlists Feature, And More...When Were They Added?

    Hi All,
    I started "Playlist Cleaning" today, (I have over 500 p/ls), and just noticed that the iTunes 'Edit' menu now(?) includes the option to not only undo the accidental deleting of a playlist (or redo it as well), it also has the ability to undo the dragging and dropping (copying) of a song(s) into a playlist, And, go back and undo several of those tasks as well...pretty cool.
    Whenever these features were added, they sure are welcome ones...But if they've been around a while and I just didn't notice them...someone please delete this post...(or not)!!!

    Hi All,
    I started "Playlist Cleaning" today, (I have over 500 p/ls), and just noticed that the iTunes 'Edit' menu now(?) includes the option to not only undo the accidental deleting of a playlist (or redo it as well), it also has the ability to undo the dragging and dropping (copying) of a song(s) into a playlist, And, go back and undo several of those tasks as well...pretty cool.
    Whenever these features were added, they sure are welcome ones...But if they've been around a while and I just didn't notice them...someone please delete this post...(or not)!!!

  • Undo/Redo actions don't call AbstractDocument.insertString or remove?

    Hi,
    I just started working with the UNDO support in the JTextComponents. Primarily, the JTextPane. I am working on a small syntax highlighter component that uses my own extension of DefaultStyledDocument and use the "insertString(int offset, String str, AttributeSet attr, boolean replace)" method and it uses the setCharacterAttributes() method to highlight my keywords. (Pretty standard, like everyone else)
    When i run my app, i can paste code into the JTextPane and see the code highlight in the call to insertString(). When I do an UNDO action through my JMenu, I see the text dissappear from the component. But I don't see the remove() method called.
    Also, when I do a REDO action on the UndoManager. The insertString() method is never called. I have a DocumentListener attached to my JTextPane and I see that fire the insertUpdate method fire...and my text that was highlighted through the insertString method on the document..is loses it's highlighting.
    My question is, is that the correct behaviour? Am I correct in assume that the insertString()/removeString() methods should be called when a REDO/UNDO action is called on the undomanager? I looked at the source code for AbstractDocument and the UndoManager and it looks like the UndoManager simply calls the redo() and undo() methods on the classes that support undo capabilities.
    And, what is happening to my CharacterAttributes on the redo? it's like they are lost.
    Am I misunderstanding how this works? Do I need to call insertString() from inside my insertUpdate document listener?
    I've tried this on both 1.4.2_09 and 1.5.0_06
    Thanks,
    - Tim

    Ok, I'm having a mental lapse..
    I'm trying to override the fireInsert/fireRemove methods and am running into arrayindex out of bounds issues..I'm sure I'm doing something dumb..
    I've tried both calling super.xxx before and after my highlighting..
         * (non-Javadoc)
         * @see javax.swing.text.AbstractDocument#fireInsertUpdate(javax.swing.event.DocumentEvent)
        protected void fireInsertUpdate(DocumentEvent e) {
            super.fireInsertUpdate(e);
            try {
                int offset = e.getOffset();
                int length = e.getLength();
                String text = e.getDocument().getText(offset, length);
                processChangedLines(offset, text.length());
            } catch (BadLocationException ex) {
                ex.printStackTrace();
         * (non-Javadoc)
         * @see javax.swing.text.AbstractDocument#fireRemoveUpdate(javax.swing.event.DocumentEvent)
        protected void fireRemoveUpdate(DocumentEvent e) {
    //      TODO Auto-generated method stub
            super.fireRemoveUpdate(e);
            try {
                int offset = e.getOffset();
                int length = e.getLength();
                processChangedLines(offset, length);
            } catch (BadLocationException ex) {
                ex.printStackTrace();
        }Exception when trying to do an undo of text that I paste into the editor:
    java.lang.ArrayIndexOutOfBoundsException: -1
         at javax.swing.text.AbstractDocument$BranchElement.getEndOffset(AbstractDocument.java:2333)
         at javax.swing.text.View.getEndOffset(View.java:832)
         at javax.swing.text.FlowView$FlowStrategy.layout(FlowView.java:391)
         at javax.swing.text.FlowView.layout(FlowView.java:182)
         at javax.swing.text.BoxView.setSize(BoxView.java:379)
         at javax.swing.text.BoxView.updateChildSizes(BoxView.java:348)
         at javax.swing.text.BoxView.setSpanOnAxis(BoxView.java:316)
         at javax.swing.text.BoxView.layout(BoxView.java:683)
         at javax.swing.text.BoxView.setSize(BoxView.java:379)
         at javax.swing.plaf.basic.BasicTextUI$RootView.setSize(BasicTextUI.java:1599)
         at javax.swing.plaf.basic.BasicTextUI.getPreferredSize(BasicTextUI.java:801)
         at javax.swing.JComponent.getPreferredSize(JComponent.java:1275)
         at javax.swing.JEditorPane.getPreferredSize(JEditorPane.java:1212)
         at javax.swing.ScrollPaneLayout.layoutContainer(ScrollPaneLayout.java:769)
         at java.awt.Container.layout(Container.java:1020)
         at java.awt.Container.doLayout(Container.java:1010)
         at java.awt.Container.validateTree(Container.java:1092)
         at java.awt.Container.validate(Container.java:1067)
         at javax.swing.RepaintManager.validateInvalidComponents(RepaintManager.java:353)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(SystemEventQueueUtilities.java:116)
         at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:189)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:478)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:201)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:151)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:145)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:137)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:100)

  • Repainting question for my syntax highlighter

    Hello there,
    I have a syntax highlighter which reuses much of the very useful code developed by Claude Dugauy, which can be found at http://www.fawcette.com/javapro/2003_07/magazine/columns/visualcomponents/default_pf.aspx
    . The syntax highlighting uses regular expressions, so its easily extendable to meet your needs.
    However, there is one problem: whenever the user presses a key, the whole of the TextPane containing the highlighted text, is repainted in its entirety. This is fine for small amounts of text to be highlighted, but is very slow when it comes to 1000+ lines.
    Please could someone be so excellent as to tell me how to go about addressing this problem, so that only a small amount of text is repainted whenever the user types something into the TextPane e.g. that inside the current viewport, or just the last typed word - thus removing this problem of inefficiency.
    Thanks in advance,
    Edd.

    I don't think it's going to be that easy. Every time a change is made, the default style is applied to the whole document, then the whole document is copied into a String so it can be reparsed and have the syntax styles applied again. Even if you could limit what actually gets painted, you'd still have all that unnecessary work going on.
    You could try forcing the highlighter to only reparse a portion of the document--like,say, a hundred lines before and after the point where the edit occurred--but deciding exactly where to start and stop can be pretty tricky.

Maybe you are looking for

  • Re: Satellite C660 - Sound has stopped working

    I've done some online research, and it seems that its not an uncommon problem for the sound card to stop working. I've tried a couple of things, and just uninstalled the old driver and installed the new one. Still nothing. Any tips please? I'm not a

  • JDBC deadlock on DriverSapDB.connect

    Hi, Today i get a JDBC dealock that i must shutdown and restart my application, i get the follow stack when investiganting the problem: "http-80-exec-15" daemon prio=10 tid=0x0000000056fa8800 nid=0x4860 runnable [0x000000004292f000..0x0000000042930c9

  • Index creating

    hi i am new bie to this forum. just i want to grab some knowledge and share my knowledge. what is the query to know "yes we need to create an index on this particular column" base on which information we will decide to we must create indexes on parti

  • Tab Controls - Adding a page programmatically?

    It's probably not possible from what I've read on this forum, but I would really like to be able to add tabs programmatically (v6.0.2). But, having just read that they are like enums and are read only (can't change page names) it looks like this is g

  • Loading swf's not working

    Hello all. I have a 'UI' module that loads in other swf files based upon which button the user clicks. It is able to locate and load the swf files with no problems. The problem arises with combo boxes. Whenever the swf loaded with the loader has a co