private static TemplateElement findTemplateElement(TemplateElement te, int line) {
    if (te.getBeginLine() > line || te.getEndLine() < line) {
      return null;
    }
    // Find the narrowest match
    List childMatches = new ArrayList();
    for (Enumeration children = te.children(); children.hasMoreElements(); ) {
      TemplateElement child = (TemplateElement) children.nextElement();
      TemplateElement childmatch = findTemplateElement(child, line);
      if (childmatch != null) {
        childMatches.add(childmatch);
      }
    }
    // find a match that exactly matches the begin/end line
    TemplateElement bestMatch = null;
    for (int i = 0; i < childMatches.size(); i++) {
      TemplateElement e = (TemplateElement) childMatches.get(i);

      if (bestMatch == null) {
        bestMatch = e;
      }

      if (e.getBeginLine() == line && e.getEndLine() > line) {
        bestMatch = e;
      }

      if (e.getBeginLine() == e.getEndLine() && e.getBeginLine() == line) {
        bestMatch = e;
        break;
      }
    }
    if (bestMatch != null) {
      return bestMatch;
    }
    // If no child provides narrower match, return this
    return te;
  }