Beispiel #1
0
def convert_dvi_to_png(dvipath, builder):
    # type: (str, Builder) -> Tuple[str, int]
    """Convert DVI file to PNG image."""
    tempdir = ensure_tempdir(builder)
    filename = path.join(tempdir, 'math.png')

    name = 'dvipng'
    command = [
        builder.config.imgmath_dvipng, '-o', filename, '-T', 'tight', '-z9'
    ]
    command.extend(builder.config.imgmath_dvipng_args)
    if builder.config.imgmath_use_preview:
        command.append('--depth')
    command.append(dvipath)

    stdout, stderr = convert_dvi_to_image(command, name)

    depth = None
    if builder.config.imgmath_use_preview:
        for line in stdout.splitlines():
            matched = depth_re.match(line)
            if matched:
                depth = int(matched.group(1))
                write_png_depth(filename, depth)
                break

    return filename, depth
Beispiel #2
0
def convert_dvi_to_png(dvipath, builder):
    # type: (unicode, Builder) -> Tuple[unicode, int]
    """Convert DVI file to PNG image."""
    tempdir = ensure_tempdir(builder)
    filename = path.join(tempdir, 'math.png')

    name = 'dvipng'
    command = [builder.config.imgmath_dvipng, '-o', filename, '-T', 'tight', '-z9']
    command.extend(builder.config.imgmath_dvipng_args)
    if builder.config.imgmath_use_preview:
        command.append('--depth')
    command.append(dvipath)

    stdout, stderr = convert_dvi_to_image(command, name)

    depth = None
    if builder.config.imgmath_use_preview:
        for line in stdout.splitlines():
            matched = depth_re.match(line)  # type: ignore
            if matched:
                depth = int(matched.group(1))
                write_png_depth(filename, depth)
                break

    return filename, depth
Beispiel #3
0
def render_math(self, math):
    # type: (nodes.NodeVisitor, unicode) -> Tuple[unicode, int]
    """Render the LaTeX math expression *math* using latex and dvipng.

    Return the filename relative to the built document and the "depth",
    that is, the distance of image bottom and baseline in pixels, if the
    option to use preview_latex is switched on.

    Error handling may seem strange, but follows a pattern: if LaTeX or
    dvipng aren't available, only a warning is generated (since that enables
    people on machines without these programs to at least build the rest
    of the docs successfully).  If the programs are there, however, they
    may not fail since that indicates a problem in the math source.
    """
    use_preview = self.builder.config.pngmath_use_preview
    latex = DOC_HEAD + self.builder.config.pngmath_latex_preamble
    latex += (use_preview and DOC_BODY_PREVIEW or DOC_BODY) % math

    shasum = "%s.png" % sha1(latex.encode('utf-8')).hexdigest()
    relfn = posixpath.join(self.builder.imgpath, 'math', shasum)
    outfn = path.join(self.builder.outdir, self.builder.imagedir, 'math',
                      shasum)
    if path.isfile(outfn):
        depth = read_png_depth(outfn)
        return relfn, depth

    # if latex or dvipng has failed once, don't bother to try again
    if hasattr(self.builder, '_mathpng_warned_latex') or \
       hasattr(self.builder, '_mathpng_warned_dvipng'):
        return None, None

    # use only one tempdir per build -- the use of a directory is cleaner
    # than using temporary files, since we can clean up everything at once
    # just removing the whole directory (see cleanup_tempdir)
    if not hasattr(self.builder, '_mathpng_tempdir'):
        tempdir = self.builder._mathpng_tempdir = tempfile.mkdtemp()
    else:
        tempdir = self.builder._mathpng_tempdir

    with codecs.open(path.join(tempdir, 'math.tex'), 'w',
                     'utf-8') as tf:  # type: ignore
        tf.write(latex)

    # build latex command; old versions of latex don't have the
    # --output-directory option, so we have to manually chdir to the
    # temp dir to run it.
    ltx_args = [self.builder.config.pngmath_latex, '--interaction=nonstopmode']
    # add custom args from the config file
    ltx_args.extend(self.builder.config.pngmath_latex_args)
    ltx_args.append('math.tex')

    with cd(tempdir):
        try:
            p = Popen(ltx_args, stdout=PIPE, stderr=PIPE)
        except OSError as err:
            if err.errno != ENOENT:  # No such file or directory
                raise
            logger.warning(
                'LaTeX command %r cannot be run (needed for math '
                'display), check the pngmath_latex setting',
                self.builder.config.pngmath_latex)
            self.builder._mathpng_warned_latex = True
            return None, None

    stdout, stderr = p.communicate()
    if p.returncode != 0:
        raise MathExtError('latex exited with error', stderr, stdout)

    ensuredir(path.dirname(outfn))
    # use some standard dvipng arguments
    dvipng_args = [self.builder.config.pngmath_dvipng]
    dvipng_args += ['-o', outfn, '-T', 'tight', '-z9']
    # add custom ones from config value
    dvipng_args.extend(self.builder.config.pngmath_dvipng_args)
    if use_preview:
        dvipng_args.append('--depth')
    # last, the input file name
    dvipng_args.append(path.join(tempdir, 'math.dvi'))
    try:
        p = Popen(dvipng_args, stdout=PIPE, stderr=PIPE)
    except OSError as err:
        if err.errno != ENOENT:  # No such file or directory
            raise
        logger.warning(
            'dvipng command %r cannot be run (needed for math '
            'display), check the pngmath_dvipng setting',
            self.builder.config.pngmath_dvipng)
        self.builder._mathpng_warned_dvipng = True
        return None, None
    stdout, stderr = p.communicate()
    if p.returncode != 0:
        raise MathExtError('dvipng exited with error', stderr, stdout)
    depth = None
    if use_preview:
        for line in stdout.splitlines():
            m = depth_re.match(line)
            if m:
                depth = int(m.group(1))
                write_png_depth(outfn, depth)
                break

    return relfn, depth
