示例#1
0
def parse():
    """
    Converts mixed files from source to an intermediate based on the extension of the template file. Once converted the
    intermediate is run through the default filters and the extension formatter's processors.

    :return: A list of intermediates corresponding to each of the mixed files
    """
    intermediates, parser = [], get_format(options.state.template())
    if not parser['format']:
        raise FormatError('This format is export only!')
    # Loop through all weaved files
    for file in fileutil.with_extension('.tex'):
        options.post('Using ' + parser['name'] + ' format to parse ' + file)
        intermediate = util.Map({
            'ast': [],
            'src': parser['parser_preprocessor'](fileutil.read(file)),
            'fmt': parser,
            'name': file.replace('.tex', '')
        })
        intermediate.ast = parse_tokens(intermediate.src, parser)
        for default_filter in config.default_filters:
            intermediate.ast = default_filter(intermediate.ast)
        intermediate = parser['parser_postprocessor'](intermediate)
        intermediates.append(intermediate)
        fileutil.write(options.state.cwd() + '/parsed-ast', ''.join(str_token(intermediate.ast)))
    options.post('Successfully parsed', parser['name'] + '.')
    return intermediates
示例#2
0
def load_plugins():
    """
    Call the load function on all plugins in the appropriate order. Loads the following
    [option](%/Modules/options.html):
     - `plugins -plg` List all currently loaded plugins
    """
    options.add_option('plugins', '-plg', 'List all currently loaded plugins', False, bool)
    plugins = [plugin[:-3] for plugin in os.listdir(config.plugin_directory) if plugin.endswith('.py')]
    # Put logging at the start of list
    plugins.insert(0, plugins.pop(plugins.index('_logging')))
    # Put options at the end of the list
    plugins.append(plugins.pop(plugins.index('_options')))
    # Attempt to load plugins
    for plugin in plugins:
        try:
            exec('import plugins.{}; load(plugins.{}.load())'.format(plugin, plugin))
            logging.info('Loaded ' + plugin)
        except AttributeError:
            raise PluginError('Failed to load ' + plugin + ': plugin has no load function')
        except TypeError:
            raise PluginError('Failed to load ' + plugin + ': plugin returned an invalid plugin signature or was None')
    # Display plugin list and exit
    options.post('Successfully loaded', len(_plugins), 'plugins.')
    if options.state.plugins():
        for plugin in _plugins.values():
            print('\t' + plugin['name'] + ' by ' + plugin['author'] + '\n\t\t' + plugin['description'])
        exit()
示例#3
0
def setup():
    """
    Mix the composed files with the specified method then copy all mixed files to the out directory with the
    appropriate names. If any files are in the figure directory they are copied out as well.
    """
    for n in range(options.state.number()):
        mix(n, {'first': '', 'last': '', 'name': '','number': ''}, default=True)
    _methods[options.state.method()](options.state.number(), csv_read(options.state.population()))
    options.post('Template successfully weaved.')
示例#4
0
def pdflatex(file):
    """
    Calls pdflatex on a LaTeX file to compile it. By default no output is shown and no user input is allowed. If this
    fails the compilation is attempted again but this time pdflatex is run in interactive mode to allow the user to see
    what issues there may be.
    :param file: The path to the LaTeX file to compile
    """
    try:
        with open(os.devnull, 'r') as stdin:
            subprocess.check_output(['pdflatex', '-shell-escape', file], stdin=stdin, cwd=options.state.out())
    except:
        pass
    if not any(os.path.isfile(file[:-3] + extension) for extension in ['pdf', 'dvi']):
        options.post('Failed to compile latex file: ' + file + '\n' + 'Running pdflatex in interactive mode...')
        subprocess.call(['pdflatex', '-shell-escape', file], cwd=options.state.out())
示例#5
0
def setup():
    """
    Mix the composed files with the specified method then copy all mixed files to the out directory with the
    appropriate names. If any files are in the figure directory they are copied out as well.
    """
    for n in range(options.state.number()):
        mix(n, {
            'first': '',
            'last': '',
            'name': '',
            'number': ''
        },
            default=True)
    _methods[options.state.method()](options.state.number(),
                                     csv_read(options.state.population()))
    options.post('Template successfully weaved.')
