Exemplo n.º 1
0
    def run(self):
        """
		This method actually runs BibTeX with the appropriate environment
		variables set.
		"""
        msg.progress(_("running BibTeX on %s") % msg.simplify(self.base))
        doc = {}
        if len(self.bib_path) != 1:
            doc["BIBINPUTS"] = string.join(
                self.bib_path + [os.getenv("BIBINPUTS", "")], ":")
        if len(self.bst_path) != 1:
            doc["BSTINPUTS"] = string.join(
                self.bst_path + [os.getenv("BSTINPUTS", "")], ":")
        if self.crossrefs is None:
            cmd = ["bibtex"]
        else:
            cmd = ["bibtex", "-min-crossrefs=" + self.crossrefs]
        # BibTeX comes with a straightjacket in some TeX distros and can't write
        # to absolute paths.  strip the directory, and change into that dir.
        workdir = os.path.dirname(self.base)
        basename = os.path.basename(self.base)
        if self.doc.env.execute(['bibtex', basename], doc, pwd=workdir):
            msg.info(_("There were errors making the bibliography."))
            return False
        self.run_needed = 0
        self.doc.must_compile = 1
        return True
Exemplo n.º 2
0
	def help (self):
		"""
		Display the description of all the options and exit.
		"""
		print _("""\
This is Rubber version %s.
usage: rubber-pipe [options]
available options:
  -b, --bzip2              compress the final document with bzip2
  -c, --command=CMD        run the directive CMD before parsing (see man page)
  -e, --epilogue=CMD       run the directive CMD after parsing
  -z, --gzip               compress the final document
  -h, --help               display this help
      --into=DIR           go to directory DIR before compiling
  -k, --keep               keep the temporary files after compiling
  -l, --landscape          change paper orientation (if relevant)
  -n, --maxerr=NUM         display at most NUM errors (default: 10)
  -m, --module=MOD[:OPTS]  use module MOD (with options OPTS)
      --only=SOURCES       only include the specified SOURCES
  -o, --post=MOD[:OPTS]    postprocess with module MOD (with options OPTS)
  -d, --pdf                produce a pdf (synonym for -m pdftex or -o ps2pdf)
  -p, --ps                 process through dvips (synonym for -m dvips)
  -q, --quiet              suppress messages
  -r, --read=FILE          read additional directives from FILE
  -S, --src-specials       enable insertion of source specials
  -s, --short              display errors in a compact form
  -I, --texpath=DIR        add DIR to the search path for LaTeX
  -v, --verbose            increase verbosity
      --version            print version information and exit\
""") % version
Exemplo n.º 3
0
	def process (self, path):
		"""
		This method is called when an included file is processed. The argument
		must be a valid file name.
		"""
		if self.processed_sources.has_key(path):
			msg.debug(_("%s already parsed") % path, pkg='latex')
			return
		self.processed_sources[path] = None
		if path not in self.sources:
			self.add_source(path)

		try:
			saved_vars = self.vars
			try:
				msg.log(_("parsing %s") % path, pkg='latex')
				self.vars = Variables(saved_vars,
					{ "file": path, "line": None })
				file = open(path)
				try:
					self.parse_file(file)
				finally:
					file.close()

			finally:
				self.vars = saved_vars
				msg.debug(_("end of %s") % path, pkg='latex')

		except EndInput:
			pass
Exemplo n.º 4
0
	def first_run_needed (self):
		"""
		The condition is only on the database files' modification dates, but
		it would be more clever to check if the results have changed.
		BibTeXing is also needed when the last run of BibTeX failed, and in
		the very particular case when the style has changed since last
		compilation.
		"""
		if not exists(self.base + ".aux"):
			return 0
		if not exists(self.base + ".blg"):
			return 1

		dtime = getmtime(self.base + ".blg")
		for db in self.db.values():
			if getmtime(db) > dtime:
				msg.log(_("bibliography database %s was modified") % db, pkg="bibtex")
				return 1

		blg = open(self.base + ".blg")
		for line in blg.readlines():
			if re_error.search(line):
				blg.close()
				msg.log(_("last BibTeXing failed"), pkg="bibtex")
				return 1
		blg.close()

		if self.style_changed():
			return 1
		if self.bst_file and getmtime(self.bst_file) > dtime:
			msg.log(_("the bibliography style file was modified"), pkg="bibtex")
			return 1
		return 0
Exemplo n.º 5
0
	def process (self, path):
		"""
		This method is called when an included file is processed. The argument
		must be a valid file name.
		"""
		if self.processed_sources.has_key(path):
			msg.debug(_("%s already parsed") % path, pkg='latex')
			return
		self.processed_sources[path] = None
		if path not in self.sources:
			self.add_source(path)

		try:
			saved_vars = self.vars
			try:
				msg.log(_("parsing %s") % path, pkg='latex')
				self.vars = Variables(saved_vars,
					{ "file": path, "line": None })
				file = open(path)
				try:
					self.parse_file(file)
				finally:
					file.close()

			finally:
				self.vars = saved_vars
				msg.debug(_("end of %s") % path, pkg='latex')

		except EndInput:
			pass
