# HG changeset patch
# User J. H. Palmieri <palmieri@math.washington.edu>
# Date 1311223150 25200
# Node ID a3cf5eae8ffba4a7486b9b10866e59b604faa02b
# Parent  34d8284ab576153fa65ecbea2f57deb15bfec064
#6495: Break the reference manual into more manageable pieces.
Part 2: all important changes to files.

diff --git a/.hgignore b/.hgignore
--- a/.hgignore
+++ b/.hgignore
@@ -60,3 +60,5 @@
 doc/output/
 doc/en/reference/sage/
 doc/en/reference/sagenb/
+doc/en/reference/.*/sage/
+doc/en/reference/.*/sagenb/
diff --git a/MANIFEST.in b/MANIFEST.in
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -34,7 +34,7 @@
 include doc/fr/a_tour_of_sage/sin_plot.png
 include doc/tr/a_tour_of_sage/eigen_plot.png
 include doc/tr/a_tour_of_sage/sin_plot.png
-graft   doc/en/reference/media
+graft   doc/en/reference/*/media
 graft   doc/en/thematic_tutorials/media
 graft   doc/en/prep/media
 prune   doc/en/reference/sage
diff --git a/doc/common/builder.py b/doc/common/builder.py
--- a/doc/common/builder.py
+++ b/doc/common/builder.py
@@ -61,6 +61,32 @@
         raise shutil.Error(errors)
 
 
+##########################################
+#      Parallel Building Ref Manual      #
+##########################################
+
+def build_ref_doc(doc, lang, format, output_dir, *args, **kwds):
+    # Build the reference manual for doc
+    static_dir = os.path.join(output_dir, 'reference', '_static')
+    bad_static = os.path.join(output_dir, doc, '_static')
+    # We need to remove the link to "_static" before generating the
+    # documentation, because the html doc builder writes to the
+    # _static directory.
+    if (os.path.isdir(static_dir) and os.path.isdir(bad_static)
+        and os.path.islink(bad_static)):
+        os.remove(bad_static)
+    getattr(ReferenceSubBuilder(doc, lang), format)(*args, **kwds)
+    # The standard Sphinx html build puts a copy of the "static"
+    # directory in reference/doc/_static.  For the reference manual,
+    # these are all identical to reference/_static, so delete the
+    # directory reference/doc/_static and replace it with a link to
+    # reference/_static.  This saves hundreds of megabytes of disk
+    # space.
+    if (os.path.isdir(static_dir) and os.path.isdir(bad_static)
+        and not os.path.islink(bad_static)):
+        shutil.rmtree(bad_static)
+    if os.path.isdir(static_dir):
+        os.symlink(static_dir, bad_static)
 
 ##########################################
 #             Builders                   #
@@ -103,11 +129,15 @@
 
         - ``lang`` - (default "en") the language of the document.
         """
-        if '/' in name:
-            lang, name = name.split(os.path.sep)
-        self.name = name
+        doc = name.split(os.path.sep)
+
+        if doc[0] in LANGUAGES:
+            lang = doc[0]
+            doc.pop(0)
+
+        self.name = os.path.join(*doc)
         self.lang = lang
-        self.dir = os.path.join(SAGE_DOC, lang, name)
+        self.dir = os.path.join(SAGE_DOC, self.lang, self.name)
 
         #Make sure the .static and .templates directories are there
         mkdir(os.path.join(self.dir, "static"))
@@ -209,6 +239,7 @@
     changes = builder_helper('changes')
     linkcheck = builder_helper('linkcheck')
 
+
 class AllBuilder(object):
     """
     A class used to build all of the documentation.
@@ -228,7 +259,25 @@
         This is the function which goes through all of the documents
         and does the actual building.
         """
-        for document in self.get_all_documents():
+        docs = self.get_all_documents()
+        refs = [x for x in docs if x.endswith('reference')]
+        others = [x for x in docs if not x.endswith('reference')]
+        for document in others:
+            logger.warning("\nBuilding %s.\n" % document)
+            getattr(get_builder(document), name)(*args, **kwds)
+        # Build the reference manual twice to resolve references.
+        # That is, build once to construct the intersphinx inventory
+        # files, and then build the second time for real.  So the
+        # first build should be as fast as possible; thus do an html
+        # build first.
+        logger.warning("\nBuilding reference manual, first pass.\n")
+        global ALLSPHINXOPTS
+        ALLSPHINXOPTS += ' -Q '
+        for document in refs:
+            getattr(get_builder(document), 'html')(*args, **kwds)
+        logger.warning("Building reference manual, second pass.\n")
+        ALLSPHINXOPTS = ALLSPHINXOPTS.replace('-Q', '-q') + ' '
+        for document in refs:
             getattr(get_builder(document), name)(*args, **kwds)
 
     def get_all_documents(self):
@@ -261,6 +310,7 @@
 
         return documents
 
+
 class WebsiteBuilder(DocBuilder):
     def html(self):
         """
@@ -292,9 +342,209 @@
 
         DocBuilder.clean(self)
 
-class ReferenceBuilder(DocBuilder):
+
+class ReferenceBuilder(AllBuilder):
     """
-    This the class used to build the reference manual.  It is
+    This class builds the reference manual.  It uses DocBuilder to
+    build the top-level page and ReferenceSubBuilder for each
+    sub-component.
+    """
+    def __init__(self, name, lang='en'):
+        """
+        Records the reference manual's name, in case it's not
+        identical to 'reference'.
+        """
+        AllBuilder.__init__(self)
+        doc = name.split(os.path.sep)
+
+        if doc[0] in LANGUAGES:
+            lang = doc[0]
+            doc.pop(0)
+
+        self.name = doc[0]
+        self.lang = lang
+
+    def _output_dir(self, type, lang='en'):
+        """
+        Returns the directory where the output of type type is stored.
+        If the directory does not exist, then it will automatically be
+        created.
+
+        EXAMPLES::
+
+            sage: import os, sys; sys.path.append(os.environ['SAGE_DOC']+'/common/'); import builder
+            sage: b = builder.ReferenceBuilder('reference')
+            sage: b._output_dir('html')
+            '.../devel/sage/doc/output/html/en/reference'
+        """
+        return mkdir(os.path.join(SAGE_DOC, "output", type, lang, self.name))
+
+    def _wrapper(self, format, *args, **kwds):
+        """
+        Builds reference manuals.  For each language, it builds the
+        top-level document and its components.
+        """
+        for lang in LANGUAGES:
+            refdir = os.path.join(SAGE_DOC, lang, self.name)
+            if not os.path.exists(refdir):
+                continue
+
+            output_dir = self._output_dir(format, lang)
+            getattr(DocBuilder(self.name, lang), format)(*args, **kwds)
+
+            from multiprocessing import Pool, cpu_count
+            # Determine the number of threads from the environment variable
+            # SAGE_NUM_THREADS.
+            pool = Pool(int(os.environ.get('SAGE_NUM_THREADS', 1)))
+            for doc in self.get_all_documents(refdir):
+                pool.apply_async(build_ref_doc,
+                                 (doc, lang, format,
+                                  os.path.split(output_dir)[0]) + args, kwds)
+            pool.close()
+            pool.join()
+            if format == 'html':
+                # html build: combine the todo lists from the
+                # different modules.
+                todofile = os.path.join(output_dir, 'todolist', 'index.html')
+                old = open(todofile).read()
+                note = "The combined to do list is only available in the html version of the reference manual."
+                preamble = old.find(note)
+                postamble = preamble + len(note)
+                if preamble != -1:
+                    old_todofile = os.path.join(output_dir, 'todolist', 'index-old.html')
+                    shutil.move(todofile, old_todofile)
+                    new = open(todofile, 'w')
+                    new.write(old[:preamble])
+                    for f in os.listdir(output_dir):
+                        index = os.path.join(output_dir, f, 'index.html')
+                        if (f != 'todolist' and os.path.exists(index)):
+                            html = open(index).read()
+                            start = html.find('<div class="admonition-todo')
+                            end = html.find('<div class="section" id="indices-and-tables">')
+                            if start != -1:
+                                html = html[start:end].replace('sage/%s' %f,
+                                                               '../%s/sage/%s' % (f, f))
+                                new.write(html)
+                    new.write(old[postamble:])
+                    new.close()
+
+                logger.warning('''
+Build finished.  The Sage reference manual can be found in
+
+  %s
+''' % (os.path.join(output_dir, 'index.html')))
+            # PDF: we need to build master index file which lists all
+            # of the PDF file.  So we create an html file, based on
+            # the file index.html from the "website" target.
+            if format == 'pdf':
+                import re
+                # First build the website page.  (This only takes a
+                # few seconds.)
+                getattr(get_builder('website'), 'html')()
+                # Copy the relevant pieces of
+                # output/html/en/website/_static to output_dir.
+                # (Don't copy all of _static to save some space: we
+                # don't need all of the MathJax stuff, and in
+                # particular we don't need the fonts.)
+                website_dir = os.path.join(SAGE_DOC, 'output', 'html',
+                                           'en', 'website')
+                static_files = ['COPYING.txt', 'basic.css', 'blank.gif',
+                         'default.css', 'doctools.js', 'favicon.ico',
+                         'file.png', 'jquery.js', 'minus.png',
+                         'pdf.png', 'plus.png', 'pygments.css',
+                         'sage.css', 'sageicon.png', 'sagelogo.png',
+                         'searchtools.js', 'sidebar.js', 'underscore.js']
+                try:
+                    os.mkdir(os.path.join(output_dir, '_static'))
+                except OSError:
+                    pass
+                for f in static_files:
+                    shutil.copyfile(os.path.join(website_dir, '_static', f),
+                                    os.path.join(output_dir, '_static', f))
+                # Now modify website's index.html page and write it
+                # to output_dir.
+                f = open(os.path.join(website_dir, 'index.html'))
+                html = f.read().replace('Documentation', 'Reference')
+                f.close()
+                html_output_dir = os.path.dirname(website_dir)
+                html = html.replace('http://www.sagemath.org',
+                                    os.path.join(html_output_dir, 'index.html'))
+                # From index.html, we want the preamble and the tail.
+                html_end_preamble = html.find('<h1>Sage Reference')
+                html_bottom = html.rfind('</table>') + len('</table>')
+                # For the content, we modify doc/en/reference/index.rst,
+                # which has two parts: the body and the table of contents.
+                f = open(os.path.join(SAGE_DOC, lang, 'reference', 'index.rst'))
+                rst = f.read()
+                f.close()
+                # Replace rst links with html links.  There are two types:
+                #
+                # `blah`__
+                # __ link
+                #
+                # `blah <module/index.html>`_
+                #
+                # For the second type, also change "module/index.html"
+                # to "module/module.pdf".
+                rst = re.sub('`([^`]*)`__\.\n\n__ (.*)',
+                                  r'<a href="\2">\1</a>.', rst)
+                rst = re.sub(r'`([^<]*?)\s+<(.*)/index\.html>`_',
+                             r'<a href="\2/\2.pdf">\1 <img src="_static/pdf.png" /></a>',
+                             rst)
+                start = rst.find('=\n') + 1
+                end = rst.find('Table of Contents')
+                # Body: add paragraph <p> markup.
+                rst_body = rst[start:end]
+                rst_body = rst_body.replace('\n\n', '</p>\n<p>')
+                start = rst.find('Table of Contents') + 2*len('Table of Contents') + 1
+                end = rst.find('.. include:: footer.txt')
+                # TOC: change * to <li>, change rst headers to html headers.
+                rst_toc = rst[start:end]
+                rst_toc = rst_toc.replace('*', '<li>')
+                rst_toc = re.sub('\n([A-Z][a-zA-Z, ]*)\n-*\n',
+                             '</ul>\n\n\n<h2>\\1</h2>\n\n<ul>\n', rst_toc)
+                # Now write the file.
+                new_index = open(os.path.join(output_dir, 'index.html'), 'w')
+                new_index.write(html[:html_end_preamble])
+                new_index.write('<h1>' + rst[:rst.find('\n')] +
+                                ' (PDF version)'+ '</h1>')
+                new_index.write(rst_body)
+                new_index.write('<h2>Table of Contents</h2>\n\n<ul>')
+                new_index.write(rst_toc)
+                new_index.write('</ul>\n\n')
+                new_index.write(html[html_bottom:])
+                new_index.close()
+                logger.warning('''
+PDF documents have been created in subdirectories of
+
+  %s
+
+Alternatively, you can open
+
+  %s
+
+for a webpage listing all of the documents.''' % (output_dir,
+                                                 os.path.join(output_dir,
+                                                              'index.html')))
+
+    def get_all_documents(self, refdir):
+        """
+        Returns a list of all reference manual components to build.
+        We add a component name if it's a subdirectory of the manual's
+        directory and contains a file named 'index.rst'.
+        """
+        documents = []
+
+        for doc in os.listdir(refdir):
+            if os.path.exists(os.path.join(refdir, doc, 'index.rst')):
+                documents.append(os.path.join(self.name, doc))
+        
+        return documents
+
+
+class ReferenceSubBuilder(DocBuilder):
+    """
+    This class builds sub-components of the reference manual.  It is
     resposible for making sure the auto generated ReST files for the
     Sage library are up to date.
 
@@ -705,14 +955,16 @@
 
 def get_builder(name):
     """
-    Returns a either a AllBuilder or DocBuilder object depending
-    on whether ``name`` is 'all' or not.  These are the objects
-    which do all the real work in building the documentation.
+    Returns an appropriate *Builder object for the document ``name``.
+    DocBuilder and its subclasses do all the real work in building the
+    documentation.
     """
     if name == 'all':
         return AllBuilder()
     elif name.endswith('reference'):
         return ReferenceBuilder(name)
+    elif 'reference' in name:
+        return ReferenceSubBuilder(name)
     elif name.endswith('website'):
         return WebsiteBuilder(name)
     elif name in get_documents() or name in AllBuilder().get_all_documents():
@@ -802,9 +1054,14 @@
     shortcut 'all' for all documents, available to the Sage
     documentation builder.
     """
+    docs = get_documents()
     s += "DOCUMENTs:\n"
-    s += format_columns(get_documents() + ['all  (!)'])
-    s += "(!) Builds everything.\n"
+    s += format_columns(docs + ['all  (!)'])
+    s += "(!) Builds everything.\n\n"
+    if 'reference' in docs:
+        s+= "Other valid document names take the form 'reference/DIR', where\n"
+        s+= "DIR is a subdirectory of SAGE_ROOT/devel/sage/doc/en/reference/.\n"
+        s+= "This builds just the specified part of the reference manual.\n"
     return s
 
 def get_formats():
diff --git a/doc/common/themes/sage/layout.html b/doc/common/themes/sage/layout.html
--- a/doc/common/themes/sage/layout.html
+++ b/doc/common/themes/sage/layout.html
@@ -7,7 +7,7 @@
     {% if pathto(master_doc).endswith('.html') %}
       <a href="{{ '../' + pathto(master_doc) }}"><img src="{{ pathto('_static/sagelogo.png', 1) }}" style="vertical-align: middle" title="Sage Logo"></a>
     {% else %}
-      <a href="{{ '../' + pathto(master_doc) + 'index.html' }}"><img src="{{ pathto('_static/sagelogo.png', 1) }}" style="vertical-align: middle" title="Sage Logo"></a>
+      <a href="{{ '../' + pathto(master_doc, 1) + '.html' }}"><img src="{{ pathto('_static/sagelogo.png', 1) }}" style="vertical-align: middle" title="Sage Logo"></a>
     {% endif %}
   {% endif %}
   {{ super() }}
diff --git a/doc/common/themes/sageref/layout.html b/doc/common/themes/sageref/layout.html
new file mode 100644
--- /dev/null
+++ b/doc/common/themes/sageref/layout.html
@@ -0,0 +1,182 @@
+{% extends "basic/layout.html" %}
+
+{% block rootrellink %}
+  {% if docstitle.startswith('Sage Documentation') %}
+    <a href="http://www.sagemath.org"><img src="{{ pathto('_static/sagelogo.png', 1) }}" style="vertical-align: middle" title="Sage Logo"></a>
+  {% else %}
+    {% if pathto(master_doc).endswith('.html') %}
+      <a href="{{ '../../' + pathto(master_doc) }}"><img src="{{ pathto('_static/sagelogo.png', 1) }}" style="vertical-align: middle" title="Sage Logo"></a>
+    {% else %}
+      <a href="{{ '../../' + pathto(master_doc,1) + '.html' }}"><img src="{{ pathto('_static/sagelogo.png', 1) }}" style="vertical-align: middle" title="Sage Logo"></a>
+      <a href="{{ '../' + 'index.html' }}"> Sage Reference Manual </a> &raquo;
+    {% endif %}
+  {% endif %}
+  {{ super() }}
+{% endblock %}
+
+{% block extrahead %}
+    <link rel="icon" href="{{ pathto('_static/sageicon.png', 1) }}" type="image/x-icon" />
+{% endblock %}
+
+{%- block footer %}
+    {{ super() }}
+    <script type="text/javascript">
+/*global jQuery, window */
+/* Sphinx sidebar toggle.  Putting this code at the end of the body
+ * enables the toggle for the live, static, and offline docs.  Note:
+ * sage.misc.html.math_parse() eats jQuery's dollar-sign shortcut. */
+var jq = jQuery;  
+jq(document).ready(function () {
+    var bar, bod, bg, fg, key, tog, wid_old, wid_new, resize, get_state, set_state;
+    bod = jq('div.bodywrapper');
+    bar = jq('div.sphinxsidebar');
+    tog = jq('<div class="sphinxsidebartoggle"></div>');
+    
+    /* Delayed resize helper.  Not perfect but good enough. */
+    resize = function () {
+        setTimeout(function () {
+            tog.height(bod.height());
+        }, 100);
+    };
+    jq(window).resize(function () {
+        resize();
+    });
+    
+    /* Setup and add the toggle. See Sphinx v0.5.1 default.css. */
+    fg = jq('div.sphinxsidebar p a').css('color') || 'rgb(152, 219, 204)';
+    bg = jq('div.document').css('background-color') || 'rgb(28, 78, 99)';
+    wid_old = '230px';
+    wid_new = '5px';
+    tog.css('background-color', bg)
+        .css('border-width', '0px')
+        .css('border-right', wid_new + ' ridge ' + bg)
+        .css('cursor', 'pointer')
+        .css('position', 'absolute')
+        .css('left', '-' + wid_new)
+        .css('top', '0px')
+        .css('width', wid_new);
+    bod.css('position', 'relative');
+    bod.prepend(tog);
+    resize();
+    
+    /* Cookie helpers. */
+    key = 'sphinxsidebar=';
+    set_state = function (s) {
+        var date = new Date();
+        /* Expiry in 7 days. */
+        date.setTime(date.getTime() + (7 * 24 * 3600 * 1000));
+        document.cookie = key + encodeURIComponent(s) + '; expires=' +
+            date.toUTCString() + '; path=/';
+    };
+    get_state = function () {
+        var i, c, crumbs = document.cookie.split(';');
+        for (i = 0; i < crumbs.length; i += 1) {
+            c = crumbs[i].replace(/^\s+/, '');
+            if (c.indexOf(key) === 0) {
+                return decodeURIComponent(c.substring(key.length, c.length));
+            }
+        }
+        return null;
+    };
+    
+    /* Event handlers. */
+    tog.mouseover(function (ev) {
+        tog.css('border-right-color', fg);
+    }).mouseout(function (ev) {
+        tog.css('border-right-color', bg);
+    }).click(function (ev) {
+        if (bod.hasClass('wide')) {
+            bod.removeClass('wide');
+            bod.css('margin-left', wid_old);
+            bar.css('width', wid_old);
+            bar.show();
+            set_state('visible');
+        } else {
+            set_state('hidden');
+            bar.hide();
+            bar.css('width', '0px');
+            bod.css('margin-left', wid_new);
+            bod.addClass('wide');
+        }
+        resize();
+    });
+    
+    /* Hide the normally visible sidebar? */
+    if (get_state() === 'hidden') {
+        tog.trigger('click');
+    } else {
+        set_state('visible');
+    }
+});
+    </script>
+{%- endblock %}
+
+<!-- This macro block for the sidebar is heavily borrowed from the basic -->
+<!-- theme of Sphinx 0.6.3. In particular, we borrowed from the file -->
+<!-- themes/basic/layout.html distributed with Sphinx 0.6.3. -->
+{%- macro sidebar() %}
+      {%- if not embedded %}{% if not theme_nosidebar|tobool %}
+      <div class="sphinxsidebar">
+        <div class="sphinxsidebarwrapper">
+          {%- block sidebarlogo %}
+          {%- if logo %}
+            <p class="logo"><a href="{{ pathto(master_doc) }}">
+              <img class="logo" src="{{ pathto('_static/' + logo, 1) }}" alt="Logo"/>
+            </a></p>
+          {%- endif %}
+          {%- endblock %}
+          {%- block sidebartoc %}
+          {%- if display_toc %}
+            <h3><a href="{{ pathto(master_doc) }}">{{ _('Table Of Contents') }}</a></h3>
+            {{ toc }}
+          {%- endif %}
+          {%- endblock %}
+          {%- block sidebarrel %}
+          {%- if prev %}
+            <h4>{{ _('Previous topic') }}</h4>
+            <p class="topless"><a href="{{ prev.link|e }}"
+                                  title="{{ _('previous chapter') }}">{{ prev.title }}</a></p>
+          {%- endif %}
+          {%- if next %}
+            <h4>{{ _('Next topic') }}</h4>
+            <p class="topless"><a href="{{ next.link|e }}"
+                                  title="{{ _('next chapter') }}">{{ next.title }}</a></p>
+          {%- endif %}
+          {%- endblock %}
+          {%- block sidebarsourcelink %}
+          {%- if show_source and has_source and sourcename %}
+            <h3>{{ _('This Page') }}</h3>
+            <ul class="this-page-menu">
+              <li><a href="{{ pathto('_sources/' + sourcename, true)|e }}"
+                     rel="nofollow">{{ _('Show Source') }}</a></li>
+            </ul>
+          {%- endif %}
+          {%- endblock %}
+          {%- if customsidebar %}
+          {% include customsidebar %}
+          {%- endif %}
+          {%- block sidebarsearch %}
+          {%- if pagename != "search" %}
+          <div id="searchbox" style="display: none">
+            <h3>{{ _('Quick search') }}</h3>
+              <form class="search" action="{{ pathto('search') }}" method="get">
+                <input type="text" name="q" size="18" />
+               <!-- The shading of the "Go" button should be consistent -->
+               <!-- with the colour of the header and footer. See the file -->
+               <!-- doc/common/themes/sage/theme.conf for colours used by -->
+               <!-- the Sage theme. -->
+                <input type="submit" style="background-color: #B8B9F6" value="{{ _('Go') }}" />
+                <input type="hidden" name="check_keywords" value="yes" />
+                <input type="hidden" name="area" value="default" />
+              </form>
+              <p class="searchtip" style="font-size: 90%">
+              {{ _('Enter search terms or a module, class or function name.') }}
+              </p>
+          </div>
+          <script type="text/javascript">$('#searchbox').show(0);</script>
+          {%- endif %}
+          {%- endblock %}
+        </div>
+      </div>
+      {%- endif %}{% endif %}
+{%- endmacro %}
diff --git a/doc/common/themes/sageref/static/favicon.ico b/doc/common/themes/sageref/static/favicon.ico
new file mode 100644
index 0000000000000000000000000000000000000000..51775bc542a5d8653935c5223b9ecd616cb1e085
GIT binary patch
literal 1150
zc$}q^KT88a5XI-z_zxqeVh|AtA|eQ4DMCcCv$3+X(Mmr+K(M%gtyrWLECfYJC)n9o
z2^L9_A}A@u;z;mAoNv5$FsyefxZxKzGy7&|XC@*ZKE5ybF3Mq_NI^sv0Zg#O_OAtB
zD<6}rC<s1McmwC)IK%%FZEyfIb}twP^NdybMf(mm!6+C31yBduU=`%R7<kFhuY(c@
zK^06pv2TH&@vdF41-j<^lyjy7YM^LruRLe92?LB{ZA~y^YH<lXzD>`sfF0)Ou?8KZ
z*SC#>vU5*`xjcdku*4oHdG;Ux&%D26^mB}B^IT)x9^S9I1uzSSm|L4?m%)+Imd)F>
zkN3vcWo{FuUUy)F`|Bv4n+AVtE%uE5lzMk=^bHTx){O6l_0s(l_ij%Vozs4B=Ga5V
z)c?dJ>+5Pm*280*EA~0@YrS-4PExc9nw!q&KHsNz4KgR~VJ`YUUw=XG)ETR$`Q@MM
E6WVp2FaQ7m

diff --git a/doc/common/themes/sageref/static/mathjax_sage.js_t b/doc/common/themes/sageref/static/mathjax_sage.js_t
new file mode 100644
--- /dev/null
+++ b/doc/common/themes/sageref/static/mathjax_sage.js_t
@@ -0,0 +1,21 @@
+MathJax.Hub.Config({
+  imageFont: null,
+  tex2jax: {
+    inlineMath: [['$','$'],['\\(','\\)']],
+    processEscapes: true,
+  },
+  styles: {
+    ".MathJax .mo, .MathJax .mi": {
+      color: "inherit ! important"
+    }
+  },
+  TeX: {
+    Macros: {
+     {{ theme_mathjax_macros|join(',\n') }}
+    }
+  }
+});
+
+// This path is a little funny because we have to load our local
+// config file as '../mathjax_sage' in the theme conf.py
+MathJax.Ajax.loadComplete("[MathJax]/config/../mathjax_sage.js")
diff --git a/doc/common/themes/sageref/static/sage.css_t b/doc/common/themes/sageref/static/sage.css_t
new file mode 100644
--- /dev/null
+++ b/doc/common/themes/sageref/static/sage.css_t
@@ -0,0 +1,253 @@
+/**
+ * Sage stylesheet theme. This stylesheet is heavily borrowed from the
+ * Sphinx stylesheet default theme distributed as the file
+ * themes/default/static/default.css_t in Sphinx 0.6.3.
+ */
+
+@import url("basic.css");
+
+/* -- page layout ----------------------------------------------------------- */
+
+body {
+    font-family: {{ theme_bodyfont }};
+    font-size: 100%;
+    background-color: {{ theme_footerbgcolor }};
+    color: #000;
+    margin: 0;
+    padding: 0;
+}
+
+div.document {
+    background-color: {{ theme_sidebarbgcolor }};
+}
+
+div.documentwrapper {
+    float: left;
+    width: 100%;
+}
+
+div.bodywrapper {
+    margin: 0 0 0 230px;
+}
+
+div.body {
+    background-color: {{ theme_bgcolor }};
+    color: {{ theme_textcolor }};
+    padding: 0 20px 30px 20px;
+}
+
+{%- if theme_rightsidebar|tobool %}
+div.bodywrapper {
+    margin: 0 230px 0 0;
+}
+{%- endif %}
+
+div.footer {
+    color: {{ theme_footertextcolor }};
+    width: 100%;
+    padding: 9px 0 9px 0;
+    text-align: center;
+    font-size: 75%;
+}
+
+div.footer a {
+    color: {{ theme_footertextcolor }};
+    text-decoration: underline;
+}
+
+div.related {
+    background-color: {{ theme_relbarbgcolor }};
+    line-height: 30px;
+    color: {{ theme_relbartextcolor }};
+}
+
+div.related a {
+    color: {{ theme_relbarlinkcolor }};
+}
+
+div.sphinxsidebar {
+    {%- if theme_stickysidebar|tobool %}
+    top: 30px;
+    margin: 0;
+    position: fixed;
+    overflow: auto;
+    height: 100%;
+    {%- endif %}
+    {%- if theme_rightsidebar|tobool %}
+    float: right;
+    {%- if theme_stickysidebar|tobool %}
+    right: 0;
+    {%- endif %}
+    {%- endif %}
+}
+
+{%- if theme_stickysidebar|tobool %}
+/* this is nice, but it it leads to hidden headings when jumping
+   to an anchor */
+/*
+div.related {
+    position: fixed;
+}
+
+div.documentwrapper {
+    margin-top: 30px;
+}
+*/
+{%- endif %}
+
+div.sphinxsidebar h3 {
+    font-family: {{ theme_headfont }};
+    color: {{ theme_sidebartextcolor }};
+    font-size: 1.4em;
+    font-weight: normal;
+    margin: 0;
+    padding: 0;
+}
+
+div.sphinxsidebar h3 a {
+    color: {{ theme_sidebartextcolor }};
+}
+
+div.sphinxsidebar h4 {
+    font-family: {{ theme_headfont }};
+    color: {{ theme_sidebartextcolor }};
+    font-size: 1.3em;
+    font-weight: normal;
+    margin: 5px 0 0 0;
+    padding: 0;
+}
+
+div.sphinxsidebar p {
+    color: {{ theme_sidebartextcolor }};
+}
+
+div.sphinxsidebar p.topless {
+    margin: 5px 10px 10px 10px;
+}
+
+div.sphinxsidebar ul {
+    margin: 10px;
+    padding: 0;
+    color: {{ theme_sidebartextcolor }};
+}
+
+div.sphinxsidebar a {
+    color: {{ theme_sidebarlinkcolor }};
+}
+
+div.sphinxsidebar input {
+    border: 1px solid {{ theme_sidebarlinkcolor }};
+    font-family: sans-serif;
+    font-size: 1em;
+}
+
+/* -- body styles ----------------------------------------------------------- */
+
+a {
+    color: {{ theme_linkcolor }};
+    text-decoration: none;
+}
+
+a:hover {
+    text-decoration: underline;
+}
+
+div.body p, div.body dd, div.body li {
+    text-align: justify;
+    line-height: 130%;
+}
+
+div.body h1,
+div.body h2,
+div.body h3,
+div.body h4,
+div.body h5,
+div.body h6 {
+    font-family: {{ theme_headfont }};
+    background-color: {{ theme_headbgcolor }};
+    font-weight: normal;
+    color: {{ theme_headtextcolor }};
+    border-bottom: 1px solid #ccc;
+    margin: 20px -20px 10px -20px;
+    padding: 3px 0 3px 10px;
+}
+
+div.body h1 { margin-top: 0; font-size: 200%; }
+div.body h2 { font-size: 160%; }
+div.body h3 { font-size: 140%; }
+div.body h4 { font-size: 120%; }
+div.body h5 { font-size: 110%; }
+div.body h6 { font-size: 100%; }
+
+a.headerlink {
+    color: {{ theme_headlinkcolor }};
+    font-size: 0.8em;
+    padding: 0 4px 0 4px;
+    text-decoration: none;
+}
+
+a.headerlink:hover {
+    background-color: {{ theme_headlinkcolor }};
+    color: white;
+}
+
+div.body p, div.body dd, div.body li {
+    text-align: justify;
+    line-height: 130%;
+}
+
+div.admonition p.admonition-title + p {
+    display: inline;
+}
+
+div.note {
+    background-color: #eee;
+    border: 1px solid #ccc;
+}
+
+div.seealso {
+    background-color: #ffc;
+    border: 1px solid #ff6;
+}
+
+div.topic {
+    background-color: #eee;
+}
+
+div.warning {
+    background-color: #ffe4e4;
+    border: 1px solid #f66;
+}
+
+p.admonition-title {
+    display: inline;
+}
+
+p.admonition-title:after {
+    content: ":";
+}
+
+/**
+ * Code block.
+ * The border colour should be a darker shade of the background colour.
+ * The hex code #E8D898 used below is a pale, light grayish amber.
+ */
+pre {
+    padding: 5px;
+    background-color: {{ theme_codebgcolor }};
+    color: {{ theme_codetextcolor }};
+    line-height: 120%;
+    border: 1px solid #E8D898;
+    border-left: none;
+    border-right: none;
+}
+
+/**
+ * Commands or code within text. The hex code #EAEAF8 used below is a
+ * pale, light grayish blue.
+ */
+tt {
+    background-color: #EAEAF8;
+    padding: 0 1px 0 1px;
+    font-size: 0.95em;
+}
diff --git a/doc/common/themes/sageref/theme.conf b/doc/common/themes/sageref/theme.conf
new file mode 100644
--- /dev/null
+++ b/doc/common/themes/sageref/theme.conf
@@ -0,0 +1,54 @@
+[theme]
+inherit = default
+stylesheet = sage.css
+pygments_style = sphinx
+
+[options]
+# Custom Sage theme options
+
+# MathJax settings filled in by conf.py
+mathjax_macros =
+
+# Sphinx default theme options
+
+#nosidebar = false
+#rightsidebar = false
+#stickysidebar = false
+
+# Background color for the footer line: pale, light grayish blue (CSS color):
+footerbgcolor    = #B8B9F6
+# Text color for the footer line: black (CSS color): 
+footertextcolor  = #000000
+# Background color for the sidebar: light bluish gray (CSS color): 
+sidebarbgcolor   = #EAEAF8
+# Text color for the sidebar: black (CSS color): 
+sidebartextcolor = #000000
+# Link color for the sidebar: dark blue (CSS color): 
+sidebarlinkcolor = #090999
+# Background color for the relation bar: pale, light grayish blue (CSS color): 
+relbarbgcolor    = #B8B9F6
+# Text color for the relation bar: black (CSS color): 
+relbartextcolor  = #000000
+# Link color for the relation bar: dark blue (CSS color): 
+relbarlinkcolor  = #090999
+# Body background color (CSS color):
+#bgcolor          = #ffffff
+# Body text color: black (CSS color): 
+textcolor        = #000000
+# Background color for headings: light bluish gray (CSS color): 
+headbgcolor      = #EAEAF8
+# Text color for headings (CSS color):
+#headtextcolor    = #20435c
+# Link color for headings (CSS color):
+#headlinkcolor    = #c60f0f
+# Body link color: dark greenish blue (CSS color): 
+linkcolor        = #45529B
+# Background color for code blocks: very pale yellow (CSS color): 
+codebgcolor      = #FFFFE5
+# Default text color for code blocks, if not set differently by the highlighting style (CSS color):
+#codetextcolor    = #333333
+
+# Font for normal text (CSS font-family):
+#bodyfont = sans-serif
+# Font for headings (CSS font-family):
+#headfont = 'Trebuchet MS', sans-serif
diff --git a/doc/en/reference/arithgroup/index.rst b/doc/en/reference/arithgroup/index.rst
--- a/doc/en/reference/arithgroup/index.rst
+++ b/doc/en/reference/arithgroup/index.rst
@@ -1,5 +1,5 @@
-Arithmetic Subgroups of `{\rm SL}_2(\ZZ)`
-================================================
+Arithmetic Subgroups of `{\rm SL}_2({\bf Z})`
+=============================================
 
 This chapter describes the basic functionality for finite index subgroups of
 the modular group `{\rm SL}_2(\ZZ)`.
diff --git a/doc/en/reference/conf.py b/doc/en/reference/conf.py
--- a/doc/en/reference/conf.py
+++ b/doc/en/reference/conf.py
@@ -15,6 +15,16 @@
 sys.path.append(os.environ['SAGE_DOC'])
 from common.conf import *
 
+# settings for the intersphinx extension:
+
+ref_src = os.path.join(SAGE_DOC, 'en', 'reference')
+ref_out = os.path.join(SAGE_DOC, 'output', 'html', 'en', 'reference')
+intersphinx_mapping[ref_out] = None
+
+for doc in os.listdir(ref_src):
+    if os.path.exists(os.path.join(ref_src, doc, 'index.rst')):
+        intersphinx_mapping[os.path.join(ref_out, doc)] = None
+
 # General information about the project.
 project = u"Sage Reference Manual"
 name = "reference"
@@ -50,3 +60,67 @@
 
 #Ignore all .rst in the _sage subdirectory
 exclude_trees = exclude_trees + ['_sage']
+
+# List of directories, relative to source directory, that shouldn't be
+# searched for source files.
+exclude_trees = exclude_trees + [
+    'algebras',
+    'arithgroup',
+    'calculus',
+    'categories',
+    'cmd',
+    'coding',
+    'coercion',
+    'combinat',
+    'constants',
+    'cryptography',
+    'databases',
+    'finance',
+    'finite_rings',
+    'function_fields',
+    'functions',
+    'games',
+    'geometry',
+    'graphs',
+    'groups',
+    'hecke',
+    'history_and_license',
+    'homology',
+    'interfaces',
+    'lfunctions',
+    'libs',
+    'logic',
+    'matrices',
+    'misc',
+    'modabvar',
+    'modfrm',
+    'modmisc',
+    'modsym',
+    'modules',
+    'monoids',
+    'notebook',
+    'number_fields',
+    'numerical',
+    'options',
+    'padics',
+    'parallel',
+    'plane_curves',
+    'plot3d',
+    'plotting',
+    'polynomial_rings',
+    'power_series',
+    'probability',
+    'quadratic_forms',
+    'quat_algebras',
+    'rings',
+    'rings_numerical',
+    'rings_standard',
+    'sage',
+    'sagenb',
+    'schemes',
+    'semirings',
+    'stats',
+    'structure',
+    'tensor',
+    'todolist'
+    ]
diff --git a/doc/en/reference/conf_sub.py b/doc/en/reference/conf_sub.py
new file mode 100644
--- /dev/null
+++ b/doc/en/reference/conf_sub.py
@@ -0,0 +1,71 @@
+# -*- coding: utf-8 -*-
+#
+# Sage documentation build configuration file, created by
+# sphinx-quickstart on Thu Aug 21 20:15:55 2008.
+#
+# This file is execfile()d with the current directory set to its containing dir.
+#
+# The contents of this file are pickled, so don't put values in the namespace
+# that aren't pickleable (module imports are okay, they're removed automatically).
+#
+# All configuration values have a default; values that are commented out
+# serve to show the default.
+
+import sys, os
+sys.path.append(os.environ['SAGE_DOC'])
+from common.conf import *
+
+# settings for the intersphinx extension:
+
+ref_src = os.path.join(SAGE_DOC, 'en', 'reference')
+ref_out = os.path.join(SAGE_DOC, 'output', 'html', 'en', 'reference')
+intersphinx_mapping[ref_out] = None
+
+for doc in os.listdir(ref_src):
+    if os.path.exists(os.path.join(ref_src, doc, 'index.rst')):
+        intersphinx_mapping[os.path.join(ref_out, doc)] = None
+
+# We use the main document's title, if we can find it.
+rst_file = open('index.rst', 'r')
+rst_lines = rst_file.read().splitlines()
+rst_file.close()
+
+title = u''
+for i in xrange(len(rst_lines)):
+    if rst_lines[i].startswith('==') and i > 0:
+        title = rst_lines[i-1].strip()
+        break
+
+# Otherwise, we use this directory's name.
+name = os.path.basename(os.path.abspath('.'))
+if not title:
+    title = name.capitalize()
+title = title.replace(u'`', u'$')
+
+# General information about the project.
+project = u'Sage Reference Manual: ' + title
+
+# The name for this set of Sphinx documents.  If None, it defaults to
+# "<project> v<release> documentation".
+html_title = u'Sage Reference Manual v' + release + ': ' + title
+
+# A shorter title for the navigation bar.  Default is the same as html_title.
+html_short_title = title
+
+# HTML theme (e.g., 'default', 'sphinxdoc').  The pages for the
+# reference manual use a custom theme, a slight variant on the 'sage'
+# theme, to set the links in the top line.
+html_theme = 'sageref'
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = name
+
+# Grouping the document tree into LaTeX files. List of tuples (source
+# start file, target name, title, author, document class
+# [howto/manual]).
+latex_documents = [
+('index', name + '.tex', project, u'The Sage Development Team', 'manual')
+]
+
+#Ignore all .rst in the _sage subdirectory
+exclude_trees = exclude_trees + ['_sage']
diff --git a/doc/en/reference/footer.txt b/doc/en/reference/footer.txt
new file mode 100644
--- /dev/null
+++ b/doc/en/reference/footer.txt
@@ -0,0 +1,12 @@
+
+.. todolist::
+
+Indices and Tables
+==================
+
+.. toctree::
+   :maxdepth: 1
+
+* :ref:`genindex`
+* :ref:`modindex`
+* :ref:`search`
diff --git a/doc/en/reference/games/index.rst b/doc/en/reference/games/index.rst
--- a/doc/en/reference/games/index.rst
+++ b/doc/en/reference/games/index.rst
@@ -2,7 +2,8 @@
 =====
 
 Sage includes a sophisticated Sudoku solver.  It also has a
