# # epydoc -- HTML output generator # Edward Loper # # Created [01/30/01 05:18 PM] # $Id: html.py 1210 2006-04-10 13:25:50Z edloper $ # """ The HTML output generator for epydoc. The main interface provided by this module is the L{HTMLWriter} class. """ __docformat__ = 'epytext en' import re, os, sys, codecs, sre_constants, pprint import urllib from epydoc.apidoc import * import epydoc.docstringparser import time, epydoc, epydoc.markup from epydoc.docwriter.html_colorize import colorize_re from epydoc.docwriter.html_colorize import PythonSourceColorizer from epydoc.docwriter import html_colorize from epydoc.docwriter.html_css import STYLESHEETS from epydoc.docwriter.html_help import HTML_HELP from epydoc.docwriter.dotgraph import * from epydoc import log from epydoc.util import plaintext_to_html, is_src_filename from epydoc.compat import * # Backwards compatibility ###################################################################### ## Template Compiler ###################################################################### # The compile_tempalte() method defined in this section is used to # define several of HTMLWriter's methods. def compile_template(docstring, template_string, output_function='out', debug=epydoc.DEBUG): """ Given a template string containing inline python source code, return a python function that will fill in the template, and output the result. The signature for this function is taken from the first line of C{docstring}. Output is generated by making repeated calls to the output function with the given name (which is typically one of the function's parameters). The templating language used by this function passes through all text as-is, with three exceptions: - If every line in the template string is indented by at least M{x} spaces, then the first M{x} spaces are stripped from each line. - Any line that begins with '>>>' (with no indentation) should contain python code, and will be inserted as-is into the template-filling function. If the line begins a control block (such as 'if' or 'for'), then the control block will be closed by the first '>>>'-marked line whose indentation is less than or equal to the line's own indentation (including lines that only contain comments.) - In any other line, any expression between two '$' signs will be evaluated and inserted into the line (using C{str()} to convert the result to a string). Here is a simple example: >>> TEMPLATE = ''' ... ... $book.title$ ... $book.count_pages()$ ... >>> for chapter in book.chapters: ... $chapter.name$ ... >>> #endfor ... >>> write_book = compile_template('write_book(out, book)', TEMPLATE) @newfield acknowledgements: Acknowledgements @acknowledgements: The syntax used by C{compile_template} is loosely based on Cheetah. """ # Extract signature from the docstring: signature = docstring.lstrip().split('\n',1)[0].strip() func_name = signature.split('(',1)[0].strip() # Regexp to search for inline substitutions: INLINE = re.compile(r'\$([^\$]+)\$') # Regexp to search for python statements in the template: COMMAND = re.compile(r'(^>>>.*)\n?', re.MULTILINE) # Strip indentation from the template. template_string = strip_indent(template_string) # If we're debugging, then we'll store the generated function, # so we can print it along with any tracebacks that depend on it. if debug: signature = re.sub(r'\)\s*$', ', __debug=__debug)', signature) # Funciton declaration line pysrc_lines = ['def %s:' % signature] indents = [-1] if debug: pysrc_lines.append(' try:') indents.append(-1) commands = COMMAND.split(template_string.strip()+'\n') for i, command in enumerate(commands): if command == '': continue # String literal segment: if i%2 == 0: pieces = INLINE.split(command) for j, piece in enumerate(pieces): if j%2 == 0: # String piece pysrc_lines.append(' '*len(indents)+ '%s(%r)' % (output_function, piece)) else: # Variable piece pysrc_lines.append(' '*len(indents)+ '%s(unicode(%s))' % (output_function, piece)) # Python command: else: srcline = command[3:].lstrip() # Update indentation indent = len(command)-len(srcline) while indent <= indents[-1]: indents.pop() # Add on the line. srcline = srcline.rstrip() pysrc_lines.append(' '*len(indents)+srcline) if srcline.endswith(':'): indents.append(indent) if debug: pysrc_lines.append(' except Exception,e:') pysrc_lines.append(' pysrc, func_name = __debug ') pysrc_lines.append(' lineno = sys.exc_info()[2].tb_lineno') pysrc_lines.append(' print ("Exception in template %s() on "') pysrc_lines.append(' "line %d:" % (func_name, lineno))') pysrc_lines.append(' print pysrc[lineno-1]') pysrc_lines.append(' raise') pysrc = '\n'.join(pysrc_lines)+'\n' if debug: localdict = {'__debug': (pysrc_lines, func_name)} else: localdict = {} try: exec pysrc in globals(), localdict except SyntaxError: log.error('Error in script:\n' + pysrc + '\n') raise template_func = localdict[func_name] template_func.__doc__ = docstring return template_func def strip_indent(s): """ Given a multiline string C{s}, find the minimum indentation for all non-blank lines, and return a new string formed by stripping that amount of indentation from all lines in C{s}. """ # Strip indentation from the template. minindent = sys.maxint lines = s.split('\n') for line in lines: stripline = line.lstrip() if stripline: minindent = min(minindent, len(line)-len(stripline)) return '\n'.join([l[minindent:] for l in lines]) ###################################################################### ## HTML Writer ###################################################################### class HTMLWriter: #//////////////////////////////////////////////////////////// # Table of Contents #//////////////////////////////////////////////////////////// # # 1. Interface Methods # # 2. Page Generation -- write complete web page files # 2.1. Module Pages # 2.2. Class Pages # 2.3. Trees Page # 2.4. Indices Page # 2.5. Help Page # 2.6. Frames-based table of contents pages # 2.7. Homepage (index.html) # 2.8. CSS Stylesheet # 2.9. Javascript file # # 3. Page Element Generation -- write pieces of a web page file # 3.1. Page Header # 3.2. Page Footer # 3.3. Navigation Bar # 3.4. Breadcrumbs # 3.5. Summary Tables # # 4. Helper functions def __init__(self, docindex, **kwargs): """ Construct a new HTML writer, using the given documentation index. @param docmap: The documentation index. @type prj_name: C{string} @keyword prj_name: The name of the project. Defaults to none. @type prj_url: C{string} @keyword prj_url: The target for the project hopeage link on the navigation bar. If C{prj_url} is not specified, then no hyperlink is created. @type prj_link: C{string} @keyword prj_link: The label for the project link on the navigation bar. This link can contain arbitrary HTML code (e.g. images). By default, a label is constructed from C{prj_name}. @type top_page: C{string} @keyword top_page: The top page for the documentation. This is the default page shown main frame, when frames are enabled. C{top} can be a URL, the name of a module, the name of a class, or one of the special strings C{"trees.html"}, C{"indices.html"}, or C{"help.html"}. By default, the top-level package or module is used, if there is one; otherwise, C{"trees"} is used. @type css: C{string} @keyword css: The CSS stylesheet file. If C{css} is a file name, then the specified file's conents will be used. Otherwise, if C{css} is the name of a CSS stylesheet in L{epydoc.docwriter.html_css}, then that stylesheet will be used. Otherwise, an error is reported. If no stylesheet is specified, then the default stylesheet is used. @type help_file: C{string} @keyword help_file: The name of the help file. If no help file is specified, then the default help file will be used. @type show_private: C{boolean} @keyword show_private: Whether to create documentation for private objects. By default, private objects are documented. @type show_frames: C{boolean}) @keyword show_frames: Whether to create a frames-based table of contents. By default, it is produced. @type show_imports: C{boolean} @keyword show_imports: Whether or not to display lists of imported functions and classes. By default, they are not shown. @type variable_maxlines: C{int} @keyword variable_maxlines: The maximum number of lines that should be displayed for the value of a variable in the variable details section. By default, 8 lines are displayed. @type variable_linelength: C{int} @keyword variable_linelength: The maximum line length used for displaying the values of variables in the variable details sections. If a line is longer than this length, then it will be wrapped to the next line. The default line length is 70 characters. @type variable_summary_linelength: C{int} @keyword variable_summary_linelength: The maximum line length used for displaying the values of variables in the summary section. If a line is longer than this length, then it will be truncated. The default is 40 characters. @type variable_tooltip_linelength: C{int} @keyword variable_tooltip_linelength: The maximum line length used for tooltips for the values of variables. If a line is longer than this length, then it will be truncated. The default is 600 characters. @type property_function_linelength: C{int} @keyword property_function_linelength: The maximum line length used to dispaly property functions (C{fget}, C{fset}, and C{fdel}) that contain something other than a function object. The default length is 40 characters. @type inheritance: C{string} @keyword inheritance: How inherited objects should be displayed. If C{inheritance='grouped'}, then inherited objects are gathered into groups; if C{inheritance='listed'}, then inherited objects are listed in a short list at the end of their group; if C{inheritance='included'}, then inherited objects are mixed in with non-inherited objects. The default is 'grouped'. @type include_sourcecode: C{boolean} @param include_sourcecode: If true, then generate colorized source code files for each python module. """ self.docindex = docindex # Process keyword arguments. self._show_private = kwargs.get('show_private', 1) """Should private docs be included?""" self._prj_name = kwargs.get('prj_name', None) """The project's name (for the project link in the navbar)""" self._prj_url = kwargs.get('prj_url', None) """URL for the project link in the navbar""" self._prj_link = kwargs.get('prj_link', None) """HTML code for the project link in the navbar""" self._top_page = kwargs.get('top_page', None) """The 'main' page""" self._css = kwargs.get('css') """CSS stylesheet to use""" self._helpfile = kwargs.get('help_file', None) """Filename of file to extract help contents from""" self._frames_index = kwargs.get('show_frames', 1) """Should a frames index be created?""" self._show_imports = kwargs.get('show_imports', False) """Should imports be listed?""" self._propfunc_linelen = kwargs.get('property_function_linelength', 40) """[XXX] Not used!""" self._variable_maxlines = kwargs.get('variable_maxlines', 8) """Max lines for variable values""" self._variable_linelen = kwargs.get('variable_linelength', 70) """Max line length for variable values""" self._variable_summary_linelen = \ kwargs.get('variable_summary_linelength', 55) """Max length for variable value summaries""" self._variable_tooltip_linelen = \ kwargs.get('variable_tooltip_linelength', 600) """Max length for variable tooltips""" self._inheritance = kwargs.get('inheritance', 'listed') """How should inheritance be displayed? 'listed', 'included', or 'grouped'""" self._incl_sourcecode = kwargs.get('include_source_code', True) """Should pages be generated for source code of modules?""" self._mark_docstrings = kwargs.get('mark_docstrings', False) """Wrap ... around docstrings?""" self._graph_types = kwargs.get('graphs', ()) or () """Graphs that we should include in our output.""" # For use with select_variables(): if self._show_private: self._public_filter = None else: self._public_filter = True # Make sure inheritance has a sane value. if self._inheritance not in ('listed', 'included', 'grouped'): raise ValueError, 'Bad value for inheritance' # Create the project homepage link, if it was not specified. if (self._prj_name or self._prj_url) and not self._prj_link: self._prj_link = plaintext_to_html(self._prj_name or 'Project Homepage') # Add a hyperlink to _prj_url, if _prj_link doesn't already # contain any hyperlinks. if (self._prj_link and self._prj_url and not re.search(r']*\shref', self._prj_link)): self._prj_link = (''+self._prj_link+'') # Precompute lists & sets of APIDoc objects that we're # interested in. self.valdocs = valdocs = sorted(docindex.reachable_valdocs( imports=False, packages=False, bases=False, submodules=False, subclasses=False, private=self._show_private)) self.module_list = [d for d in valdocs if isinstance(d, ModuleDoc)] """The list of L{ModuleDoc}s for the documented modules.""" self.module_set = set(self.module_list) """The set of L{ModuleDoc}s for the documented modules.""" self.class_list = [d for d in valdocs if isinstance(d, ClassDoc)] """The list of L{ClassDoc}s for the documented classes.""" self.class_set = set(self.class_list) """The set of L{ClassDoc}s for the documented classes.""" self.routine_list = [d for d in valdocs if isinstance(d, RoutineDoc)] """The list of L{RoutineDoc}s for the documented routines.""" self.indexed_docs = [] """The list of L{APIDoc}s for variables and values that should be included in the index.""" # Construct the value for self.indexed_docs. self.indexed_docs += [d for d in valdocs if not isinstance(d, GenericValueDoc)] for doc in valdocs: if isinstance(doc, NamespaceDoc): self.indexed_docs += [doc for doc in doc.variables.values() if isinstance(doc.value, GenericValueDoc)] self.indexed_docs.sort() # Figure out the url for the top page. self._top_page_url = self._find_top_page(self._top_page) # Figure out how many output files there will be (for progress # reporting). self.modules_with_sourcecode = set() for doc in self.module_list: if isinstance(doc, ModuleDoc) and is_src_filename(doc.filename): self.modules_with_sourcecode.add(doc) self._num_files = len(self.class_list) + 2*len(self.module_list) + 9 if self._incl_sourcecode: self._num_files += len(self.modules_with_sourcecode) def _find_top_page(self, pagename): """ Find the top page for the API documentation. This page is used as the default page shown in the main frame, when frames are used. When frames are not used, this page is copied to C{index.html}. @param pagename: The name of the page, as specified by the keyword argument C{top} to the constructor. @type pagename: C{string} @return: The URL of the top page. @rtype: C{string} """ # If a page name was specified, then we need to figure out # what it points to. if pagename: # If it's a URL, then use it directly. if pagename.lower().startswith('http:'): return pagename # If it's an object, then use that object's page. try: doc = self.docindex.get_valdoc(pagename) return self.url(doc) except: pass # Otherwise, give up. log.warning('Could not find top page %r; using trees.html ' 'instead' % pagename) # If no page name was specified, then try to choose one # automatically. else: root = [val_doc for val_doc in self.docindex.root if isinstance(val_doc, (ClassDoc, ModuleDoc))] if len(root) == 0: # No docs?? Try the trees page. return 'trees.html' elif len(root) == 1: # One item in the root; use that. return self.url(root[0]) else: # Multiple root items; if they're all in one package, # then use that. Otherwise, use trees.html root = sorted(root, key=lambda v:len(v.canonical_name)) top = root[0] for doc in root[1:]: if not top.canonical_name.dominates(doc.canonical_name): return 'trees.html' else: return self.url(top) #//////////////////////////////////////////////////////////// #{ 1. Interface Methods #//////////////////////////////////////////////////////////// def write(self, directory=None): """ Write the documentation to the given directory. @type directory: C{string} @param directory: The directory to which output should be written. If no directory is specified, output will be written to the current directory. If the directory does not exist, it will be created. @rtype: C{None} @raise OSError: If C{directory} cannot be created. @raise OSError: If any file cannot be created or written to. """ # For progress reporting: self._files_written = 0. # Keep track of failed xrefs, and report them at the end. self._failed_xrefs = {} # Create destination directories, if necessary if not directory: directory = os.curdir self._mkdir(directory) self._directory = directory # Write the CSS file. self._files_written += 1 log.progress(self._files_written/self._num_files, 'epydoc.css') self.write_css(directory, self._css) # Write the Javascript file. self._files_written += 1 log.progress(self._files_written/self._num_files, 'epydoc.js') self.write_javascript(directory) # Write the term & identifier indices self._write(self.write_indices, directory, 'indices.html') # Write the trees file (package & class hierarchies) self._write(self.write_trees, directory, 'trees.html') # Write the help file. self._write(self.write_help, directory,'help.html') # Write the frames-based table of contents. self._write(self.write_frames_index, directory, 'frames.html') self._write(self.write_toc, directory, 'toc.html') self._write(self.write_project_toc, directory, 'toc-everything.html') for doc in self.module_list: filename = 'toc-%s' % urllib.unquote(self.url(doc)) self._write(self.write_module_toc, directory, filename, doc) # Write the object documentation. for doc in self.module_list: filename = urllib.unquote(self.url(doc)) self._write(self.write_module, directory, filename, doc) for doc in self.class_list: filename = urllib.unquote(self.url(doc)) self._write(self.write_class, directory, filename, doc) # Write source code files. if self._incl_sourcecode: for doc in self.modules_with_sourcecode: filename = urllib.unquote(self.pysrc_url(doc)) self._write(self.write_sourcecode, directory, filename, doc) # Write the index.html files. # (this must be done last, since it might copy another file) self._files_written += 1 log.progress(self._files_written/self._num_files, 'index.html') self.write_homepage(directory) # Report any failed crossreferences if self._failed_xrefs: estr = 'Failed identifier crossreference targets:\n' failed_identifiers = self._failed_xrefs.keys() failed_identifiers.sort() for identifier in failed_identifiers: names = self._failed_xrefs[identifier].keys() names.sort() estr += '- %s' % identifier estr += '\n' for name in names: estr += ' (from %s)\n' % name log.docstring_warning(estr) def _write(self, write_func, directory, filename, *args): # Display our progress. self._files_written += 1 log.progress(self._files_written/self._num_files, filename) path = os.path.join(directory, filename) f = codecs.open(path, 'w', 'ascii', errors='xmlcharrefreplace') write_func(f.write, *args) f.close() def _mkdir(self, directory): """ If the given directory does not exist, then attempt to create it. @rtype: C{None} """ if not os.path.isdir(directory): if os.path.exists(directory): raise OSError('%r is not a directory' % directory) os.mkdir(directory) #//////////////////////////////////////////////////////////// #{ 2.1. Module Pages #//////////////////////////////////////////////////////////// def write_module(self, out, doc): """ Write an HTML page containing the API documentation for the given module to C{out}. @param doc: A L{ModuleDoc} containing the API documentation for the module that should be described. """ longname = doc.canonical_name shortname = doc.canonical_name[-1] # Write the page header (incl. navigation bar & breadcrumbs) self.write_header(out, str(longname)) self.write_navbar(out, doc) self.write_breadcrumbs(out, doc, self.url(doc)) # Write the name of the module we're describing. if doc.is_package is True: typ = 'Package' else: typ = 'Module' if longname[0].startswith('script-'): shortname = str(longname)[7:] typ = 'Script' out('\n') out('

