Click here to Skip to main content
15,880,469 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
I am developing a simple c-editor using java and I want to add following feature in it...I have implemented for simple space and word but having issues with indention when there are curly braces(for example, if there are space separated opening braces are there,it is not working.Also, the closing braces are not properly aligned with the opening braces).
Solutions are welcomed.Here is my code which implement the indention..
Java
import java.awt.*;
import java.awt.event.*;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.*;
import javax.swing.text.*;

public class Indent extends JFrame
{
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public Indent()
    {
        JTextPane textComponent = new JTextPane();
        JScrollPane scrollPane = new JScrollPane( textComponent );
        getContentPane().add( scrollPane );

        ActionMap am = textComponent.getActionMap();
        am.put(DefaultEditorKit.insertBreakAction, new IndentAction());
    }

    public static class IndentAction extends TextAction
    {
         /**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		/**
         * Creates this object with the appropriate identifier.
         */
        public IndentAction()
        {
            super(DefaultEditorKit.insertBreakAction);
        }

        /**
         * The operation to perform when this action is triggered.
         *
         * @param e the action event
         */
        public void actionPerformed(ActionEvent e)
        {
            JTextComponent target = getTextComponent(e);

            if (target == null) return;

            if ((! target.isEditable()) || (! target.isEnabled()))
            {
                UIManager.getLookAndFeel().provideErrorFeedback(target);
                return;
            }

            try
            {
                //  Determine which line we are on

                Document doc = target.getDocument();
                Element rootElement = doc.getDefaultRootElement();
                int selectionStart = target.getSelectionStart();
                int line = rootElement.getElementIndex( selectionStart );
                StringBuilder indent = new StringBuilder(new String(""));
                //  Get the text for this line

                int start = rootElement.getElement(line).getStartOffset();
                int end = rootElement.getElement(line).getEndOffset();
                int length = end - start;
                String text = doc.getText(start, length);
                int offset = 0;
                boolean posBrace = text.contains("{");
                boolean closeBrace = text.contains("}");
                //  Get the number of white spaces characters at the start of the line
               
                for (offset = 0; offset < length; offset++)
                {
                    char c = text.charAt(offset);

                    if (c != ' ' && c != '\t')
                        break;
                }

                //  When splitting the text include white space at start of line
                //  else do default processing

                if (selectionStart - start > offset)
                {
                	indent.append( text.substring(0, offset) );
                    if( !posBrace )
                    {
                    	indent.insert(0, "\n");
                    }
                    else
                    {
                    	indent.insert(0, "\n\t");
                    }
                    target.replaceSelection(indent.toString() );
                    if(closeBrace)
                    {
                    	indent.deleteCharAt(indent.indexOf("\t"));
                    	target.replaceSelection(indent.toString() );
                    }
                }
                else
                    target.replaceSelection("\n");
            }
            catch(BadLocationException ble) {}
        }
    }

         public static void main(String[] args)
    {
        Indent frame =new Indent();
        frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
        frame.setSize( new Dimension( 300, 100) );
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }
}
Posted
Updated 1-Apr-15 5:09am
v2
Comments
Pandu Rang 17-Mar-15 3:31am    
Hello, i believe it is working exactly how you coded. See no editor will provide auto indentation.

Regards,
svishal92 17-Mar-15 6:58am    
how can we extend it to work for curly braces?
Pandu Rang 18-Mar-15 3:20am    
How you are expecting the output?
svishal92 20-Mar-15 11:47am    
similar to an IDE for any programming lang..for example
int foo(){
//something
}
if i click after the brace i should get it exactly like an IDE provide indention for curly braces..

1 solution

In your program, need to replace below condition :

SQL
if(f==1)
      target.replaceSelection( "\n\t");


with this code:

C#
if(f==1)
               {
                    target.replaceSelection( "\n");
                    target.replaceSelection("\t //write your code");
                    target.replaceSelection( "\n");
                    target.replaceSelection("}");
                    f=0;
                }


Compile and run the program the out put will be :
Quote:
Method{
//write your code
}


This is only a sample code. Hope it helps you.

Regards,
Panduranga.
 
Share this answer
 
Comments
svishal92 1-Apr-15 11:12am    
Pandu Rang,thanx for helping.. i have edited it to work on opening braces but the closing braces are still not perfectly aligned with opening braces... any suggestion?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900