#!/usr/bin/env python
#
# $Source: /u/blais/cvsroot/conf/common/lib/python/htmlout.py,v $
# $Id: htmlout.py,v 1.23 2005/03/10 23:45:11 blais Exp $
#
# Copyright (C) 2001-2003, Martin Blais <blais@furius.ca>
#

"""
HTML output builder module.  Valid HTML output is made easy by building an XML
tree of nodes and serializing.  This is a version of the library that uses
ElementTree.

\\subsection{Usage}

To build an HTML file you build a tree of XML element using the classes in this
module.  A class with the name of each of the HTML element names is defined, in
capital letters.  By creating instances of these classes and forming a tree you
build the document tree.  Thus, this module should be import with:
\\begin{verbatim}

   from htmltree import *

\\end{verbatim}

"""

# This is the template file to piece together the written documentation from
# various parts of the source code docstrings and function specifications.
__docgen__ = """
\section{\module{htmlout} ---
         HTML output module}

\declaremodule{extension}{htmlout}
\modulesynopsis{Build a tree of HTML elements and linearize.}

__ module::

\subsection{Important Functions}

__ func:: tostring
__ func:: get_styles

"""

#===============================================================================
# EXTERNAL DECLARATIONS
#===============================================================================

import xml.dom.minidom
import types

#===============================================================================
# PUBLIC DECLARATIONS
#===============================================================================

#-------------------------------------------------------------------------------
#
def tostring( root, indent='   ',
              check_subelems=True,
              ctnttype=False, doctype=False, xmldecl=None, encoding=None, 
              styles=False ):
    """
    Render tag tree into a string of text.
    """

    doc = Document(check_subelems, True)
    xroot = root.do_create(doc)
    return top + xroot.toprettyxml(indent=indent, encoding=encoding)

#-------------------------------------------------------------------------------
#
def get_styles( node ):
    """
    Fetch all the style tags of all the nodes in the tree, and return a list of
    them.
    """

    class getstyle:
        def __init__( self ):
            self.styles = []
        def __call__( self, node ):
            if node.styles:
                assert type(self.styles) is types.ListType
                self.styles.extend(node.styles)
            return True
    gs = getstyle()
    node.visit(gs)
    return gs.styles

