> Here's the output from my linux box together with a small fix.
> 
> $ diff -u -Bbw ../build/lib/lyxrc.defaults . > lyxrc.diff
> $ diff -u configure_orig.py configure.py > configure.diff

How do you like the attached new version? checkProg() now
handles rc file and all info about checked program is now
complete at one function call.

The speed problem has been resolved. configure.py runs
at least as fast as the bsh version now.

Bo
#!/usr/bin/env python 
#
# The original script is a hand-made configure script written in bsh. 
# It contains a lot of code stolen from GNU autoconf. The author removed 
# all the code that was not useful for configuring a LyX installation.
#
# This is a python translation of the original bsh configure script
# It is supposed to be cleaner, quicker and can avoid the use of
# mingw on windows system. This will make the installation
# process less painful under windows.
#
# Bo Peng ([EMAIL PROTECTED])
# Last Modified: Sep, 2005
# 
# Implementation:
#   -- almost line to line translation, almost all variables
#      have the same name and meaning as before.
#   -- Use functions to clean up the (original ugly) code
#   -- use python::re module to replace sed
#   -- use os.system for system call.
#
# Known Bugs:
#   -- none
#

import sys, os, re, shutil

outfile = 'lyxrc.defaults'
rc_entries = ''
lyx_check_config = True
lyx_keep_temps = False
srcdir = ''
version_suffix = ''

# utility function.
# save a few lines.
def writeToFile(filename, lines, append = False):
  if append:
    file = open(filename, 'a')
  else:
    file = open(filename, 'w')
  file.write(lines)
  file.close()

# utility function, 'rm -f'
def removeFiles(filenames):
  for file in filenames:
    try:
      os.remove(file)
    except:
      pass

#### Parse the command line
for op in sys.argv[1:]:   # default shell/for list is $*, the options
  if op in [ '-help', '--help', '-h' ]:
    print '''Usage: configure [options]
Options:
  --help                   show this help lines
  --keep-temps             keep temporary files (for debug. purposes)
  --without-latex-config   do not run LaTeX to determine configuration
  --with-version-suffix=suffix suffix of binary installed files
'''
    sys.exit(0)
  elif op == '--without-latex-config':
    lyx_check_config = False
  elif op == '--keep-temps':
    lyx_keep_temps = True
  elif op[0:22] == '--with-version-suffix=':  # never mind if op is not long 
enough  
    version_suffix = op[23:]
  else:
    print "Unknown option", op
    sys.exit(1)

#### Checking for some echo oddities (ignored)
## The original script defines ac_n, ac_t and ac_c for 
## tab, newline etc, I just use python's print output. 

#### I do not really know why this is useful, but we might as well keep it.
### NLS nuisances.
### Only set these to C if already set.  These must not be set unconditionally
### because not all systems understand e.g. LANG=C (notably SCO).
### Fixing LC_MESSAGES prevents Solaris sh from translating var values in `set'!
### Non-C LC_CTYPE values break the ctype check.
## 
os.environ['LANG'] = os.getenv('LANG', 'C')
os.environ['LC'] = os.getenv('LC_ALL', 'C')
os.environ['LC_MESSAGE'] = os.getenv('LC_MESSAGE', 'C')
os.environ['LC_CTYPE'] = os.getenv('LC_CTYPE', 'C')

#### Guess the directory in which configure is located.
ac_prog = sys.argv[0]
srcdir = os.path.dirname(ac_prog)
if srcdir == '':  
  srcdir = '.'
if not os.path.isfile( os.path.join(srcdir, 'chkconfig.ltx') ):
  print "configure: error: cannot find chkconfig.ltx script"
  sys.exit(1)

#### Adjust PATH for Win32 (Cygwin)
# i.e., change /cygdrive/c to c:
#
# FIXME: necessary? I assume that lyx/win does not like cygwin.

###### Create the build directories if necessary
for dir in ['bind', 'clipart', 'doc', 'examples', 'help', \
  'images', 'kbd', 'layouts', 'reLyX' , 'scripts', 'templates', \
  'ui', 'xfonts']:
  if not os.path.isdir( dir ):
    try:
      os.mkdir( dir)
    except:
      print "Failed to create directory ", dir
      sys.exit(1)