Exemplo n.º 6
0
	def run_pythontex(self):
		call = ['pythontex', self.doc.target + '.tex', ]
		msg.debug(_("pythontex call is '%s'") % ' '.join(call), pkg="pythontex")
		if not self.doc.env.is_in_unsafe_mode_:
			msg.error(_("the document tries to run external programs which could be dangerous.  use rubber --unsafe if the document is trusted."))
			return
		subprocess.call(call)
Exemplo n.º 7
0
    def first_run_needed(self):
        """
		The condition is only on the database files' modification dates, but
		it would be more clever to check if the results have changed.
		BibTeXing is also needed when the last run of BibTeX failed, and in
		the very particular case when the style has changed since last
		compilation.
		"""
        if not exists(self.base + ".aux"):
            return 0
        if not exists(self.base + ".blg"):
            return 1

        dtime = getmtime(self.base + ".blg")
        for db in self.db.values():
            if getmtime(db) > dtime:
                msg.log(_("bibliography database %s was modified") % db,
                        pkg="bibtex")
                return 1

        blg = open(self.base + ".blg")
        for line in blg.readlines():
            if re_error.search(line):
                blg.close()
                msg.log(_("last BibTeXing failed"), pkg="bibtex")
                return 1
        blg.close()

        if self.style_changed():
            return 1
        if self.bst_file and getmtime(self.bst_file) > dtime:
            msg.log(_("the bibliography style file was modified"),
                    pkg="bibtex")
            return 1
        return 0
Exemplo n.º 8
0
	def run (self):
		"""
		This method actually runs BibTeX with the appropriate environment
		variables set.
		"""
		msg.progress(_("running BibTeX on %s") % msg.simplify(self.base))
		doc = {}
		if len(self.bib_path) != 1:
			doc["BIBINPUTS"] = string.join(self.bib_path +
				[os.getenv("BIBINPUTS", "")], ":")
		if len(self.bst_path) != 1:
			doc["BSTINPUTS"] = string.join(self.bst_path +
				[os.getenv("BSTINPUTS", "")], ":")
		if self.crossrefs is None:
			cmd = ["bibtex"]
		else:
			cmd = ["bibtex", "-min-crossrefs=" + self.crossrefs]
		cmd.append(self.doc.env.file_name(self.base))
		msg.log(_("executing: %s") % " ".join(cmd), pkg="bibtex")
		process = Popen(cmd, stdout=PIPE, stderr=PIPE)
		process.communicate()
		if process.wait() != 0:
			msg.info(_("There were errors making the bibliography."))
			return False
		self.run_needed = 0
		self.doc.must_compile = 1
		return True
Exemplo n.º 9
0
def hook_externaldocument(loc, opt, name):
    aux = doc.env.find_file(name + ".aux")
    if aux:
        doc.add_source(aux)
        msg.log(_("dependency %s added for external references") % aux, pkg="xr")
    else:
        msg.log(_("file %s is required by xr package but not found") % aux, pkg="xr")
Exemplo n.º 10
0
	def help (self):
		"""
		Display the description of all the options and exit.
		"""
		print _("""\
This is Rubber version %s.
usage: rubber [options] sources...
available options:
  -b, --bzip2              compress the final document with bzip2
      --cache              use the (experimental) caching mechanism
      --clean              remove produced files instead of compiling
  -c, --command=CMD        run the directive CMD before parsing (see man page)
  -e, --epilogue=CMD       run the directive CMD after parsing
  -f, --force              force at least one compilation
  -z, --gzip               compress the final document
  -h, --help               display this help
      --inplace            compile the documents from their source directory
      --into=DIR           go to directory DIR before compiling
      --jobname=NAME       set the job name for the first target
  -l, --landscape          change paper orientation (if relevant)
  -n, --maxerr=NUM         display at most NUM errors (default: 10)
  -m, --module=MOD[:OPTS]  use module MOD (with options OPTS)
      --only=SOURCES       only include the specified SOURCES
  -o, --post=MOD[:OPTS]    postprocess with module MOD (with options OPTS)
  -d, --pdf                produce a pdf (synonym for -m pdftex or -o ps2pdf)
  -p, --ps                 process through dvips (synonym for -o dvips)
  -q, --quiet              suppress messages
  -r, --read=FILE          read additional directives from FILE
  -S, --src-specials       enable insertion of source specials
  -s, --short              display errors in a compact form
  -I, --texpath=DIR        add DIR to the search path for LaTeX
  -v, --verbose            increase verbosity
      --version            print version information and exit
  -W, --warn=TYPE          report warnings of the given TYPE (see man page)\
""") % version
Exemplo n.º 11
0
    def readlog(self, name, limit):
        """
		Read the specified log file, checking that it was produced by the
		right compiler. Returns False if the log file is invalid or does not
		exist.
		"""
        self.lines = None
        try:
            with open(name) as fp:
                line = fp.readline()
                if not line or not re_loghead.match(line):
                    msg.log(_('empty log'), pkg='latex')
                    return False
                # do not read the whole log unconditionally
                whole_file = fp.read(limit)
                self.lines = whole_file.split('\n')
                if fp.read(1) != '':
                    # more data to be read
                    msg.warn(_(
                        'log file is very long, and will not be read completely.'
                    ),
                             pkg='latex')
            return True
        except IOError:
            msg.log(_('IO Error with log'), pkg='latex')
            return False