-Rubik's cube solver (see :ref:`Rubik's Cube Group <sec-rubik>`).
+Rubik's cube solver (see
+`Rubik's Cube Group <../groups/sage/groups/perm_gps/cubegroup.html>`_).
 
 .. toctree::
    :maxdepth: 2
diff --git a/doc/en/reference/hecke/index.rst b/doc/en/reference/hecke/index.rst
--- a/doc/en/reference/hecke/index.rst
+++ b/doc/en/reference/hecke/index.rst
@@ -3,8 +3,9 @@
 
 This chapter describes the basic functionality for modules over Hecke
 algebras, including decompositions, degeneracy maps and so on. For specific
-examples of Hecke algebras that use this functionality see :ref:`ch:modsym` and
-:ref:`ch:modular`.
+examples of Hecke algebras that use this functionality see `Modular
+Symbols <../modsym/index.html>`_ and `Modular Forms
+<../modfrm/index.html>`_.
 
 .. toctree::
    :maxdepth: 2
diff --git a/doc/en/reference/index.rst b/doc/en/reference/index.rst
--- a/doc/en/reference/index.rst
+++ b/doc/en/reference/index.rst
@@ -1,9 +1,3 @@
-.. Sage Reference Manual documentation master file, created by sphinx-quickstart on Sun Sep 28 03:34:37 2008.
-   You can adapt this file completely to your liking, but it should at least
-   contain the root `toctree` directive.
-
-.. _ch:intro:
-
 Welcome to Sage's Reference Manual!
 =================================================
 
