Esempio n. 1
0
 def init(self):
     # type: () -> None
     self.docnames = []  # type: Iterable[unicode]
     self.document_data = [
     ]  # type: List[Tuple[unicode, unicode, unicode, unicode, unicode, bool]]  # NOQA
     self.usepackages = self.app.registry.latex_packages
     texescape.init()
def setup(app):
    replacement_list = [
        tuple(line.strip().split())
        for line in replacements.strip().splitlines()
    ]

    te.tex_replacements += replacement_list
    te.init()
Esempio n. 3
0
def setup(app):
    replacement_list = [
        tuple(line.strip().split())
        for line in replacements.strip().splitlines()
    ]

    te.tex_replacements += replacement_list
    te.init()
Esempio n. 4
0
    def init(self):
        # type: () -> None
        self.context = {}           # type: Dict[str, Any]
        self.docnames = []          # type: Iterable[str]
        self.document_data = []     # type: List[Tuple[str, str, str, str, str, bool]]
        self.usepackages = self.app.registry.latex_packages
        texescape.init()

        self.init_context()
Esempio n. 5
0
def setup_module():
    global app, settings, parser
    texescape.init()  # otherwise done by the latex builder
    app = TestApp(cleanenv=True)
    optparser = frontend.OptionParser(
        components=(rst.Parser, HTMLWriter, LaTeXWriter))
    settings = optparser.get_default_values()
    settings.env = app.builder.env
    parser = rst.Parser()
Esempio n. 6
0
    def init(self):
        # type: () -> None
        self.context = {}           # type: Dict[unicode, Any]
        self.docnames = []          # type: Iterable[unicode]
        self.document_data = []     # type: List[Tuple[unicode, unicode, unicode, unicode, unicode, bool]]  # NOQA
        self.usepackages = self.app.registry.latex_packages
        texescape.init()

        self.init_context()
Esempio n. 7
0
def setup_module():
    global app, settings, parser
    texescape.init()  # otherwise done by the latex builder
    app = TestApp(cleanenv=True)
    optparser = frontend.OptionParser(components=(rst.Parser, HTMLWriter,
                                                  LaTeXWriter))
    settings = optparser.get_default_values()
    settings.env = app.builder.env
    parser = rst.Parser()
def setup(app):
    replacement_list = [
        tuple(line.strip().split())
        for line in extra_replacements.strip().splitlines()
    ]

    te.tex_replacements += replacement_list
    te.init()
    
    return {'parallel_read_safe': True}
Esempio n. 9
0
def setup_module():
    global app, settings, parser
    texescape.init()  # otherwise done by the latex builder
    app = TestApp()
    optparser = frontend.OptionParser(components=(rst.Parser, HTMLWriter,
                                                  LaTeXWriter))
    settings = optparser.get_default_values()
    settings.env = app.builder.env
    settings.env.patch_lookup_functions()
    settings.env.temp_data['docname'] = 'dummy'
    parser = rst.Parser()
Esempio n. 10
0
    def init(self):
        # type: () -> None
        self.babel = None           # type: ExtBabel
        self.context = {}           # type: Dict[str, Any]
        self.docnames = []          # type: Iterable[str]
        self.document_data = []     # type: List[Tuple[str, str, str, str, str, bool]]
        self.usepackages = self.app.registry.latex_packages
        texescape.init()

        self.init_context()
        self.init_babel()
Esempio n. 11
0
def settings(app):
    texescape.init()  # otherwise done by the latex builder
    optparser = frontend.OptionParser(
        components=(RstParser, HTMLWriter, LaTeXWriter))
    settings = optparser.get_default_values()
    settings.env = app.builder.env
    settings.env.temp_data['docname'] = 'dummy'
    domain_context = sphinx_domains(settings.env)
    domain_context.enable()
    yield settings
    domain_context.disable()
Esempio n. 12
0
def setup_module():
    global app, settings, parser
    texescape.init()  # otherwise done by the latex builder
    app = TestApp()
    optparser = frontend.OptionParser(
        components=(rst.Parser, HTMLWriter, LaTeXWriter))
    settings = optparser.get_default_values()
    settings.env = app.builder.env
    settings.env.patch_lookup_functions()
    settings.env.temp_data['docname'] = 'dummy'
    parser = rst.Parser()
Esempio n. 13
0
    def init(self) -> None:
        self.babel: ExtBabel = None
        self.context: Dict[str, Any] = {}
        self.docnames: Iterable[str] = {}
        self.document_data: List[Tuple[str, str, str, str, str, bool]] = []
        self.themes = ThemeFactory(self.app)
        texescape.init()

        self.init_context()
        self.init_babel()
        self.init_multilingual()
Esempio n. 14
0
    def init(self) -> None:
        self.babel = None           # type: ExtBabel
        self.context = {}           # type: Dict[str, Any]
        self.docnames = []          # type: Iterable[str]
        self.document_data = []     # type: List[Tuple[str, str, str, str, str, bool]]
        self.themes = ThemeFactory(self.app)
        texescape.init()

        self.init_context()
        self.init_babel()
        self.init_multilingual()
Esempio n. 15
0
def settings(app):
    texescape.init()  # otherwise done by the latex builder
    optparser = frontend.OptionParser(components=(RstParser, HTMLWriter,
                                                  LaTeXWriter))
    settings = optparser.get_default_values()
    settings.env = app.builder.env
    settings.env.temp_data['docname'] = 'dummy'
    domain_context = sphinx_domains(settings.env)
    domain_context.enable()
    yield settings
    domain_context.disable()
Esempio n. 16
0
    def init(self) -> None:
        self.babel = None           # type: ExtBabel
        self.context = {}           # type: Dict[str, Any]
        self.docnames = []          # type: Iterable[str]
        self.document_data = []     # type: List[Tuple[str, str, str, str, str, bool]]
        self.themes = ThemeFactory(self.app)
        self.usepackages = self.app.registry.latex_packages
        self.usepackages_after_hyperref = self.app.registry.latex_packages_after_hyperref
        texescape.init()

        self.init_context()
        self.init_babel()
        self.init_multilingual()
Esempio n. 17
0
def settings(app):
    texescape.init()  # otherwise done by the latex builder
    optparser = frontend.OptionParser(components=(RstParser, HTMLWriter,
                                                  LaTeXWriter))
    settings = optparser.get_default_values()
    settings.smart_quotes = True
    settings.env = app.builder.env
    settings.env.temp_data['docname'] = 'dummy'
    settings.contentsname = 'dummy'
    settings.rfc_base_url = 'http://tools.ietf.org/html/'
    domain_context = sphinx_domains(settings.env)
    domain_context.enable()
    yield settings
    domain_context.disable()