Exemplo n.º 12
0
    def help(self):
        """
		Display the description of all the options and exit.
		"""
        print _(
            """\
This is Rubber version %s.
usage: rubber-pipe [options]
available options:
  -b, --bzip2              compress the final document with bzip2
  -c, --command=CMD        run the directive CMD before parsing (see man page)
  -e, --epilogue=CMD       run the directive CMD after parsing
  -z, --gzip               compress the final document
  -h, --help               display this help
      --into=DIR           go to directory DIR before compiling
  -k, --keep               keep the temporary files after compiling
  -l, --landscape          change paper orientation (if relevant)
  -n, --maxerr=NUM         display at most NUM errors (default: 10)
  -m, --module=MOD[:OPTS]  use module MOD (with options OPTS)
      --only=SOURCES       only include the specified SOURCES
  -o, --post=MOD[:OPTS]    postprocess with module MOD (with options OPTS)
  -d, --pdf                produce a pdf (synonym for -m pdftex or -o ps2pdf)
  -p, --ps                 process through dvips (synonym for -m dvips)
  -q, --quiet              suppress messages
  -r, --read=FILE          read additional directives from FILE
  -S, --src-specials       enable insertion of source specials
  -s, --short              display errors in a compact form
  -I, --texpath=DIR        add DIR to the search path for LaTeX
  -v, --verbose            increase verbosity
      --version            print version information and exit\
"""
        ) % version
Exemplo n.º 13
0
def run(doc, env, base):
    msg.progress(_("running slatex on %s") % doc.src_base)
    if env.execute(["slatex", "-n", base], {}):
        msg.error(_("Error executing slatex"))
        return 1

    doc.must_compile = 1
    return 0
Exemplo n.º 14
0
	def pre_compile (self):
		if not os.path.exists(self.doc.target + '.pytxcode'):
			msg.info(_("Need compilation!"), pkg="pythontex")
			self.force_compilation()
		msg.info(_("running pythontex..."), pkg="pythontex")
		self.run_pythontex()
		self.doc.watch_file(self.doc.target + ".pytxcode")
		return True
Exemplo n.º 15
0
def run(doc, env, base):
	msg.progress(_("running slatex on %s") % doc.src_base)
	if env.execute(["slatex", "-n", base], {}):
		msg.error(_("Error executing slatex"))
		return 1
			
	doc.must_compile = 1
	return 0
Exemplo n.º 16
0
 def pre_compile(self):
     if not os.path.exists(self.doc.target + '.pytxcode'):
         msg.info(_("Need compilation!"), pkg="pythontex")
         self.force_compilation()
     msg.info(_("running pythontex..."), pkg="pythontex")
     self.run_pythontex()
     self.doc.watch_file(self.doc.target + ".pytxcode")
     return True
Exemplo n.º 17
0
def hook_externaldocument(loc, opt, name):
    aux = doc.env.find_file(name + '.aux')
    if aux:
        doc.add_source(aux)
        msg.log(_("dependency %s added for external references") % aux,
                pkg='xr')
    else:
        msg.log(_("file %s is required by xr package but not found") % aux,
                pkg='xr')
Exemplo n.º 18
0
Arquivo: xr.py Projeto: skapfer/rubber
 def hook_externaldocument (self, loc, opt, name):
     aux = self.doc.env.find_file(name + '.aux')
     if aux:
         self.doc.add_source(aux)
         msg.log( _(
             "dependency %s added for external references") % aux, pkg='xr')
     else:
         msg.log(_(
             "file %s.aux is required by xr package but not found") % name, pkg='xr')
Exemplo n.º 19
0
def slatex_needed(target, srcs):
    if not exists(target):
        msg.log(_("File %s does not exist") % target, pkg="slatex")
        return 1
    for src in srcs:
        if getmtime(target) < getmtime(src):
            msg.log(_("File %s older than %s") % (target, src), pkg="slatex")
            return 1
    return 0
Exemplo n.º 20
0
def slatex_needed(target, srcs):
	if not exists(target):
		msg.log(_("File %s does not exist") % target, pkg="slatex")
		return 1
	for src in srcs:
		if getmtime(target) < getmtime(src):
			msg.log(_("File %s older than %s") % (target, src), pkg="slatex")
			return 1
	return 0