##
## Write the first part of outfile
writeToFile(outfile, '''
# This file has been automatically generated by LyX' lib/configure
# script. It contains default settings that have been determined by
# examining your system. PLEASE DO NOT MODIFY ANYTHING HERE! If you
# want to customize LyX, make a copy of the file LYXDIR/lyxrc as
# ~/.lyx/lyxrc and edit this file instead. Any setting in lyxrc will
# override the values given here.
\\Format text     txt   ASCII           A
\\Format textparagraph txt ASCII(paragraphs)    ""
\\Format docbook  sgml  DocBook         B
\\Format bmp      bmp   BMP             ""
\\Format dvi      dvi   DVI             D
\\Format eps      eps   EPS             ""
\\Format fax      ""    Fax             ""
\\Format fig      fig   XFig            ""
\\Format agr      agr   GRACE           ""
\\Format html     html  HTML            H
\\Format gif      gif   GIF             ""
\\Format jpg      jpg   JPG             ""
\\Format latex    tex   LaTeX           L
\\Format linuxdoc sgml  LinuxDoc        x
\\Format lyx      lyx   LyX             ""
\\Format literate nw    NoWeb           N
\\Format pdf      pdf   PDF             P
\\Format pdf2     pdf  "PDF (pdflatex)" F
\\Format pdf3     pdf  "PDF (dvipdfm)"  m
\\Format png      png   PNG             ""
\\Format ppm      ppm   PPM             ""
\\Format pgm      pgm   PGM             ""
\\Format pbm      pbm   PBM             ""
\\Format ps       ps    Postscript      t
\\Format program  ""    Program         ""
\\Format tgif     obj   TGIF            ""
\\Format tiff     tif   TIFF            ""
\\Format word     doc   Word            W
\\Format xbm      xbm   XBM             ""
\\Format xpm      xpm   XPM             ""
\\Format lyxpreview     lyxpreview      "LyX Preview"           ""
''')

#### Searching some useful programs
## This function will search a program in $PATH plus given path
## If found, return directory and program name.
##
## description: description of the program
## progs: check programs
## path: additional path
## rc_entry: entry to outfile
##   These entry should have the same length as 
##   progs.
## FIXME: under windows, we should check registry
## instead of $PATH
def checkProg(description, progs, 
  rc_entry = [],  # \converter \viewer etc
  path = [] ):
  # one rc entry for each progs plus none entry
  if len(rc_entry) > 0 and len(rc_entry) != len(progs) + 1:
    print "rc entry should have item for each prog and none."
    sys.exit(2)
  print '\nchecking for', description, '...', 
  print '(' + ','.join(progs) + ')',
  # 
  for idx in range(len(progs)):
    # ac_prog may have options, ac_word is the command name
    ac_prog = progs[idx]
    ac_word = ac_prog.split(' ')[0]
    print '\n+checking for "' + ac_word + '"... ', 
    for ac_dir in os.environ['PATH'].split(':') + path:
      if os.path.isfile( os.path.join(ac_dir, ac_word) ):
        print ' yes',
        # write rc entries for this command
        if len(rc_entry) > 0:
          writeToFile(outfile, rc_entry[idx] + '\n', append = True) 
        return [ac_dir, ac_prog]
    # if not successful
    print ' no',
  # write rc entries for 'not found' 
  if len(rc_entry) > 0:
    writeToFile(outfile, rc_entry[len(progs)] + '\n', append = True) 
  return ['', 'none']

# Find programs! Returned path is not used now
path, LATEX = checkProg( 'a latex2e program', ['latex', 'latex2e'],
  rc_entry = [ 
    r'\converter latex dvi "latex $$i" "latex"',
    r'\converter latex dvi "latex2e $$i" "latex"',
    r'\converter latex dvi "none" "latex"' ])

# no latex
lyx_check_config = False
if LATEX != 'none': 
  # Check if latex is usable
  writeToFile('chklatex.ltx', '''
\\nonstopmode\\makeatletter
\\ifx\\undefined\\documentclass\\else
  \\message{ThisIsLaTeX2e}
\\fi
\\@@end
''')
  # run latex on chklatex.ltx and check result
  isLatex2e = False
  fout = os.popen(LATEX + ' chklatex.ltx')
  for line in fout.readlines():
    if re.search('ThisIsLaTeX2e', line) != None:
      isLatex2e = True
      break
  fout.close()
  if not isLatex2e:
    print "Latex not usable (not LaTex2e) "
  else:
    lyx_check_config = True
  # remove temporary files
  removeFiles(['chkltex.ltx', 'chklatex.log'])