@@ -20,15 +14,15 @@
 Sage, and should produce exactly the same output as in this manual,
 except for line breaks.
 
-The Sage command line is briefly described in :ref:`ch:cmdline`, which
-lists the command line options. For more details about the command
-line, see the Sage tutorial.
+The Sage command line is briefly described in `The Sage Command Line 
+<cmd/index.html>`_, which lists the command line options. For more
+details about the command line, see the Sage tutorial.
 
-The Sage graphical user interface is described in
-:ref:`ch:notebook`. This graphical user interface is unusual in that
-it operates via your web browser. It provides you with Sage worksheets
-that you can edit and evaluate, which contain scalable typeset
-mathematics and beautiful antialiased images.
+The Sage graphical user interface is described in `The Sage Notebook 
+<notebook/index.html>`_. This graphical user interface is unusual in
+that it operates via your web browser. It provides you with Sage
+worksheets that you can edit and evaluate, which contain scalable
+typeset mathematics and beautiful antialiased images.
 
 This work is licensed under a `Creative Commons Attribution-Share Alike
 3.0 License`__.
@@ -37,73 +31,105 @@
 
 Enjoy Sage!
 
-.. toctree::
-   :maxdepth: 2
+Table of Contents
+=================
 
-   cmd
-   notebook
-   calculus
-   plotting
-   plot3d
-   games
-   graphs
-   constants
-   functions
-   parallel
-   structure
-   coercion
-   misc
-   databases
-   interfaces
-   libs
-   cryptography
-   logic
-   sat
-   combinat/index
-   numerical
-   probability
-   stats 
-   finance
-   categories
-   monoids
-   groups
-   rings
-   rings_standard
-   rings_numerical
-   finite_rings
-   number_fields
-   function_fields
-   padics
-   polynomial_rings
-   power_series
-   semirings
-   algebras
-   quadratic_forms
-   quat_algebras
-   matrices
-   modules
-   geometry
-   homology
-   lfunctions
-   schemes
-   plane_curves
-   coding
-   arithgroup
-   hecke
-   modsym
-   modfrm
-   modabvar
-   modmisc
-   tensor
+   * `The Sage Command Line <cmd/index.html>`_
+   * `The Sage Notebook <notebook/index.html>`_
+ 
+Calculus, Plotting
+------------------
+ 
+   * `Symbolic Calculus <calculus/index.html>`_
+   * `Constants <constants/index.html>`_
+   * `Functions <functions/index.html>`_
+   * `2D Graphics <plotting/index.html>`_
+   * `3D Graphics <plot3d/index.html>`_
+ 
+Combinatorics, Discrete Mathematics
+-----------------------------------
+ 
+   * `Combinatorics <combinat/index.html>`_
+   * `Graph Theory <graphs/index.html>`_
+ 
+Structures, Coercion, Categories
+--------------------------------
+ 
+   * `Basic Structures <structure/index.html>`_
+   * `Coercion <coercion/index.html>`_
+   * `Category Theory and Categories <categories/index.html>`_
+ 
+Rings, Fields, Algebras
+-----------------------
+ 
+   * `General Rings, Ideals, and Morphisms <rings/index.html>`_
+   * `Standard Commutative Rings <rings_standard/index.html>`_
+   * `Fixed and Arbitrary Precision Numerical Fields <rings_numerical/index.html>`_
+   * `Finite Rings <finite_rings/index.html>`_
+   * `Algebraic Number Fields <number_fields/index.html>`_
+   * `Function Fields <function_fields/index.html>`_
+   * `p-Adics <padics/index.html>`_
+   * `Polynomial Rings <polynomial_rings/index.html>`_
+   * `Power Series Rings <power_series/index.html>`_
+   * `Standard Semirings <semirings/index.html>`_
+   * `Algebras <algebras/index.html>`_
+   * `Quaternion Algebras <quat_algebras/index.html>`_
+ 
+Groups, Monoids, Matrices, Modules
+----------------------------------
+ 
+   * `Groups <groups/index.html>`_
+   * `Monoids <monoids/index.html>`_
+   * `Matrices and Spaces of Matrices <matrices/index.html>`_
+   * `Modules <modules/index.html>`_
 
