package jp.sourceforge.projects.ee2e.core.cdt;
import jp.sourceforge.projects.ee2e.core.editors.*;

import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.BadLocationException;

/**
 * To change this generated comment edit the template variable "typecomment":
 * Window&gt;Preferences&gt;Java&gt;Templates.
 * To enable and disable the creation of type comments go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation.
 *
 * @author Toshikazu Ando [ ando@park.ruru.ne.jp ]
 */
public class EE2EIndentMake extends EE2EIndentBehavior {
    /** constractor */
    public EE2EIndentMake() {
    }

    public static final int INDENT_LEN = 4;

    /**
    * @see jp.sourceforge.projects.ee2e.core.cdt.editors.EE2EMenuBehavior#tabDestroyer(AbstractTextEditor, IDocument, ITextSelection)
    */
    protected void doIndent(int offset, IDocument document)
        throws BadLocationException {
        offset = EE2ELispBase.get().beginningOfLine(offset, document);
        int len = EE2ELispBase.get().indentLen(offset, document);
        len += INDENT_LEN;
        this.indentTo(offset, len, document);
    }
    protected void indentTo(int offset, int size, IDocument document)
        throws BadLocationException {
        if (size < 0) {
            size = 0;
        }
        int realSize = 0;
        int len = 0;
        boolean tabNotUsedFlag = true;
        int begin = EE2ELispBase.get().beginningOfLine(offset, document);
        for (int i = begin; i < document.getLength(); i++) {
            if (document.getChar(i) == ' ') {
                realSize++;
                len++;
            } else if (document.getChar(i) == '\t') {
                realSize++;
                len += 4;
                tabNotUsedFlag = false;
            } else {
                break;
            }
        }
        if ((size == len) && tabNotUsedFlag) {
            return;
        }
        StringBuffer buff = new StringBuffer();
        for (int i = 0; i < size; i += 4) {
            buff.append('\t');
        }
        document.replace(offset, realSize, buff.toString());
    }
}