Exemplo n.º 21
0
 def run(self):
     msg.progress(_("compressing %s into %s") % (self.source, self.target))
     try:
         with open(self.source, 'rb') as f_in:
             with self.constructor(self.target, 'wb') as f_out:
                 f_out.writelines(f_in)
     except:
         msg.error(_("compression failed"))
         return False
     return True
Exemplo n.º 22
0
	def run (self):
		# check if the input file exists. if not, refuse to run.
		if not os.path.exists (self.sources[0]):
			msg.info (_('input file for %s does not yet exist, deferring')
				% self.tool, pkg='pythontex')
			return True
		if not self.doc.env.is_in_unsafe_mode_:
			msg.error (_('The document tries to run embedded Python code which could be dangerous.  Use rubber --unsafe if the document is trusted.'))
			return False
		return super (PythonTeXDep, self).run ()
Exemplo n.º 23
0
 def run(self):
     msg.progress(_("running dvipdfm on %s") % self.source)
     cmd = ["dvipdfm"]
     for opt in self.doc.vars["paper"].split():
         cmd.extend(["-p", opt])
     cmd.extend(self.options + ["-o", self.target, self.source])
     if self.env.execute(cmd, kpse=1):
         msg.error(_("dvipdfm failed on %s") % self.source)
         return False
     return True
Exemplo n.º 24
0
 def run (self):
     msg.progress (_ ("compressing %s into %s") % (self.source, self.target))
     try:
         with open (self.source, 'rb') as f_in:
             with self.constructor (self.target, 'wb') as f_out:
                 f_out.writelines (f_in)
     except:
         msg.error (_ ("compression failed"))
         return False
     return True
Exemplo n.º 25
0
 def run(self):
     msg.progress(_("running dvipdfm on %s") % self.source)
     cmd = ['dvipdfm']
     for opt in self.doc.vars['paper'].split():
         cmd.extend(['-p', opt])
     cmd.extend(self.options + ['-o', self.target, self.source])
     if self.env.execute(cmd, kpse=1):
         msg.error(_("dvipdfm failed on %s") % self.source)
         return False
     return True
Exemplo n.º 26
0
    def post_compile(self):
        """
		Run makeindex if needed, with appropriate options and environment.
		"""
        if not os.path.exists(self.source):
            msg.log(_("strange, there is no %s") % self.source, pkg="index")
            return True
        if not self.run_needed():
            return True

        msg.progress(_("processing index %s") % msg.simplify(self.source))

        if self.tool == "makeindex":
            cmd = ["makeindex", "-q", "-o", self.target] + self.opts
            cmd.extend(["-t", self.transcript])
            if self.style:
                cmd.extend(["-s", self.style])
            cmd.append(self.source)
            path_var = "INDEXSTYLE"

        elif self.tool == "xindy":
            cmd = ["texindy", "--quiet"]
            for opt in self.opts:
                if opt == "-g":
                    if self.lang != "":
                        msg.warn(_("'language' overrides 'order german'"),
                                 pkg="index")
                    else:
                        self.lang = "german-din"
                elif opt == "-l":
                    self.modules.append("letter-ordering")
                    msg.warn(_(
                        "use 'module letter-ordering' instead of 'order letter'"
                    ),
                             pkg="index")
                else:
                    msg.error("unknown option to xindy: %s" % opt, pkg="index")
            for mod in self.modules:
                cmd.extend(["--module", mod])
            if self.lang:
                cmd.extend(["--language", self.lang])
            cmd.append(self.source)
            path_var = "XINDY_SEARCHPATH"

        if self.path != []:
            env = {path_var: ':'.join(self.path + [os.getenv(path_var, '')])}
        else:
            env = {}
        if self.doc.env.execute(cmd, env):
            msg.error(_("could not make index %s") % self.target)
            return False

        self.doc.must_compile = 1
        return True
Exemplo n.º 27
0
def mode_dvi ():
	global mode
	if mode == 'dvi':
		msg.error(_("XeTeX doesn't roll with dvi files"))
		return
	if doc.env.final != doc and doc.products[0][-4:] != '.dvi':
		msg.error(_("there is already a post-processor registered"))
		return
	doc.reset_products([doc.target + '.dvi'])
	doc.cmdline.insert(0, '\\pdfoutput=0')
	mode = 'dvi'