-   todolist
+Geometry and Topology
+---------------------
 
-   history_and_license
+   * `Combinatorial Geometry <geometry/index.html>`_
+   * `Cell Complexes and their Homology <homology/index.html>`_
+   * `Differential Forms <tensor/index.html>`_
 
-Indices and tables
-==================
+Number Theory, Algebraic Geometry
+---------------------------------
 
-* :ref:`genindex`
-* :ref:`modindex`
-* :ref:`search`
+   * `Quadratic Forms <quadratic_forms/index.html>`_
+   * `L-Functions <lfunctions/index.html>`_
+   * `Schemes <schemes/index.html>`_
+   * `Elliptic, Plane, and Hyperelliptic Curves <plane_curves/index.html>`_
+   * `Arithmetic Subgroups of SL_2(Z) <arithgroup/index.html>`_
+   * `General Hecke Algebras and Hecke Modules <hecke/index.html>`_
+   * `Modular Symbols <modsym/index.html>`_
+   * `Modular Forms <modfrm/index.html>`_
+   * `Modular Abelian Varieties <modabvar/index.html>`_
+   * `Miscellaneous Modular-Form-Related Modules <modmisc/index.html>`_
 
+Miscellaneous Mathematics
+-------------------------
+
+   * `Games <games/index.html>`_
+   * `Symbolic Logic <logic/index.html>`_
+   * `SAT solvers <sat/index.html>`_
+   * `Cryptography <cryptography/index.html>`_
+   * `Numerical Optimization <numerical/index.html>`_
+   * `Probability <probability/index.html>`_
+   * `Statistics <stats/index.html>`_
+   * `Quantitative Finance <finance/index.html>`_
+   * `Coding Theory <coding/index.html>`_
+
+Interfaces, Databases, Miscellany
+---------------------------------
+
+   * `Interpreter Interfaces <interfaces/index.html>`_
+   * `C/C++ Library Interfaces <libs/index.html>`_
+   * `Databases <databases/index.html>`_
+   * `Parallel Computing <parallel/index.html>`_
+   * `Miscellaneous <misc/index.html>`_
+
+Other
+-----
+
+   * `Sage's To Do List <todolist/index.html>`_
+   * `History and License <history_and_license/index.html>`_
+
+.. include:: footer.txt
diff --git a/doc/en/reference/interfaces/index.rst b/doc/en/reference/interfaces/index.rst
--- a/doc/en/reference/interfaces/index.rst
+++ b/doc/en/reference/interfaces/index.rst
@@ -3,7 +3,8 @@
 
 Sage provides a unified interface to the best computational
 software. This is accomplished using both C-libraries (see
-:ref:`ch:libraries`) and interpreter interfaces, which are
+`C/C++ Library Interfaces <../libs/index.html>`_)
+and interpreter interfaces, which are
 implemented using pseudo-tty's, system files, etc. This chapter is
 about these interpreter interfaces.
 