Esempio n. 18
0
def settings(app):
    texescape.init()  # otherwise done by the latex builder
    with warnings.catch_warnings():
        warnings.filterwarnings('ignore', category=DeprecationWarning)
        # DeprecationWarning: The frontend.OptionParser class will be replaced
        # by a subclass of argparse.ArgumentParser in Docutils 0.21 or later.
        optparser = frontend.OptionParser(components=(RstParser, HTMLWriter,
                                                      LaTeXWriter),
                                          defaults=default_settings)
    settings = optparser.get_default_values()
    settings.smart_quotes = True
    settings.env = app.builder.env
    settings.env.temp_data['docname'] = 'dummy'
    settings.contentsname = 'dummy'
    domain_context = sphinx_domains(settings.env)
    domain_context.enable()
    yield settings
    domain_context.disable()
def generate(d, overwrite=True, silent=False):
    """Generate project based on values in *d*."""

    texescape.init()
    indent = ' ' * 4

    if 'mastertoctree' not in d:
        d['mastertoctree'] = ''
    if 'mastertocmaxdepth' not in d:
        d['mastertocmaxdepth'] = 2

    d['project_fn'] = make_filename(d['project'])
    d['project_manpage'] = d['project_fn'].lower()
    d['now'] = time.asctime()
    d['project_underline'] = column_width(d['project']) * '='
    extensions = (',\n' + indent).join(
        repr('sphinx.ext.' + name)
        for name in ('autodoc', 'doctest', 'intersphinx', 'todo', 'coverage',
                     'pngmath', 'mathjax', 'ifconfig', 'viewcode')
        if d.get('ext_' + name))
    if extensions:
        d['extensions'] = '\n' + indent + extensions + ',\n'
    else:
        d['extensions'] = extensions
    d['copyright'] = time.strftime('%Y') + ', ' + d['author']
    d['author_texescaped'] = unicode(d['author']).\
                             translate(texescape.tex_escape_map)
    d['project_doc'] = d['project'] + ' Documentation'
    d['project_doc_texescaped'] = unicode(d['project'] + ' Documentation').\
                                  translate(texescape.tex_escape_map)

    # escape backslashes and single quotes in strings that are put into
    # a Python string literal
    for key in ('project', 'project_doc', 'project_doc_texescaped', 'author',
                'author_texescaped', 'copyright', 'version', 'release',
                'master'):
        d[key + '_str'] = d[key].replace('\\', '\\\\').replace("'", "\\'")

    if not path.isdir(d['path']):
        mkdir_p(d['path'])

    srcdir = d['sep'] and path.join(d['path'], 'source') or d['path']

    mkdir_p(srcdir)
    if d['sep']:
        builddir = path.join(d['path'], 'build')
        d['exclude_patterns'] = ''
    else:
        builddir = path.join(srcdir, d['dot'] + 'build')
        d['exclude_patterns'] = repr(d['dot'] + 'build')
    mkdir_p(builddir)
    mkdir_p(path.join(srcdir, d['dot'] + 'templates'))
    mkdir_p(path.join(srcdir, d['dot'] + 'static'))

    def write_file(fpath, content, newline=None):
        if overwrite or not path.isfile(fpath):
            print 'Creating file %s.' % fpath
            f = open(fpath, 'wt', encoding='utf-8', newline=newline)
            try:
                f.write(content)
            finally:
                f.close()
        else:
            print 'File %s already exists, skipping.' % fpath

    conf_text = QUICKSTART_CONF % d
    if d['epub']:
        conf_text += EPUB_CONFIG % d
    if d.get('ext_intersphinx'):
        conf_text += INTERSPHINX_CONFIG

    write_file(path.join(srcdir, 'conf.py'), conf_text)

    masterfile = path.join(srcdir, d['master'] + d['suffix'])
    write_file(masterfile, MASTER_FILE % d)

    if d['makefile']:
        d['rsrcdir'] = d['sep'] and 'source' or '.'
        d['rbuilddir'] = d['sep'] and 'build' or d['dot'] + 'build'
        # use binary mode, to avoid writing \r\n on Windows
        write_file(path.join(d['path'], 'Makefile'), MAKEFILE % d, u'\n')

    if d['batchfile']:
        d['rsrcdir'] = d['sep'] and 'source' or '.'
        d['rbuilddir'] = d['sep'] and 'build' or d['dot'] + 'build'
        write_file(path.join(d['path'], 'make.bat'), BATCHFILE % d, u'\r\n')

    if silent:
        return
    print
    print bold('Finished: An initial directory structure has been created.')
    print '''
You should now populate your master file %s and create other documentation
source files. ''' % masterfile + ((d['makefile'] or d['batchfile']) and '''\
Use the Makefile to build the docs, like so:
   make builder
''' or '''\
Use the sphinx-build command to build the docs, like so:
   sphinx-build -b builder %s %s
''' % (srcdir, builddir)) + '''\
Esempio n. 20
0
File: start.py Progetto: tg-m/ablog
def generate(d, overwrite=True, silent=False):
    """
    Borrowed from Sphinx 1.3b3.

    Generate project based on values in *d*.
    """

    texescape.init()

    if "mastertoctree" not in d:
        d["mastertoctree"] = ""
    if "mastertocmaxdepth" not in d:
        d["mastertocmaxdepth"] = 2

    d["project_fn"] = make_filename(d["project"])
    d["project_manpage"] = d["project_fn"].lower()
    d["now"] = time.asctime()
    d["project_underline"] = column_width(d["project"]) * "="

    d["copyright"] = time.strftime("%Y") + ", " + d["author"]
    d["author_texescaped"] = texescape.escape(
        str(d["author"]).translate(str(d["author"])))
    d["project_doc"] = d["project"] + " Documentation"
    d["project_doc_texescaped"] = texescape.escape(
        str(d["project"] + " Documentation").translate(
            str(d["project"] + " Documentation")))

    if not path.isdir(d["path"]):
        ensuredir(d["path"])

    srcdir = d["sep"] and path.join(d["path"], "source") or d["path"]

    ensuredir(srcdir)
    d["exclude_patterns"] = ""
    # TODO: Work if we want this.
    # if d['sep']:
    #    builddir = path.join(d['path'], 'build')
    #
    # else:
    #    builddir = path.join(srcdir, d['dot'] + 'build')
    #    d['exclude_patterns'] = repr(d['dot'] + 'build')
    # ensuredir(builddir)
    ensuredir(path.join(srcdir, d["dot"] + "templates"))
    ensuredir(path.join(srcdir, d["dot"] + "static"))

    def write_file(fpath, content, newline=None):
        if overwrite or not path.isfile(fpath):
            print(f"Creating file {fpath}.")
            f = open(fpath, "wt", encoding="utf-8", newline=newline)
            try:
                f.write(content)
            finally:
                f.close()
        else:
            print(f"File {fpath} already exists, skipping.")

    conf_text = ABLOG_CONF.format(**d)
    write_file(path.join(srcdir, "conf.py"), conf_text)

    masterfile = path.join(srcdir, d["master"] + d["suffix"])
    write_file(masterfile, ABLOG_INDEX.format(**d))

    about = path.join(srcdir, "about" + d["suffix"])
    write_file(about, ABLOG_ABOUT.format(**d))

    d["post_date"] = datetime.datetime.today().strftime("%b %d, %Y")
    firstpost = path.join(srcdir, "first-post" + d["suffix"])
    write_file(firstpost, ABLOG_POST.format(**d))

    if silent:
        return

    print(bold("Finished: An initial directory structure has been created."))
Esempio n. 21
0
 def init(self):
     self.docnames = []
     self.document_data = []
     texescape.init()
     self.check_options()
Esempio n. 22
0
def generate(d, overwrite=True, silent=False):
    """Generate project based on values in *d*."""

    texescape.init()
    indent = " " * 4

    if "mastertoctree" not in d:
        d["mastertoctree"] = ""
    if "mastertocmaxdepth" not in d:
        d["mastertocmaxdepth"] = 2

    d["project_fn"] = make_filename(d["project"])
    d["project_manpage"] = d["project_fn"].lower()
    d["now"] = time.asctime()
    d["project_underline"] = len(d["project"]) * "="
    extensions = (",\n" + indent).join(
        repr("sphinx.ext." + name)
        for name in (
            "autodoc",
            "doctest",
            "intersphinx",
            "todo",
            "coverage",
            "pngmath",
            "mathjax",
            "ifconfig",
            "viewcode",
        )
        if d.get("ext_" + name)
    )
    if extensions:
        d["extensions"] = "\n" + indent + extensions + ",\n"
    else:
        d["extensions"] = extensions
    d["copyright"] = time.strftime("%Y") + ", " + d["author"]
    d["author_texescaped"] = unicode(d["author"]).translate(texescape.tex_escape_map)
    d["project_doc"] = d["project"] + " Documentation"
    d["project_doc_texescaped"] = unicode(d["project"] + " Documentation").translate(texescape.tex_escape_map)

    # escape backslashes and single quotes in strings that are put into
    # a Python string literal
    for key in (
        "project",
        "project_doc",
        "project_doc_texescaped",
        "author",
        "author_texescaped",
        "copyright",
        "version",
        "release",
        "master",
    ):
        d[key + "_str"] = d[key].replace("\\", "\\\\").replace("'", "\\'")

    if not path.isdir(d["path"]):
        mkdir_p(d["path"])

    srcdir = d["sep"] and path.join(d["path"], "source") or d["path"]

    mkdir_p(srcdir)
    if d["sep"]:
        builddir = path.join(d["path"], "build")
        d["exclude_patterns"] = ""
    else:
        builddir = path.join(srcdir, d["dot"] + "build")
        d["exclude_patterns"] = repr(d["dot"] + "build")
    mkdir_p(builddir)
    mkdir_p(path.join(srcdir, d["dot"] + "templates"))
    mkdir_p(path.join(srcdir, d["dot"] + "static"))

    def write_file(fpath, content, newline=None):
        if overwrite or not path.isfile(fpath):
            print "Creating file %s." % fpath
            f = open(fpath, "wt", encoding="utf-8", newline=newline)
            try:
                f.write(content)
            finally:
                f.close()
        else:
            print "File %s already exists, skipping." % fpath

    conf_text = QUICKSTART_CONF % d
    if d["epub"]:
        conf_text += EPUB_CONFIG % d
    if d.get("ext_intersphinx"):
        conf_text += INTERSPHINX_CONFIG

    write_file(path.join(srcdir, "conf.py"), conf_text)

    masterfile = path.join(srcdir, d["master"] + d["suffix"])
    write_file(masterfile, MASTER_FILE % d)

    if d["makefile"]:
        d["rsrcdir"] = d["sep"] and "source" or "."
        d["rbuilddir"] = d["sep"] and "build" or d["dot"] + "build"
        # use binary mode, to avoid writing \r\n on Windows
        write_file(path.join(d["path"], "Makefile"), MAKEFILE % d, u"\n")

    if d["batchfile"]:
        d["rsrcdir"] = d["sep"] and "source" or "."
        d["rbuilddir"] = d["sep"] and "build" or d["dot"] + "build"
        write_file(path.join(d["path"], "make.bat"), BATCHFILE % d, u"\r\n")

    if silent:
        return
    print
    print bold("Finished: An initial directory structure has been created.")
    print """
You should now populate your master file %s and create other documentation
source files. """ % masterfile + (
        (d["makefile"] or d["batchfile"])
        and """\
Use the Makefile to build the docs, like so:
   make builder
"""
        or """\
Use the sphinx-build command to build the docs, like so:
   sphinx-build -b builder %s %s
"""
        % (srcdir, builddir)
    ) + """\
Esempio n. 23
0
 def init(self):
     self.docnames = []
     self.document_data = []
     texescape.init()
Esempio n. 24
0
def generate(d, overwrite=True, silent=False):
    '''Borrowed from Sphinx 1.3b3'''

    """Generate project based on values in *d*."""

    texescape.init()

    if 'mastertoctree' not in d:
        d['mastertoctree'] = ''
    if 'mastertocmaxdepth' not in d:
        d['mastertocmaxdepth'] = 2

    d['project_fn'] = make_filename(d['project'])
    d['project_manpage'] = d['project_fn'].lower()
    d['now'] = time.asctime()
    d['project_underline'] = column_width(d['project']) * '='

    d['copyright'] = time.strftime('%Y') + ', ' + d['author']
    d['author_texescaped'] = text_type(d['author']
        ).translate(texescape.tex_escape_map)
    d['project_doc'] = d['project'] + ' Documentation'
    d['project_doc_texescaped'] = text_type(d['project'] + ' Documentation'
        ).translate(texescape.tex_escape_map)

    # escape backslashes and single quotes in strings that are put into
    # a Python string literal
    for key in ('project', 'project_doc', 'project_doc_texescaped',
                'author', 'author_texescaped', 'copyright',
                'version', 'release', 'master'):
        d[key + '_str'] = d[key].replace('\\', '\\\\').replace("'", "\\'")

    if not path.isdir(d['path']):
        mkdir_p(d['path'])

    srcdir = d['sep'] and path.join(d['path'], 'source') or d['path']

    mkdir_p(srcdir)
    d['exclude_patterns'] = ''
    #if d['sep']:
    #    builddir = path.join(d['path'], 'build')
    #
    #else:
    #    builddir = path.join(srcdir, d['dot'] + 'build')
    #    d['exclude_patterns'] = repr(d['dot'] + 'build')
    #mkdir_p(builddir)
    mkdir_p(path.join(srcdir, d['dot'] + 'templates'))
    mkdir_p(path.join(srcdir, d['dot'] + 'static'))

    def write_file(fpath, content, newline=None):
        if overwrite or not path.isfile(fpath):
            print('Creating file %s.' % fpath)
            f = open(fpath, 'wt', encoding='utf-8', newline=newline)
            try:
                f.write(content)
            finally:
                f.close()
        else:
            print('File %s already exists, skipping.' % fpath)

    conf_text = ABLOG_CONF % d
    write_file(path.join(srcdir, 'conf.py'), conf_text)

    masterfile = path.join(srcdir, d['master'] + d['suffix'])
    write_file(masterfile, ABLOG_INDEX % d)

    about = path.join(srcdir, 'about' + d['suffix'])
    write_file(about, ABLOG_ABOUT % d)

    d['post_date'] = datetime.datetime.today().strftime('%b %d, %Y')
    firstpost = path.join(srcdir, 'first-post' + d['suffix'])
    write_file(firstpost, ABLOG_POST % d)

    if silent:
        return

    print(bold('Finished: An initial directory structure has been created.'))
Esempio n. 25
0
def generate(d, overwrite=True, silent=False):
    """Generate project based on values in *d*."""
    template = SphinxRenderer()

    texescape.init()
    indent = " " * 4

    if "mastertoctree" not in d:
        d["mastertoctree"] = ""
    if "mastertocmaxdepth" not in d:
        d["mastertocmaxdepth"] = 2

    d["PY3"] = PY3
    d["project_fn"] = make_filename(d["project"])
    d["project_url"] = urlquote(d["project"].encode("idna"))
    d["project_manpage"] = d["project_fn"].lower()
    d["now"] = time.asctime()
    d["project_underline"] = column_width(d["project"]) * "="
    extensions = (",\n" + indent).join(repr("sphinx.ext." + name) for name in EXTENSIONS if d.get("ext_" + name))
    if extensions:
        d["extensions"] = "\n" + indent + extensions + ",\n"
    else:
        d["extensions"] = extensions
    d["copyright"] = time.strftime("%Y") + ", " + d["author"]
    d["author_texescaped"] = text_type(d["author"]).translate(texescape.tex_escape_map)
    d["project_doc"] = d["project"] + " Documentation"
    d["project_doc_texescaped"] = text_type(d["project"] + " Documentation").translate(texescape.tex_escape_map)

    # escape backslashes and single quotes in strings that are put into
    # a Python string literal
    for key in (
        "project",
        "project_doc",
        "project_doc_texescaped",
        "author",
        "author_texescaped",
        "copyright",
        "version",
        "release",
        "master",
    ):
        d[key + "_str"] = d[key].replace("\\", "\\\\").replace("'", "\\'")

    if not path.isdir(d["path"]):
        mkdir_p(d["path"])

    srcdir = d["sep"] and path.join(d["path"], "source") or d["path"]

    mkdir_p(srcdir)
    if d["sep"]:
        builddir = path.join(d["path"], "build")
        d["exclude_patterns"] = ""
    else:
        builddir = path.join(srcdir, d["dot"] + "build")
        exclude_patterns = map(repr, [d["dot"] + "build", "Thumbs.db", ".DS_Store"])
        d["exclude_patterns"] = ", ".join(exclude_patterns)
    mkdir_p(builddir)
    mkdir_p(path.join(srcdir, d["dot"] + "templates"))
    mkdir_p(path.join(srcdir, d["dot"] + "static"))

    def write_file(fpath, content, newline=None):
        if overwrite or not path.isfile(fpath):
            print("Creating file %s." % fpath)
            with open(fpath, "wt", encoding="utf-8", newline=newline) as f:
                f.write(content)
        else:
            print("File %s already exists, skipping." % fpath)

    with open(os.path.join(package_dir, "templates", "quickstart", "conf.py_t")) as f:
        conf_text = convert_python_source(f.read())

    write_file(path.join(srcdir, "conf.py"), template.render_string(conf_text, d))

    masterfile = path.join(srcdir, d["master"] + d["suffix"])
    write_file(masterfile, template.render("quickstart/master_doc.rst_t", d))

    if d.get("make_mode") is True:
        makefile_template = "quickstart/Makefile.new_t"
        batchfile_template = "quickstart/make.bat.new_t"
    else:
        makefile_template = "quickstart/Makefile_t"
        batchfile_template = "quickstart/make.bat_t"

    if d["makefile"] is True:
        d["rsrcdir"] = d["sep"] and "source" or "."
        d["rbuilddir"] = d["sep"] and "build" or d["dot"] + "build"
        # use binary mode, to avoid writing \r\n on Windows
        write_file(path.join(d["path"], "Makefile"), template.render(makefile_template, d), u"\n")

    if d["batchfile"] is True:
        d["rsrcdir"] = d["sep"] and "source" or "."
        d["rbuilddir"] = d["sep"] and "build" or d["dot"] + "build"
        write_file(path.join(d["path"], "make.bat"), template.render(batchfile_template, d), u"\r\n")

    if silent:
        return
    print()
    print(bold("Finished: An initial directory structure has been created."))
    print(
        """
You should now populate your master file %s and create other documentation
source files. """
        % masterfile
        + (
            (d["makefile"] or d["batchfile"])
            and """\
Use the Makefile to build the docs, like so:
   make builder
"""
            or """\
Use the sphinx-build command to build the docs, like so:
   sphinx-build -b builder %s %s
"""
            % (srcdir, builddir)
        )
        + """\
where "builder" is one of the supported builders, e.g. html, latex or linkcheck.
"""
    )
Esempio n. 26
0
 def init(self):
     # type: () -> None
     self.docnames = []          # type: Iterable[unicode]
     self.document_data = []     # type: List[Tuple[unicode, unicode, unicode, unicode, unicode, bool]]  # NOQA
     self.usepackages = []       # type: List[unicode]
     texescape.init()
Esempio n. 27
0
def generate(d, overwrite=True, silent=False, templatedir=None):
    # type: (Dict, bool, bool, str) -> None
    """Generate project based on values in *d*."""
    template = QuickstartRenderer(templatedir=templatedir)

    texescape.init()

    if 'mastertoctree' not in d:
        d['mastertoctree'] = ''
    if 'mastertocmaxdepth' not in d:
        d['mastertocmaxdepth'] = 2

    d['PY3'] = True
    d['project_fn'] = make_filename(d['project'])
    d['project_url'] = quote(d['project'].encode('idna'))
    d['project_manpage'] = d['project_fn'].lower()
    d['now'] = time.asctime()
    d['project_underline'] = column_width(d['project']) * '='
    d.setdefault('extensions', [])
    d['copyright'] = time.strftime('%Y') + ', ' + d['author']
    d['author_texescaped'] = text_type(d['author']).\
        translate(texescape.tex_escape_map)
    d['project_doc'] = d['project'] + ' Documentation'
    d['project_doc_texescaped'] = text_type(d['project'] + ' Documentation').\
        translate(texescape.tex_escape_map)

    # escape backslashes and single quotes in strings that are put into
    # a Python string literal
    for key in ('project', 'project_doc', 'project_doc_texescaped', 'author',
                'author_texescaped', 'copyright', 'version', 'release',
                'master'):
        d[key + '_str'] = d[key].replace('\\', '\\\\').replace("'", "\\'")

    ensuredir(d['path'])

    srcdir = d['sep'] and path.join(d['path'], 'source') or d['path']

    ensuredir(srcdir)
    if d['sep']:
        builddir = path.join(d['path'], 'build')
        d['exclude_patterns'] = ''
    else:
        builddir = path.join(srcdir, d['dot'] + 'build')
        exclude_patterns = map(repr, [
            d['dot'] + 'build',
            'Thumbs.db',
            '.DS_Store',
        ])
        d['exclude_patterns'] = ', '.join(exclude_patterns)
    ensuredir(builddir)
    ensuredir(path.join(srcdir, d['dot'] + 'templates'))
    ensuredir(path.join(srcdir, d['dot'] + 'static'))

    def write_file(fpath, content, newline=None):
        # type: (str, str, str) -> None
        if overwrite or not path.isfile(fpath):
            if 'quiet' not in d:
                print(__('Creating file %s.') % fpath)
            with open(fpath, 'wt', encoding='utf-8', newline=newline) as f:
                f.write(content)
        else:
            if 'quiet' not in d:
                print(__('File %s already exists, skipping.') % fpath)

    conf_path = os.path.join(templatedir, 'conf.py_t') if templatedir else None
    if not conf_path or not path.isfile(conf_path):
        conf_path = os.path.join(package_dir, 'templates', 'quickstart',
                                 'conf.py_t')
    with open(conf_path) as f:
        conf_text = f.read()

    write_file(path.join(srcdir, 'conf.py'),
               template.render_string(conf_text, d))

    masterfile = path.join(srcdir, d['master'] + d['suffix'])
    write_file(masterfile, template.render('quickstart/master_doc.rst_t', d))

    if d.get('make_mode') is True:
        makefile_template = 'quickstart/Makefile.new_t'
        batchfile_template = 'quickstart/make.bat.new_t'
    else:
        makefile_template = 'quickstart/Makefile_t'
        batchfile_template = 'quickstart/make.bat_t'

    if d['makefile'] is True:
        d['rsrcdir'] = d['sep'] and 'source' or '.'
        d['rbuilddir'] = d['sep'] and 'build' or d['dot'] + 'build'
        # use binary mode, to avoid writing \r\n on Windows
        write_file(path.join(d['path'], 'Makefile'),
                   template.render(makefile_template, d), '\n')

    if d['batchfile'] is True:
        d['rsrcdir'] = d['sep'] and 'source' or '.'
        d['rbuilddir'] = d['sep'] and 'build' or d['dot'] + 'build'
        write_file(path.join(d['path'], 'make.bat'),
                   template.render(batchfile_template, d), '\r\n')

    if silent:
        return
    print()
    print(
        bold(__('Finished: An initial directory structure has been created.')))
    print(
        __('''
