示例#1
0
#!/usr/bin/env python

from datetime import datetime
from plasTeX.Tokenizer import Token, EscapeSequence, Other
from plasTeX import Macro, Command, CountCommand
from plasTeX import sourceChildren
from plasTeX.Logging import getLogger

log = getLogger()
status = getLogger('status')
deflog = getLogger('parse.definitions')
mathshiftlog = getLogger('parse.mathshift')


class relax(Command):
    pass


class protect(Command):
    pass


class global_(Command):
    macroName = 'global'


class par(Command):
    """ Paragraph """
    level = Command.PAR_LEVEL

    def invoke(self, tex):
示例#2
0
from __future__ import division
#!/usr/bin/env python

from plasTeX.Logging import getLogger
import plasTeX.Imagers, glob, sys

status = getLogger('status')

gs = 'gs'
if sys.platform.startswith('win'):
   gs = 'gswin32c'

class GSPDFPNG(plasTeX.Imagers.Imager):
    """ Imager that uses gs to convert pdf to png """
    command = ('%s -dSAFER -dBATCH -dNOPAUSE -sDEVICE=png16m -r250 ' % gs) + \
              '-dGraphicsAlphaBits=4 -sOutputFile=img%d.png'
    compiler = 'pdflatex'
    fileExtension = '.png'

    def executeConverter(self, output):
        res = plasTeX.Imagers.Imager.executeConverter(self, output)
        self.scaleImages()
        return res

    def scaleImages(self):
        """ Scale images down and anti-alias """
        if plasTeX.Imagers.PILImage is not None:
            PILImage = plasTeX.Imagers.PILImage
            scaledown = 2.2
            for filename in glob.glob('img*.png'):
                status.info('[%s]' % filename,)
#!/usr/bin/env python

"""
C.1.2 Environments (p167)

"""

from plasTeX import Command, Environment
from plasTeX.Logging import getLogger

envlog = getLogger('parse.environments')

class begin(Command):
    """ Beginning of an environment """
    args = 'name:str'

    def invoke(self, tex):
        """ Parse the \\begin{...} """
#       name = self.parse(tex)['name']
        name = tex.readArgument(type=str)
        envlog.debug(name)

        self.ownerDocument.context.currenvir = name

        # Instantiate the correct macro and let it know
        # that it came from a \begin{...} macro
        obj = self.ownerDocument.createElement(name)
        obj.macroMode = Command.MODE_BEGIN
        obj.parentNode = self.parentNode

        # Return the output of the instantiated macro in
示例#4
0

import codecs
import os

from six.moves.urllib.parse import quote as url_quote

from zope.dottedname.resolve import resolve as resolve_import

from plasTeX.Filenames import Filenames
from plasTeX.DOM import Node, Document
from plasTeX.Logging import getLogger
#from plasTeX.Imagers import Image, PILImage
from plasTeX.Imagers import Imager as DefaultImager, VectorImager as DefaultVectorImager

log = getLogger(__name__)
status = getLogger(__name__ + '.status')

from six import string_types
try:
    unicode
except NameError:
    unicode = str # py3

__all__ = ['Renderer','Renderable']

def baseclasses(cls):
    return [x for x in cls.mro() if x is not object]
    # XXX: What's the difference between this and mro()?
    #  mro() is only defined on new-style classes;
    #  this could result in multiple copies of the same class
示例#5
0
import re
import shutil
import string

from zope import component
from zope import interface

from plasTeX.Renderers import Renderer as BaseRenderer

from .interfaces import ITextTemplateEngine
from .interfaces import IXMLTemplateEngine
from .interfaces import IHTMLTemplateEngine
from .interfaces import ITemplateEngine

from plasTeX.Logging import getLogger
log = getLogger(__name__)
logger = log

from six.moves import configparser
from six import text_type

ConfigParser = configparser.SafeConfigParser if sys.version_info[0] < 3 else configparser.ConfigParser