%s %s' % (typ.lower(), typ, shortname)) src_link = self.pysrc_link(doc) if src_link: out('\n
' + src_link) out('

\n') # If the module has a description, then list it. if doc.descr not in (None, UNKNOWN): out(self.descr(doc, 2)+'

\n\n') # Write any standarad metadata (todo, author, etc.) if doc.metadata is not UNKNOWN and doc.metadata: out('
\n') self.write_standard_fields(out, doc) # If it's a package, then list the modules it contains. if doc.is_package is True: self.write_module_list(out, doc) # Write summary tables describing the variables that the # module defines. self.write_summary_table(out, "Classes", doc, "class") self.write_summary_table(out, "Functions", doc, "function") self.write_summary_table(out, "Variables", doc, "other") # Write a list of all imported objects. if self._show_imports: self.write_imports(out, doc) # Write detailed descriptions of functions & variables defined # in this module. self.write_details_list(out, "Function Details", doc, "function") self.write_details_list(out, "Variables Details", doc, "other") # Write the page footer (including navigation bar) self.write_navbar(out, doc) self.write_footer(out) #//////////////////////////////////////////////////////////// #{ 2.??. Source Code Pages #//////////////////////////////////////////////////////////// def write_sourcecode(self, out, doc): filename = doc.filename name = str(doc.canonical_name) # Header self.write_header(out, name) self.write_navbar(out, doc) self.write_breadcrumbs(out, doc, self.pysrc_url(doc)) # Source code listing out('