checkProg('a pdflatex program', ['pdflatex'], 
  rc_entry = [ r'\converter latex pdf2 "pdflatex $$i" "latex"',
               r'\converter latex pdf2 "none" "latex"' ])

checkProg('a LaTeX -> LyX converter', ['reLyX'], path = ['./reLyX'], 
  rc_entry = [ 
    r'\converter latex lyx "reLyX' + version_suffix + ' -f $$i" ""',
    r'\converter latex lyx "none" ""' ])

checkProg('a Noweb -> LyX converter', ['noweb2lyx'], path = ['./reLyX'],
  rc_entry = [ 
    r'\converter literate lyx "noweb2lyx' + version_suffix + ' $$i $$o" ""',
    r'\converter literate lyx "none" ""' ]) 

checkProg('a Noweb -> LaTex converter', ['noweave'], path = ['./reLyX'], 
  rc_entry = [ 
    r'\converter literate latex "noweave' + version_suffix + '  -delay -index 
$$i > $$o" ""',
    r'\converter literate latex "none" ""' ]) 

checkProg('a HTML -> LaTex converter', ['html2latex'],
  rc_entry = [
    r'\converter html latex "html2latex $$i" ""',
    r'\converter html latex "none" ""' ])

checkProg('a MSWord -> LaTex converter', ['wvCleanLatex', 'word2x'],
  rc_entry = [
    r'\converter word latex "wvCleanLatex $$i $$o" ""',
    r'\converter word latex "word2x -f latex $$i" ""',
    r'\converter word latex "none" ""' ])

# FIXME: image_command is not used anywhere. 
path, image_command = checkProg('Image converter', ['convert'])
if image_command == 'convert':
  image_command += ' $$i $$o'

checkProg('a Postscript interpreter', ['gs'], 
  rc_entry = [
    r'\ps_command "gs"',
    r'\ps_command "none"' ])

# add viewer for ps and eps
# FIXME: eps does not need -swap? (this is the original setting)
checkProg('a Postscript previewer', ['gsview32', 'gv', 'ghostview'],
  rc_entry = [
    r'''\viewer ps "gsview32"
\viewer eps "gsview32"''',
    r'''\viewer ps "gv -swap"
\viewer eps "gv"''',
    r'''\viewer ps "ghostview -swap"
\viewer eps "ghostview"''',
    r'''\viewer ps "none"
\viewer eps "none"'''])
  
checkProg('a PDF previewer', ['acrobat', 'acrord32', 'gsview32', \
  'acroread', 'gv', 'ghostview', 'xpdf'], 
  rc_entry = [
    r'\viewer pdf "acrobat"', 
    r'\viewer pdf "acrord32"', 
    r'\viewer pdf "gsview32"',
    r'\viewer pdf "acroread"',
    r'\viewer pdf "gv"',
    r'\viewer pdf "ghostview"', 
    r'\viewer pdf "xpdf"', 
    r'\viewer pdf "none"'])

checkProg('a DVI previewer', ['xdvi', 'windvi', 'yap'],
  rc_entry = [
    r'\viewer dvi "xdvi"', 
    r'\viewer dvi "windvi"', 
    r'\viewer dvi "yap"', 
    r'\viewer dvi "none"' ])

checkProg('a HTML previewer', ['mozilla file://$$p$$i', 'netscape'], 
  rc_entry = [
    r'\viewer html "mozilla file://$$p$$i"', 
    r'\viewer html "netscape"', 
    r'\viewer html "none"' ])

checkProg('a PS to PDF converter', ['ps2pdf'],
  rc_entry = [ 
    r'\converter ps pdf "ps2pdf -dCompatibilityLevel=1.3 $$i" ""',  
    r'\converter ps pdf "none" ""' ])

