001package org.apache.maven.doxia.module.twiki.parser;
002
003/*
004 * Licensed to the Apache Software Foundation (ASF) under one
005 * or more contributor license agreements.  See the NOTICE file
006 * distributed with this work for additional information
007 * regarding copyright ownership.  The ASF licenses this file
008 * to you under the Apache License, Version 2.0 (the
009 * "License"); you may not use this file except in compliance
010 * with the License.  You may obtain a copy of the License at
011 *
012 *   http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing,
015 * software distributed under the License is distributed on an
016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017 * KIND, either express or implied.  See the License for the
018 * specific language governing permissions and limitations
019 * under the License.
020 */
021
022import java.util.ArrayList;
023import java.util.List;
024import java.util.regex.Matcher;
025import java.util.regex.Pattern;
026
027import org.apache.maven.doxia.parser.ParseException;
028import org.apache.maven.doxia.util.ByLineSource;
029
030/**
031 * Parse verbatim blocks
032 *
033 * @author Christian Nardi
034 * @version $Id: VerbatimBlockParser.html 905940 2014-04-12 16:27:29Z hboutemy $
035 * @since 1.1
036 */
037public class VerbatimBlockParser
038    implements BlockParser
039{
040    /**
041     * pattern to detect verbatim start tags
042     */
043    private static final Pattern VERBATIM_START_PATTERN = Pattern.compile( "\\s*<verbatim>" );
044
045    private static final Pattern VERBATIM_END_PATTERN = Pattern.compile( "</verbatim>" );
046
047    /** {@inheritDoc} */
048    public final boolean accept( final String line )
049    {
050        return VERBATIM_START_PATTERN.matcher( line ).lookingAt();
051    }
052
053    /**
054     * {@inheritDoc}
055     */
056    public final Block visit( final String line, final ByLineSource source )
057        throws ParseException
058    {
059        if ( !accept( line ) )
060        {
061            throw new IllegalAccessError( "call accept before this ;)" );
062        }
063
064        final List<Block> lines = new ArrayList<Block>();
065        Matcher matcher = VERBATIM_START_PATTERN.matcher( line );
066        matcher.find();
067        String l = line.substring( matcher.end() );
068
069        while ( l != null )
070        {
071            matcher = VERBATIM_END_PATTERN.matcher( l );
072            if ( matcher.find() )
073            {
074                lines.add( new TextBlock( l.substring( 0, matcher.start() ) + "\n" ) );
075                break;
076            }
077            lines.add( new TextBlock( l + "\n" ) );
078            l = source.getNextLine();
079        }
080
081        return new VerbatimBlock( lines.toArray( new Block[] {} ) );
082    }
083}