Source Code for %s

\n' % self.href(doc, label='%s %s' % (self.doc_kind(doc), name))) out('
\n') out('
\n')
        out(PythonSourceColorizer(filename, name, self.docindex,
                                  self.indexed_docs, self.url).colorize())
        out('
\n
\n
\n') # Footer self.write_navbar(out, doc) self.write_footer(out) #//////////////////////////////////////////////////////////// #{ 2.2. Class Pages #//////////////////////////////////////////////////////////// def write_class(self, out, doc): """ Write an HTML page containing the API documentation for the given class to C{out}. @param doc: A L{ClassDoc} containing the API documentation for the class that should be described. """ longname = doc.canonical_name shortname = doc.canonical_name[-1] # Write the page header (incl. navigation bar & breadcrumbs) self.write_header(out, str(longname)) self.write_navbar(out, doc) self.write_breadcrumbs(out, doc, self.url(doc)) # Write the name of the class we're describing. if doc.is_type(): typ = 'Type' elif doc.is_exception(): typ = 'Exception' else: typ = 'Class' out('\n') out('

%s %s' % (typ.lower(), typ, shortname)) src_link = self.pysrc_link(doc) if src_link: out('\n
' + src_link) out('

\n') if ((doc.bases not in (UNKNOWN, None) and len(doc.bases) > 0) or (doc.subclasses not in (UNKNOWN,None) and len(doc.subclasses)>0)): # Display bases graphically, if requested. if 'umlclasstree' in self._graph_types: linker = _HTMLDocstringLinker(self, doc) graph = uml_class_tree_graph(doc, linker, doc) out('
\n%s
\n' % self.render_graph(graph)) elif 'classtree' in self._graph_types: linker = _HTMLDocstringLinker(self, doc) graph = class_tree_graph([doc], linker, doc) out('
\n%s
\n' % self.render_graph(graph)) # Otherwise, use ascii-art. else: # Write the base class tree. if doc.bases not in (UNKNOWN, None) and len(doc.bases) > 0: out('
\n%s
\n\n' % self.base_tree(doc)) # Write the known subclasses if (doc.subclasses not in (UNKNOWN, None) and len(doc.subclasses) > 0): out('
Known Subclasses:
\n
\n ') out(',\n '.join([self.href(c, context=doc) for c in doc.subclasses])) out('\n
\n\n') out('
\n') # If the class has a description, then list it. if doc.descr not in (None, UNKNOWN): out(self.descr(doc, 2)+'

\n\n') # Write any standarad metadata (todo, author, etc.) if doc.metadata is not UNKNOWN and doc.metadata: out('
\n') self.write_standard_fields(out, doc) # Write summary tables describing the variables that the # class defines. self.write_summary_table(out, "Nested Classes", doc, "class") self.write_summary_table(out, "Instance Methods", doc, "instancemethod") self.write_summary_table(out, "Class Methods", doc, "classmethod") self.write_summary_table(out, "Static Methods", doc, "staticmethod") self.write_summary_table(out, "Class Variables", doc, "classvariable") self.write_summary_table(out, "Instance Variables", doc, "instancevariable") self.write_summary_table(out, "Properties", doc, "property") # Write a list of all imported objects. if self._show_imports: self.write_imports(out, doc) # Write detailed descriptions of functions & variables defined # in this class. # [xx] why group methods into one section but split vars into two? # seems like we should either group in both cases or split in both # cases. self.write_details_list(out, "Method Details", doc, "method") self.write_details_list(out, "Class Variable Details", doc, "classvariable") self.write_details_list(out, "Instance Variable Details", doc, "instancevariable") self.write_details_list(out, "Property Details", doc, "property") # Write the page footer (including navigation bar) self.write_navbar(out, doc) self.write_footer(out) #//////////////////////////////////////////////////////////// #{ 2.3. Trees page #//////////////////////////////////////////////////////////// def write_trees(self, out): """ Write an HTML page containing the module and class hierarchies to the given streams. @param public: The output stream for the public version of the page. @param private: The output stream for the private version of the page. """ # Header material. self.write_header(out, 'Trees') self.write_navbar(out, 'trees') self.write_breadcrumbs(out, 'trees', 'trees.html') # Write the module hierarchy out('\n') out('

Module Hierarchy

\n') self.write_module_tree(out) # Does the project define any classes? defines_classes = len(self.class_list) > 0 # Write the class hierarchy if defines_classes: out('\n') out('

Class Hierarchy

\n') self.write_class_tree(out) # Footer material. self.write_navbar(out, 'trees') self.write_footer(out) #//////////////////////////////////////////////////////////// #{ 2.4. Indices page #//////////////////////////////////////////////////////////// def write_indices(self, out): """ Write an HTML page containing the term and identifier indices to the given streams. @bug: If there are private indexed terms, but no public indexed terms, then this function will still write a header for the Term Index to the public stream. @param public: The output stream for the public version of the page. @param private: The output stream for the private version of the page. """ # Header material. self.write_header(out, 'Index') self.write_navbar(out, 'indices') self.write_breadcrumbs(out, 'indices', 'indices.html') out('
\n') terms = self._extract_term_index() if terms: self.write_term_index(out, terms) # [xx] this will only find variables if they have values. # (e.g., it won't list any instance variables.) identifiers = [] for doc in self.indexed_docs: name = doc.canonical_name if self.url(doc) is None: continue key = name[-1].lower() key = (key[:1] in 'abcdefghijklmnopqrstuvwxyz', key) identifiers.append( (key, name, doc) ) identifiers.sort() if identifiers: self.write_identifier_index(out, identifiers) # Footer material. self.write_navbar(out, 'indices') self.write_footer(out) write_identifier_index_header = compile_template( """ write_identifier_index_header(self, out) """, # /------------------------- Template -------------------------\ ''' ''') # \------------------------------------------------------------/ write_identifier_index = compile_template( """ write_identifier_index(self, out, index) """, # /------------------------- Template -------------------------\ ''' >>> #self.write_table_header(out, "index", "Identifier Index") >>> self.write_identifier_index_header(out) >>> letters = "abcdefghijklmnopqrstuvwxyz" >>> for sortkey, name, doc in index: >>> if self._doc_or_ancestor_is_private(doc): >>> if not self._show_private: continue >>> #endfor
Identifier Index [ _ >>> for c in "abcdefghijklmnopqrstuvwxyz": $c$ >>> #endfor ]
>>> else:
>>> #endif >>> while letters and letters[0] <= name[-1][:1].lower(): >>> letters = letters[1:] >>> #endif $self.href(doc, name[-1])$ $self.doc_kind(doc)$ >>> container_name = name.container() >>> if container_name is not None: >>> container = self.docindex.get_valdoc(container_name) >>> if container is not None: in $self.doc_kind(container)$ $self.href(container)$ >>> #endif >>> #endif
>>> for letter in letters: >>> #endfor
''') # \------------------------------------------------------------/ write_term_index = compile_template( """ write_term_index(self, out, index) """, # /------------------------- Template -------------------------\ ''' >>> if not index: return >>> self.write_table_header(out, "index", "Term Index") >>> for (key, term, links) in index: $term.to_plaintext(None)$ >>> for link in links[:-1]: $self.href(link)$, >>> #endfor $self.href(links[-1])$ >>> #endfor
''') # \------------------------------------------------------------/ #//////////////////////////////////////////////////////////// #{ 2.5. Help Page #//////////////////////////////////////////////////////////// def write_help(self, out): """ Write an HTML help file to the given stream. If C{self._helpfile} contains a help file, then use it; otherwise, use the default helpfile from L{epydoc.docwriter.html_help}. @param public: The output stream for the public version of the page. @param private: The output stream for the private version of the page. """ # todo: optionally parse .rst etc help files? # Get the contents of the help file. if self._helpfile: if os.path.exists(self._helpfile): try: help = open(self._helpfile).read() except: raise IOError("Can't open help file: %r" % self._helpfile) else: raise IOError("Can't find help file: %r" % self._helpfile) else: if self._prj_name: thisprj = self._prj_name else: thisprj = 'this project' help = HTML_HELP % {'this_project':thisprj} # Insert the help contents into a webpage. self.write_header(out, 'Help') self.write_navbar(out, 'help') self.write_breadcrumbs(out, 'help', 'help.html') out(help) self.write_navbar(out, 'help') self.write_footer(out) #//////////////////////////////////////////////////////////// #{ 2.6. Frames-based Table of Contents #//////////////////////////////////////////////////////////// write_frames_index = compile_template( """ write_frames_index(self, out) Write the frames index file for the frames-based table of contents to the given streams. """, # /------------------------- Template -------------------------\ ''' $self._prj_name or "API Documentation"$ ''') # \------------------------------------------------------------/ write_toc = compile_template( """ write_toc(self, out) """, # /------------------------- Template -------------------------\ ''' >>> self.write_header(out, "Table of Contents")

Table of Contents


Everything

>>> self.write_toc_section(out, "Modules", self.module_list)
>>> if self._show_private: $self.PRIVATE_LINK$ >>> #endif >>> self.write_footer(out, short=True) ''') # \------------------------------------------------------------/ def write_toc_section(self, out, name, docs, fullname=True): if not docs: return # Assign names to each item, and sort by name. if fullname: docs = [(str(d.canonical_name), d) for d in docs] else: docs = [(str(d.canonical_name[-1]), d) for d in docs] docs.sort() out('

%s

\n' % name) for label, doc in docs: doc_url = self.url(doc) toc_url = 'toc-%s' % doc_url is_private = self._doc_or_ancestor_is_private(doc) if is_private: if not self._show_private: continue out('
\n') out('

\n') if isinstance(doc, ModuleDoc): out(' %s

' % (toc_url, toc_url, doc_url, label)) else: out(' %s

' % (doc_url, label)) if is_private: out('
\n') def write_project_toc(self, out): self.write_header(out, "Everything") out('

Everything

\n') out('
\n') # List the classes. self.write_toc_section(out, "All Classes", self.class_list) # List the functions. funcs = [d for d in self.routine_list if not isinstance(self.docindex.container(d), (ClassDoc, types.NoneType))] self.write_toc_section(out, "All Functions", funcs) # List the variables. vars = [] for doc in self.module_list: vars += doc.select_variables(value_type='other', imported=False, public=self._public_filter) self.write_toc_section(out, "All Variables", vars) # Footer material. out('
\n') if self._show_private: out(self.PRIVATE_LINK+'\n') self.write_footer(out, short=True) def write_module_toc(self, out, doc): """ Write an HTML page containing the table of contents page for the given module to the given streams. This page lists the modules, classes, exceptions, functions, and variables defined by the module. @param public: The output stream for the public version of the page. @param private: The output stream for the private version of the page. """ name = doc.canonical_name[-1] self.write_header(out, name) out('

Module %s

\n' % name) out('
\n') # List the classes. classes = doc.select_variables(value_type='class', imported=False, public=self._public_filter) self.write_toc_section(out, "Classes", classes, fullname=False) # List the functions. funcs = doc.select_variables(value_type='function', imported=False, public=self._public_filter) self.write_toc_section(out, "Functions", funcs, fullname=False) # List the variables. variables = doc.select_variables(value_type='other', imported=False, public=self._public_filter) self.write_toc_section(out, "Variables", variables, fullname=False) # Footer material. out('
\n') if self._show_private: out(self.PRIVATE_LINK+'\n') self.write_footer(out, short=True) #//////////////////////////////////////////////////////////// #{ 2.7. Project homepage (index.html) #//////////////////////////////////////////////////////////// def write_homepage(self, directory): """ Write an C{index.html} file in the given directory. The contents of this file are copied or linked from an existing page, so this method must be called after all pages have been written. The page used is determined by L{_frames_index} and L{_top_page}: - If L{_frames_index} is true, then C{frames.html} is copied. - Otherwise, the page specified by L{_top_page} is copied. """ filename = os.path.join(directory, 'index.html') if self._frames_index: top = 'frames.html' else: top = self._top_page_url # Copy the non-frames index file from top, if it's internal. if top[:5] != 'http:' and '/' not in top: try: # Read top into `s`. topfile = os.path.join(directory, top) s = open(topfile, 'r').read() # Write the output file. open(filename, 'w').write(s) return except: log.error('Warning: error copying index; ' 'using a redirect page') # Use a redirect if top is external, or if we faild to copy. name = self._prj_name or 'this project' f = open(filename, 'w') self.write_redirect_index(f.write, top, name) f.close() write_redirect_index = compile_template( """ write_redirect_index(self, out, top, name) """, # /------------------------- Template -------------------------\ ''' Redirect

Redirecting to the API documentation for $self._prj_name or "this project"$...

''') # \------------------------------------------------------------/ #//////////////////////////////////////////////////////////// #{ 2.8. Stylesheet (epydoc.css) #//////////////////////////////////////////////////////////// def write_css(self, directory, cssname): """ Write the CSS stylesheet in the given directory. If C{cssname} contains a stylesheet file or name (from L{epydoc.docwriter.html_css}), then use that stylesheet; otherwise, use the default stylesheet. @rtype: C{None} """ filename = os.path.join(directory, 'epydoc.css') # Get the contents for the stylesheet file. if cssname is None: css = STYLESHEETS['default'][0] else: if os.path.exists(cssname): try: css = open(cssname).read() except: raise IOError("Can't open CSS file: %r" % cssname) elif STYLESHEETS.has_key(cssname): css = STYLESHEETS[cssname][0] else: raise IOError("Can't find CSS file: %r" % cssname) # Write the stylesheet. cssfile = open(filename, 'w') cssfile.write(css) cssfile.close() #//////////////////////////////////////////////////////////// #{ 2.9. Javascript (epydoc.js) #//////////////////////////////////////////////////////////// def write_javascript(self, directory): jsfile = open(os.path.join(directory, 'epydoc.js'), 'w') print >> jsfile, self.TOGGLE_PRIVATE_JS print >> jsfile, self.GET_COOKIE_JS print >> jsfile, self.SET_FRAME_JS print >> jsfile, self.HIDE_PRIVATE_JS print >> jsfile, self.TOGGLE_CALLGRAPH_JS print >> jsfile, html_colorize.PYSRC_JAVASCRIPTS jsfile.close() #: A javascript that is used to show or hide the API documentation #: for private objects. In order for this to work correctly, all #: documentation for private objects should be enclosed in #: C{
...
} elements. TOGGLE_PRIVATE_JS = ''' function toggle_private() { // Search for any private/public links on this page. Store // their old text in "cmd," so we will know what action to // take; and change their text to the opposite action. var cmd = "?"; var elts = document.getElementsByTagName("a"); for(var i=0; i