checkProg('a DVI to PS converter', ['dvips'],
  rc_entry = [ 
    r'\converter dvi ps "dvips -o $$o $$i" ""',  
    r'\converter dvi ps "none" ""' ])

checkProg('a DVI to PDF converter', ['dvipdfm'],
  rc_entry = [
    r'\converter dvi pdf3 "dvipdfm $$i" ""', 
    r'\converter dvi pdf3 "none" ""' ])

### We have a script to convert previewlyx to ppm
writeToFile(outfile, '\\converter lyxpreview ppm "lyxpreview2ppm.py" ""\n', 
  append = True)

checkProg('a *roff formatter', ['groff -t -Tlatin1 $$FName', 'nroff'],
  rc_entry = [
    r'\ascii_roff_command "groff -t -Tlatin1 $$FName"', 
    r'\ascii_roff_command "tbl $$FName | nroff"', 
    '' ])

checkProg('ChkTeX', ['chktex -n1 -n3 -n6 -n9 -n22 -n25 -n30 -n38'],
  rc_entry = [
    r'\chktex_command "chktex -n1 -n3 -n6 -n9 -n22 -n25 -n30 -n38"',
    r'\chktex_command "none"' ])

checkProg('a spell-checker', ['ispell'],
  rc_entry = [
    r'\spell_command "ispell"', '' ] )

## FIXME: OCTAVE is not used anywhere
path, OCTAVE = checkProg('Octave', ['octave'])

## FIXME: MAPLE is not used anywhere
path, MAPLE = checkProg('Maple', ['maple'])

checkProg('a fax program', ['kdeprintfax', 'ksendfax'], 
  rc_entry = [
    r'\converter ps fax "kdeprintfax $$i" ""',
    r'\converter ps fax "ksendfax $$i" ""',
    r'\converter ps fax "none" ""'])

path, LINUXDOC = checkProg('SGML-tools 1.x (LinuxDoc)', ['sgml2lyx'],
  rc_entry = [
    r'''\converter linuxdoc lyx "sgml2lyx $$i" ""
\converter linuxdoc latex "sgml2latex $$i" ""
\converter linuxdoc dvi "sgml2latex -o dvi $$i" ""
\converter linuxdoc html "sgml2html $$i" "" ''',
    r'''\converter linuxdoc lyx "none" ""
\converter linuxdoc latex "none" ""
\converter linuxdoc dvi "none" ""
\converter linuxdoc html "none" "" ''' ])

if LINUXDOC != 'none':
  chk_linuxdoc = 'yes'
  bool_linuxdoc = 'true'
  linuxdoc_cmd = '\\def\\haslinuxdoc{yes}'
else:
  chk_linuxdoc = 'no'
  bool_linuxdoc = 'false'

path, DOCBOOK = checkProg('SGML-tools 2.x (DocBook) or db2x scripts', 
['sgmltools', 'db2dvi'],
  rc_entry = [
    r'''\converter docbook dvi "sgmltools -b dvi $$i" ""
\converter docbook html "sgmltools -b html $$i" ""''',
    r'''\converter docbook dvi "db2dvi $$i" ""
\converter docbook html "db2html $$i" ""''',
    r'''\converter docbook dvi "none" ""
\converter docbook html "none" ""'''])

if DOCBOOK != 'none':
  chk_docbook = 'yes'
  bool_docbook = 'true'
  docbook_cmd = '\\def\\hasdocbook{yes}'
else:
  chk_docbook = 'no'
  bool_docbook = 'false'

checkProg('a spool command', ['lp', 'lpr'],
  rc_entry = [
    r'''\print_spool_printerprefix "-d "
\print_spool_command "lp"''',
    r'''\print_spool_printerprefix "-P"',
\print_spool_command "lpr"''',
    ''])

checkProg('a LaTeX -> HTML converter', ['tth', 'latex2html', 'hevea'],
  rc_entry = [
    r'\converter latex html "tth -t -e2 -L$$b < $$i > $$o" 
"originaldir,needaux"',
    r'\converter latex html "latex2html -no_subdir -split 0 
-show_section_numbers $$i" "originaldir,needaux"',
    r'\converter latex html "hevea -s $$i" "originaldir,needaux"',
    r'\converter latex html "none" "originaldir,needaux"' ])