Beispiel #4
0
        self.builder.warn('dvipng command %r cannot be run (needed for math '
                          'display), check the pngmath_dvipng setting' %
                          self.builder.config.pngmath_dvipng)
        self.builder._mathpng_warned_dvipng = True
        return None, None
    stdout, stderr = p.communicate()
    if p.returncode != 0:
        raise MathExtError('dvipng exited with error:\n[stderr]\n%s\n'
                           '[stdout]\n%s' % (stderr, stdout))
    depth = None
    if use_preview:
        for line in stdout.splitlines():
            m = depth_re.match(line)
            if m:
                depth = int(m.group(1))
                write_png_depth(outfn, depth)
                break

    return relfn, depth


def cleanup_tempdir(app, exc):
    if exc:
        return
    if not hasattr(app.builder, '_mathpng_tempdir'):
        return
    try:
        shutil.rmtree(app.builder._mathpng_tempdir)
    except Exception:
        pass
        self.builder.warn('dvipng command %r cannot be run (needed for math '
                          'display), check the pngmath_dvipng setting' %
                          self.builder.config.pngmath_dvipng)
        self.builder._mathpng_warned_dvipng = True
        return None, None
    stdout, stderr = p.communicate()
    if p.returncode != 0:
        raise MathExtError('dvipng exited with error:\n[stderr]\n%s\n'
                           '[stdout]\n%s' % (stderr, stdout))
    depth = None
    if use_preview:
        for line in stdout.splitlines():
            m = depth_re.match(line)
            if m:
                depth = int(m.group(1))
                write_png_depth(outfn, depth)
                break

    return relfn, depth

def cleanup_tempdir(app, exc):
    if exc:
        return
    if not hasattr(app.builder, '_mathpng_tempdir'):
        return
    try:
        shutil.rmtree(app.builder._mathpng_tempdir)
    except Exception:
        pass