示例#6
0
def pdf_compile():
    """
    Compiles any tex files in the out directory to PDF or DVI depending on what `compile_format` is set to. All
    additional files (aux, log, tex) are removed once compilation completes.
    """
    options.state.cwd(options.state.out())
    options.post('Compiling', len(fileutil.with_extension('.tex')), 'files.')
    for file in fileutil.with_extension('.tex'):
        if compile_format == 'dvi':
            fileutil.write(file, '%&latex\n' + fileutil.read(file))
        try:
            fileutil.remove(file.replace('.tex', '.pdf'))
        except:
            pass
        for i in range(options.state.recomps()):
            lib_loader.pdflatex(file)
    fileutil.remove(fileutil.with_extension(['.aux', '.log', '.tex']))
    options.post('Finished compiling.\n')
示例#7
0
def pdf_compile():
    """
    Compiles any tex files in the out directory to PDF or DVI depending on what `compile_format` is set to. All
    additional files (aux, log, tex) are removed once compilation completes.
    """
    options.state.cwd(options.state.out())
    options.post('Compiling', len(fileutil.with_extension('.tex')), 'files.')
    for file in fileutil.with_extension('.tex'):
        if compile_format == 'dvi':
            fileutil.write(file, '%&latex\n' + fileutil.read(file))
        try:
            fileutil.remove(file.replace('.tex', '.pdf'))
        except:
            pass
        for i in range(options.state.recomps()):
            lib_loader.pdflatex(file)
    fileutil.remove(fileutil.with_extension(['.aux', '.log', '.tex']))
    options.post('Finished compiling.\n')
示例#8
0
def pdflatex(file):
    """
    Calls pdflatex on a LaTeX file to compile it. By default no output is shown and no user input is allowed. If this
    fails the compilation is attempted again but this time pdflatex is run in interactive mode to allow the user to see
    what issues there may be.
    :param file: The path to the LaTeX file to compile
    """
    try:
        with open(os.devnull, 'r') as stdin:
            subprocess.check_output(['pdflatex', '-shell-escape', file],
                                    stdin=stdin,
                                    cwd=options.state.out())
    except:
        pass
    if not any(
            os.path.isfile(file[:-3] + extension)
            for extension in ['pdf', 'dvi']):
        options.post('Failed to compile latex file: ' + file + '\n' +
                     'Running pdflatex in interactive mode...')
        subprocess.call(['pdflatex', '-shell-escape', file],
                        cwd=options.state.out())
示例#9
0
def compose(intermediates):
    """
    Converts intermediates to a source file based on the format option. The formatter's processors are run on the
    intermediate and final source. If the source is being converted to the same format it came from the intermediate
    will be discarded in favour of the original source.

    :param intermediates: A list of intermediates
    """
    try:
        composer = formats[options.state.format()]
    except:
        raise FormatError('Unknown format')
    for intermediate in intermediates:
        composed = intermediate.src
        # If not already in native format
        if intermediate.fmt != composer:
            intermediate = composer['composer_preprocessor'](intermediate)
            fileutil.write(options.state.cwd() + '/composed-ast', ''.join(str_token(intermediate.ast)))
            composed = ''.join([pack(token, composer) for token in intermediate.ast]).strip()
        composed = composer['composer_postprocessor'](composed)
        fileutil.write(intermediate.name + '.cmp', composed)
    options.post('Successfully composed', composer['name'] + '.')
示例#10
0
def goodbye():
    """
    Posts a goodbye message
    """
    options.post('Thanks for using Pyxam, have a nice day!')
示例#11
0
def welcome():
    """
    Posts the Pyxam title and version number
    """
    options.post(title, '\n\n\tLatex Exam Generation.', __version__, '\n')
示例#12
0
def goodbye():
    """
    Posts a goodbye message
    """
    options.post('Thanks for using Pyxam, have a nice day!')
示例#13
0
def welcome():
    """
    Posts the Pyxam title and version number
    """
    options.post(title, '\n\n\tLatex Exam Generation.', __version__, '\n')