#### Explore the LaTeX configuration
print '\nchecking LaTeX configuration... ',
#
### First, remove the files that we want to re-create
removeFiles(['textclass.lst', 'packages.lst', 'chkconfig.sed'])

if not lyx_check_config:
  print ' default values',
  print '\n+checking list of textclasses... '
  tx = open('textclass.lst', 'w')
  tx.write('''
# This file declares layouts and their associated definition files
# (include dir. relative to the place where this file is).
# It contains only default values, since chkconfig.ltx could not be run
# for some reason. Run ./configure if you need to update it after a
# configuration change.
''')
  # build the list of available layout files and convert it to commands
  # for chkconfig.ltx
  foundClasses = []
  # sed filters
  p1 = re.compile(r'\Declare(LaTeX|DocBook|LinuxDoc)Class')
  p2 = re.compile(r'^.*\DeclareLaTeXClass *(.*)')
  p3 = re.compile(r'^.*\DeclareDocBookClass *(.*)')
  p4 = re.compile(r'^.*\DeclareLinuxDocClass *(.*)')
  p5 = re.compile(r'\[([^,]*),[^]]*\]')
  p6 = re.compile('^{')
  p7 = re.compile(r'\[([^]]*)\] *{([^}]*)}')
  for file in os.listdir('layouts') + os.listdir( os.path.join(srcdir, 
'layouts') ):
    # remove none-layout file
    if file[-7:] != '.layout': 
      continue
    # diretory info is lost
    if os.path.isfile(os.path.join('layouts', file)):
      file = os.path.join('layouts', file)
    elif os.path.isfile(os.path.join(srcdir, file)):
      file = os.path.join(srcdir, file)
    else:
      continue
    # get stuff between /xxxx.layout .
    classname = file.split(os.sep)[-1].split('.')[0]
    #  tr ' -' '__'`
    cleanclass = classname.replace(' ', '_')
    cleanclass = cleanclass.replace('-', '_')
    # make sure the same class is not considered twice
    if foundClasses.count(cleanclass) == 0: # not found before
      foundClasses.append(cleanclass)
      # The sed commands below are a bit scary. Here is what they do:
      # 1-3: remove the \DeclareFOO macro and add the correct boolean 
      #      at the end of the line telling whether the class is 
      #      available
      # 4: if the macro had an optional argument with several 
      #    parameters, only keep the first one
      # 5: if the macro did not have an optional argument, provide one 
      #    (equal to the class name)
      # 6: remove brackets and replace with correctly quoted entries
      #     grep '\\Declare\(LaTeX\|DocBook\|LinuxDoc\)Class' "$file" \
      #      | sed -e 's/^.*\DeclareLaTeXClass *\(.*\)/\1 "false"/' \
      #     -e 's/^.*\DeclareDocBookClass *\(.*\)/\1 "'$bool_docbook'"/' \
      #     -e 's/^.*\DeclareLinuxDocClass *\(.*\)/\1 "'$bool_linuxdoc'"/' \
      #     -e 's/\[\([^,]*\),[^]]*\]/[\1]/' \
      #     -e 's/^{/['$class']{/' \
      #     -e 's/\[\([^]]*\)\] *{\([^}]*\)}/"'$class'" "\1" "\2"/' \
      #                   >>textclass.lst
      #
      for line in open(file).readlines():
        try:
          # Declear ...?
          if p1.search(line) == None: 
            continue
          line = p2.sub(r'\1 "false"', line)
          line = p3.sub(r'\1 "' + bool_docbook + '"', line)
          line = p4.sub(r'\1 "' + bool_linuxdoc + '"', line)
          line = p5.sub(r'[\1]', line)
          line = p6.sub("[" + classname + "]{", line)  
          line = p7.sub( "'" + classname + "'" + r'"\1" "\2"', line)
          tx.write(line)
        except:
          raise
          continue
  tx.close()
  print '\tdone'