def get_tooltip(self, node):
Beispiel #6
0
def render_math(self, math):
    """Render the LaTeX math expression *math* using latex and dvipng or
    dvisvgm.

    Return the filename relative to the built document and the "depth",
    that is, the distance of image bottom and baseline in pixels, if the
    option to use preview_latex is switched on.

    Error handling may seem strange, but follows a pattern: if LaTeX or dvipng
    (dvisvgm) aren't available, only a warning is generated (since that enables
    people on machines without these programs to at least build the rest of the
    docs successfully).  If the programs are there, however, they may not fail
    since that indicates a problem in the math source.
    """
    image_format = self.builder.config.imgmath_image_format
    if image_format not in ('png', 'svg'):
        raise MathExtError(
            'imgmath_image_format must be either "png" or "svg"')

    font_size = self.builder.config.imgmath_font_size
    use_preview = self.builder.config.imgmath_use_preview
    latex = DOC_HEAD + self.builder.config.imgmath_latex_preamble
    latex += (use_preview and DOC_BODY_PREVIEW
              or DOC_BODY) % (font_size, int(round(font_size * 1.2)), math)

    shasum = "%s.%s" % (sha1(latex.encode('utf-8')).hexdigest(), image_format)
    relfn = posixpath.join(self.builder.imgpath, 'math', shasum)
    outfn = path.join(self.builder.outdir, self.builder.imagedir, 'math',
                      shasum)
    if path.isfile(outfn):
        depth = read_png_depth(outfn)
        return relfn, depth

    # if latex or dvipng (dvisvgm) has failed once, don't bother to try again
    if hasattr(self.builder, '_imgmath_warned_latex') or \
       hasattr(self.builder, '_imgmath_warned_image_translator'):
        return None, None

    # use only one tempdir per build -- the use of a directory is cleaner
    # than using temporary files, since we can clean up everything at once
    # just removing the whole directory (see cleanup_tempdir)
    if not hasattr(self.builder, '_imgmath_tempdir'):
        tempdir = self.builder._imgmath_tempdir = tempfile.mkdtemp()
    else:
        tempdir = self.builder._imgmath_tempdir

    tf = codecs.open(path.join(tempdir, 'math.tex'), 'w', 'utf-8')
    tf.write(latex)
    tf.close()

    # build latex command; old versions of latex don't have the
    # --output-directory option, so we have to manually chdir to the
    # temp dir to run it.
    ltx_args = [self.builder.config.imgmath_latex, '--interaction=nonstopmode']
    # add custom args from the config file
    ltx_args.extend(self.builder.config.imgmath_latex_args)
    ltx_args.append('math.tex')

    with cd(tempdir):
        try:
            p = Popen(ltx_args, stdout=PIPE, stderr=PIPE)
        except OSError as err:
            if err.errno != ENOENT:  # No such file or directory
                raise
            self.builder.warn(
                'LaTeX command %r cannot be run (needed for math '
                'display), check the imgmath_latex setting' %
                self.builder.config.imgmath_latex)
            self.builder._imgmath_warned_latex = True
            return None, None

    stdout, stderr = p.communicate()
    if p.returncode != 0:
        raise MathExtError('latex exited with error', stderr, stdout)

    ensuredir(path.dirname(outfn))
    if image_format == 'png':
        image_translator = 'dvipng'
        image_translator_executable = self.builder.config.imgmath_dvipng
        # use some standard dvipng arguments
        image_translator_args = [self.builder.config.imgmath_dvipng]
        image_translator_args += ['-o', outfn, '-T', 'tight', '-z9']
        # add custom ones from config value
        image_translator_args.extend(self.builder.config.imgmath_dvipng_args)
        if use_preview:
            image_translator_args.append('--depth')
    elif image_format == 'svg':
        image_translator = 'dvisvgm'
        image_translator_executable = self.builder.config.imgmath_dvisvgm
        # use some standard dvisvgm arguments
        image_translator_args = [self.builder.config.imgmath_dvisvgm]
        image_translator_args += ['-o', outfn]
        # add custom ones from config value
        image_translator_args.extend(self.builder.config.imgmath_dvisvgm_args)
    else:
        raise MathExtError(
            'imgmath_image_format must be either "png" or "svg"')

    # last, the input file name
    image_translator_args.append(path.join(tempdir, 'math.dvi'))

    try:
        p = Popen(image_translator_args, stdout=PIPE, stderr=PIPE)
    except OSError as err:
        if err.errno != ENOENT:  # No such file or directory
            raise
        self.builder.warn(
            '%s command %r cannot be run (needed for math '
            'display), check the imgmath_%s setting' %
            (image_translator, image_translator_executable, image_translator))
        self.builder._imgmath_warned_image_translator = True
        return None, None

    stdout, stderr = p.communicate()
    if p.returncode != 0:
        raise MathExtError('%s exited with error' % image_translator, stderr,
                           stdout)
    depth = None
    if use_preview and image_format == 'png':  # depth is only useful for png
        for line in stdout.splitlines():
            m = depth_re.match(line)
            if m:
                depth = int(m.group(1))
                write_png_depth(outfn, depth)
                break

    return relfn, depth