You should now populate your master file %s and create other documentation
source files. ''') % masterfile +
        ((d['makefile'] or d['batchfile']) and __('''\
Use the Makefile to build the docs, like so:
   make builder
''') or __('''\
Use the sphinx-build command to build the docs, like so:
   sphinx-build -b builder %s %s
''') % (srcdir, builddir)) + __('''\
where "builder" is one of the supported builders, e.g. html, latex or linkcheck.
'''))
Esempio n. 28
0
from sphinx import addnodes
from sphinx.locale import _
from sphinx.highlighting import PygmentsBridge
from sphinx.util import texescape
from sphinx.writers.latex import (
    LaTeXWriter,
    Table,
)
from sphinx_clatex.writer import (
    BEGIN_DOC,
    CustomLaTeXTranslator,
)


if not texescape.tex_escape_map:
    texescape.init()

texescape.tex_escape_map[ord(u'&')] = u'\\&{}'
texescape.tex_escape_map[ord(u'%')] = u'\\%{}'


class ShapeLaTeXTranslator(CustomLaTeXTranslator):

    def visit_document(self, node):
        """
        Comparing to the standard builder do not add `\phantomsection`.
        """
        self.footnotestack.append(self.collect_footnotes(node))
        self.curfilestack.append(node.get('docname', ''))
        if self.first_document == 1:
            # the first document is all the regular content ...
Esempio n. 29
0
    def __init__(self, document, builder):
        Translator.__init__(self, document)
        docCfg = self.document.docCfg

        self.builder = builder
        self.settings = document.settings
        self.d_class = DocumentClass(docCfg)
        self.polyglossia = Polyglossia(self.settings.language_code)
        self.requirements = Requirements()

        # elements
        # --------

        self.elements = self.default_ctx.copy()
        self.elements.update(docCfg)
        self.elements.documentoptions = self.d_class.documentoptions
        self.elements.documentclass = self.d_class.documentclass
        self.elements.language = self.polyglossia.language

        # common flags & stacks
        # ---------------------

        self.out = []
        self.bibitems = []
        self.in_title = False
        self.in_minipage = False

        self.body = []
        self.table = None
        self.next_table_colspec = None

        self.curfilestack = []

        self.first_document = 1
        self.first_param = 0
        self.this_is_the_title = 1
        # self.next_hyperlink_ids = {}

        # PDF properties (hyperref package)
        # ---------------------------------

        self.pdfsetup = []
        self.pdfinfo = []  # PDF properties: pdftitle, pdfauthor
        self.pdfauthor = []

        # footnotes
        # ---------

        self.in_footnote = 0
        self.footnotestack = []
        self.footnote_restricted = False
        self.pending_footnotes = []

        # sectioning
        # ----------

        self.next_section_ids = set()
        self.next_figure_ids = set()
        self.next_table_ids = set()

        if docCfg.get('tocdepth'):
            self.elements['tocdepth'] = (r'\setcounter{tocdepth}{%d}' %
                                         docCfg.get('tocdepth'))

        # code highlighter
        # ----------------

        # XeLaTeX makes no use of the sphinx.util.texescape, but the
        # sphinx.highlighting.PygmentsBridge uses the *tex_hl_escape_map_new*
        # which has to be initialized.
        from sphinx.util import texescape
        texescape.init()

        self.highlighter = highlighting.PygmentsBridge(
            'latex',
            self.builder.config.pygments_style
            or 'tango'  # prefer tango as default
            ,
            self.builder.config.trim_doctest_flags)
        # stack of [language, linenothreshold] settings per file the first item
        # here is the default and must not be changed the second item is the
        # default for the master file and can be changed by .. highlight::
        # directive in the master file

        self.hlsettingstack = 2 * [[
            self.builder.config.highlight_language, sys.maxsize
        ]]
Esempio n. 30
0
 def init(self):
     self.docnames = []
     self.document_data = []
     texescape.init()
Esempio n. 31
0
def inner_main(args):
    d = {}
    texescape.init()

    if not color_terminal():
        nocolor()

    print bold('Welcome to the Sphinx quickstart utility.')
    print '''