# Support for Python string templates
def stringtemplate(s, encoding='utf8',filename=None):
    if isinstance(s, bytes):
        s = s.decode(encoding)
    template = string.Template(s)
    def renderstring(obj):
        tvars = {
            'here':obj,
示例#6
0
#!/usr/bin/env python

import codecs
from plasTeX.Tokenizer import Token, EscapeSequence
from plasTeX import Command, Environment, CountCommand
from plasTeX import IgnoreCommand, sourceChildren
from plasTeX.Logging import getLogger

log = getLogger(__name__)
status = getLogger(__name__ + '.status')
deflog = getLogger(__name__ + '.parse.definitions')
envlog = getLogger(__name__ + '.parse.environments')
mathshiftlog = getLogger(__name__ + '.parse.mathshift')

class relax(Command):
    pass

class protect(Command):
    pass

class global_(Command):
    macroName = 'global'

class par(Command):
    """
    Paragraph

    The 'continuation' attribute flags if the paragraph is not the first
    segment of a paragraph broken-up by other block-level elements.

    """
示例#7
0
    # in which we do things
    if sys.path[0] == '':
        del sys.path[0]
    sys.path.insert( 0, os.path.abspath( os.path.dirname( os.path.dirname(__file__ ) ) ) )
    print( os.path.abspath(os.getcwd() ))

import plasTeX
from plasTeX.TeX import TeX
import plasTeX.Renderers
from plasTeX.Config import newConfig

from plasTeX.Logging import getLogger
from zope.configuration import xmlconfig
from zope.dottedname import resolve as dottedname

log = getLogger('plasTeX')


__version__ = '0.9.3'

def main(argv=None):
    """ Main program routine """

    as_main = False
    if argv is None:
        as_main = True
        print( 'plasTeX version %s' % __version__, file=sys.stderr )
        argv = sys.argv
    xml_conf_context = xmlconfig.file('configure.zcml', package=plasTeX)
    # Parse the command line options
    config = newConfig()
示例#8
0
import os, time, tempfile, shutil, re, string, pickle, codecs
try: from hashlib import md5
except ImportError: from md5 import new as md5
from plasTeX.Logging import getLogger
from StringIO import StringIO
from plasTeX.Filenames import Filenames
from plasTeX.dictutils import ordereddict
import subprocess
import shlex

from plasTeX.Imagers import WorkingFile

import plasTeX.Imagers

log = getLogger()
depthlog = getLogger('render.images.depth')
status = getLogger('status')
imagelog = getLogger('imager')

class Tralics(plasTeX.Imagers.Imager):
    """ Imager that uses dvipng """
    command = 'tralics'

    compiler = 'tralics'

    fileExtension = '.xml'

    imageAttrs = ''
    imageUnits = ''
示例#9
0
#!/usr/bin/env python

import os, shutil, string, importlib
from plasTeX.Filenames import Filenames
from plasTeX.DOM import Node
from plasTeX.Logging import getLogger
from plasTeX.Imagers import Image, PILImage
import collections.abc

log = getLogger()
status = getLogger('status')

import logging
logging.getLogger('simpleTAL').setLevel(logging.WARNING)
logging.getLogger('simpleTALES').setLevel(logging.WARNING)

__all__ = ['Renderer', 'Renderable']


def baseclasses(cls):
    output = [cls]
    for item in cls.__bases__:
        output.extend(baseclasses(item))
    return [x for x in output if x is not object]


def mixin(base, mix, overwrite=False):
    """
    Mix the methods and members of class `mix` into `base`

    Required Arguments:
示例#10
0
    if sys.path[0] == '':
        del sys.path[0]
    sys.path.insert(
        0, os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
    print(os.path.abspath(os.getcwd()))

import plasTeX
from plasTeX.TeX import TeX
import plasTeX.Renderers
from plasTeX.Config import newConfig

from plasTeX.Logging import getLogger
from zope.configuration import xmlconfig
from zope.dottedname import resolve as dottedname

log = getLogger('plasTeX')

__version__ = '0.9.3'


def main(argv=None):
    """ Main program routine """

    as_main = False
    if argv is None:
        as_main = True
        print('plasTeX version %s' % __version__, file=sys.stderr)
        argv = sys.argv
    xml_conf_context = xmlconfig.file('configure.zcml', package=plasTeX)
    # Parse the command line options
    config = newConfig()
示例#11
0
"""
C.1.2 Environments (p167)

"""

from plasTeX import Command
from plasTeX.Logging import getLogger

envlog = getLogger('parse.environments')


class begin(Command):
    """ Beginning of an environment """
    args = 'name:str'

    def invoke(self, tex):
        """ Parse the \\begin{...} """
        #       name = self.parse(tex)['name']
        name = tex.readArgument(type=str)
        envlog.debug(name)

        self.ownerDocument.context.currenvir = name

        # Instantiate the correct macro and let it know
        # that it came from a \begin{...} macro
        obj = self.ownerDocument.createElement(name)
        obj.macroMode = Command.MODE_BEGIN
        obj.parentNode = self.parentNode

        # Return the output of the instantiated macro in
        # place of self
示例#12
0
#!/usr/bin/env python

import os, time, tempfile, shutil, re, string, pickle, md5, codecs
from plasTeX.Logging import getLogger
from StringIO import StringIO
from plasTeX.Filenames import Filenames
from plasTeX.dictutils import ordereddict

log = getLogger()
depthlog = getLogger('render.images.depth')
status = getLogger('status')

try:
    import Image as PILImage
    import ImageChops as PILImageChops
except ImportError:
    PILImage = PILImageChops = None

def autoCrop(im, bgcolor=None, margin=0):
    """
    Automatically crop image down to non-background portion

    Required Argument:
    im -- image object

    Optional Argument:
    bgcolor -- value or tuple containing the color to use for the 
        background color when cropping
    margin -- leave this many pixels around the content.  If there
        aren't that many pixels to leave, leave as many as possible.
示例#13
0
from importlib import import_module
from importlib.util import find_spec

from plasTeX import ismacro, macroName
from plasTeX.TeX import TeX
from plasTeX.Logging import getLogger
from plasTeX.Base.TeX.Primitives import relax
from plasTeX.Tokenizer import Tokenizer, Token, DEFAULT_CATEGORIES, VERBATIM_CATEGORIES
import plasTeX
import plasTeX.Packages

# Only export the Context singleton
__all__ = ['Context']

# Set up loggers
log = getLogger()
status = getLogger('status')
stacklog = getLogger('context.stack')
macrolog = getLogger('context.macros')


class ContextItem(dict):
    """
    Localized macro/category code stack element

    """
    def __init__(self, data=None):
        dict.__init__(self, data or {})
        self.categories = None  # type: Optional[List[str]]
        self.lets = {}
        self.obj = None
示例#14
0
#!/usr/bin/env python

import codecs
from plasTeX.Tokenizer import Token, EscapeSequence
from plasTeX import Command, Environment, CountCommand
from plasTeX import IgnoreCommand, sourceChildren
from plasTeX.Logging import getLogger

log = getLogger()
status = getLogger('status')
deflog = getLogger('parse.definitions')
envlog = getLogger('parse.environments')
mathshiftlog = getLogger('parse.mathshift')

class relax(Command):
    pass

class protect(Command):
    pass

class global_(Command):
    macroName = 'global'

class par(Command):
    """ Paragraph """
    level = Command.PAR_LEVEL

    def invoke(self, tex):
        status.dot()

    @property
示例#15
0
#!/usr/bin/env python
"""
C.10.2 The array and tabular Environments

"""

import sys
from plasTeX import Macro, Environment, Command, DimenCommand
from plasTeX import sourceChildren, sourceArguments
from plasTeX.Base.TeX.Text import bgroup

from plasTeX.Logging import getLogger
logger = getLogger(__name__)

#pylint: disable=R0904


class ColumnType(Macro):

    columnAttributes = None  # instance
    columnTypes = {}  # class

    def __init__(self):  #, *args, **kwargs):
        super(ColumnType, self).__init__()
        self.style.update(self.columnAttributes or {})

    @classmethod
    def new(cls, name, attributes, args='', before=(), after=(), between=()):
        """
        Generate a new column type definition
示例#16
0
#!/usr/bin/env python

from plasTeX import Command
from plasTeX.Base.LaTeX.Arrays import Array
from plasTeX.Base.LaTeX.Math import EqnarrayStar, equation, eqnarray
#### Imports Added by Tim ####
from plasTeX.Base.LaTeX.Math import math, MathEnvironmentPre

from plasTeX import Tokenizer
from plasTeX.Logging import getLogger

deflog = getLogger('parse.definitions')

class pmatrix(Array):
    pass

class _AMSEquation(eqnarray):
    pass

class _AMSEquationStar(EqnarrayStar):
    macroName = None

class align(_AMSEquation):
    pass

class AlignStar(_AMSEquationStar):
    macroName = 'align*'

class gather(_AMSEquation):
    pass
示例#17
0
"""
C.8 Definitions, Numbering, and Programming

"""

from plasTeX import Command, Environment
from plasTeX.Logging import getLogger

deflog = getLogger('parse.definitions')

#
# C.8.1 Defining Commands
#


class newcommand(Command):
    """ \\newcommand """
    args = '* name:cs [ nargs:int ] [ opt:nox ] definition:nox'

    def invoke(self, tex):
        self.parse(tex)
        a = self.attributes
        args = (a['name'], a['nargs'], a['definition'])
        kwargs = {'opt': a['opt']}
        deflog.debug('command %s %s %s', *args)
        self.ownerDocument.context.newcommand(*args, **kwargs)


class renewcommand(newcommand):
    """ \\renewcommand """
    args = '* name:cs [ nargs:int ] [ opt:nox ] definition:nox'
示例#18
0
def convert(problem, options=None):
    problem = os.path.realpath(problem)

    problembase = os.path.splitext(os.path.basename(problem))[0]
    destdir = Template(options.destdir).safe_substitute(problem=problembase)
    destfile = Template(options.destfile).safe_substitute(problem=problembase)
    imgbasedir = Template(options.imgbasedir).safe_substitute(problem=problembase)

    if options.quiet:
        disableLogging()
    else:
        getLogger().setLevel(eval("logging." + options.loglevel.upper()))
        getLogger('status').setLevel(eval("logging." + options.loglevel.upper()))

    texfile = problem
    # Set up template if necessary
    templ = None
    if os.path.isdir(problem):
        templ = template.Template(problem, language=options.language, title=options.title)
        texfile = templ.get_file_name()

    origcwd = os.getcwd()

    # Setup parser and renderer etc
    fileh = open(texfile,'r');
    tex = TeX(file=fileh)

    ProblemsetMacros.init(tex)

    tex.ownerDocument.config['general']['copy-theme-extras'] = options.css
    if not options.headers:
        tex.ownerDocument.userdata['noheaders'] = True
    tex.ownerDocument.config['files']['filename'] = destfile
    tex.ownerDocument.config['images']['filenames'] = 'img-$num(4)'
    tex.ownerDocument.config['images']['enabled'] = False
    tex.ownerDocument.config['images']['imager'] = 'none'
    tex.ownerDocument.config['images']['base-url'] = imgbasedir

    renderer = ProblemRenderer()

    if not options.quiet:
        print 'Parsing TeX source...'
    doc = tex.parse()
    fileh.close()

    # Go to destdir
    if destdir:
        if not os.path.isdir(destdir):
            os.makedirs(destdir)
        os.chdir(destdir)

    try:
        if not options.quiet:
            print 'Rendering!'
        renderer.render(doc)

        # Annoying: I have not figured out any way of stopping the plasTeX
        # renderer from generating a .paux file
        if os.path.isfile('.paux'):
            os.remove('.paux')

        if options.tidy:
            os.system('tidy -utf8 -i -q -m %s 2> /dev/null' % destfile)

        if options.bodyonly:
            content = open(destfile).read()
            body = re.search('<body>(.*)</body>', content, re.DOTALL)
            assert body
            open(destfile, 'w').write(body.group(1))
    finally:
        # restore cwd
        os.chdir(origcwd)
        if templ:
            templ.cleanup()

    return True
示例#19
0
#!/usr/bin/env python

import codecs
from plasTeX.Tokenizer import Token, EscapeSequence
from plasTeX import Command, Environment, CountCommand
from plasTeX import IgnoreCommand, sourceChildren
from plasTeX.Logging import getLogger

log = getLogger()
status = getLogger('status')
deflog = getLogger('parse.definitions')
envlog = getLogger('parse.environments')
mathshiftlog = getLogger('parse.mathshift')


class relax(Command):
    pass


class protect(Command):
    pass


class global_(Command):
    macroName = 'global'


class par(Command):
    """ Paragraph """
    level = Command.PAR_LEVEL
示例#20
0
#!/usr/bin/env python

import new, os, ConfigParser, re, time, codecs
import plasTeX
from plasTeX import ismacro, macroName
from plasTeX.DOM import Node
from plasTeX.Logging import getLogger
from Tokenizer import Tokenizer, Token, DEFAULT_CATEGORIES, VERBATIM_CATEGORIES

# Only export the Context singleton
__all__ = ['Context']

# Set up loggers
log = getLogger()
status = getLogger('status')
stacklog = getLogger('context.stack')
macrolog = getLogger('context.macros')


class ContextItem(dict):
    """ 
    Localized macro/category code stack element

    """

    def __init__(self, data={}):
        dict.__init__(self, data)
        self.categories = None
        self.obj = None
        self.parent = None
        self.owner = None
示例#21
0
#!/usr/bin/env python

from plasTeX.Logging import getLogger
import plasTeX.Imagers, glob, sys

status = getLogger('status')

gs = 'gs'
if sys.platform.startswith('win'):
    gs = 'gswin32c'


class GSPDFPNG(plasTeX.Imagers.Imager):
    """ Imager that uses gs to convert pdf to png """
    command = ('%s -dSAFER -dBATCH -dNOPAUSE -sDEVICE=png16m -r250 ' % gs) + \
              '-dGraphicsAlphaBits=4 -sOutputFile=img%d.png'
    compiler = 'pdflatex'
    fileExtension = '.png'

    def executeConverter(self, output):
        res = plasTeX.Imagers.Imager.executeConverter(self, output)
        self.scaleImages()
        return res

    def scaleImages(self):
        """ Scale images down and anti-alias """
        if plasTeX.Imagers.PILImage is not None:
            PILImage = plasTeX.Imagers.PILImage
            scaledown = 2.2
            for filename in glob.glob('img*.png'):
                status.info('[%s]' % filename, )
示例#22
0
import tempfile
import shutil
import re
import string

import codecs
from hashlib import md5
from plasTeX.Logging import getLogger
from io import StringIO
from plasTeX.Filenames import Filenames
from collections import OrderedDict as ordereddict
import subprocess

from six.moves import cPickle as pickle

log = getLogger()
depthlog = getLogger("render.images.depth")
status = getLogger("status")
imagelog = getLogger("imager")

try:
    from PIL import Image as PILImage
    from PIL import ImageChops as PILImageChops
except ImportError:
    PILImage = PILImageChops = None


def autoCrop(im, bgcolor=None, margin=0):
    """
    Automatically crop image down to non-background portion
示例#23
0
#!/usr/bin/env python
"""
C.15 Font Selection (p225)

"""

from plasTeX import Command, Environment, sourceArguments
from plasTeX.Logging import getLogger

log = getLogger()

#
# C.15.1 Changing the Type Style
#


class TextDeclaration(Environment):
    pass


class mdseries(TextDeclaration):
    pass


class bfseries(TextDeclaration):
    pass


class rmfamily(TextDeclaration):
    pass
##    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
##    THE SOFTWARE.
##
## Modifications are Copyright 2010 Phillip Lord, Newcastle University. 
##
## Modifications are distributed under the terms of the GNU LGPL license. 

import os, sys, codecs, string, glob
import plasTeX

from plasTeX.TeX import TeX
from plasTeX.Config import config
from plasTeX.ConfigManager import *
from plasTeX.Logging import getLogger

log = getLogger()

## PWL hard code import!
from knowledgeblog.wordpress import Renderer

__version__ = '0.1'

def main(argv):

    print >>sys.stderr, 'latextowordpress version %s' % __version__

    # Parse the command line options
    try: 
        opts, args = config.getopt(argv[1:])
    except Exception, msg:
        log.error(msg)
示例#25
0
import zope.dottedname.resolve
from zope import component
from zope import interface
from .interfaces import IDocumentContext
from .interfaces import IPythonPackage

from six.moves import configparser as ConfigParser
from six.moves import cPickle as pickle
from six import string_types

# Only export the Context singleton
__all__ = ['Context']

# Set up loggers
log = getLogger(__name__)
status = getLogger(__name__ + '.status')
stacklog = getLogger(__name__ + '.context.stack')
macrolog = getLogger(__name__ + '.context.macros')

class ContextItem(dict):
    """
    Localized macro/category code stack element

    """

    def __init__(self, data=None):
        dict.__init__(self, data or {})
        self.categories = None
        self.obj = None
        self.parent = None
示例#26
0
import sys
import os
import os.path
import codecs
import cgi
from plasTeX.DOM import Node
from plasTeX.Base import Command
from plasTeX.Base import DimenCommand
from plasTeX.Logging import getLogger
import plasTeX.Packages.graphics as graphics

log = getLogger()
status = getLogger('status')

# Ugly hack: assume textwidth is 600pt.  True for Kattis but not in
# general.
class textwidth(DimenCommand):
    value = DimenCommand.new('600pt')


# Convert an expression of the form "X\textwidth" to 100*x%
# (Used in ugly hack to handle illustrations)
def clean_width(width):
    if not isinstance(width, Node):
        return width
    nodes = width.childNodes
    if len(nodes) != 2 or nodes[1].nodeName != 'textwidth':
        return width
    return u'%.2f%%' % (100*float(nodes[0]))

示例#27
0
"""

import sys, os
from plasTeX import Command, Environment, DimenCommand, Token
from plasTeX.Logging import getLogger

# Put the plasTeX packages into the path
# JAM: FIXME: This is a little scary
# JAM (later): This is also broken when absolute
# imports are used, as is required under py3. The code in Context.py
# works either way, but we should probably stop doing this
from plasTeX import Packages
sys.path.append(os.path.abspath(os.path.dirname(Packages.__file__)))
del Packages

log = getLogger(__name__)
status = getLogger(__name__ + '.status')

class PackageLoader(Command):
    extension = '.sty'
    def load(self, tex, package_file, options=None):
        try:
            self.ownerDocument.context.loadPackage(tex, package_file + self.extension, options if options is not None else {})
        except Exception:
            log.exception('Could not load package "%s"', package_file )

#
# C.5.1 Document Class
#

class documentclass(PackageLoader):