@@ -18,7 +19,8 @@
     There is overhead associated with each call to one of these
     systems. For example, computing ``2+2`` thousands of times using
     the GAP interface will be slower than doing it directly in
-    Sage. In contrast, the C-library interfaces of :ref:`ch:libraries`
+    Sage. In contrast, the C-library interfaces of
+    `C/C++ Library Interfaces <../libs/index.html>`_
     incur less overhead.
 
 
diff --git a/doc/en/reference/misc/index.rst b/doc/en/reference/misc/index.rst
--- a/doc/en/reference/misc/index.rst
+++ b/doc/en/reference/misc/index.rst
@@ -56,7 +56,7 @@
 .. toctree::
    :maxdepth: 2
 
-   other/sagetex
+   sagetex
    sage/misc/latex
    sage/misc/latex_macros
 
diff --git a/doc/en/reference/todolist.rst b/doc/en/reference/todolist.rst
--- a/doc/en/reference/todolist.rst
+++ b/doc/en/reference/todolist.rst
@@ -15,4 +15,6 @@
         Rewrite the hand-written TODOs by using the correct ``.. todo::``
         markup.
 
+The combined to do list is only available in the html version of the reference manual.
+
 .. todolist::
diff --git a/doc/en/website/templates/index.html b/doc/en/website/templates/index.html
--- a/doc/en/website/templates/index.html
+++ b/doc/en/website/templates/index.html
@@ -137,7 +137,7 @@
         <a class="biglink" href="reference/index.html">
           Reference Manual
         </a>