Please enter values for the following settings (just press Enter to
accept a default value, if one is given in brackets).'''

    print '''
Enter the root path for documentation.'''
    do_prompt(d, 'path', 'Root path for the documentation', '.', is_path)

    while path.isfile(path.join(d['path'], 'conf.py')) or \
          path.isfile(path.join(d['path'], 'source', 'conf.py')):
        print
        print bold('Error: an existing conf.py has been found in the '
                   'selected root path.')
        print 'sphinx-quickstart will not overwrite existing Sphinx projects.'
        print
        do_prompt(d, 'path', 'Please enter a new root path (or just Enter '
                  'to exit)', '', is_path)
        if not d['path']:
            sys.exit(1)

    print '''
You have two options for placing the build directory for Sphinx output.
Either, you use a directory "_build" within the root path, or you separate
"source" and "build" directories within the root path.'''
    do_prompt(d, 'sep', 'Separate source and build directories (y/N)', 'n',
              boolean)

    print '''
Inside the root directory, two more directories will be created; "_templates"
for custom HTML templates and "_static" for custom stylesheets and other static
files. You can enter another prefix (such as ".") to replace the underscore.'''
    do_prompt(d, 'dot', 'Name prefix for templates and static dir', '_', ok)

    print '''
The project name will occur in several places in the built documentation.'''
    do_prompt(d, 'project', 'Project name')
    do_prompt(d, 'author', 'Author name(s)')
    print '''