Exemplo n.º 28
0
    def set_source(self, path, jobname):
        """
		Specify the main source for the document. The exact path and file name
		are determined, and the source building process is updated if needed,
		according the the source file's extension. The optional argument
		'jobname' can be used to specify the job name to something else that
		the base of the file name.
		"""
        assert os.path.exists(path)
        self.sources = []
        self.vars['source'] = path
        (src_path, name) = os.path.split(path)
        self.vars['path'] = src_path
        # derive jobname, which latex uses as the basename for all output
        (job, self.vars['ext']) = os.path.splitext(name)
        if jobname is None:
            self.set_job = 0
        else:
            self.set_job = 1
            job = jobname
        self.vars['job'] = job
        if src_path == "":
            src_path = "."
            self.vars['base'] = job
        else:
            self.env.path.append(src_path)
            self.vars['base'] = os.path.join(src_path, job)

        source = path
        prefix = os.path.join(self.vars["cwd"], "")
        if source[:len(prefix)] == prefix:
            comp_name = source[len(prefix):]
        else:
            comp_name = source
        if comp_name.find('"') >= 0:
            msg.error(_("The filename contains \", latex cannot handle this."))
            return 1
        for c in " \n\t()":
            if source.find(c) >= 0:
                msg.warn(
                    _("Source path uses special characters, error tracking might get confused."
                      ))
                break

        self.add_product(self.basename(with_suffix=".dvi"))
        self.add_product(self.basename(with_suffix=".log"))

        # always expect a primary aux file
        self.new_aux_file(self.basename(with_suffix=".aux"))
        self.add_product(self.basename(with_suffix=".synctex.gz"))

        return 0
Exemplo n.º 29
0
	def post_compile (self):
		"""
		Run makeindex if needed, with appropriate options and environment.
		"""
		if not os.path.exists(self.source):
			msg.log(_("strange, there is no %s") % self.source, pkg="index")
			return True
		if not self.run_needed():
			return True

		msg.progress(_("processing index %s") % msg.simplify(self.source))

		if self.tool == "makeindex":
			cmd = ["makeindex", "-q", "-o", self.target] + self.opts
			cmd.extend(["-t", self.transcript])
			if self.style:
				cmd.extend(["-s", self.style])
			cmd.append(self.source)
			path_var = "INDEXSTYLE"

		elif self.tool == "xindy":
			cmd = ["texindy", "--quiet"]
			for opt in self.opts:
				if opt == "-g":
					if self.lang != "":
						msg.warn(_("'language' overrides 'order german'"),
							pkg="index")
					else:
						self.lang = "german-din"
				elif opt == "-l":
					self.modules.append("letter-ordering")
					msg.warn(_("use 'module letter-ordering' instead of 'order letter'"),
						pkg="index")
				else:
					msg.error("unknown option to xindy: %s" % opt, pkg="index")
			for mod in self.modules:
				cmd.extend(["--module", mod])
			if self.lang:
				cmd.extend(["--language", self.lang])
			cmd.append(self.source)
			path_var = "XINDY_SEARCHPATH"

		if self.path != []:
			env = { path_var: ':'.join(self.path + [os.getenv(path_var, '')]) }
		else:
			env = {}
		if self.doc.env.execute(cmd, env):
			msg.error(_("could not make index %s") % self.target)
			return False

		self.doc.must_compile = 1
		return True
Exemplo n.º 30
0
 def run_pythontex(self):
     call = [
         'pythontex',
         self.doc.target + '.tex',
     ]
     msg.debug(_("pythontex call is '%s'") % ' '.join(call),
               pkg="pythontex")
     if not self.doc.env.is_in_unsafe_mode_:
         msg.error(
             _("the document tries to run external programs which could be dangerous.  use rubber --unsafe if the document is trusted."
               ))
         return
     subprocess.call(call)
Exemplo n.º 31
0
	def run (self):
		if self.doc.vars['engine'] == 'Omega':
			cmd = ['odvips']
		else:
			cmd = ['dvips']
		msg.progress(_("running %s on %s") % (cmd[0], self.source))
		for opt in self.doc.vars['paper'].split():
			cmd.extend(['-t', opt])
		cmd.extend(self.options + ['-o', self.target, self.source])
		if self.env.execute(cmd, kpse=1):
			msg.error(_("%s failed on %s") % (cmd[0], self.source))
			return False
		return True
Exemplo n.º 32
0
	def do_set (self, name, val):
		try:
			if type (self.vars[name]) is list:
				msg.warn (_("cannot set list-type variable to scalar: set %s %s (ignored; use setlist, not set)") % (name, val))
				return
			if type (self.vars[name]) is int:
				try:
					val = int (val)
				except:
					msg.warn (_("cannot set int variable %s to value %s (ignored)") % (name, val))
					return
			self.vars[name] = val
		except KeyError:
			msg.warn(_("unknown variable: %s") % name, **self.vars)
