All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cat.inspiracio.orange.ProgramWriter Maven / Gradle / Ivy

/*    Copyright 2019 Alexander Bunkenburg

   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 cat.inspiracio.orange;

import cat.inspiracio.html.DocumentWriter;

import java.io.IOException;
import java.io.Writer;

abstract class ProgramWriter extends DocumentWriter {

    /** Is the cursor at the start of a new line? */
    private boolean newline=true;

    /** How many tabs at the start of the line? */
    private int indentation=0;

    /** accumulated string that will got into write(s). */
    private final StringBuilder builder=new StringBuilder();

    // construction --------------------------------------------

    protected ProgramWriter(Writer w){super(w);}

    // helpers -------------------------------------------------

    protected boolean whitespace(String s){return s.trim().isEmpty();}

    /** Escapes for html: < &
     * For null returns "". */
    protected String escape(String s){
        if(s==null)
            return "";
        return s.replace("&", "&").replace("<", "<");
    }

    /** Quotes a value so that it can be an attribute's value.
     * Escapes " by " and encloses in ". */
    protected String quote(String value){
        //optimise usual case
        if(contains(value, '"'))
            value=value.replaceAll("\"", """);
        return '"' + value + '"';
    }

    /** Does the string contain this character? */
    protected boolean contains(String value, char c){return 0<=value.indexOf(c);}

    // helpers -------------------------------------------------

    protected ProgramWriter indent() throws IOException {
        flush();
        indentation++;
        return this;
    }

    protected ProgramWriter outdent() throws IOException{
        flush();
        indentation--;
        return this;
    }

    /** If at start of new line, write the indentation. */
    private void dent() throws IOException{
        if(newline)
            for(int i=0; i




© 2015 - 2024 Weber Informatics LLC | Privacy Policy