Sphinx has the notion of a "version" and a "release" for the
software. Each version can have multiple releases. For example, for
Python the version is something like 2.5 or 3.0, while the release is
something like 2.5.1 or 3.0a1.  If you don't need this dual structure,
just set both to the same value.'''
    do_prompt(d, 'version', 'Project version')
    do_prompt(d, 'release', 'Project release', d['version'])
    print '''
The file name suffix for source files. Commonly, this is either ".txt"
or ".rst".  Only files with this suffix are considered documents.'''
    do_prompt(d, 'suffix', 'Source file suffix', '.rst', suffix)
    print '''
One document is special in that it is considered the top node of the
"contents tree", that is, it is the root of the hierarchical structure
of the documents. Normally, this is "index", but if your "index"
document is a custom template, you can also set this to another filename.'''
    do_prompt(d, 'master', 'Name of your master document (without suffix)',
              'index')

    while path.isfile(path.join(d['path'], d['master']+d['suffix'])) or \
          path.isfile(path.join(d['path'], 'source', d['master']+d['suffix'])):
        print
        print bold('Error: the master file %s has already been found in the '
                   'selected root path.' % (d['master']+d['suffix']))
        print 'sphinx-quickstart will not overwrite the existing file.'
        print
        do_prompt(d, 'master', 'Please enter a new file name, or rename the '
                  'existing file and press Enter', d['master'])

    print '''