Exemplo n.º 33
0
    def hook_includegraphics(self, loc, starred, optional, name):
        # no suffixes are tried when the extension is explicit

        allowed_suffixes = self.suffixes

        options = parse_keyval(optional)
        if 'ext' in options:
            allowed_suffixes = ['']
            if options['ext']:
                name = name + options['ext']

        for suffix in self.suffixes:
            if name[-len(suffix):] == suffix:
                allowed_suffixes = ['']
                break

        # If the file name looks like it contains a control sequence or a macro
        # argument, forget about this \includegraphics.

        if name.find('\\') >= 0 or name.find('#') >= 0:
            return

        # We only accept conversions from file types we don't know and cannot
        # produce.

        def check(vars):
            source = vars['source']
            if os.path.exists(
                    vars['target']) and self.doc.env.may_produce(source):
                return False
            if self.suffixes == ['']:
                return True
            for suffix in allowed_suffixes:
                if source[-len(suffix):] == suffix:
                    return False
            return True

        node = self.doc.env.convert(name,
                                    suffixes=allowed_suffixes,
                                    prefixes=self.prefixes,
                                    check=check,
                                    context=self.doc.vars)

        if node:
            msg.log(_("graphics `%s' found") % name, pkg='graphics')
            for file in node.products:
                self.doc.add_source(file)
            self.files.append(node)
        else:
            msg.warn(_("graphics `%s' not found") % name, **dict(loc))
Exemplo n.º 34
0
	def set_source (self, path, jobname):
		"""
		Specify the main source for the document. The exact path and file name
		are determined, and the source building process is updated if needed,
		according the the source file's extension. The optional argument
		'jobname' can be used to specify the job name to something else that
		the base of the file name.
		"""
		assert os.path.exists(path)
		self.sources = []
		self.vars['source'] = path
		(src_path, name) = os.path.split(path)
		self.vars['path'] = src_path
		# derive jobname, which latex uses as the basename for all output
		(job, self.vars['ext']) = os.path.splitext(name)
		if jobname is None:
			self.set_job = 0
		else:
			self.set_job = 1
			job = jobname
		self.vars['job'] = job
		if src_path == "":
			src_path = "."
			self.vars['base'] = job
		else:
			self.env.path.append(src_path)
			self.vars['base'] = os.path.join(src_path, job)

		source = path
		prefix = os.path.join(self.vars["cwd"], "")
		if source[:len(prefix)] == prefix:
			comp_name = source[len(prefix):]
		else:
			comp_name = source
		if comp_name.find('"') >= 0:
			msg.error(_("The filename contains \", latex cannot handle this."))
			return 1
		for c in " \n\t()":
			if source.find(c) >= 0:
				msg.warn(_("Source path uses special characters, error tracking might get confused."))
				break

		self.add_product (self.basename (with_suffix=".dvi"))
		self.add_product (self.basename (with_suffix=".log"))

		# always expect a primary aux file
		self.new_aux_file (self.basename (with_suffix=".aux"))
		self.add_product (self.basename (with_suffix=".synctex.gz"))

		return 0
Exemplo n.º 35
0
	def set_source (self, path, jobname=None):
		"""
		Specify the main source for the document. The exact path and file name
		are determined, and the source building process is updated if needed,
		according the the source file's extension. The optional argument
		'jobname' can be used to specify the job name to something else that
		the base of the file name.
		"""
		name = self.env.find_file(path, ".tex")
		if not name:
			msg.error(_("cannot find %s") % name)
			return 1
		self.reset_sources()
		self.vars['source'] = name
		(src_path, name) = os.path.split(name)
		self.vars['path'] = src_path
		(job, self.vars['ext']) = os.path.splitext(name)
		if jobname is None:
			self.set_job = 0
		else:
			self.set_job = 1
			job = jobname
		self.vars['job'] = job
		if src_path == "":
			src_path = "."
			self.vars['base'] = job
		else:
			self.env.path.append(src_path)
			self.vars['base'] = os.path.join(src_path, job)

		source = self.source()
		prefix = os.path.join(self.vars["cwd"], "")
		if source[:len(prefix)] == prefix:
			comp_name = source[len(prefix):]
		else:
			comp_name = source
		if comp_name.find('"') >= 0:
			msg.error(_("The filename contains \", latex cannot handle this."))
			return 1
		for c in " \n\t()":
			if source.find(c) >= 0:
				msg.warn(_("Source path uses special characters, error tracking might get confused."))
				break

		self.vars['target'] = self.target = os.path.join(prefix, job)
		self.reset_products([self.target + ".dvi"])

		return 0
Exemplo n.º 36
0
	def set_source (self, path, jobname=None):
		"""
		Specify the main source for the document. The exact path and file name
		are determined, and the source building process is updated if needed,
		according the the source file's extension. The optional argument
		'jobname' can be used to specify the job name to something else that
		the base of the file name.
		"""
		name = self.env.find_file(path, ".tex")
		if not name:
			msg.error(_("cannot find %s") % name)
			return 1
		self.reset_sources()
		self.vars['source'] = name
		(src_path, name) = os.path.split(name)
		self.vars['path'] = src_path
		(job, self.vars['ext']) = os.path.splitext(name)
		if jobname is None:
			self.set_job = 0
		else:
			self.set_job = 1
			job = jobname
		self.vars['job'] = job
		if src_path == "":
			src_path = "."
			self.vars['base'] = job
		else:
			self.env.path.append(src_path)
			self.vars['base'] = os.path.join(src_path, job)

		source = self.source()
		prefix = os.path.join(self.vars["cwd"], "")
		if source[:len(prefix)] == prefix:
			comp_name = source[len(prefix):]
		else:
			comp_name = source
		if comp_name.find('"') >= 0:
			msg.error(_("The filename contains \", latex cannot handle this."))
			return 1
		for c in " \n\t()":
			if source.find(c) >= 0:
				msg.warn(_("Source path uses special characters, error tracking might get confused."))
				break

		self.vars['target'] = self.target = os.path.join(prefix, job)
		self.reset_products([self.target + ".dvi"])

		return 0
