content: /*
   * Copyright 2013-2016 Raffael Herzog, Marko Umek
   *
   * This file is part of markdown-doclet.
   *
   * markdown-doclet is free software: you can redistribute it and/or modify
   * it under the terms of the GNU General Public License as published by
   * the Free Software Foundation, either version 3 of the License, or
   * (at your option) any later version.
   *
   * markdown-doclet is distributed in the hope that it will be useful,
   * but WITHOUT ANY WARRANTY; without even the implied warranty of
   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   * GNU General Public License for more details.
   *
   * You should have received a copy of the GNU General Public License
   * along with markdown-doclet.  If not, see <http://www.gnu.org/licenses/>.
   *
   */
  package ch.raffael.mddoclet.mdrepair;
  
  import java.util.LinkedList;
  import java.util.List;
  import java.util.regex.Matcher;
  import java.util.regex.Pattern;
  
  /**
   * HtmlEntitiesRepair support the possibility of escaping html entities, even in code blocks - `{&any code;}`.
   */
  final class HtmlEntitiesRepair extends DefaultMarkdownRepair {
      private static final String STORED_MARKER = "-he-";
      private static final String MARKER = "{" + STORED_MARKER + "}";
  
      private static final Pattern SUBST_REGEX = Pattern.compile("\\{(?<he>&[^;]+;|-he-)\\}");
      private static final Pattern RESTORE_REGEX = Pattern.compile("\\{-he-\\}");
  
      private final List<String> storage;
  
      HtmlEntitiesRepair() {
          this(new LinkedList<String>());
      }
  
      HtmlEntitiesRepair(List<String> storage) {
          this.storage = storage;
      }
  
      @Override
      public String beforeMarkdownParser(String markdown) {
          final StringBuffer result = new StringBuffer();
          final Matcher matcher = SUBST_REGEX.matcher(markdown);
          while (matcher.find()) {
              storage.add(matcher.group("he"));
              matcher.appendReplacement(result, MARKER);
          }
  
          matcher.appendTail(result);
  
          return result.toString();
      }
  
      @Override
      public String afterMarkdownParser(String markup) {
          final StringBuffer result = new StringBuffer();
          final Matcher matcher = RESTORE_REGEX.matcher(markup);
          while (matcher.find()) {
              String replacement = MARKER;
              if (!storage.isEmpty()) {
                  replacement = storage.remove(0);
              }
  
              if (!STORED_MARKER.equals(replacement)) {
                  matcher.appendReplacement(result, replacement);
              } else {
                  matcher.appendReplacement(result, MARKER);
              }
          }
  
          matcher.appendTail(result);
  
          return result.toString();
      }
  }
  