summaryrefslogtreecommitdiff
path: root/gnu/dist/sgmltools-lite/python
diff options
context:
space:
mode:
authorfukachan <fukachan>2005-06-06 03:45:57 +0000
committerfukachan <fukachan>2005-06-06 03:45:57 +0000
commitf7cbfec74df8f8fd7e135c16de75b2fa6f5ab6a3 (patch)
tree8c8fb14178b0d5ef6de0be740868ac6bfc10f1ce /gnu/dist/sgmltools-lite/python
parente19ad4df732efb6d4cd3e857120c7ecff4674abb (diff)
downloadfml8-f7cbfec74df8f8fd7e135c16de75b2fa6f5ab6a3.tar.gz
fml8-f7cbfec74df8f8fd7e135c16de75b2fa6f5ab6a3.tar.bz2
fml8-f7cbfec74df8f8fd7e135c16de75b2fa6f5ab6a3.zip
Initial revision
Diffstat (limited to 'gnu/dist/sgmltools-lite/python')
-rw-r--r--gnu/dist/sgmltools-lite/python/Backend.py136
-rw-r--r--gnu/dist/sgmltools-lite/python/SGMLtools.py272
-rw-r--r--gnu/dist/sgmltools-lite/python/backends/Dvi.py87
-rw-r--r--gnu/dist/sgmltools-lite/python/backends/Html.py88
-rw-r--r--gnu/dist/sgmltools-lite/python/backends/JadeTeX.py46
-rw-r--r--gnu/dist/sgmltools-lite/python/backends/Ld2db.py71
-rw-r--r--gnu/dist/sgmltools-lite/python/backends/Lynx.py59
-rw-r--r--gnu/dist/sgmltools-lite/python/backends/OneHtml.py46
-rw-r--r--gnu/dist/sgmltools-lite/python/backends/Pdf.py87
-rw-r--r--gnu/dist/sgmltools-lite/python/backends/Ps.py58
-rw-r--r--gnu/dist/sgmltools-lite/python/backends/Rtf.py45
-rw-r--r--gnu/dist/sgmltools-lite/python/backends/W3m.py71
-rw-r--r--gnu/dist/sgmltools-lite/python/backends/iSilo.py79
-rw-r--r--gnu/dist/sgmltools-lite/python/utils.py393
14 files changed, 1538 insertions, 0 deletions
diff --git a/gnu/dist/sgmltools-lite/python/Backend.py b/gnu/dist/sgmltools-lite/python/Backend.py
new file mode 100644
index 00000000..de9e54d2
--- /dev/null
+++ b/gnu/dist/sgmltools-lite/python/Backend.py
@@ -0,0 +1,136 @@
+#
+# Backend.py - Backend interface
+#
+# $Id: Backend.py,v 1.1 2000/03/24 09:16:45 cdegroot Exp $
+#
+# SGMLtools - an SGML toolkit.
+# Copyright (C)1998 Cees A. de Groot
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+
+"""
+ This module defines base classes for backend modules.
+ Backends need to inherit from this.
+"""
+
+class Backend:
+ """Base backend class.
+
+ This class is actually a backend _process_, one is instantiated
+ for every file processed. Therefore, the class may store
+ information between passes to facilitate work.
+ """
+
+ _filename = ''
+ _fileparts = ()
+
+ def __init__(self, filename, fileparts, globs, tracer, autoconf):
+ """Create a new instance.
+
+ The filename is the file that will be parsed, the globs
+ argument is a pointer to the BackendGlobals class
+ associated with this object. Fileparts is a 3-tuple
+ containing (name, path, extension)
+
+ This base constructor stores the arguments in corresponding
+ fields (with underscore-prefix).
+ """
+
+ self._filename = filename
+ self._fileparts = fileparts
+ self._globs = globs
+ self._tracer = tracer
+ self._autoconf = autoconf
+
+ def preJade(self, fh):
+ """Execute actions that need to take place before Jade is invoked.
+
+ This method receives a filehandle that points to the main
+ input file as indicated on the command line.
+
+ The method should return a filehandle that needs to be
+ passed as input to Jade (the base implementation simply
+ returns its input filehandle).
+ """
+
+ return fh
+
+ def postJade(self, outfile, stdoutfile):
+ """Execute actions that need to take place after Jade has run.
+
+ The method receives two filenames: the first is the filename
+ that was given to Jade as a '-o' parameter, the second is the
+ filename where stdout was redirected to.
+
+ """
+
+ pass
+
+
+class BackendGlobals:
+ """A class containing backend-global stuff.
+
+ This base class will be instantiated exactly once per backend. It
+ is used to handle and store options, etcetera.
+ """
+
+ def getName(self):
+ """Get the name for this backend.
+
+ This returns the name which can be used on the command
+ line --backend option to invoke this backend.
+ """
+
+ return 'base'
+
+ def getMoreOptions(self):
+ """Get extra options for this backend.
+
+ This method should return, in the same form as the global
+ options in utils.py, a list containing any extra options
+ defined by this backend. Each element contains a tuple
+ (short, long, helptext)
+ """
+
+ return []
+
+
+ def setOptions(self, options):
+ """Communicate optoins back to the backend.
+
+ This method is called after option processing so that the
+ backend may do anything it wants with the options as passed
+ on the command line.
+ """
+
+ pass
+
+ def getJadeSettings(self):
+ """Return stylesheet/backend information for Jade.
+
+ This method returns a tuple containing two elements:
+ 1. The Jade backend to use for this backend
+ 2. The stylesheet to use.
+ """
+
+ return ('', '')
+
+ def printHelp(self, fh):
+ """Print help information on the backend."""
+
+ pass
+
+
diff --git a/gnu/dist/sgmltools-lite/python/SGMLtools.py b/gnu/dist/sgmltools-lite/python/SGMLtools.py
new file mode 100644
index 00000000..9c14a8b4
--- /dev/null
+++ b/gnu/dist/sgmltools-lite/python/SGMLtools.py
@@ -0,0 +1,272 @@
+#
+# SGMLtools.py - SGMLtools main routine.
+#
+# $Id: SGMLtools.py,v 1.4 2000/10/25 06:00:05 cdegroot Exp $
+#
+# SGMLtools - an SGML toolkit.
+# Copyright (C)1998 Cees A. de Groot
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+
+"""
+ This module contains the main logic for SGMLtools. It is wrapped
+ in a class so that once somebody cooks up a use for it, you can
+ actually have multiple copies active (although we'd need to factor
+ initialization into repeatable and non-repeatable parts, then).
+"""
+
+import sys, os, glob, imp, getopt
+import Backend, utils
+
+class SGMLtools:
+ _globals = {}
+ _classes = {}
+ _autoconf = {}
+
+ def __init__(self, autoconf):
+ """Create an SGMLtools object.
+
+ This method hunts for backend modules and does some other
+ assorted initialization things. The autoconf argument
+ contains some assorted settings that are passed down from
+ autoconf.
+
+ """
+
+ self._autoconf = autoconf
+
+ #
+ # Expand path
+ #
+ sys.path.append(os.path.join(autoconf['shrdir'], 'python'))
+ sys.path = sys.path + autoconf['backends']
+
+ #
+ # Import backends, instantiate a BackendGlobals object for
+ # each of them, and stash it away.
+ #
+ files = []
+ for dir in autoconf['backends']:
+ pattern = os.path.join(dir, '*.py')
+ files = files + glob.glob(pattern)
+ for file in files:
+ name, junk = os.path.splitext(file)
+ dir, module = os.path.split(name)
+ cmd = 'from %s import %s, %s' % (module, module, module + 'Globals')
+ exec cmd
+ cmd = 'glob = %sGlobals()' % module
+ exec cmd
+ self._globals[glob.getName()] = glob
+ cmd = 'cls = %s' % module
+ exec cmd
+ self._classes[glob.getName()] = cls
+
+ #
+ # Read alias file
+ #
+ self._aliases = utils.readAliases(autoconf)
+
+
+ #
+ # Setup SGML environment
+ #
+ if not os.environ.has_key('SGML_CATALOG_FILES'):
+ os.environ['SGML_CATALOG_FILES'] = \
+ os.path.join(autoconf['etcdir'], 'catalog') \
+ + ":" + "/usr/share/sgml/stylesheets/sgmltools/sgmltools.cat" \
+ + ":" + "/usr/share/sgml/CATALOG.docbkdsl"
+
+
+ def processOptions(self, args):
+ """Process command line options.
+
+ Process command line options, dynamically expanding them
+ based on the --backend option, and returning the list of
+ files that's left.
+ """
+
+ #
+ # Hunt down the backend option. The first test tests for
+ # "-b x", the second for "-bx" (or the equivalend long versions).
+ #
+ numArgs = len(args)
+ for i in range(numArgs):
+ arg = args[i]
+ if arg in ["-b", "--backend"]:
+ if i+1 >= numArgs:
+ raise getopt.error, "option %s requires an argument" % arg
+ miniargs = [arg, args[i+1]]
+ break
+ if arg[:2] == "-b" or arg[:10] == "--backend=":
+ miniargs = [arg]
+ break
+ else:
+ #
+ # Default to the HTML backend.
+ #
+ miniargs = [ "--backend=onehtml" ];
+
+ #
+ # We should have a backend option now. Ask getopt to parse it. Once
+ # we have it, ask the backend for extra options so we can get
+ # down to business.
+ #
+ opt, junk = getopt.getopt(miniargs, 'b:', ['backend='])
+ #
+ # if opt = 'txt', check for 'w3m' else fallback to 'lynx'
+ #
+ if opt[0][1] == "txt":
+ if not self._autoconf['progs']['w3m'] == 'N/A':
+ self._curbackend = "w3m"
+ else:
+ self._curbackend = "lynx"
+ else:
+ self._curbackend = opt[0][1]
+
+ try:
+ self._curglobal = self._globals[self._curbackend]
+ except KeyError:
+ utils.usage(None, "Unknown backend " + self._curbackend)
+ if not self._globals.has_key(self._curbackend):
+ utils.usage(None, "Unknown backend " + self._curbackend)
+
+ #
+ # Merge all the options and parse them. Return whatever is
+ # left (the list of files we need to run).
+ #
+ shortopts, longopts = utils.makeOpts(self._curglobal)
+ try:
+ options, retval = getopt.getopt(args, shortopts, longopts)
+ except getopt.error, e:
+ utils.usage(self._curglobal, 'Error parsing arguments: ' + `e`)
+
+ self._options = utils.normalizeOpts(self._curglobal, options)
+
+ #
+ # Check for help/version/... options
+ #
+ if utils.findOption(self._options, 'help'):
+ utils.version(self._autoconf['shrdir'])
+ print
+ utils.usage(self._curglobal, None)
+ if utils.findOption(self._options, 'version'):
+ utils.version(self._autoconf['shrdir'])
+ sys.exit(0)
+ if utils.findOption(self._options, 'license'):
+ utils.license()
+
+ return retval
+
+ def processFile(self, file):
+ """Process the indicated file"""
+
+
+ #
+ # Some filename munching so the user can invoke us with our
+ # without the .sgml/.SGML extension.
+ #
+ filepath, filename = os.path.split(file)
+ filename, fileext = os.path.splitext(filename)
+ if filepath == '':
+ filepath = '.'
+ if os.path.isfile(file):
+ self._fileinfo = (filename, filepath, fileext)
+ elif os.path.isfile(os.path.join(filepath, filename + '.sgml')):
+ self._fileinfo = (filename, filepath, '.sgml')
+ elif os.path.isfile(os.path.join(filepath, filename + '.SGML')):
+ self._fileinfo = (filename, filepath, '.SGML')
+ elif os.path.isfile(os.path.join(filepath, filename)):
+ self._fileinfo = (filename, filepath, '')
+ else:
+ raise IOError, "file %s not found" % file
+
+ self._filename = os.path.join(self._fileinfo[1],
+ self._fileinfo[0] + self._fileinfo[2])
+
+ #
+ # Create a backend instance.
+ #
+ if utils.findOption(self._options, 'verbose') != None:
+ dotrace = 1
+ else:
+ dotrace = 0
+ self._tracer = utils.Tracer(dotrace)
+ be = self._classes[self._curbackend](self._filename, self._fileinfo,
+ self._curglobal, self._tracer, self._autoconf)
+
+ #
+ # Make SGML_SEARCH_PATH absolute.
+ #
+ savdir = os.getcwd()
+ os.chdir(filepath)
+ envname = 'SGML_SEARCH_PATH'
+ if os.environ.has_key(envname):
+ os.environ[envname] = os.environ[envname] + ':' + os.getcwd()
+ else:
+ os.environ[envname] = os.getcwd()
+ os.chdir(savdir)
+
+ #
+ # Get the Jade parameters and see whether the stylesheet was
+ # overriden. Translate the stylesheet to an absolute filename
+ #
+ stylesheet, jadebe = self._curglobal.getJadeSettings()
+ userSheet = utils.findOption(self._options, 'dsssl-spec')
+ if userSheet != None:
+ stylesheet = userSheet
+ dssslfile = utils.findStylesheet(stylesheet, self._aliases)
+ addJadeOpt = ''
+ userJadeOpt = utils.findOption(self._options, 'jade-opt')
+ if userJadeOpt != None:
+ addJadeOpt = ' ' + userJadeOpt
+
+ #
+ # Open the input file and give the pre-Jade routine a shot.
+ #
+ infile = open(self._filename, 'r')
+ nextfile = be.preJade(infile)
+
+ #
+ # Run Jade attached to a pipe
+ #
+ jadecmd = self._autoconf['progs']['jade']
+ jadecmd = jadecmd + ' -t ' + jadebe
+ jadecmd = jadecmd + ' -d ' + dssslfile
+ jadeoutfile = utils.makeTemp()
+ jadecmd = jadecmd + ' -o ' + jadeoutfile
+ jadecmd = jadecmd + addJadeOpt
+ jadestdoutfile = utils.makeTemp()
+ jadecmd = jadecmd + ' >' + jadestdoutfile
+ self._tracer.trace(jadecmd)
+ jadepipe = os.popen(jadecmd, 'w')
+
+ #
+ # Pump nextfile->jadepipe, and close all files.
+ #
+ jadepipe.writelines(nextfile.readlines())
+ try:
+ jadepipe.close();
+ infile.close();
+ nextfile.close();
+ except:
+ pass
+
+ #
+ # Run the postJade stage.
+ #
+ be.postJade(jadeoutfile, jadestdoutfile)
+
+
diff --git a/gnu/dist/sgmltools-lite/python/backends/Dvi.py b/gnu/dist/sgmltools-lite/python/backends/Dvi.py
new file mode 100644
index 00000000..dc2692d6
--- /dev/null
+++ b/gnu/dist/sgmltools-lite/python/backends/Dvi.py
@@ -0,0 +1,87 @@
+#
+# backends/Dvi.py
+#
+# $Id: Dvi.py,v 1.2 2000/08/03 12:38:57 cdegroot Exp $
+#
+# SGMLtools DVI backend driver.
+#
+# SGMLtools - an SGML toolkit.
+# Copyright (C) 1998 Cees A. de Groot
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+from Backend import Backend, BackendGlobals
+from utils import registerTemp
+import os
+
+class Dvi(Backend):
+
+ def postJade(self, outfile, stdoutfile):
+
+ #
+ # Looks like that from 1.1.8, jadetex writes output in cwd
+ # instead of TMPDIR. No matter what jadetex chooses to do,
+ # this will make sure it lands in TMPDIR. We set TEXINPUTS
+ # so that included graphics are found.
+ #
+ savdir = os.getcwd()
+ envname = 'TEXINPUTS'
+ if os.environ.has_key(envname):
+ os.environ[envname] = '.:%s:%s' % (savdir, os.environ[envname])
+ else:
+ os.environ[envname] = '.:%s:' % (savdir)
+ (tmpdir, junk) = os.path.split(outfile)
+ self._tracer.chdir(tmpdir)
+
+ #
+ # Run JadeTeX on the generated file, thrice.
+ #
+ (dvibase, junk) = os.path.splitext(outfile)
+ destfile = dvibase + '.dvi'
+ cmdline = 'jadetex ' + outfile
+ for run in range(3):
+ try:
+ os.unlink(destfile)
+ except:
+ pass
+ self._tracer.system(cmdline)
+ if not os.path.isfile(destfile):
+ raise IOError, 'JadeTeX run failed'
+
+ #
+ # Write generated DVI file to destination if we're the final
+ # backend. If we're nested, leave the file hanging around.
+ #
+ self._tracer.chdir(savdir)
+ if self._globs.getName() == 'dvi':
+ finalfile = os.path.join (self._fileparts[1],
+ self._fileparts[0] + '.dvi')
+ self._tracer.mv(destfile, finalfile)
+
+ #
+ # Make sure that the temporary files are unlinked, later on.
+ #
+ registerTemp(os.path.join(tmpdir, dvibase + '.log'))
+ registerTemp(os.path.join(tmpdir, dvibase + '.aux'))
+
+
+
+class DviGlobals(BackendGlobals):
+
+ def getName(self):
+ return 'dvi'
+
+ def getJadeSettings(self):
+ return ('sgmltools-dvi', 'tex')
diff --git a/gnu/dist/sgmltools-lite/python/backends/Html.py b/gnu/dist/sgmltools-lite/python/backends/Html.py
new file mode 100644
index 00000000..bf57ab17
--- /dev/null
+++ b/gnu/dist/sgmltools-lite/python/backends/Html.py
@@ -0,0 +1,88 @@
+#
+# backends/Html.py
+#
+# $Id: Html.py,v 1.5 2000/10/26 06:20:23 cdegroot Exp $
+#
+# SGMLtools HTML backend driver.
+#
+# SGMLtools - an SGML toolkit.
+# Copyright (C) 1998 Cees A. de Groot
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+from Backend import Backend, BackendGlobals
+import utils, os, string, stat
+
+class Html(Backend):
+
+ def preJade(self, fh):
+ #
+ # Make a temporary directory, and change in there. Correct the
+ # filename if it wasn't absolute by prepending the old working
+ # directory.
+ #
+ self._savdir = os.getcwd();
+ self._tempdir, junk = os.path.splitext(utils.makeTemp())
+ self._tracer.mkdir(self._tempdir, 0700)
+ self._tracer.chdir(self._tempdir)
+
+ return fh
+
+ def postJade(self, outfile, stdoutfile):
+ #
+ # If we land here, everything worked out fine. Below the
+ # original working directory, create a subdirectory, and copy
+ # the results from the temporary directory over there.
+ #
+ # We clean the destination directory first so that old parts
+ # don't hang around, and we make a symlink named "index.html"
+ # pointing to the logical starting point of the resulting html
+ # set.
+ #
+ self._tracer.chdir(self._savdir) # so relative names work ok.
+ (srcdir, junk) = os.path.split(outfile)
+ destdir = os.path.join(self._fileparts[1], self._fileparts[0])
+
+ if os.path.exists(destdir):
+ self._tracer.system('rm -rf ' + destdir + '/*')
+ else:
+ self._tracer.mkdir(destdir)
+
+ self._tracer.mv(self._tempdir + '/*', destdir)
+ self._tracer.rmdir(self._tempdir)
+
+ #
+ # The first file in the manifest is what we'll see as index.html
+ #
+ self._tracer.chdir(destdir)
+ try:
+ fh = open('HTML.manifest', 'r')
+ indexfile = string.strip(fh.readline())
+ fh.close()
+ self._tracer.symlink(indexfile, 'index.html')
+ except:
+ pass
+
+
+ self._tracer.chdir(self._savdir)
+
+
+class HtmlGlobals(BackendGlobals):
+
+ def getName(self):
+ return 'html'
+
+ def getJadeSettings(self):
+ return ('sgmltools-html', 'sgml')
diff --git a/gnu/dist/sgmltools-lite/python/backends/JadeTeX.py b/gnu/dist/sgmltools-lite/python/backends/JadeTeX.py
new file mode 100644
index 00000000..87c50555
--- /dev/null
+++ b/gnu/dist/sgmltools-lite/python/backends/JadeTeX.py
@@ -0,0 +1,46 @@
+#
+# backends/JadeTeX.py
+#
+# $Id: JadeTeX.py,v 1.3 2000/08/03 12:38:57 cdegroot Exp $
+#
+# SGMLtools JadeTeX backend driver.
+#
+# SGMLtools - an SGML toolkit.
+# Copyright (C) 1998 Cees A. de Groot
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+from Backend import Backend, BackendGlobals
+from utils import registerTemp
+import os
+
+class JadeTeX(Backend):
+
+ def postJade(self, outfile, stdoutfile):
+
+ savdir = os.getcwd()
+ (tmpdir, junk) = os.path.split(outfile)
+ self._tracer.chdir(savdir)
+ finalfile = os.path.join(self._fileparts[1],
+ self._fileparts[0] + '.tex')
+ self._tracer.mv(outfile, finalfile)
+
+class JadeTeXGlobals(BackendGlobals):
+
+ def getName(self):
+ return 'jadetex'
+
+ def getJadeSettings(self):
+ return ('sgmltools-tex', 'tex')
diff --git a/gnu/dist/sgmltools-lite/python/backends/Ld2db.py b/gnu/dist/sgmltools-lite/python/backends/Ld2db.py
new file mode 100644
index 00000000..7787fc87
--- /dev/null
+++ b/gnu/dist/sgmltools-lite/python/backends/Ld2db.py
@@ -0,0 +1,71 @@
+#
+# backends/Ld2db.py
+#
+# $Id: Ld2db.py,v 1.2 2000/08/03 12:38:57 cdegroot Exp $
+#
+# SGMLtools LinuxDoc conversion backend driver.
+#
+# SGMLtools - an SGML toolkit.
+# Copyright (C) 1998 Cees A. de Groot
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+from Backend import Backend, BackendGlobals
+import os, string
+
+class Ld2db(Backend):
+
+ def preJade(self, fh):
+ #
+ # We need to patch up the SGML_CATALOG_FILES so that
+ # just the elements we need are in there. Otherwise, we
+ # have trouble with finding the wrong SGML declaration.
+ #
+ pathelems = string.split(os.environ["SGML_CATALOG_FILES"], ':')
+ newcatfiles = []
+ for i in pathelems:
+ if string.find(i, 'dtd/sgmltools') != -1:
+ newcatfiles.append(i)
+ elif string.find(i, 'stylesheets/sgmltools') != -1:
+ newcatfiles.append(i)
+ elif string.find(i, 'dtd/jade') != -1:
+ newcatfiles.append(i)
+ elif string.find(i, 'entities/iso-entities-8879.1986') != -1:
+ newcatfiles.append(i)
+
+ os.environ["SGML_CATALOG_FILES"] = string.join(newcatfiles, ':')
+ self._tracer.trace('SGML_CATALOG_FILES=' +
+ os.environ["SGML_CATALOG_FILES"])
+
+ return fh
+
+ def postJade(self, outfile, stdoutfile):
+ #
+ # Write generated DVI file to destination if we're the final
+ # backend. Note that Jade spits stuff to stdoutfile in this
+ # case.
+ #
+ destfile = os.path.join(self._fileparts[1],
+ self._fileparts[0] + '.db-sgml')
+ self._tracer.mv(stdoutfile, destfile)
+
+
+class Ld2dbGlobals(BackendGlobals):
+
+ def getName(self):
+ return 'ld2db'
+
+ def getJadeSettings(self):
+ return ('sgmltools-db', 'sgml')
diff --git a/gnu/dist/sgmltools-lite/python/backends/Lynx.py b/gnu/dist/sgmltools-lite/python/backends/Lynx.py
new file mode 100644
index 00000000..3436af78
--- /dev/null
+++ b/gnu/dist/sgmltools-lite/python/backends/Lynx.py
@@ -0,0 +1,59 @@
+#
+# backends/Lynx.py
+#
+# $Id: Lynx.py,v 1.2 2000/10/25 06:00:05 cdegroot Exp $
+#
+# SGMLtools Lynx-based text backend driver.
+#
+# SGMLtools - an SGML toolkit.
+# Copyright (C) 1998 Cees A. de Groot
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+from Backend import Backend, BackendGlobals
+import os
+
+class Lynx(Backend):
+
+ def preJade(self, fh):
+ #
+ # Check whether Lynx is there, if not: die
+ #
+ if self._autoconf['progs']['lynx'] == 'N/A':
+ raise Exception, 'Lynx not configured, cannot produce output'
+ else:
+ return fh
+
+ def postJade(self, outfile, stdoutfile):
+ #
+ # Jade wrote HTML, run it through lynx.
+ #
+ destfile = os.path.join(self._fileparts[1], self._fileparts[0] + '.txt')
+ self._tracer.system ("lynx -dump -nolist -force_html %s >%s" \
+ % (stdoutfile, destfile))
+
+
+class LynxGlobals(BackendGlobals):
+
+ def getName(self):
+ #
+ # Now that there is more than one txt backend, we pose as 'lynx', not
+ # as 'txt'
+ #
+ return 'lynx'
+
+ def getJadeSettings(self):
+ return ('sgmltools-lynx', 'sgml')
+
diff --git a/gnu/dist/sgmltools-lite/python/backends/OneHtml.py b/gnu/dist/sgmltools-lite/python/backends/OneHtml.py
new file mode 100644
index 00000000..c3a30d0c
--- /dev/null
+++ b/gnu/dist/sgmltools-lite/python/backends/OneHtml.py
@@ -0,0 +1,46 @@
+#
+# backends/OneHtml.py
+#
+# $Id: OneHtml.py,v 1.2 2000/08/03 12:38:57 cdegroot Exp $
+#
+# SGMLtools DVI backend driver.
+#
+# SGMLtools - an SGML toolkit.
+# Copyright (C) 1998 Cees A. de Groot
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+from Backend import Backend, BackendGlobals
+from utils import registerTemp
+import os, string
+
+class OneHtml(Backend):
+
+ def postJade(self, outfile, stdoutfile):
+
+ #
+ # Write generated HTML file to destination.
+ #
+ destfile = os.path.join(self._fileparts[1],
+ self._fileparts[0] + '.html')
+ self._tracer.mv(stdoutfile, destfile)
+
+class OneHtmlGlobals(BackendGlobals):
+
+ def getName(self):
+ return 'onehtml'
+
+ def getJadeSettings(self):
+ return ('sgmltools-onehtml', 'sgml')
diff --git a/gnu/dist/sgmltools-lite/python/backends/Pdf.py b/gnu/dist/sgmltools-lite/python/backends/Pdf.py
new file mode 100644
index 00000000..256c607c
--- /dev/null
+++ b/gnu/dist/sgmltools-lite/python/backends/Pdf.py
@@ -0,0 +1,87 @@
+#
+# backends/Pdf.py
+#
+# $Id: Pdf.py,v 1.2 2000/08/03 12:38:57 cdegroot Exp $
+#
+# SGMLtools DVI backend driver.
+#
+# SGMLtools - an SGML toolkit.
+# Copyright (C) 1998 Cees A. de Groot
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+from Backend import Backend, BackendGlobals
+from utils import registerTemp
+import os
+
+class Pdf(Backend):
+
+ def postJade(self, outfile, stdoutfile):
+
+ #
+ # Looks like that from 1.1.8, jadetex writes output in cwd
+ # instead of TMPDIR. No matter what jadetex chooses to do,
+ # this will make sure it lands in TMPDIR. We set TEXINPUTS
+ # so that included graphics are found.
+ #
+ savdir = os.getcwd()
+ envname = 'TEXINPUTS'
+ if os.environ.has_key(envname):
+ os.environ[envname] = '.:%s:%s' % (savdir, os.environ[envname])
+ else:
+ os.environ[envname] = '.:%s:' % (savdir)
+ (tmpdir, junk) = os.path.split(outfile)
+ self._tracer.chdir(tmpdir)
+
+ #
+ # Run JadeTeX on the generated file, thrice.
+ #
+ (pdfbase, junk) = os.path.splitext(outfile)
+ destfile = pdfbase + '.pdf'
+ cmdline = 'pdfjadetex ' + outfile
+ for run in range(3):
+ try:
+ os.unlink(destfile)
+ except:
+ pass
+ self._tracer.system(cmdline)
+ if not os.path.isfile(destfile):
+ raise IOError, 'JadeTeX run failed'
+
+ #
+ # Write generated PDF file to destination if we're the final
+ # backend. If we're nested, leave the file hanging around.
+ #
+ self._tracer.chdir(savdir)
+ if self._globs.getName() == 'pdf':
+ finalfile = os.path.join (self._fileparts[1],
+ self._fileparts[0] + '.pdf')
+ self._tracer.mv(destfile, finalfile)
+
+ #
+ # Make sure that the temporary files are unlinked, later on.
+ #
+ registerTemp(os.path.join(tmpdir, pdfbase + '.log'))
+ registerTemp(os.path.join(tmpdir, pdfbase + '.aux'))
+
+
+
+class PdfGlobals(BackendGlobals):
+
+ def getName(self):
+ return 'pdf'
+
+ def getJadeSettings(self):
+ return ('sgmltools-pdf', 'tex')
diff --git a/gnu/dist/sgmltools-lite/python/backends/Ps.py b/gnu/dist/sgmltools-lite/python/backends/Ps.py
new file mode 100644
index 00000000..b63aee15
--- /dev/null
+++ b/gnu/dist/sgmltools-lite/python/backends/Ps.py
@@ -0,0 +1,58 @@
+#
+# backends/Ps.py
+#
+# $Id: Ps.py,v 1.1 2000/03/24 09:16:45 cdegroot Exp $
+#
+# SGMLtools PostScript backend driver.
+#
+# SGMLtools - an SGML toolkit.
+# Copyright (C) 1998 Cees A. de Groot
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+from Backend import Backend, BackendGlobals
+import os
+from Dvi import Dvi
+
+class Ps(Dvi):
+
+ def postJade(self, outfile, stdoutfile):
+ #
+ # Call the DVI postJade routine, this leaves a DVI file we
+ # can postprocess.
+ #
+ Dvi.postJade(self, outfile, stdoutfile)
+
+ (tmpdir, junk) = os.path.split(outfile)
+ (dvibase, junk) = os.path.splitext(outfile)
+ dvifile = os.path.join(tmpdir, dvibase + '.dvi')
+
+ destfile = os.path.join(self._fileparts[1],
+ self._fileparts[0] + '.ps')
+
+ #
+ # Call dvips on the DVI file.
+ #
+ cmdline = 'dvips -o %s %s' % (destfile, dvifile)
+ self._tracer.system(cmdline)
+
+
+class PsGlobals(BackendGlobals):
+
+ def getName(self):
+ return 'ps'
+
+ def getJadeSettings(self):
+ return ('sgmltools-ps', 'tex')
diff --git a/gnu/dist/sgmltools-lite/python/backends/Rtf.py b/gnu/dist/sgmltools-lite/python/backends/Rtf.py
new file mode 100644
index 00000000..ca8042e5
--- /dev/null
+++ b/gnu/dist/sgmltools-lite/python/backends/Rtf.py
@@ -0,0 +1,45 @@
+#
+# backends/Rtf.py
+#
+# $Id: Rtf.py,v 1.2 2000/08/03 12:38:57 cdegroot Exp $
+#
+# SGMLtools RTF backend driver.
+#
+# SGMLtools - an SGML toolkit.
+# Copyright (C) 1998 Cees A. de Groot
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+from Backend import Backend, BackendGlobals
+import os
+
+class Rtf(Backend):
+
+ def postJade(self, outfile, stdoutfile):
+ #
+ # Jade wrote RTF, send it to its final destination
+ #
+ destfile = os.path.join(self._fileparts[1], self._fileparts[0] + '.rtf')
+ self._tracer.mv(outfile, destfile)
+
+
+class RtfGlobals(BackendGlobals):
+
+ def getName(self):
+ return 'rtf'
+
+ def getJadeSettings(self):
+ return ('sgmltools-rtf', 'rtf')
+
diff --git a/gnu/dist/sgmltools-lite/python/backends/W3m.py b/gnu/dist/sgmltools-lite/python/backends/W3m.py
new file mode 100644
index 00000000..f327ae72
--- /dev/null
+++ b/gnu/dist/sgmltools-lite/python/backends/W3m.py
@@ -0,0 +1,71 @@
+#
+# backends/W3m.py
+#
+# $Id: W3m.py,v 1.2 2000/11/27 20:11:57 dnedrow Exp $
+#
+# SGMLtools W3m-based text backend driver.
+#
+# SGMLtools - an SGML toolkit.
+# Copyright (C) 1998 Cees A. de Groot
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+from Backend import Backend, BackendGlobals
+import os
+
+class W3m(Backend):
+
+ def preJade(self, fh):
+ #
+ # Check whether W3m is there, if not: die
+ #
+ if self._autoconf['progs']['w3m'] == 'N/A':
+ raise Exception, 'w3m not configured, cannot produce output'
+ else:
+ return fh
+
+ def postJade(self, outfile, stdoutfile):
+ #
+ # Jade wrote HTML, run it through w3m.
+ #
+ destfile = os.path.join(self._fileparts[1], self._fileparts[0] + '.txt')
+ self._tracer.system ("w3m -T text/html -dump %s >%s" \
+ % (stdoutfile, destfile))
+
+
+class W3mGlobals(BackendGlobals):
+
+ def getName(self):
+ #
+ # As long as we're the only txt backend, we pose as 'txt', not
+ # as 'w3m'
+ #
+ return 'w3m'
+
+ def getJadeSettings(self):
+ return ('sgmltools-w3m', 'sgml')
+
+ def printHelp(self, fh):
+ """Not much help for w3m."""
+ print '\n\n'
+ print 'w3m (http://ei5nazha.yz.yamagata-u.ac.jp/~aito/w3m/eng) is a'
+ print 'text-based pager that can be used to browse websites from a'
+ print 'console. It can also be used to generate text versions of'
+ print 'websites, generally with better output than the Lynx dump'
+ print 'facility. If w3m is found when sgmltools-lite is installed'
+ print 'it becomes the default parser for the txt backend.'
+
+ pass
+
diff --git a/gnu/dist/sgmltools-lite/python/backends/iSilo.py b/gnu/dist/sgmltools-lite/python/backends/iSilo.py
new file mode 100644
index 00000000..c3efa8b6
--- /dev/null
+++ b/gnu/dist/sgmltools-lite/python/backends/iSilo.py
@@ -0,0 +1,79 @@
+#
+# backends/iSilo.py
+#
+# $Id: iSilo.py,v 1.2 2000/11/27 20:11:57 dnedrow Exp $
+#
+# SGMLtools iSilo-based text backend driver.
+#
+# SGMLtools - an SGML toolkit.
+# Copyright (C) 1998 Cees A. de Groot
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+from Backend import Backend, BackendGlobals
+import os
+
+class iSilo(Backend):
+
+ def preJade(self, fh):
+ #
+ # Check whether iSilo is there, if not: die
+ #
+ if self._autoconf['progs']['iSilo'] == 'N/A':
+ raise Exception, 'iSilo not configured, cannot produce output'
+ else:
+ return fh
+
+ def postJade(self, outfile, stdoutfile):
+ #
+ # Jade wrote HTML, run it through iSilo.
+ #
+ destfile = os.path.join(self._fileparts[1], self._fileparts[0] + '.pdb')
+ self._tracer.system ("%s -y -I %s %s" \
+ % (self._autoconf['progs']['iSilo'],
+ stdoutfile, destfile))
+
+
+class iSiloGlobals(BackendGlobals):
+
+ def getName(self):
+ #
+ # As long as we're the only txt backend, we pose as 'pdb', not
+ # as 'iSilo'
+ #
+ return 'pdb'
+
+ def getJadeSettings(self):
+ return ('sgmltools-pdb', 'sgml')
+
+ def printHelp(self, fh):
+ """Not much help for iSilo."""
+ print '\n\n'
+ print 'iSilo (http://www.isilo.com) is an application that converts'
+ print 'HTML and ASCII to documents which can be viewed on Palm'
+ print 'compatible devices using the free iSilo reader.'
+ print ''
+ print 'While iSilo can parse HTML directly, the sgmltools'
+ print 'implementation uses a text backend to generate the input'
+ print 'to the iSilo encoder.'
+ print ''
+ print 'A future improvement to this backend will be input options'
+ print 'that will allow the user to specify pre-processing formats.'
+ print ''
+ print 'Free linux encoders and Palm readers are available from the'
+ print 'URL above.'
+
+ pass
+
diff --git a/gnu/dist/sgmltools-lite/python/utils.py b/gnu/dist/sgmltools-lite/python/utils.py
new file mode 100644
index 00000000..1bdc4fda
--- /dev/null
+++ b/gnu/dist/sgmltools-lite/python/utils.py
@@ -0,0 +1,393 @@
+#
+# utils.py - Assorted utilities
+#
+# $Id: utils.py,v 1.6 2001/02/05 01:18:37 dnedrow Exp $
+#
+# SGMLtools - an SGML toolkit.
+# Copyright (C)1998 Cees A. de Groot
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 2 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+#
+
+"""
+ This module defines assorted utility functions.
+"""
+
+import sys, tempfile, os, string, re
+
+#
+# Global options and associated help text.
+#
+globalOptions = [
+ ('v', 'verbose', 'Print verbose output'),
+ ('d', 'debug', 'Do not remove temporary files'),
+ ('b:', 'backend=', 'Backend to use (default: onehtml)'),
+ ('j:', 'jade-opt=', 'Options passed on to jade'),
+ ('s:', 'dsssl-spec=', 'DSSSL spec to use'),
+ ('V', 'version', 'Print version number and exit'),
+ ('h', 'help', 'Print usage and exit'),
+ ('l', 'license', 'Print license information')
+]
+
+usagePre = """ sgmltools [OPTION...] [INPUT-FILE...]
+
+Convert SGML files into various output formats.
+
+Options:"""
+
+usagePost = """
+For help on a specific backend, use "--backend xyz --help".
+"""
+
+
+def makeOpts(backendOpts):
+ """Merge the global options with the backend options.
+
+ This function merges the global options with the backend
+ options and returns a tuple usable for getopt.
+ """
+
+ retshort = ''
+ retlong = []
+ optlist = globalOptions + backendOpts.getMoreOptions()
+ for opt in optlist:
+ retshort = retshort + opt[0]
+ retlong.append(opt[1])
+
+ return retshort, retlong
+
+
+def normalizeOpts(backendGlobs, optList):
+ """Normalize the option list returned by getopt by converting short->long
+
+ getopts() returns a mix of short and long options, which is a
+ bit unpractical. This function takes the result of getopts() and
+ normalizes it by replacing the option elements with the long
+ option without any add-on's like dashes and equals signs.
+ """
+
+ options = globalOptions + backendGlobs.getMoreOptions()
+
+ #
+ # Build translation table from short->long.
+ #
+ shortToLong = {}
+ for opt in options:
+ if opt[0][-1] == ':':
+ short = opt[0][:-1]
+ else:
+ short = opt[0]
+ if opt[1][-1] == '=':
+ long = opt[1][:-1]
+ else:
+ long = opt[1]
+
+ shortToLong[short] = long
+
+ #
+ # Normalist list.
+ #
+ retval = []
+ for opt in optList:
+ if opt[0][:2] == '--':
+ newval = (opt[0][2:], opt[1])
+ else:
+ newval = (shortToLong[opt[0][1:]], opt[1])
+ retval.append(newval)
+
+ return retval
+
+
+def findOption(optlist, optname):
+ """Look for an option in an option list and return optval.
+
+ This method checks whether an option appears in an option
+ list and returns optval (or '1' if no optval was set) if
+ the option was found. Otherwise, it returns None.
+ """
+
+ for curopt in optlist:
+ if curopt[0] == optname:
+ if curopt[1] != '':
+ return curopt[1]
+ else:
+ return 1
+ return None
+
+
+def usage(backendGlobs, message):
+ """Print a usage string, the message, and exit.
+
+ This method prints out all possible options and their help
+ texts (including those from the backend, if available), then
+ prints the message, and finally exits.
+ """
+
+ print "Usage:\n"
+ print usagePre
+ if backendGlobs != None:
+ optlist = globalOptions + backendGlobs.getMoreOptions()
+ else:
+ optlist = globalOptions
+ for opt in optlist:
+ print ' -%s, --%-15s %s' % (opt[0][0], opt[1], opt[2])
+
+ if backendGlobs != None:
+ backendGlobs.printHelp(sys.stderr)
+
+ print usagePost
+ print
+ if message != None:
+ print message
+ print
+ sys.exit(1)
+ else:
+ sys.exit(0)
+
+
+def version(sharedir):
+ """This procedure prints a version identifier to stdout"""
+
+ fh = open(os.path.join(sharedir, 'VERSION'))
+ print 'SGMLtools-Lite version ' + string.rstrip(fh.readline())
+ fh.close()
+
+
+tempfiles = []
+def makeTemp():
+ """Make a temporary file which is cleaned up at exit
+
+ This method calls mktemp() to create a temporary filename and
+ stashes the returned file in an array that will be checked at
+ exit time by exitHandler().
+ """
+
+ newname = tempfile.mktemp()
+ global tempfiles
+ tempfiles.append(newname)
+ return newname
+
+def registerTemp(file):
+ """Register a temporary file for cleaning up at exit
+
+ This method registers a temporary file for cleanup at
+ exit. This can be used in order to deal with temporary
+ files whose names are not generated by us (but by, say,
+ TeX).
+ """
+ tempfiles.append(file)
+
+def exitHandler():
+ """Cleaning lady for makeTemp()
+
+ This method walks over the tempfiles list and attempts to remove
+ each element in it.
+ """
+
+ for file in tempfiles:
+ try:
+ os.remove(file)
+ except:
+ pass
+
+#
+# Register us as an exit function
+#
+sys.exitfunc = exitHandler
+
+
+def readAliases(autoconf):
+ """Read %(etcdir)/aliases and ~/.sgmlaliases
+
+ This function reads the SGML alias files and returns a hash
+ containing the merged contents of these files.
+ """
+
+ retval = {}
+ for file in [ os.path.join(autoconf['etcdir'], 'aliases'),
+ os.path.expanduser('~/.sgmlaliases') ]:
+ if not os.path.isfile(file):
+ continue
+
+ fh = open(file, 'r')
+ for line in fh.readlines():
+ line = string.strip(line)
+ if len(line) == 0:
+ continue
+ if line[0] == '#':
+ continue
+
+ key, rest = string.split(line, ' ', 1)
+ retval[key] = string.lstrip(rest)
+ fh.close()
+
+ return retval
+
+#
+# Search our path, SGML_CATALOG_FILES, by reading all them files
+# and looking for our pubid. We really need a catalog file parser...
+#
+def _searchInCat(curcat, id, section):
+ fh = open(curcat, 'r')
+ for line in fh.readlines():
+ #
+ # Check for nested catalogs, recurse if yes.
+ #
+ mo = re.compile(r'CATALOG\s*"([^"]+)"').match(line)
+ if mo != None:
+ retval = _searchInCat(mo.group(1), id, section)
+ if retval != None:
+ return retval;
+
+ if not re.compile(r'^\s*PUBLIC').match(line):
+ continue
+ if string.find(line, id) == -1:
+ continue
+
+ fh.close()
+
+ #
+ # Looks like a good one - extract the relevant parts. If the
+ # sysid is not absolute, prepend the current catalog's
+ # location to it.
+ #
+ retval = re.compile(r'^.*\s\"?([^"\s]+)\"?$').match(line).group(1)
+ if not os.path.isabs(retval):
+ catdir, junk = os.path.split(curcat)
+ retval = os.path.join(catdir, retval)
+ if not os.path.exists(retval):
+ raise IOError, \
+ "Found catalog file %s but it doesn't exist" % retval
+
+ if len(section) > 0:
+ retval = retval + '#' + section
+ return retval
+
+ fh.close()
+ return None
+
+
+def findStylesheet(name, aliases):
+ """Searches for the stylesheet indicated by name
+
+ This function translates a public stylesheet identifier into a
+ system identifier. It uses the alias list to expand aliases.
+ """
+
+ #
+ # Test whether it is already a system identifier
+ #
+ try:
+ (id, section) = string.split(name, '#', 1)
+ except:
+ id = name
+ section = ''
+ if os.path.isfile(id):
+ return name
+
+ #
+ # Expand alias, and retest.
+ #
+ if aliases.has_key(id):
+ name = aliases[id]
+ if len(section) > 0:
+ name = name + '#' + section
+ return findStylesheet(name, aliases)
+
+ for curcat in string.split(os.environ['SGML_CATALOG_FILES'], ':'):
+ if not os.path.isfile(curcat):
+ continue
+
+ retval = _searchInCat(curcat, id, section);
+ if retval != None:
+ return retval;
+
+ raise IOError, "Couldn't resolve pubid [%s]" % id
+
+def shellProtect(file):
+ """Protects a filename against shell interpretation.
+ This is done by putting the name in single quotes, and by
+ escaping single quotes in the filename. If the last character
+ is an asterisk, the asterisk is NOT quoted and is appended
+ after the final single quote.
+ """
+ if file[-1] != '*':
+ return "'%s'" % string.replace(file, "'", "'\\''")
+ else:
+ return "'%s'*" % string.replace(file[:-1], "'", "'\\''")
+
+class Tracer:
+ """Simple tracer class."""
+
+ def __init__(self, doTrace):
+ self._isTracing = doTrace
+
+ def trace(self, message):
+ if self._isTracing:
+ print ('+' + message)
+
+ def system(self, cmd):
+ """Shorthand for the pattern trace(x);os.system(x)"""
+ self.trace(cmd)
+ os.system(cmd)
+
+ def mkdir(self, dir, mode=0755):
+ """Shorthand for the pattern trace('mkdir ' + x);os.mkdir(x)"""
+ self.trace('mkdir ' + dir)
+ os.mkdir(dir, mode)
+
+ def chdir(self, dir):
+ """Shorthand for the pattern trace('chdir ' + x);os.chdir(x)"""
+ self.trace('chdir ' + dir)
+ os.chdir(dir)
+
+ def rmdir(self, dir):
+ """Shorthand for the pattern trace('rmdir ' + x);os.rmdir(x)"""
+ self.trace('rmdir ' + dir)
+ os.rmdir(dir)
+
+ def symlink(self, src, dest):
+ """Shorthand for the pattern trace('symlink... );os.symlink(...)"""
+ self.trace('ln -s ' + src + ' ' + dest)
+ os.symlink(src, dest)
+
+ def mv(self, src, dest):
+ """Shorthand for the pattern trace('mv...);os.system("mv...)."""
+ self.system("mv %s %s" % (shellProtect(src), shellProtect(dest)))
+
+#
+# License information printer
+#
+def license():
+ print """
+ SGMLtools - an SGML toolkit.
+ Copyright (C)1998 Cees A. de Groot
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+"""
+ sys.exit(0)