001/* 
002    Licensed to the Apache Software Foundation (ASF) under one
003    or more contributor license agreements.  See the NOTICE file
004    distributed with this work for additional information
005    regarding copyright ownership.  The ASF licenses this file
006    to you under the Apache License, Version 2.0 (the
007    "License"); you may not use this file except in compliance
008    with the License.  You may obtain a copy of the License at
009
010       http://www.apache.org/licenses/LICENSE-2.0
011
012    Unless required by applicable law or agreed to in writing,
013    software distributed under the License is distributed on an
014    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015    KIND, either express or implied.  See the License for the
016    specific language governing permissions and limitations
017    under the License.  
018 */
019package org.apache.wiki.htmltowiki;
020
021import java.io.IOException;
022import java.io.Writer;
023import java.util.regex.Matcher;
024import java.util.regex.Pattern;
025
026/**
027 * Part of the XHtmlToWikiTranslator.
028 * 
029 */
030// FIXME: Needs a better description as to how it works.
031public class WhitespaceTrimWriter extends Writer {
032
033    private final StringBuffer m_result = new StringBuffer();
034
035    private StringBuffer m_buffer = new StringBuffer();
036
037    private boolean m_trimMode = true;
038
039    public static final String NO_TRIMMED_SPACE = " ";
040    private static final Pattern ONLINE_PATTERN = Pattern.compile( ".*?\\n\\s*?", Pattern.MULTILINE );
041
042    private boolean m_currentlyOnLineBegin = true;
043
044    /**
045     *  {@inheritDoc}
046     */
047    @Override
048    public void flush()
049    {
050        if( m_buffer.length() > 0 )
051        {
052            String s = m_buffer.toString();
053            s = s.replaceAll( "\r\n", "\n" );
054            if( m_trimMode )
055            {
056                s = s.replaceAll( "(\\w+) \\[\\?\\|Edit\\.jsp\\?page=\\1\\]", "[$1]" );
057                s = s.replaceAll( "\n{2,}", "\n\n" );
058                s = s.replaceAll( "\\p{Blank}+", " " );
059                s = s.replaceAll( "[ ]*\n[ ]*", "\n" );
060                s = replacePluginNewlineBackslashes( s );
061                s = s.replace( NO_TRIMMED_SPACE, " " );
062            }
063            m_result.append( s );
064            m_buffer = new StringBuffer();
065        }
066    }
067
068    private String replacePluginNewlineBackslashes( String s )
069    {
070        final Pattern p = Pattern.compile( "\\{\\{\\{(.*?)\\}\\}\\}|\\{\\{(.*?)\\}\\}|\\[\\{", Pattern.DOTALL + Pattern.MULTILINE );
071        final Matcher m = p.matcher( s );
072        final StringBuilder sb = new StringBuilder();
073        int pos = 0;
074        while( m.find( pos ) )
075        {
076            final boolean plugin = s.startsWith( "[{", m.start() );
077            final int end = plugin ? endOfPlugin( s, m.start() ) : m.end();
078            if( end < 0 )
079            {
080                sb.append( s, pos, m.end() );
081                pos = m.end();
082                continue;
083            }
084            sb.append( s, pos, m.start() );
085            final String text = s.substring( m.start(), end );
086            sb.append( plugin ? text.replace( "\\\\", "\n" ) : text );
087            pos = end;
088        }
089        sb.append( s, pos, s.length() );
090        return sb.toString();
091    }
092
093    /**
094     *  Returns the index after the closing "}]" of the plugin that starts at {@code start}, counting the plugins nested in it.
095     *  When the brackets do not balance it falls back to the first "}]", and returns -1 when there is none.
096     */
097    private static int endOfPlugin( final String s, final int start )
098    {
099        int depth = 0;
100        for( int i = start; i < s.length() - 1; i++ )
101        {
102            if( s.startsWith( "[{", i ) )
103            {
104                depth++;
105                i++;
106            }
107            else if( s.startsWith( "}]", i ) )
108            {
109                depth--;
110                if( depth == 0 )
111                {
112                    return i + 2;
113                }
114                i++;
115            }
116        }
117        final int first = s.indexOf( "}]", start + 2 );
118        return first < 0 ? -1 : first + 2;
119    }
120
121    /**
122     *  Returns true, if this Writer is currently trimming any whitespaces.
123     *  
124     *  @return True, if trimming.
125     */
126    public boolean isWhitespaceTrimMode()
127    {
128        return m_trimMode;
129    }
130
131    /**
132     *  Set the trimming mode on/off.
133     *  
134     *  @param trimMode True, if you want trimming to be turned on.  False otherwise.
135     */
136    public void setWhitespaceTrimMode(final boolean trimMode )
137    {
138        if( m_trimMode != trimMode )
139        {
140            flush();
141            m_trimMode = trimMode;
142        }
143    }
144
145    /**
146     *  {@inheritDoc}
147     */
148    @Override
149    public void write(final char[] arg0, final int arg1, final int arg2 ) throws IOException
150    {
151        m_buffer.append( arg0, arg1, arg2 );
152        m_currentlyOnLineBegin = ONLINE_PATTERN.matcher( m_buffer ).matches();
153    }
154
155    /**
156     *  {@inheritDoc}
157     */
158    @Override
159    public void close() throws IOException
160    {}
161
162    /**
163     *  {@inheritDoc}
164     */
165    @Override
166    public String toString()
167    {
168        flush();
169        return m_result.toString();
170    }
171
172    /**
173     *  Returns true, if the writer is currently writing a line start.
174     *  
175     *  @return True or false.
176     */
177    public boolean isCurrentlyOnLineBegin()
178    {
179        return m_currentlyOnLineBegin;
180    }
181}