-        <a title="Download PDF" class="pdf" href="../../pdf/en/reference/reference.pdf">
+        <a title="Link to PDF" class="pdf" href="../../pdf/en/reference/index.html">
           <img class="icon" src="_static/pdf.png"></img>
         </a>
         <br>
diff --git a/sage/combinat/tutorial.py b/sage/combinat/tutorial.py
--- a/sage/combinat/tutorial.py
+++ b/sage/combinat/tutorial.py
@@ -209,7 +209,7 @@
 
 .. _figure-examples-catalan-trees:
 
-.. figure:: ../../media/combinat/complete-binary-trees-4.png
+.. figure:: ../../media/complete-binary-trees-4.png
     :scale: 150 %
 
     Figure: The five complete binary trees with four leaves
@@ -866,7 +866,7 @@
 
     sage: C.unrank(20).plot()
 
-.. image:: ../../media/combinat/a_poset.png
+.. image:: ../../media/a_poset.png
 
 One can iterate through all graphs up to isomorphism. For example,
 there are 34 simple graphs with 5 vertices::
@@ -878,7 +878,7 @@
 
     sage: show(graphs(5, lambda G: G.size() <= 4))
 
-.. image:: ../../media/combinat/graphs-5.png
+.. image:: ../../media/graphs-5.png
 
 However, the *set* ``C`` of these graphs is not yet available in
 ``Sage``; as a result, the following commands are not yet