Please indicate if you want to use one of the following Sphinx extensions:'''
    do_prompt(d, 'ext_autodoc', 'autodoc: automatically insert docstrings '
              'from modules (y/N)', 'n', boolean)
    do_prompt(d, 'ext_doctest', 'doctest: automatically test code snippets '
              'in doctest blocks (y/N)', 'n', boolean)
    do_prompt(d, 'ext_intersphinx', 'intersphinx: link between Sphinx '
              'documentation of different projects (y/N)', 'n', boolean)
    do_prompt(d, 'ext_todo', 'todo: write "todo" entries '
              'that can be shown or hidden on build (y/N)', 'n', boolean)
    do_prompt(d, 'ext_coverage', 'coverage: checks for documentation '
              'coverage (y/N)', 'n', boolean)
    do_prompt(d, 'ext_pngmath', 'pngmath: include math, rendered '
              'as PNG images (y/N)', 'n', boolean)
    do_prompt(d, 'ext_jsmath', 'jsmath: include math, rendered in the '
              'browser by JSMath (y/N)', 'n', boolean)
    if d['ext_pngmath'] and d['ext_jsmath']:
        print '''Note: pngmath and jsmath cannot be enabled at the same time.
pngmath has been deselected.'''
    do_prompt(d, 'ext_ifconfig', 'ifconfig: conditional inclusion of '
              'content based on config values (y/N)', 'n', boolean)
    print '''