else:
  print '\tauto'
  removeFiles(['wrap_chkconfig.ltx', 'chkconfig.vars', \
    'chkconfig.classes', 'chklayouts.tex'])
  writeToFile('wrap_chkconfig.ltx', '''\\newcommand\\srcdir{%s}
%s
%s
\\input{%s/chkconfig.ltx}
''' % (srcdir, linuxdoc_cmd, docbook_cmd, srcdir) )
  cl = open('chklayouts.tex', 'w')
  ## Construct the list of classes to test for.
  # build the list of available layout files and convert it to commands
  # for chkconfig.ltx
  for file in os.listdir('layouts') + os.listdir( os.path.join(srcdir, 
'layouts') ):
    # remove none-layout file
    if file[-7:] != '.layout': 
      continue

    # directory info is lost
    if os.path.isfile(os.path.join('layouts', file)) or \
      os.path.isfile(os.path.join(srcdir, 'layouts', file)):
      # \TestDocClass{\1}
      line = re.sub(r'^(.*)\.layout$', r'\TestDocClass{\1}', file)
      cl.write(line)
  cl.close()
  #
  # we have chklayouts.tex, then process it
  fout = os.popen(LATEX + ' wrap_chkconfig.ltx')
  for line in fout.readlines():
    if re.match('^\+', line):
      print line,
  fout.close()
  #
  #  evalulate lines in chkconfig.vars?
  # is it really necessary?
  for line in open('chkconfig.vars').readlines():
    exec( re.sub('-', '_', line) )

### Do we have all the files we need? Useful if latex did not run

### if chkconfig.sed does not exist (because LaTeX did not run),
### then provide a standard version.
if not os.path.isfile('chkconfig.sed'):
  writeToFile('chkconfig.sed', '''
##s/@.*@/???/g
''')

print "creating packages.lst"
### if packages.lst does not exist (because LaTeX did not run),
### then provide a standard version.
if not os.path.isfile('packages.lst'):
  writeToFile('packages.lst', '''
### This file should contain the list of LaTeX packages that have been
### recognized by LyX. Unfortunately, since configure could not find
### your LaTeX2e program, the tests have not been run. Run ./configure
### if you need to update it after a configuration change.
''')

print 'creating doc/LaTeXConfig.lyx'
#
# This is originally done by sed, using a 
# tex-generated file chkconfig.sed
# Now, we have to do it by hand.
#
# add to chekconfig.sed
writeToFile('chkconfig.sed', '''[EMAIL PROTECTED]@!%s!g
[EMAIL PROTECTED]@!%s!g 
''' % (chk_linuxdoc, chk_docbook) , append=True)
#
# process this sed file!!!!
# This is much slower than the sed command below.
##sed -f chkconfig.sed ${srcdir}/doc/LaTeXConfig.lyx.in 
##  >doc/LaTeXConfig.lyx
lyxin = open( os.path.join(srcdir, 'doc', 'LaTeXConfig.lyx.in')).readlines()
# get the rules
p = re.compile(r's!(.*)!(.*)!g')
# process each sed replace.
for sed in open('chkconfig.sed').readlines():
  try:
    fr, to = p.match(sed).groups()
    for line in range(len(lyxin)):
      lyxin[line] = lyxin[line].replace(fr, to)
  except:
    pass

writeToFile( os.path.join('doc', 'LaTeXConfig.lyx'), 
  ''.join(lyxin))

writeToFile(outfile, '\\font_encoding "%s"\n' % chk_fontenc, append = True)

checkProg('an FIG -> EPS/PPM converter', ['fig2dev'],
  rc_entry = [ 
    r'''\converter fig eps "fig2dev -L eps $$i $$o" ""
\converter fig ppm "fig2dev -L ppm $$i $$o" ""''',
    ''])

checkProg('a TIFF -> PS converter', ['tiff2ps'],
  rc_entry = [
    r'\converter tiff eps "tiff2ps $$i > $$o" ""',
    ''])

checkProg('a TGIF -> EPS/PPM converter', ['tgif'],
  rc_entry = [
    r'''\converter tgif eps "tgif -stdout -print -color -eps $$i > $$o" ""
\converter tgif png "tgif -stdout -print -color -xpm $$i | xpmtoppm | pnmtopng 
> $$o" ""''',
    ''])

checkProg('a EPS -> PDF converter', ['epstopdf'],
  rc_entry = [ r'\converter eps pdf "epstopdf --outfile=$$o $$i" ""', ''])