@@ -1609,7 +1609,7 @@
 
 .. _figure-prefix-tree-partitions:
 
-.. figure:: ../../media/combinat/prefix-tree-partitions-5.png
+.. figure:: ../../media/prefix-tree-partitions-5.png
     :scale: 150%
 
     Figure: The prefix tree of the partitions of 5.
@@ -1674,7 +1674,7 @@
 
 .. _figure-polytope:
 
-.. figure:: ../../media/combinat/polytope.png
+.. figure:: ../../media/polytope.png
     :scale: 75%
 
     Figure: The polytope `L` and its integer points, in cross-eyed stereographic perspective.
@@ -1840,7 +1840,7 @@
 the ones that are still canonical [4]_. Recursively, one obtains all
 the canonical graphs.
 
-.. figure:: ../../media/combinat/prefix-tree-graphs-4.png
+.. figure:: ../../media/prefix-tree-graphs-4.png
 
    Figure: The generation tree of simple graphs with `4` vertices.
 
diff --git a/sage/graphs/base/static_sparse_graph.pyx b/sage/graphs/base/static_sparse_graph.pyx
--- a/sage/graphs/base/static_sparse_graph.pyx
+++ b/sage/graphs/base/static_sparse_graph.pyx
@@ -24,7 +24,7 @@
 Data structure
 --------------
 