Exemplo n.º 37
0
 def do_onchange(self, file, cmd):
     if not self.env.is_in_unsafe_mode_:
         msg.warn(
             _("Rubber directive 'onchange' is valid only in unsafe mode"))
         return
     self.onchange_cmd[file] = cmd
     self.onchange_md5[file] = md5_file(file)
Exemplo n.º 38
0
	def do_order (self, *args):
		for opt in args:
			if opt == "standard": self.opts = []
			elif opt == "german": self.opts.append("-g")
			elif opt == "letter": self.opts.append("-l")
			else: msg.warn(
				_("unknown option '%s' for 'makeidx.order'") % opt)
Exemplo n.º 39
0
	def pre_compile (self, force):
		"""
		Prepare the source for compilation using package-specific functions.
		This function must return False on failure. This function sets
		`must_compile' to True if we already know that a compilation is
		needed, because it may avoid some unnecessary preprocessing (e.g.
		BibTeXing).
		"""
		aux = self.target + ".aux"
		if os.path.exists(aux):
			self.aux_md5[aux] = md5_file(aux)
		else:
			self.aux_md5[aux] = None
		self.aux_old[aux] = None

		self.log.read(self.target + ".log")

		self.must_compile = force
		self.must_compile = self.compile_needed()

		msg.log(_("building additional files..."), pkg='latex')

		for mod in self.modules.objects.values():
			if not mod.pre_compile():
				self.failed_module = mod
				return False
		return True
Exemplo n.º 40
0
def clean ():
	for bib in bibs.keys():
		for suffix in '.aux', '.bbl', '.blg':
			file = bib + suffix
			if os.path.exists(file):
				msg.log(_("removing %s") % file, pkg='multibib')
				os.unlink(file)
Exemplo n.º 41
0
 def __init__ (self, doc, dict):
     doc.vars["program"] = "xelatex"
     doc.vars["engine"] = "XeLaTeX"
     if doc.env.final != doc and doc.prods[0][-4:] != ".pdf":
         msg.error(_("there is already a post-processor registered"))
         sys.exit(2)
     doc.prods = [doc.src_base + ".pdf"]
Exemplo n.º 42
0
 def __init__(self, doc, dict):
     doc.vars["program"] = "xelatex"
     doc.vars["engine"] = "XeLaTeX"
     if doc.env.final != doc and doc.prods[0][-4:] != ".pdf":
         msg.error(_("there is already a post-processor registered"))
         sys.exit(2)
     doc.prods = [doc.src_base + ".pdf"]
Exemplo n.º 43
0
	def do_depend (self, *args):
		for arg in args:
			file = self.env.find_file(arg)
			if file:
				self.add_source(file)
			else:
				msg.warn(_("dependency '%s' not found") % arg, **self.vars)
Exemplo n.º 44
0
    def run(self):
        """
		This method reads the source file (which is supposed to be a
		gzip-compressed PostScript file) until it finds a line that contains a
		bounding box indication. Then it creates the target file with this
		single line.
		"""
        msg.progress(_("extracting bounding box from %s") % self.source)
        with GzipFile(self.source) as source:
            for line in source:
                if re_bbox.match(line):
                    with open(self.target, "w") as target:
                        target.write(line)
                    return True
        msg.error(_("no bounding box was found in %s!") % self.source)
        return False
Exemplo n.º 45
0
	def pre_compile (self, force):
		"""
		Prepare the source for compilation using package-specific functions.
		This function must return False on failure. This function sets
		`must_compile' to True if we already know that a compilation is
		needed, because it may avoid some unnecessary preprocessing (e.g.
		BibTeXing).
		"""
		aux = self.target + ".aux"
		if os.path.exists(aux):
			self.aux_md5[aux] = md5_file(aux)
		else:
			self.aux_md5[aux] = None
		self.aux_old[aux] = None

		self.log.read(self.target + ".log")

		self.must_compile = force
		self.must_compile = self.compile_needed()

		msg.log(_("building additional files..."), pkg='latex')

		for mod in self.modules.objects.values():
			if not mod.pre_compile():
				self.failed_module = mod
				return False
		return True
Exemplo n.º 46
0
	def short_help (self):
		"""
		Display a short description of the command line.
		"""
		msg(0, _("""\
usage: rubber [options] sources...
For more information, try `rubber --help'."""))
Exemplo n.º 47
0
	def do_depend (self, *args):
		for arg in args:
			file = self.env.find_file(arg)
			if file:
				self.add_source(file)
			else:
				msg.warn(_("dependency '%s' not found") % arg, **self.vars)