path, GRACE = checkProg('a  Grace -> Image converter', ['gracebat'],
  rc_entry = [ 
    r'''\converter agr eps "gracebat -hardcopy -printfile $$o -hdevice EPS $$i 
2>/dev/null" ""
\converter agr png "gracebat -hardcopy -printfile $$o -hdevice PNG $$i 
2>/dev/null" ""
\converter agr jpg "gracebat -hardcopy -printfile $$o -hdevice JPEG $$i 
2>/dev/null" ""
\converter agr ppm "gracebat -hardcopy -printfile $$o -hdevice PNM $$i 
2>/dev/null" ""''',
    ''])

######## X FONTS
# create a fonts.dir file to make X fonts available to LyX
print "\nchecking for TeX fonts",

fontlist = ['cmex10', 'cmmi10', 'cmr10', 'cmsy10', 'eufm10', \
  'msam10', 'msbm10', 'wasy10']
removeFiles([ "xfonts/fonts.dir", "xfonts/fonts.scale", \
  "xfonts/tmpfonts"])

# kpsewhich is a texmf command! 
# how do I know is it available?
#
path, kpsewhich = checkProg('kpsewhich (under texmf)', ['kpsewhich'])
if kpsewhich != 'kpsewhich':
  print "Tex is not installed properly. (Can not find kpsewhich"
else:
  num = 0
  for font in fontlist:
    print '\n+checking for ', font, '... ',
    result = False
    for ext in ['.pfb', '.pfa', '.ttf']:
      filepath = os.popen(kpsewhich + ' ' + font + ext).readline()
      if filepath.strip() != '':
        result = "yes (" + ext + ")"
        removeFiles( [os.path.join('xfonts', font+ext)] )
        # hey, ln -s under windows?
        try:
          if sys.platform == 'win32':
            shutil(filepath, 'xfonts') 
          else: # mac or linux?
            os.symlink(filepath, 'xfonts')
        except:  # pass if file exists
          pass
        writeToFile(
          os.path.join('xfonts', 'tmpfonts'), 
          "%s%s -unknown-%s-medium-r-normal--0-0-0-0-p-0-adobe-fontspecific\n" 
% (font, ext, font),
          append = True)
        num += 1
        break
    print ' ', result,

if num > 0: # found fonts
  writeToFile( os.path.join('xfonts', 'fonts.scale'), '%d\n' % num)
  writeToFile( os.path.join('xfonts', 'fonts.scale'), 
    open( os.path.join('xfonts', 'tmpfonts')).read(), 
    append = True)
  shutil.copy( os.path.join('xfonts', 'fonts.scale'),
    os.path.join('xfonts', 'fonts.dir') )
  # create a resource list file for Display Postscript
  removeFiles( [os.path.join('xfonts', 'PSres.upr'), 
    os.path.join('xfonts', 'tmpfonts')] )
  os.popen('makepsres xfonts' )  # message is not displayed
  shutil.move('PSres.upr', os.path.join('xfonts', 'PSres.upr')) 

# Remove superfluous files if we are not writing in the main lib
# directory
for file in [outfile, 'textclass.lst', 'packages.lst', \
  'doc/LaTeXConfig.lyx', 'xfonts/fonts.dir']:
  try:
    # we rename the file first, so that we avoid comparing a file with itself
    os.rename(file, file + '.new')
    mycfg = open( os.path.join(srcdir, file) ).read()
    syscfg = open( file + '.new').read()
    if mycfg == syscfg:
      print "removing $file, which is identical to the system global version"
      removeFiles( [file + '.new'] )
    else:
      os.rename( file + '.new', file )
  except:  # ignore if file not found
    os.rename( file + '.new', file )
    pass 

if not os.path.isfile( os.path.join('xfonts', 'fonts.dir')):
  print "removing font links"
  removeFiles( os.path.join('xfonts', 'fonts.scale'))
  for file in os.listdir('xfonts'):
    if file[-4:] == '.pfb':
      removeFiles([os.path.join('xfonts', file)])

# Final clean-up
if not lyx_keep_temps:
  removeFiles(['chkconfig.sed', 'chkconfig.vars',  \
    'wrap_chkconfig.ltx', 'wrap_chkconfig.log', \
    'chklayouts.tex', 'missfont.log'])

Reply via email to