-.. image:: ../../../media/graphs/structure.png
+.. image:: ../../../media/structure.png
 
 The data structure is actually pretty simple and compact. ``short_digraph`` has
 three fields
diff --git a/sage/graphs/graph_decompositions/graph_products.pyx b/sage/graphs/graph_decompositions/graph_products.pyx
--- a/sage/graphs/graph_decompositions/graph_products.pyx
+++ b/sage/graphs/graph_decompositions/graph_products.pyx
@@ -64,7 +64,7 @@
 
   A contradiction indeed.
 
-  .. image:: ../../../media/graphs/cycle.png
+  .. image:: ../../../media/cycle.png
 
   That means that, for instance, the edges of a triangle necessarily have the
   same color.
@@ -76,7 +76,7 @@
   In this situation, opposed edges necessarily have the same colors because of
   the previous remark.
 
-  .. image:: ../../../media/graphs/square.png
+  .. image:: ../../../media/square.png
 
   **1st criterion** : As a corollary, we know that:
 
diff --git a/sage/graphs/graph_latex.py b/sage/graphs/graph_latex.py
--- a/sage/graphs/graph_latex.py
+++ b/sage/graphs/graph_latex.py
@@ -16,7 +16,7 @@
 LaTeX Versions of Graphs
 -------------------------------------
 
-.. image:: ../../media/graphs/heawood-graph-latex.png
+.. image:: ../../media/heawood-graph-latex.png
    :align: center
 
 Many mathematical objects in Sage have LaTeX representations, and graphs are no exception.  For a graph ``g``, the command ``view(g)``, issued at the Sage command line or in the notebook, will create a graphic version of ``g``.  Similarly, ``latex(g)`` will return a (long) string that is a representation of the graph in LaTeX.  Other ways of employing LaTeX in Sage, such as ``%latex`` in a notebook cell, or the Typeset checkbox in the notebook, will handle ``g`` appropriately.
diff --git a/sage/graphs/graph_plot.py b/sage/graphs/graph_plot.py
--- a/sage/graphs/graph_plot.py
+++ b/sage/graphs/graph_plot.py
@@ -106,7 +106,7 @@
       settings from ``DEFAULT_SHOW_OPTIONS`` only affects ``G.show()``.
 
     * In order to define a default value permanently, you can add a couple of
-      lines to :doc:`Sage's startup scripts <../../startup>`. Example ::
+      lines to `Sage's startup scripts <../../../cmd/startup.html>`_. Example ::
 
        sage: import sage.graphs.graph_plot
        sage: sage.graphs.graph_plot.DEFAULT_SHOW_OPTIONS['figsize'] = [4,4]
diff --git a/sage/homology/delta_complex.py b/sage/homology/delta_complex.py
--- a/sage/homology/delta_complex.py
+++ b/sage/homology/delta_complex.py
@@ -149,7 +149,7 @@
       first in the prescribed way.  The three edges each start and end
       at the single vertex, ``Simplex(0)``.
 
-      .. image:: ../../media/homology/torus_labelled.png
+      .. image:: ../../media/torus_labelled.png
 
     - ``data`` may be nested lists or tuples.  The nth entry in the
       list is a list of the n-simplices in the complex, and each
@@ -178,7 +178,7 @@
       If one draws two triangles and identifies them according to this
       description, the result is the real projective plane.
 
-      .. image:: ../../media/homology/rp2.png
+      .. image:: ../../media/rp2.png
 
       ::
 
@@ -1483,7 +1483,7 @@
         A `\Delta`-complex representation of the torus, consisting of one
         vertex, three edges, and two triangles.
 
-        .. image:: ../../media/homology/torus.png
+        .. image:: ../../media/torus.png
 
         EXAMPLES::
 
@@ -1497,7 +1497,7 @@
         A `\Delta`-complex representation of the real projective plane,
         consisting of two vertices, three edges, and two triangles.
 
-        .. image:: ../../media/homology/rp2.png
+        .. image:: ../../media/rp2.png
 
         EXAMPLES::
 
@@ -1518,7 +1518,7 @@
         A `\Delta`-complex representation of the Klein bottle, consisting
         of one vertex, three edges, and two triangles.
 
-        .. image:: ../../media/homology/klein.png
+        .. image:: ../../media/klein.png
 
         EXAMPLES::
 
diff --git a/sage/homology/simplicial_complex.py b/sage/homology/simplicial_complex.py
--- a/sage/homology/simplicial_complex.py
+++ b/sage/homology/simplicial_complex.py
@@ -34,7 +34,7 @@
 denote both the simplicial complex and the associated topological
 space.
 
-.. image:: ../../media/homology/simplices.png
+.. image:: ../../media/simplices.png
 
 For any simplicial complex `K` and any commutative ring `R` there is
 an associated chain complex, with differential of degree `-1`.  The
diff --git a/sage/modular/arithgroup/farey_symbol.pyx b/sage/modular/arithgroup/farey_symbol.pyx
--- a/sage/modular/arithgroup/farey_symbol.pyx
+++ b/sage/modular/arithgroup/farey_symbol.pyx
@@ -419,7 +419,7 @@
         Farey symbol of the arithmetic group. The sides of the
         hyperbolic polygon are numbered 0, 1, ... from left to right.
 
-        .. image:: ../../../media/modular/arithgroup/pairing.png
+        .. image:: ../../../media/pairing.png
 
         EXAMPLES::
         