Exemplo n.º 48
0
	def run (self):
		"""
		This method reads the source file (which is supposed to be a
		gzip-compressed PostScript file) until it finds a line that contains a
		bounding box indication. Then it creates the target file with this
		single line.
		"""
		msg.progress(_("extracting bounding box from %s") % self.source)
		with GzipFile(self.source) as source:
			for line in source:
				if re_bbox.match(line):
					with open(self.target, "w") as target:
						target.write(line)
					return True
		msg.error(_("no bounding box was found in %s!") % self.source)
		return False
Exemplo n.º 49
0
 def clean(self):
     self.doc.remove_suffixes([".pytxcode"])
     pythontex_files = 'pythontex-files-' + os.path.basename(
         self.doc.target)
     if os.path.exists(pythontex_files):
         msg.log(_("removing tree %s") % pythontex_files)
         shutil.rmtree(pythontex_files)
Exemplo n.º 50
0
    def hook_includegraphics(self, loc, starred, optional, name):
        # no suffixes are tried when the extension is explicit

        allowed_suffixes = self.suffixes

        options = parse_keyval(optional)
        if "ext" in options:
            allowed_suffixes = [""]
            if options["ext"]:
                name = name + options["ext"]

        for suffix in self.suffixes:
            if name[-len(suffix) :] == suffix:
                allowed_suffixes = [""]
                break

        # If the file name looks like it contains a control sequence or a macro
        # argument, forget about this \includegraphics.

        if name.find("\\") >= 0 or name.find("#") >= 0:
            return

        # We only accept conversions from file types we don't know and cannot
        # produce.

        def check(vars):
            source = vars["source"]
            if os.path.exists(vars["target"]) and self.doc.env.may_produce(source):
                return False
            if self.suffixes == [""]:
                return True
            for suffix in allowed_suffixes:
                if source[-len(suffix) :] == suffix:
                    return False
            return True

        node = self.doc.env.convert(
            name, suffixes=allowed_suffixes, prefixes=self.prefixes, check=check, context=self.doc.vars
        )

        if node:
            msg.log(_("graphics `%s' found") % name, pkg="graphics")
            for file in node.products:
                self.doc.add_source(file)
            self.files.append(node)
        else:
            msg.warn(_("graphics `%s' not found") % name, **dict(loc))
Exemplo n.º 51
0
    def clean(self):
        """
		Remove all generated files related to the index.
		"""
        for file in self.source, self.target, self.transcript:
            if os.path.exists(file):
                msg.log(_("removing %s") % file, pkg="index")
                os.unlink(file)
Exemplo n.º 52
0
	def run (self):
		msg.progress(_("compressing %s") % self.sources[0])
		out = BZ2File(self.products[0], 'w')
		file = open(self.sources[0])
		out.write(file.read())
		file.close()
		out.close()
		return True
Exemplo n.º 53
0
	def clean (self):
		"""
		Remove all generated files related to the index.
		"""
		for file in self.source, self.target, self.transcript:
			if os.path.exists(file):
				msg.log(_("removing %s") % file, pkg="index")
				os.unlink(file)
Exemplo n.º 54
0
 def run(self):
     msg.progress(_("compressing %s") % self.sources[0])
     out = GzipFile(self.products[0], 'w')
     file = open(self.sources[0])
     out.write(file.read())
     file.close()
     out.close()
     return True
Exemplo n.º 55
0
    def parse(self):
        """
		Parse the source for packages and supported macros.
		"""
        try:
            self.process(self.source())
        except EndDocument:
            pass
        msg.log(_("dependencies: %r") % self.sources, pkg='latex')
Exemplo n.º 56
0
 def do_set(self, name, val):
     try:
         if type(self.vars[name]) is list:
             msg.warn(
                 _("cannot set list-type variable to scalar: set %s %s (ignored; use setlist, not set)"
                   ) % (name, val))
             return
         if type(self.vars[name]) is int:
             try:
                 val = int(val)
             except:
                 msg.warn(
                     _("cannot set int variable %s to value %s (ignored)") %
                     (name, val))
                 return
         self.vars[name] = val
     except KeyError:
         msg.warn(_("unknown variable: %s") % name, **self.vars)
Exemplo n.º 57
0
	def clean (self, all=0):
		"""
		Remove all files that are produced by compilation.
		"""
		self.remove_suffixes([".log", ".aux", ".toc", ".lof", ".lot"])

		for file in self.products + self.removed_files:
			if os.path.exists(file):
				msg.log(_("removing %s") % file, pkg='latex')
				os.unlink(file)

		msg.log(_("cleaning additional files..."), pkg='latex')

		for dep in self.source_nodes():
			dep.clean()

		for mod in self.modules.objects.values():
			mod.clean()