Beispiel #7
0
def render_math(self, math):
    """Render the LaTeX math expression *math* using latex and dvipng.

    Return the filename relative to the built document and the "depth",
    that is, the distance of image bottom and baseline in pixels, if the
    option to use preview_latex is switched on.

    Error handling may seem strange, but follows a pattern: if LaTeX or
    dvipng aren't available, only a warning is generated (since that enables
    people on machines without these programs to at least build the rest
    of the docs successfully).  If the programs are there, however, they
    may not fail since that indicates a problem in the math source.
    """
    use_preview = self.builder.config.pngmath_use_preview
    latex = DOC_HEAD + self.builder.config.pngmath_latex_preamble
    latex += (use_preview and DOC_BODY_PREVIEW or DOC_BODY) % math

    shasum = "%s.png" % sha1(latex.encode('utf-8')).hexdigest()
    relfn = posixpath.join(self.builder.imgpath, 'math', shasum)
    outfn = path.join(self.builder.outdir, self.builder.imagedir, 'math', shasum)
    if path.isfile(outfn):
        depth = read_png_depth(outfn)
        return relfn, depth

    # if latex or dvipng has failed once, don't bother to try again
    if hasattr(self.builder, '_mathpng_warned_latex') or \
       hasattr(self.builder, '_mathpng_warned_dvipng'):
        return None, None

    # use only one tempdir per build -- the use of a directory is cleaner
    # than using temporary files, since we can clean up everything at once
    # just removing the whole directory (see cleanup_tempdir)
    if not hasattr(self.builder, '_mathpng_tempdir'):
        tempdir = self.builder._mathpng_tempdir = tempfile.mkdtemp()
    else:
        tempdir = self.builder._mathpng_tempdir

    tf = codecs.open(path.join(tempdir, 'math.tex'), 'w', 'utf-8')
    tf.write(latex)
    tf.close()

    # build latex command; old versions of latex don't have the
    # --output-directory option, so we have to manually chdir to the
    # temp dir to run it.
    ltx_args = [self.builder.config.pngmath_latex, '--interaction=nonstopmode']
    # add custom args from the config file
    ltx_args.extend(self.builder.config.pngmath_latex_args)
    ltx_args.append('math.tex')

    with cd(tempdir):
        try:
            p = Popen(ltx_args, stdout=PIPE, stderr=PIPE)
        except OSError as err:
            if err.errno != ENOENT:   # No such file or directory
                raise
            self.builder.warn('LaTeX command %r cannot be run (needed for math '
                              'display), check the pngmath_latex setting' %
                              self.builder.config.pngmath_latex)
            self.builder._mathpng_warned_latex = True
            return None, None

    stdout, stderr = p.communicate()
    if p.returncode != 0:
        raise MathExtError('latex exited with error', stderr, stdout)

    ensuredir(path.dirname(outfn))
    # use some standard dvipng arguments
    dvipng_args = [self.builder.config.pngmath_dvipng]
    dvipng_args += ['-o', outfn, '-T', 'tight', '-z9']
    # add custom ones from config value
    dvipng_args.extend(self.builder.config.pngmath_dvipng_args)
    if use_preview:
        dvipng_args.append('--depth')
    # last, the input file name
    dvipng_args.append(path.join(tempdir, 'math.dvi'))
    try:
        p = Popen(dvipng_args, stdout=PIPE, stderr=PIPE)
    except OSError as err:
        if err.errno != ENOENT:   # No such file or directory
            raise
        self.builder.warn('dvipng command %r cannot be run (needed for math '
                          'display), check the pngmath_dvipng setting' %
                          self.builder.config.pngmath_dvipng)
        self.builder._mathpng_warned_dvipng = True
        return None, None
    stdout, stderr = p.communicate()
    if p.returncode != 0:
        raise MathExtError('dvipng exited with error', stderr, stdout)
    depth = None
    if use_preview:
        for line in stdout.splitlines():
            m = depth_re.match(line)
            if m:
                depth = int(m.group(1))
                write_png_depth(outfn, depth)
                break

    return relfn, depth