A Makefile and a Windows command file can be generated for you so that you
only have to run e.g. `make html' instead of invoking sphinx-build
directly.'''
    do_prompt(d, 'makefile', 'Create Makefile? (Y/n)', 'y', boolean)
    do_prompt(d, 'batchfile', 'Create Windows command file? (Y/n)',
              'y', boolean)

    d['project_fn'] = make_filename(d['project'])
    d['now'] = time.asctime()
    d['underline'] = len(d['project']) * '='
    d['extensions'] = ', '.join(
        repr('sphinx.ext.' + name)
        for name in ('autodoc', 'doctest', 'intersphinx', 'todo', 'coverage',
                     'pngmath', 'jsmath', 'ifconfig')
        if d['ext_' + name])
    d['copyright'] = time.strftime('%Y') + ', ' + d['author']
    d['author_texescaped'] = unicode(d['author']).\
                             translate(texescape.tex_escape_map)
    d['project_doc'] = d['project'] + ' Documentation'
    d['project_doc_texescaped'] = unicode(d['project'] + ' Documentation').\
                                  translate(texescape.tex_escape_map)

    # escape backslashes and single quotes in strings that are put into
    # a Python string literal
    for key in ('project', 'copyright', 'author_texescaped',
                'project_doc_texescaped', 'version', 'release', 'master'):
        d[key + '_str'] = d[key].replace('\\', '\\\\').replace("'", "\\'")

    if not path.isdir(d['path']):
        mkdir_p(d['path'])

    srcdir = d['sep'] and path.join(d['path'], 'source') or d['path']

    mkdir_p(srcdir)
    if d['sep']:
        builddir = path.join(d['path'], 'build')
        d['exclude_trees'] = ''
    else:
        builddir = path.join(srcdir, d['dot'] + 'build')
        d['exclude_trees'] = repr(d['dot'] + 'build')
    mkdir_p(builddir)
    mkdir_p(path.join(srcdir, d['dot'] + 'templates'))
    mkdir_p(path.join(srcdir, d['dot'] + 'static'))

    conf_text = QUICKSTART_CONF % d
    if d['ext_intersphinx']:
        conf_text += INTERSPHINX_CONFIG

    f = open(path.join(srcdir, 'conf.py'), 'w')
    f.write(conf_text.encode('utf-8'))
    f.close()

    masterfile = path.join(srcdir, d['master'] + d['suffix'])
    f = open(masterfile, 'w')
    f.write((MASTER_FILE % d).encode('utf-8'))
    f.close()

    if d['makefile']:
        d['rsrcdir'] = d['sep'] and 'source' or '.'
        d['rbuilddir'] = d['sep'] and 'build' or d['dot'] + 'build'
        f = open(path.join(d['path'], 'Makefile'), 'w')
        f.write((MAKEFILE % d).encode('utf-8'))
        f.close()

    if d['batchfile']:
        d['rsrcdir'] = d['sep'] and 'source' or '.'
        d['rbuilddir'] = d['sep'] and 'build' or d['dot'] + 'build'
        f = open(path.join(d['path'], 'make.bat'), 'w')
        f.write((BATCHFILE % d).encode('utf-8'))
        f.close()

    print
    print bold('Finished: An initial directory structure has been created.')
    print '''
You should now populate your master file %s and create other documentation
source files. ''' % masterfile + ((d['makefile'] or d['batchfile']) and '''\
Use the Makefile to build the docs, like so:
   make builder
''' or '''\
Use the sphinx-build command to build the docs, like so:
   sphinx-build -b builder %s %s
''' % (srcdir, builddir)) + '''\
Esempio n. 32
0
def generate(d, overwrite=True, silent=False):
    '''Borrowed from Sphinx 1.3b3'''
    """Generate project based on values in *d*."""

    texescape.init()

    if 'mastertoctree' not in d:
        d['mastertoctree'] = ''
    if 'mastertocmaxdepth' not in d:
        d['mastertocmaxdepth'] = 2

    d['project_fn'] = make_filename(d['project'])
    d['project_manpage'] = d['project_fn'].lower()
    d['now'] = time.asctime()
    d['project_underline'] = column_width(d['project']) * '='

    d['copyright'] = time.strftime('%Y') + ', ' + d['author']
    d['author_texescaped'] = text_type(d['author']).translate(
        texescape.tex_escape_map)
    d['project_doc'] = d['project'] + ' Documentation'
    d['project_doc_texescaped'] = text_type(d['project'] +
                                            ' Documentation').translate(
                                                texescape.tex_escape_map)

    # escape backslashes and single quotes in strings that are put into
    # a Python string literal
    for key in ('project', 'project_doc', 'project_doc_texescaped', 'author',
                'author_texescaped', 'copyright', 'version', 'release',
                'master'):
        d[key + '_str'] = d[key].replace('\\', '\\\\').replace("'", "\\'")

    if not path.isdir(d['path']):
        ensuredir(d['path'])

    srcdir = d['sep'] and path.join(d['path'], 'source') or d['path']

    ensuredir(srcdir)
    d['exclude_patterns'] = ''
    # TODO: Work if we want this.
    # if d['sep']:
    #    builddir = path.join(d['path'], 'build')
    #
    # else:
    #    builddir = path.join(srcdir, d['dot'] + 'build')
    #    d['exclude_patterns'] = repr(d['dot'] + 'build')
    # ensuredir(builddir)
    ensuredir(path.join(srcdir, d['dot'] + 'templates'))
    ensuredir(path.join(srcdir, d['dot'] + 'static'))

    def write_file(fpath, content, newline=None):
        if overwrite or not path.isfile(fpath):
            print('Creating file %s.' % fpath)
            f = open(fpath, 'wt', encoding='utf-8', newline=newline)
            try:
                f.write(content)
            finally:
                f.close()
        else:
            print('File %s already exists, skipping.' % fpath)

    conf_text = ABLOG_CONF % d
    write_file(path.join(srcdir, 'conf.py'), conf_text)

    masterfile = path.join(srcdir, d['master'] + d['suffix'])
    write_file(masterfile, ABLOG_INDEX % d)

    about = path.join(srcdir, 'about' + d['suffix'])
    write_file(about, ABLOG_ABOUT % d)

    d['post_date'] = datetime.datetime.today().strftime('%b %d, %Y')
    firstpost = path.join(srcdir, 'first-post' + d['suffix'])
    write_file(firstpost, ABLOG_POST % d)

    if silent:
        return

    print(bold('Finished: An initial directory structure has been created.'))
Esempio n. 33
0
def generate(d, overwrite=True, silent=False, templatedir=None):
    # type: (Dict, bool, bool, unicode) -> None
    """Generate project based on values in *d*."""
    template = QuickstartRenderer(templatedir=templatedir)

    texescape.init()
    indent = ' ' * 4

    if 'mastertoctree' not in d:
        d['mastertoctree'] = ''
    if 'mastertocmaxdepth' not in d:
        d['mastertocmaxdepth'] = 2

    d['PY3'] = PY3
    d['project_fn'] = make_filename(d['project'])
    d['project_url'] = urlquote(d['project'].encode('idna'))
    d['project_manpage'] = d['project_fn'].lower()
    d['now'] = time.asctime()
    d['project_underline'] = column_width(d['project']) * '='
    d.setdefault('extensions', [])
    for name in EXTENSIONS:
        if d.get('ext_' + name):
            d['extensions'].append('sphinx.ext.' + name)
    d['extensions'] = (',\n' + indent).join(repr(name) for name in d['extensions'])
    d['copyright'] = time.strftime('%Y') + ', ' + d['author']
    d['author_texescaped'] = text_type(d['author']).\
        translate(texescape.tex_escape_map)
    d['project_doc'] = d['project'] + ' Documentation'
    d['project_doc_texescaped'] = text_type(d['project'] + ' Documentation').\
        translate(texescape.tex_escape_map)

    # escape backslashes and single quotes in strings that are put into
    # a Python string literal
    for key in ('project', 'project_doc', 'project_doc_texescaped',
                'author', 'author_texescaped', 'copyright',
                'version', 'release', 'master'):
        d[key + '_str'] = d[key].replace('\\', '\\\\').replace("'", "\\'")

    if not path.isdir(d['path']):
        ensuredir(d['path'])

    srcdir = d['sep'] and path.join(d['path'], 'source') or d['path']

    ensuredir(srcdir)
    if d['sep']:
        builddir = path.join(d['path'], 'build')
        d['exclude_patterns'] = ''
    else:
        builddir = path.join(srcdir, d['dot'] + 'build')
        exclude_patterns = map(repr, [
            d['dot'] + 'build',
            'Thumbs.db', '.DS_Store',
        ])
        d['exclude_patterns'] = ', '.join(exclude_patterns)
    ensuredir(builddir)
    ensuredir(path.join(srcdir, d['dot'] + 'templates'))
    ensuredir(path.join(srcdir, d['dot'] + 'static'))

    def write_file(fpath, content, newline=None):
        # type: (unicode, unicode, unicode) -> None
        if overwrite or not path.isfile(fpath):
            if 'quiet' not in d:
                print('Creating file %s.' % fpath)
            with open(fpath, 'wt', encoding='utf-8', newline=newline) as f:
                f.write(content)
        else:
            if 'quiet' not in d:
                print('File %s already exists, skipping.' % fpath)

    conf_path = os.path.join(templatedir, 'conf.py_t') if templatedir else None
    if not conf_path or not path.isfile(conf_path):
        conf_path = os.path.join(package_dir, 'templates', 'quickstart', 'conf.py_t')
    with open(conf_path) as f:
        conf_text = convert_python_source(f.read())

    write_file(path.join(srcdir, 'conf.py'), template.render_string(conf_text, d))

    masterfile = path.join(srcdir, d['master'] + d['suffix'])
    write_file(masterfile, template.render('quickstart/master_doc.rst_t', d))

    if d.get('make_mode') is True:
        makefile_template = 'quickstart/Makefile.new_t'
        batchfile_template = 'quickstart/make.bat.new_t'
    else:
        makefile_template = 'quickstart/Makefile_t'
        batchfile_template = 'quickstart/make.bat_t'

    if d['makefile'] is True:
        d['rsrcdir'] = d['sep'] and 'source' or '.'
        d['rbuilddir'] = d['sep'] and 'build' or d['dot'] + 'build'
        # use binary mode, to avoid writing \r\n on Windows
        write_file(path.join(d['path'], 'Makefile'),
                   template.render(makefile_template, d), u'\n')

    if d['batchfile'] is True:
        d['rsrcdir'] = d['sep'] and 'source' or '.'
        d['rbuilddir'] = d['sep'] and 'build' or d['dot'] + 'build'
        write_file(path.join(d['path'], 'make.bat'),
                   template.render(batchfile_template, d), u'\r\n')

    if silent:
        return
    print()
    print(bold('Finished: An initial directory structure has been created.'))
    print('''
You should now populate your master file %s and create other documentation
source files. ''' % masterfile + ((d['makefile'] or d['batchfile']) and '''\
Use the Makefile to build the docs, like so:
   make builder
''' or '''\
Use the sphinx-build command to build the docs, like so:
   sphinx-build -b builder %s %s
''' % (srcdir, builddir)) + '''\
where "builder" is one of the supported builders, e.g. html, latex or linkcheck.
''')
Esempio n. 34
0
def generate(d, overwrite=True, silent=False):
    """Generate project based on values in *d*."""

    texescape.init()

    if 'mastertoctree' not in d:
        d['mastertoctree'] = ''
    if 'mastertocmaxdepth' not in d:
        d['mastertocmaxdepth'] = 2

    d['project_fn'] = make_filename(d['project'])
    d['project_manpage'] = d['project_fn'].lower()
    d['now'] = time.asctime()
    d['project_underline'] = len(d['project']) * '='
    d['extensions'] = ', '.join(
        repr('sphinx.ext.' + name)
        for name in ('autodoc', 'doctest', 'intersphinx', 'todo', 'coverage',
                     'pngmath', 'mathjax', 'ifconfig', 'viewcode')
        if d.get('ext_' + name))
    d['copyright'] = time.strftime('%Y') + ', ' + d['author']
    d['author_texescaped'] = unicode(d['author']).\
                             translate(texescape.tex_escape_map)
    d['project_doc'] = d['project'] + ' Documentation'
    d['project_doc_texescaped'] = unicode(d['project'] + ' Documentation').\
                                  translate(texescape.tex_escape_map)

    # escape backslashes and single quotes in strings that are put into
    # a Python string literal
    for key in ('project', 'project_doc', 'project_doc_texescaped',
                'author', 'author_texescaped', 'copyright',
                'version', 'release', 'master'):
        d[key + '_str'] = d[key].replace('\\', '\\\\').replace("'", "\\'")

    if not path.isdir(d['path']):
        mkdir_p(d['path'])

    srcdir = d['sep'] and path.join(d['path'], 'source') or d['path']

    mkdir_p(srcdir)
    if d['sep']:
        builddir = path.join(d['path'], 'build')
        d['exclude_patterns'] = ''
    else:
        builddir = path.join(srcdir, d['dot'] + 'build')
        d['exclude_patterns'] = repr(d['dot'] + 'build')
    mkdir_p(builddir)
    mkdir_p(path.join(srcdir, d['dot'] + 'templates'))
    mkdir_p(path.join(srcdir, d['dot'] + 'static'))

    def write_file(fpath, mode, content):
        if overwrite or not path.isfile(fpath):
            print 'Creating file %s.' % fpath
            f = open(fpath, mode, encoding='utf-8')
            try:
                f.write(content)
            finally:
                f.close()
        else:
            print 'File %s already exists, skipping.' % fpath

    conf_text = QUICKSTART_CONF % d
    if d['epub']:
        conf_text += EPUB_CONFIG % d
    if d.get('ext_intersphinx'):
        conf_text += INTERSPHINX_CONFIG

    write_file(path.join(srcdir, 'conf.py'), 'w', conf_text)

    masterfile = path.join(srcdir, d['master'] + d['suffix'])
    write_file(masterfile, 'w', MASTER_FILE % d)

    if d['makefile']:
        d['rsrcdir'] = d['sep'] and 'source' or '.'
        d['rbuilddir'] = d['sep'] and 'build' or d['dot'] + 'build'
        # use binary mode, to avoid writing \r\n on Windows
        write_file(path.join(d['path'], 'Makefile'), 'wb', MAKEFILE % d)

    if d['batchfile']:
        d['rsrcdir'] = d['sep'] and 'source' or '.'
        d['rbuilddir'] = d['sep'] and 'build' or d['dot'] + 'build'
        write_file(path.join(d['path'], 'make.bat'), 'w', BATCHFILE % d)

    if silent:
        return
    print
    print bold('Finished: An initial directory structure has been created.')
    print '''
You should now populate your master file %s and create other documentation
source files. ''' % masterfile + ((d['makefile'] or d['batchfile']) and '''\
Use the Makefile to build the docs, like so:
   make builder
''' or '''\
Use the sphinx-build command to build the docs, like so:
   sphinx-build -b builder %s %s
''' % (srcdir, builddir)) + '''\