]> git.lyx.org Git - lyx.git/blob - lib/configure.py
Add Bo Peng's experimental Python script to the repository.
[lyx.git] / lib / configure.py
1 #! /usr/bin/env python
2 #
3 # file configure.py
4 # This file is part of LyX, the document processor.
5 # Licence details can be found in the file COPYING.
6
7 # author Bo Peng
8 # Full author contact details are available in file CREDITS.
9
10 # This is an experimental version of the configure script, written
11 # in Python. It is not yet used by LyX but aims to replace the
12 # configure script eventually. Part of the goal to reduce the
13 # number of scripting languages used by an official LyX distribution
14 # to just one --- Python.
15
16 import sys, os, re, shutil, glob
17
18 outfile = 'lyxrc.defaults'
19 rc_entries = ''
20 lyx_check_config = True
21 lyx_keep_temps = False
22 srcdir = ''
23 version_suffix = ''
24
25 def writeToFile(filename, lines, append = False):
26   " utility function: write or append lines to filename "
27   if append:
28     file = open(filename, 'a')
29   else:
30     file = open(filename, 'w')
31   file.write(lines)
32   file.close()
33
34 def addToRC(lines):
35   ''' utility function: shortcut for appending lines to outfile
36     add newline at the end of lines.
37   '''
38   if lines.strip() != '':
39     writeToFile(outfile, lines + '\n', append = True)
40
41 def removeFiles(filenames):
42   '''utility function: 'rm -f'
43     ignore erroes when file does not exist, or is a directory.
44   '''
45   for file in filenames:
46     try:
47       os.remove(file)
48     except:
49       pass
50
51 def cmdOutput(cmd):
52   '''utility function: run a command and get its output as a string
53     cmd: command to run
54   '''
55   fout = os.popen(cmd)
56   output = fout.read()
57   fout.close()
58   return output.strip()
59
60 ## Parse the command line
61 for op in sys.argv[1:]:   # default shell/for list is $*, the options
62   if op in [ '-help', '--help', '-h' ]:
63     print '''Usage: configure [options]
64 Options:
65   --help                   show this help lines
66   --keep-temps             keep temporary files (for debug. purposes)
67   --without-latex-config   do not run LaTeX to determine configuration
68   --with-version-suffix=suffix suffix of binary installed files
69 '''
70     sys.exit(0)
71   elif op == '--without-latex-config':
72     lyx_check_config = False
73   elif op == '--keep-temps':
74     lyx_keep_temps = True
75   elif op[0:22] == '--with-version-suffix=':  # never mind if op is not long enough
76     version_suffix = op[23:]
77   else:
78     print "Unknown option", op
79     sys.exit(1)
80
81 ## Checking for some echo oddities (ignored)
82 ## The original script defines ac_n, ac_t and ac_c for
83 ## tab, newline etc, I just use python's print output.
84
85 ## I do not really know why this is useful, but we might as well keep it.
86 ### NLS nuisances.
87 ### Only set these to C if already set.  These must not be set unconditionally
88 ### because not all systems understand e.g. LANG=C (notably SCO).
89 ### Fixing LC_MESSAGES prevents Solaris sh from translating var values in `set'!
90 ### Non-C LC_CTYPE values break the ctype check.
91 ##
92 os.environ['LANG'] = os.getenv('LANG', 'C')
93 os.environ['LC'] = os.getenv('LC_ALL', 'C')
94 os.environ['LC_MESSAGE'] = os.getenv('LC_MESSAGE', 'C')
95 os.environ['LC_CTYPE'] = os.getenv('LC_CTYPE', 'C')
96
97 ## Guess the directory in which configure is located.
98 ac_prog = sys.argv[0]
99 srcdir = os.path.dirname(ac_prog)
100 if srcdir == '':
101   srcdir = '.'
102 if not os.path.isfile( os.path.join(srcdir, 'chkconfig.ltx') ):
103   print "configure: error: cannot find chkconfig.ltx script"
104   sys.exit(1)
105
106 ## Adjust PATH for Win32 (Cygwin)
107 #
108 use_cygwin_path_fix = ''
109 if sys.platform == 'cygwin':
110   from tempfile import mkstemp
111   fd, tmpfname = mkstemp(suffix='.ltx')
112   os.write(fd, r'''
113 \documentstyle{article}
114 \begin{document}\end{document}
115 ''')
116   os.close(fd)
117   inpname = cmdOutput('cygpath -w ' + tmpfname).replace('\\', '/')
118   # a wrapper file
119   wfd, wtmpfname = mkstemp(suffix='.ltx')
120   os.write(wfd, r'\input{' + inpname + '}' )
121   os.close(wfd)
122   if cmdOutput('latex ' + wtmpfname).find('Error') != -1:
123     print "configure: cygwin detected; path correction"
124     srcdir = cmdOutput('cygpath -w ' + srcdir).replace(r'\\', '')
125     print "srcdir = ", srcdir
126     use_cygwin_path_fix = 'true'
127   else:
128     print "configure: cygwin detected; path correction is not needed"
129     use_cygwin_path_fix = 'false'
130   removeFiles( [ tmpfname, wtmpfname ])
131
132 #### Create the build directories if necessary
133 for dir in ['bind', 'clipart', 'doc', 'examples', 'images', 'kbd', \
134   'layouts', 'scripts', 'templates', 'ui' ]:
135   if not os.path.isdir( dir ):
136     try:
137       os.mkdir( dir)
138     except:
139       print "Failed to create directory ", dir
140       sys.exit(1)
141
142 ## Write the first part of outfile
143 writeToFile(outfile, '''# This file has been automatically generated by LyX' lib/configure
144 # script. It contains default settings that have been determined by
145 # examining your system. PLEASE DO NOT MODIFY ANYTHING HERE! If you
146 # want to customize LyX, make a copy of the file LYXDIR/lyxrc as
147 # ~/.lyx/lyxrc and edit this file instead. Any setting in lyxrc will
148 # override the values given here.
149 ''')
150
151 ## Searching some useful programs
152 def checkProg(description, progs, rc_entry = [], path = [] ):
153   '''
154     This function will search a program in $PATH plus given path
155     If found, return directory and program name (not the options).
156
157     description: description of the program
158
159     progs: check programs, for each prog, the first word is used
160       for searching but the whole string is used to replace
161       %% for a rc_entry. So, feel free to add '$$i' etc for programs.
162
163     path: additional path
164
165     rc_entry: entry to outfile, can be emtpy, one pattern (%% for chosen
166        prog or 'none'), or one for each prog and 'none'.
167
168     NOTE: if you do not want 'none' entry to be added to the RC file,
169       specify an entry for each prog and use '' for 'none' entry.
170
171     FIXME: under windows, we should check registry instead of $PATH
172   '''
173   # one rc entry for each progs plus none entry
174   if len(rc_entry) > 1 and len(rc_entry) != len(progs) + 1:
175     print "rc entry should have one item or item for each prog and none."
176     sys.exit(2)
177   print 'checking for ' + description + '...'
178   ## print '(' + ','.join(progs) + ')',
179   for idx in range(len(progs)):
180     # ac_prog may have options, ac_word is the command name
181     ac_prog = progs[idx]
182     ac_word = ac_prog.split(' ')[0]
183     print '+checking for "' + ac_word + '"... ',
184     path = os.environ["PATH"].split(os.pathsep) + path
185     for ac_dir in path:
186       # check both ac_word and ac_word.exe (for windows system)
187       if os.path.isfile( os.path.join(ac_dir, ac_word) ) or \
188          os.path.isfile( os.path.join(ac_dir, ac_word + ".exe") ):
189         print ' yes'
190         # write rc entries for this command
191         if len(rc_entry) == 1:
192           addToRC(rc_entry[0].replace('%%', ac_prog))
193         elif len(rc_entry) > 1:
194           addToRC(rc_entry[idx].replace('%%', ac_prog))
195         return [ac_dir, ac_word]
196     # if not successful
197     print ' no'
198   # write rc entries for 'not found'
199   if len(rc_entry) > 0:  # the last one.
200     addToRC(rc_entry[-1].replace('%%', 'none'))
201   return ['', 'none']
202
203 # Find programs! Returned path is not used now
204 path, LATEX = checkProg( 'a Latex2e program', ['pplatex $$i', 'latex $$i', 'latex2e $$i'],
205   rc_entry = [ r'\converter latex      dvi        "%%" "latex"' ] )
206
207 # no latex
208 lyx_check_config = False
209 if LATEX != 'none':
210   # Check if latex is usable
211   writeToFile('chklatex.ltx', '''
212 \\nonstopmode\\makeatletter
213 \\ifx\\undefined\\documentclass\\else
214   \\message{ThisIsLaTeX2e}
215 \\fi
216 \\@@end
217 ''')
218   # run latex on chklatex.ltx and check result
219   if cmdOutput(LATEX + ' chklatex.ltx').find('ThisIsLaTeX2e') != -1:
220     lyx_check_config = True
221   else:
222     print "Latex not usable (not LaTeX2e) "
223   # remove temporary files
224   removeFiles(['chkltex.ltx', 'chklatex.log'])
225
226 checkProg('the pdflatex program', ['pdflatex $$i'],
227   rc_entry = [ r'\converter latex       pdf2    "%%" "latex"' ])
228
229 checkProg('a Tgif viewer and editor', ['tgif'],
230   rc_entry = [ r'\Format tgif       obj     Tgif                   "" "%%"      "%%"'])
231
232 checkProg('a FIG viewer and editor', ['xfig'],
233   rc_entry = [ r'\Format fig        fig     FIG                    "" "%%"      "%%"'] )
234
235 checkProg('a Grace viewer and editor', ['xmgrace'],
236   rc_entry = [  r'\Format agr   agr     Grace  "" "%%" "%%"' ] )
237
238 checkProg('a FEN viewer and editor', ['xboard -lpf $$i -mode EditPosition'],
239   rc_entry = [ r'\Format fen        fen     FEN                    "" "%%"      "%%"' ])
240
241 path, iv = checkProg('a raster image viewer', ['xv', 'kview', 'gimp'])
242 path, ie = checkProg('a raster image editor', ['gimp'])
243 addToRC(r'''\Format bmp        bmp     BMP  "" "%s"     "%s"
244 \Format gif        gif     GIF                    "" "%s"       "%s"
245 \Format jpg        jpg     JPEG                   "" "%s"       "%s"
246 \Format pbm        pbm     PBM                    "" "%s"       "%s"
247 \Format pgm        pgm     PGM                    "" "%s"       "%s"
248 \Format png        png     PNG                    "" "%s"       "%s"
249 \Format ppm        ppm     PPM                    "" "%s"       "%s"
250 \Format tiff       tif     TIFF                   "" "%s"       "%s"
251 \Format xbm        xbm     XBM                    "" "%s"       "%s"
252 \Format xpm        xpm     XPM                    "" "%s"       "%s"''' % \
253 (iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie) )
254
255 checkProg('a text editor', ['xemacs', 'gvim', 'kedit', 'kwrite', 'kate', \
256   'nedit', 'gedit', 'notepad'],
257   rc_entry = [
258     r'''\Format asciichess asc    "Plain text (chess output)"  "" ""    "%%"
259 \Format asciiimage asc    "Plain text (image)"         "" ""    "%%"
260 \Format asciixfig  asc    "Plain text (Xfig output)"   "" ""    "%%"
261 \Format dateout    tmp    "date (output)"         "" "" "%%"
262 \Format docbook    sgml    DocBook                B  "" "%%"
263 \Format docbook-xml xml   "Docbook (XML)"         "" "" "%%"
264 \Format literate   nw      NoWeb                  N  "" "%%"
265 \Format latex      tex     LaTeX                  L  "" "%%"
266 \Format linuxdoc   sgml    LinuxDoc               x  "" "%%"
267 \Format text       txt    "Plain text"            a  "" "%%"
268 \Format textparagraph txt "Plain text (paragraphs)"    "" ""    "%%"''' ])
269
270 checkProg('a LaTeX -> LyX converter', [os.path.join('..','src','tex2lyx','tex2lyx') + ' -f $$i $$o', \
271   'tex2lyx' +  version_suffix + ' -f $$i $$o' ],
272   rc_entry = [ r'\converter latex      lyx        "%%" ""' ])
273
274 checkProg('a Noweb -> LyX converter', ['noweb2lyx' + version_suffix + ' $$i $$o'], path = ['./reLyX'],
275   rc_entry = [ r'\converter literate   lyx        "%%" ""' ])
276
277 checkProg('a Noweb -> LaTeX converter', ['noweave' + version_suffix + ' -delay -index $$i > $$o'],
278   path = ['./reLyX'], rc_entry = [ r'\converter literate        latex   "%%" ""' ])
279
280 checkProg('a HTML -> LaTeX converter', ['html2latex $$i'],
281   rc_entry = [ r'\converter html       latex      "%%" ""' ])
282
283 checkProg('a MSWord -> LaTeX converter', ['wvCleanLatex $$i $$o'],
284   rc_entry = [ r'\converter word       latex      "%%" ""' ])
285
286 checkProg('a LaTeX -> MS Word converter', ["htlatex $$i 'html,word' 'symbol/!' '-cvalidate'"],
287   rc_entry = [  r'\converter latex      wordhtml        "%%"  ""' ])
288
289 # FIXME: image_command is not used anywhere.
290 checkProg('Image converter', ['convert $$i $$o'])
291
292 checkProg('an OpenOffice.org -> LaTeX converter', ['w2l -clean $$i'],
293   rc_entry = [r'\converter sxw      latex        "%%"   ""' ])
294
295 checkProg('an LaTeX -> OpenOffice.org LaTeX converter', ['oolatex $$i', 'oolatex.sh $$i'],
296   rc_entry = [r'\converter latex      sxw        "%%"   "latex"' ])
297
298 #checkProg('a Postscript interpreter', ['gs'],
299 #  rc_entry = [ r'\ps_command "%%"' ])
300
301 checkProg('a Postscript previewer', ['gsview32', 'gv', 'ghostview -swap', 'kghostview'],
302   rc_entry = [
303     r'''\Format eps        eps     EPS                    "" "%%"       ""
304 \Format ps         ps      Postscript             t  "%%"       ""''' ])
305
306 checkProg('a PDF previewer', ['acrobat', 'acrord32', 'gsview32', \
307   'acroread', 'gv', 'ghostview', 'xpdf', 'kpdf', 'kghostview'],
308   rc_entry = [ r'''\Format pdf        pdf    "PDF (ps2pdf)"          P  "%%"    ""
309 \Format pdf2       pdf    "PDF (pdflatex)"        F  "%%"       ""
310 \Format pdf3       pdf    "PDF (dvipdfm)"         m  "%%"       ""''' ])
311
312 checkProg('a DVI previewer', ['xdvi', 'windvi', 'yap', 'kdvi'],
313   rc_entry = [ r'\Format dvi        dvi     DVI                    D  "%%"      ""' ])
314
315 checkProg('a HTML previewer', ['mozilla file://$$p$$i', 'netscape'],
316   rc_entry = [ r'\Format html       html    HTML                   H  "%%"      ""' ])
317
318 checkProg('a PS to PDF converter', ['ps2pdf13 $$i'],
319   rc_entry = [ r'\converter ps         pdf        "%%"  ""' ])
320
321 checkProg('a DVI to PS converter', ['dvips -o $$o $$i'],
322   rc_entry = [ r'\converter dvi        ps         "%%"  ""' ])
323
324 checkProg('a DVI to PDF converter', ['dvipdfm $$i'],
325   rc_entry = [ r'\converter dvi        pdf3       "%%" ""' ])
326
327 ### We have a script to convert previewlyx to ppm
328 addToRC(r'\converter lyxpreview ppm     "python $$s/scripts/lyxpreview2bitmap.py"       ""')
329
330 path, dvipng = checkProg('dvipng', ['dvipng'])
331 if dvipng == "dvipng":
332   addToRC(r'\converter lyxpreview       png     "python $$s/scripts/lyxpreview2bitmap.py"       ""')
333 else:
334   addToRC(r'\converter lyxpreview       png     ""      ""')
335
336 checkProg('a *roff formatter', ['groff', 'nroff'],
337   rc_entry = [
338     r'\ascii_roff_command "groff -t -Tlatin1 $$FName"',
339     r'\ascii_roff_command "tbl $$FName | nroff"',
340     r'\ascii_roff_command "none"' ])
341
342 checkProg('ChkTeX', ['chktex -n1 -n3 -n6 -n9 -n22 -n25 -n30 -n38'],
343   rc_entry = [ r'\chktex_command "%%"' ])
344
345 checkProg('a spellchecker', ['ispell'],
346   rc_entry = [ r'\spell_command "%%"' ])
347
348 ## FIXME: OCTAVE is not used anywhere
349 path, OCTAVE = checkProg('Octave', ['octave'])
350
351 ## FIXME: MAPLE is not used anywhere
352 path, MAPLE = checkProg('Maple', ['maple'])
353
354 checkProg('a fax program', ['kdeprintfax $$i', 'ksendfax $$i'],
355   rc_entry = [ r'\converter ps  fax     "%%" ""'])
356
357 path, LINUXDOC = checkProg('SGML-tools 1.x (LinuxDoc)', ['sgml2lyx'],
358   rc_entry = [
359     r'''\converter linuxdoc     lyx "sgml2lyx $$i" ""
360 \converter linuxdoc     latex   "sgml2latex $$i" ""
361 \converter linuxdoc     dvi     "sgml2latex -o dvi $$i" ""
362 \converter linuxdoc     html    "sgml2html $$i" "" ''',
363     r'''\converter      linuxdoc lyx "none" ""
364 \converter linuxdoc     latex "none" ""
365 \converter linuxdoc     dvi "none" ""
366 \converter linuxdoc     html "none" "" ''' ])
367
368 if LINUXDOC != 'none':
369   chk_linuxdoc = 'yes'
370   bool_linuxdoc = 'true'
371   linuxdoc_cmd = '\\def\\haslinuxdoc{yes}'
372 else:
373   chk_linuxdoc = 'no'
374   bool_linuxdoc = 'false'
375   linuxdoc_cmd = ''
376
377 path, DOCBOOK = checkProg('SGML-tools 2.x (DocBook) or db2x scripts', ['sgmltools', 'db2dvi'],
378   rc_entry = [
379     r'''\converter docbook    dvi        "sgmltools -b dvi $$i" ""
380 \converter docbook    html       "sgmltools -b html $$i" ""''',
381     r'''\converter docbook    dvi        "db2dvi $$i" ""
382 \converter docbook    html       "db2html $$i" ""''',
383     r'''\converter docbook    dvi        "none" ""
384 \converter docbook    html       "none" ""'''])
385
386 if DOCBOOK != 'none':
387   chk_docbook = 'yes'
388   bool_docbook = 'true'
389   docbook_cmd = '\\def\\hasdocbook{yes}'
390 else:
391   chk_docbook = 'no'
392   bool_docbook = 'false'
393   docbook_cmd = ''
394
395 checkProg('a spool command', ['lp', 'lpr'],
396   rc_entry = [
397     r'''\print_spool_printerprefix "-d "
398 \print_spool_command "lp"''',
399     r'''\print_spool_printerprefix "-P",
400 \print_spool_command "lpr"''',
401     ''])
402
403 checkProg('a LaTeX -> HTML converter', ['htlatex $$i', 'tth  -t -e2 -L$$b < $$i > $$o', \
404   'latex2html -no_subdir -split 0 -show_section_numbers $$i', 'hevea -s $$i'],
405   rc_entry = [ r'\converter latex      html       "%%" "originaldir,needaux"' ])
406
407 # Add the rest of the entries (no checkProg is required)
408 addToRC(r'''\Format date       ""     "date command"          "" ""     ""
409 \Format fax        ""      Fax                    "" "" ""
410 \Format lyx        lyx     LyX                    "" "lyx"      "lyx"
411 \Format lyxpreview lyxpreview "LyX Preview"       "" "" ""
412 \Format pdftex     pdftex_t PDFTEX                "" "" ""
413 \Format program    ""      Program                "" "" ""
414 \Format pstex      pstex_t PSTEX                  "" "" ""
415 \Format sxw        sxw    "OpenOffice.Org Writer" O  "" ""
416 \Format word       doc    "MS Word"               W  "" ""
417 \Format wordhtml   html   "MS Word (HTML)"        "" ""        ""
418 \converter date       dateout    "date +%d-%m-%Y > $$o" ""
419 \converter docbook    docbook-xml "cp $$i $$o" "xml"
420 \converter fen        asciichess "python $$s/scripts/fen2ascii.py $$i $$o"      ""
421 \converter fig        pdftex     "sh $$s/scripts/fig2pdftex.sh $$i $$o" ""
422 \converter fig        pstex      "sh $$s/scripts/fig2pstex.sh $$i $$o"  ""
423 \copier    fig        "sh $$s/scripts/fig_copy.sh $$i $$o"
424 \copier    pstex      "python $$s/scripts/tex_copy.py $$i $$o $$l"
425 \copier    pdftex     "python $$s/scripts/tex_copy.py $$i $$o $$l"
426 ''')
427
428 ## Explore the LaTeX configuration
429 print 'checking LaTeX configuration... ',
430 ## First, remove the files that we want to re-create
431 removeFiles(['textclass.lst', 'packages.lst', 'chkconfig.sed'])
432
433 if not lyx_check_config:
434   print ' default values'
435   print '+checking list of textclasses... '
436   tx = open('textclass.lst', 'w')
437   tx.write('''
438 # This file declares layouts and their associated definition files
439 # (include dir. relative to the place where this file is).
440 # It contains only default values, since chkconfig.ltx could not be run
441 # for some reason. Run ./configure if you need to update it after a
442 # configuration change.
443 ''')
444   # build the list of available layout files and convert it to commands
445   # for chkconfig.ltx
446   foundClasses = []
447   # sed filters
448   # FIXME: this is a direct translation of the sed commands
449   # There may be more efficient methods
450   p1 = re.compile(r'\Declare(LaTeX|DocBook|LinuxDoc)Class')
451   p2 = re.compile(r'^.*\DeclareLaTeXClass *(.*)')
452   p3 = re.compile(r'^.*\DeclareDocBookClass *(.*)')
453   p4 = re.compile(r'^.*\DeclareLinuxDocClass *(.*)')
454   p5 = re.compile(r'\[([^,]*),[^]]*\]')
455   p6 = re.compile('^{')
456   p7 = re.compile(r'\[([^]]*)\] *{([^}]*)}')
457   for file in glob.glob( os.path.join('layouts', '*.layout') ) + \
458     glob.glob( os.path.join(srcdir, 'layouts', '*.layout' ) ) :
459     # valid file?
460     if not os.path.isfile(file): continue
461     # get stuff between /xxxx.layout .
462     classname = file.split(os.sep)[-1].split('.')[0]
463     #  tr ' -' '__'`
464     cleanclass = classname.replace(' ', '_')
465     cleanclass = cleanclass.replace('-', '_')
466     # make sure the same class is not considered twice
467     if foundClasses.count(cleanclass) == 0: # not found before
468       foundClasses.append(cleanclass)
469       # The sed commands below are a bit scary. Here is what they do:
470       # 1-3: remove the \DeclareFOO macro and add the correct boolean
471       #      at the end of the line telling whether the class is
472       #      available
473       # 4: if the macro had an optional argument with several
474       #    parameters, only keep the first one
475       # 5: if the macro did not have an optional argument, provide one
476       #    (equal to the class name)
477       # 6: remove brackets and replace with correctly quoted entries
478       #     grep '\\Declare\(LaTeX\|DocBook\|LinuxDoc\)Class' "$file" \
479       #      | sed -e 's/^.*\DeclareLaTeXClass *\(.*\)/\1 "false"/' \
480       #     -e 's/^.*\DeclareDocBookClass *\(.*\)/\1 "'$bool_docbook'"/' \
481       #     -e 's/^.*\DeclareLinuxDocClass *\(.*\)/\1 "'$bool_linuxdoc'"/' \
482       #     -e 's/\[\([^,]*\),[^]]*\]/[\1]/' \
483       #     -e 's/^{/['$class']{/' \
484       #     -e 's/\[\([^]]*\)\] *{\([^}]*\)}/"'$class'" "\1" "\2"/' \
485       #                   >>textclass.lst
486       for line in open(file).readlines():
487         if p1.search(line) == None:
488           continue
489         line = p2.sub(r'\1 "false"', line)
490         line = p3.sub(r'\1 "' + bool_docbook + '"', line)
491         line = p4.sub(r'\1 "' + bool_linuxdoc + '"', line)
492         line = p5.sub(r'[\1]', line)
493         line = p6.sub("[" + classname + "]{", line)
494         line = p7.sub( "'" + classname + "'" + r'"\1" "\2"', line)
495         tx.write(line)
496         break       # one file, one line.
497   tx.close()
498   print '\tdone'
499 else:
500   print '\tauto'
501   removeFiles(['wrap_chkconfig.ltx', 'chkconfig.vars', \
502     'chkconfig.classes', 'chklayouts.tex'])
503   rmcopy = False
504   if not os.path.isfile( 'chkconfig.ltx' ):
505     shutil.copy( os.path.join(srcdir, 'chkconfig.ltx'),  'chkconfig.ltx' )
506     rmcopy = True
507   writeToFile('wrap_chkconfig.ltx', '%s\n%s\n\\input{chkconfig.ltx}\n' \
508     % (linuxdoc_cmd, docbook_cmd) )
509   cl = open('chklayouts.tex', 'w')
510   ## Construct the list of classes to test for.
511   # build the list of available layout files and convert it to commands
512   # for chkconfig.ltx
513   p1 = re.compile(r'\Declare(LaTeX|DocBook|LinuxDoc)Class')
514   for file in glob.glob( os.path.join('layouts', '*.layout') ) + \
515     glob.glob( os.path.join(srcdir, 'layouts', '*.layout' ) ) :
516     if not os.path.isfile(file): continue
517     classname = file.split(os.sep)[-1].split('.')[0]
518     for line in open(file).readlines():
519       if p1.search(line) == None:
520         continue
521       if line[0] != '#':
522         print "Wrong input layout file with line '" + line
523         sys.exit(3)
524       cl.write( "\\TestDocClass{%s}{%s}\n" % \
525         ( classname, line[1:].strip() ) )
526       break
527   cl.close()
528   #
529   # we have chklayouts.tex, then process it
530   for line in cmdOutput(LATEX + ' wrap_chkconfig.ltx').splitlines():
531     if re.match('^\+', line):
532       print line
533   #
534   #  evalulate lines in chkconfig.vars?
535   # is it really necessary?
536   for line in open('chkconfig.vars').readlines():
537     exec( re.sub('-', '_', line) )
538   if rmcopy:   # remove the copied file
539     removeFiles( [ 'chkconfig.ltx' ] )
540
541 ### Do we have all the files we need? Useful if latex did not run
542
543 ### if chkconfig.sed does not exist (because LaTeX did not run),
544 ### then provide a standard version.
545 if not os.path.isfile('chkconfig.sed'):
546   writeToFile('chkconfig.sed', '##s/@.*@/???/g\n')
547
548 print "creating packages.lst"
549 ### if packages.lst does not exist (because LaTeX did not run),
550 ### then provide a standard version.
551 if not os.path.isfile('packages.lst'):
552   writeToFile('packages.lst', '''
553 ### This file should contain the list of LaTeX packages that have been
554 ### recognized by LyX. Unfortunately, since configure could not find
555 ### your LaTeX2e program, the tests have not been run. Run ./configure
556 ### if you need to update it after a configuration change.
557 ''')
558
559 print 'creating doc/LaTeXConfig.lyx'
560 #
561 # This is originally done by sed, using a
562 # tex-generated file chkconfig.sed
563 ##sed -f chkconfig.sed ${srcdir}/doc/LaTeXConfig.lyx.in
564 ##  >doc/LaTeXConfig.lyx
565 # Now, we have to do it by hand (python).
566 #
567 # add to chekconfig.sed
568 writeToFile('chkconfig.sed', '''s!@chk_linuxdoc@!%s!g
569 s!@chk_docbook@!%s!g
570 ''' % (chk_linuxdoc, chk_docbook) , append=True)
571 # process this sed file!!!!
572 lyxin = open( os.path.join(srcdir, 'doc', 'LaTeXConfig.lyx.in')).readlines()
573 # get the rules
574 p = re.compile(r's!(.*)!(.*)!g')
575 # process each sed replace.
576 for sed in open('chkconfig.sed').readlines():
577   try:
578     fr, to = p.match(sed).groups()
579     for line in range(len(lyxin)):
580       lyxin[line] = lyxin[line].replace(fr, to)
581   except:  # wrong sed entry?
582     print "Wrong sed entry in chkconfig.sed:", sed
583     sys.exit(4)
584
585 writeToFile( os.path.join('doc', 'LaTeXConfig.lyx'),
586   ''.join(lyxin))
587
588 ### Let's check whether spaces are allowed in TeX file names
589 print "Checking whether TeX allows spaces in file names... ",
590 tex_allows_spaces = 'false'
591 if not lyx_check_config:
592   writeToFile('a b.tex', r'\message{working^^J}' )
593   # FIXME: the bsh version uses < /dev/null which is not portable.
594   # Can anyone confirm if this option (-interaction) is available
595   # at other flavor of latex as well? (MikTex/win, Web2C/linux are fine.) 
596   if ''.join(cmdOutput('latex -interaction=nonstopmode "a b"')).find('working') != -1:
597     print 'yes'
598     tex_allows_spaces = 'true'
599   else:
600     print 'no'
601     tex_allows_spaces = 'false'
602   removeFiles( [ 'a b.tex', 'a b.log', 'texput.log' ])
603
604 checkProg('a FIG -> EPS/PPM converter', ['fig2dev'],
605   rc_entry = [
606     r'''\converter fig eps "fig2dev -L eps $$i $$o" ""
607 \converter fig  ppm     "fig2dev -L ppm $$i $$o" ""
608 \converter fig  png     "fig2dev -L png $$i $$o" ""''',
609     ''])
610
611 checkProg('a TIFF -> PS converter', ['tiff2ps $$i > $$o'],
612   rc_entry = [ r'\converter tiff        eps     "%%" ""', ''])
613
614 checkProg('a TGIF -> EPS/PPM converter', ['tgif'],
615   rc_entry = [
616     r'''\converter tgif eps "tgif -stdout -print -color -eps $$i > $$o" ""
617 \converter tgif pdf     "tgif -stdout -print -color -pdf $$i > $$o" ""''',
618     ''])
619
620 checkProg('a EPS -> PDF converter', ['epstopdf'],
621   rc_entry = [ r'\converter eps       pdf      "epstopdf --outfile=$$o $$i" ""', ''])
622
623 path, GRACE = checkProg('a  Grace -> Image converter', ['gracebat'],
624   rc_entry = [
625     r'''\converter agr  eps     "gracebat -hardcopy -printfile $$o -hdevice EPS $$i 2>/dev/null" ""
626 \converter agr  png     "gracebat -hardcopy -printfile $$o -hdevice PNG $$i 2>/dev/null" ""
627 \converter agr  jpg     "gracebat -hardcopy -printfile $$o -hdevice JPEG $$i 2>/dev/null" ""
628 \converter agr  ppm     "gracebat -hardcopy -printfile $$o -hdevice PNM $$i 2>/dev/null" ""''',
629     ''])
630
631 # chk_fontenc may not exist 
632 try:
633   addToRC(r'\font_encoding "%s"' % chk_fontenc)
634 except:
635   pass
636 addToRC(r'\tex_allows_spaces ' + tex_allows_spaces)
637
638 if use_cygwin_path_fix == 'true':
639   addToRC(r'\cygwin_path_fix_needed ' + use_cygwin_path_fix)
640
641 # Remove superfluous files if we are not writing in the main lib
642 # directory
643 for file in [outfile, 'textclass.lst', 'packages.lst', \
644   'doc/LaTeXConfig.lyx']:
645   try:
646     # we rename the file first, so that we avoid comparing a file with itself
647     os.rename(file, file + '.new')
648     syscfg = open( os.path.join(srcdir, file) ).read()
649     mycfg = open( file + '.new').read()
650     if mycfg == syscfg:
651       print "removing ", file, " which is identical to the system global version"
652       removeFiles( [file + '.new'] )
653     else:
654       os.rename( file + '.new', file )
655   except:  # use local version if anthing goes wrong.
656     os.rename( file + '.new', file )
657     pass
658
659 # Final clean-up
660 if not lyx_keep_temps:
661   removeFiles(['chkconfig.sed', 'chkconfig.vars',  \
662     'wrap_chkconfig.ltx', 'wrap_chkconfig.log', \
663     'chklayouts.tex', 'missfont.log'])
664