Beispiel #8
0
def render_math(self, math):
    """Render the LaTeX math expression *math* using latex and dvipng or
    dvisvgm.

    Return the filename relative to the built document and the "depth",
    that is, the distance of image bottom and baseline in pixels, if the
    option to use preview_latex is switched on.

    Error handling may seem strange, but follows a pattern: if LaTeX or dvipng
    (dvisvgm) aren't available, only a warning is generated (since that enables
    people on machines without these programs to at least build the rest of the
    docs successfully).  If the programs are there, however, they may not fail
    since that indicates a problem in the math source.
    """
    image_format = self.builder.config.imgmath_image_format
    if image_format not in ("png", "svg"):
        raise MathExtError('imgmath_image_format must be either "png" or "svg"')

    font_size = self.builder.config.imgmath_font_size
    use_preview = self.builder.config.imgmath_use_preview
    latex = DOC_HEAD + self.builder.config.imgmath_latex_preamble
    latex += (use_preview and DOC_BODY_PREVIEW or DOC_BODY) % (font_size, int(round(font_size * 1.2)), math)

    shasum = "%s.%s" % (sha1(latex.encode("utf-8")).hexdigest(), image_format)
    relfn = posixpath.join(self.builder.imgpath, "math", shasum)
    outfn = path.join(self.builder.outdir, self.builder.imagedir, "math", shasum)
    if path.isfile(outfn):
        depth = read_png_depth(outfn)
        return relfn, depth

    # if latex or dvipng (dvisvgm) has failed once, don't bother to try again
    if hasattr(self.builder, "_imgmath_warned_latex") or hasattr(self.builder, "_imgmath_warned_image_translator"):
        return None, None

    # use only one tempdir per build -- the use of a directory is cleaner
    # than using temporary files, since we can clean up everything at once
    # just removing the whole directory (see cleanup_tempdir)
    if not hasattr(self.builder, "_imgmath_tempdir"):
        tempdir = self.builder._imgmath_tempdir = tempfile.mkdtemp()
    else:
        tempdir = self.builder._imgmath_tempdir

    tf = codecs.open(path.join(tempdir, "math.tex"), "w", "utf-8")
    tf.write(latex)
    tf.close()

    # build latex command; old versions of latex don't have the
    # --output-directory option, so we have to manually chdir to the
    # temp dir to run it.
    ltx_args = [self.builder.config.imgmath_latex, "--interaction=nonstopmode"]
    # add custom args from the config file
    ltx_args.extend(self.builder.config.imgmath_latex_args)
    ltx_args.append("math.tex")

    with cd(tempdir):
        try:
            p = Popen(ltx_args, stdout=PIPE, stderr=PIPE)
        except OSError as err:
            if err.errno != ENOENT:  # No such file or directory
                raise
            self.builder.warn(
                "LaTeX command %r cannot be run (needed for math "
                "display), check the imgmath_latex setting" % self.builder.config.imgmath_latex
            )
            self.builder._imgmath_warned_latex = True
            return None, None

    stdout, stderr = p.communicate()
    if p.returncode != 0:
        raise MathExtError("latex exited with error", stderr, stdout)

    ensuredir(path.dirname(outfn))
    if image_format == "png":
        image_translator = "dvipng"
        image_translator_executable = self.builder.config.imgmath_dvipng
        # use some standard dvipng arguments
        image_translator_args = [self.builder.config.imgmath_dvipng]
        image_translator_args += ["-o", outfn, "-T", "tight", "-z9"]
        # add custom ones from config value
        image_translator_args.extend(self.builder.config.imgmath_dvipng_args)
        if use_preview:
            image_translator_args.append("--depth")
    elif image_format == "svg":
        image_translator = "dvisvgm"
        image_translator_executable = self.builder.config.imgmath_dvisvgm
        # use some standard dvisvgm arguments
        image_translator_args = [self.builder.config.imgmath_dvisvgm]
        image_translator_args += ["-o", outfn]
        # add custom ones from config value
        image_translator_args.extend(self.builder.config.imgmath_dvisvgm_args)
        # last, the input file name
        image_translator_args.append(path.join(tempdir, "math.dvi"))
    else:
        raise MathExtError('imgmath_image_format must be either "png" or "svg"')

    # last, the input file name
    image_translator_args.append(path.join(tempdir, "math.dvi"))

    try:
        p = Popen(image_translator_args, stdout=PIPE, stderr=PIPE)
    except OSError as err:
        if err.errno != ENOENT:  # No such file or directory
            raise
        self.builder.warn(
            "%s command %r cannot be run (needed for math " "display), check the imgmath_%s setting" % image_translator,
            image_translator_executable,
            image_translator,
        )
        self.builder._imgmath_warned_image_translator = True
        return None, None

    stdout, stderr = p.communicate()
    if p.returncode != 0:
        raise MathExtError("%s exited with error", image_translator, stderr, stdout)
    depth = None
    if use_preview and image_format == "png":  # depth is only useful for png
        for line in stdout.splitlines():
            m = depth_re.match(line)
            if m:
                depth = int(m.group(1))
                write_png_depth(outfn, depth)
                break

    return relfn, depth