]> git.lyx.org Git - lyx.git/blob - lib/configure.py
fb26a264a1946065b6b3b962f9d7aa2c4a57b18d
[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[22:]
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(['chklatex.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 -delay -index $$i > $$o'],
278   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                    "" "" ""
411 \Format lyx13x     lyx13  "LyX 1.3.x"             "" "" ""
412 \Format lyxpreview lyxpreview "LyX Preview"       "" "" ""
413 \Format pdftex     pdftex_t PDFTEX                "" "" ""
414 \Format program    ""      Program                "" "" ""
415 \Format pstex      pstex_t PSTEX                  "" "" ""
416 \Format sxw        sxw    "OpenOffice.Org Writer" O  "" ""
417 \Format word       doc    "MS Word"               W  "" ""
418 \Format wordhtml   html   "MS Word (HTML)"        "" ""        ""
419 \converter date       dateout    "date +%d-%m-%Y > $$o" ""
420 \converter docbook    docbook-xml "cp $$i $$o"  "xml"
421 \converter fen        asciichess "python $$s/scripts/fen2ascii.py $$i $$o"      ""
422 \converter fig        pdftex     "sh $$s/scripts/fig2pdftex.sh $$i $$o" ""
423 \converter fig        pstex      "sh $$s/scripts/fig2pstex.sh $$i $$o"  ""
424 \converter lyx        lyx13x     "python $$s/lyx2lyx/lyx2lyx -t 221 $$i > $$o"  ""
425 \copier    fig        "sh $$s/scripts/fig_copy.sh $$i $$o"
426 \copier    pstex      "python $$s/scripts/tex_copy.py $$i $$o $$l"
427 \copier    pdftex     "python $$s/scripts/tex_copy.py $$i $$o $$l"
428 ''')
429
430 ## Explore the LaTeX configuration
431 print 'checking LaTeX configuration... ',
432 ## First, remove the files that we want to re-create
433 removeFiles(['textclass.lst', 'packages.lst', 'chkconfig.sed'])
434
435 if not lyx_check_config:
436   print ' default values'
437   print '+checking list of textclasses... '
438   tx = open('textclass.lst', 'w')
439   tx.write('''
440 # This file declares layouts and their associated definition files
441 # (include dir. relative to the place where this file is).
442 # It contains only default values, since chkconfig.ltx could not be run
443 # for some reason. Run ./configure if you need to update it after a
444 # configuration change.
445 ''')
446   # build the list of available layout files and convert it to commands
447   # for chkconfig.ltx
448   foundClasses = []
449   # sed filters
450   # FIXME: this is a direct translation of the sed commands
451   # There may be more efficient methods
452   p1 = re.compile(r'\Declare(LaTeX|DocBook|LinuxDoc)Class')
453   p2 = re.compile(r'^.*\DeclareLaTeXClass *(.*)')
454   p3 = re.compile(r'^.*\DeclareDocBookClass *(.*)')
455   p4 = re.compile(r'^.*\DeclareLinuxDocClass *(.*)')
456   p5 = re.compile(r'\[([^,]*),[^]]*\]')
457   p6 = re.compile('^{')
458   p7 = re.compile(r'\[([^]]*)\] *{([^}]*)}')
459   for file in glob.glob( os.path.join('layouts', '*.layout') ) + \
460     glob.glob( os.path.join(srcdir, 'layouts', '*.layout' ) ) :
461     # valid file?
462     if not os.path.isfile(file): continue
463     # get stuff between /xxxx.layout .
464     classname = file.split(os.sep)[-1].split('.')[0]
465     #  tr ' -' '__'`
466     cleanclass = classname.replace(' ', '_')
467     cleanclass = cleanclass.replace('-', '_')
468     # make sure the same class is not considered twice
469     if foundClasses.count(cleanclass) == 0: # not found before
470       foundClasses.append(cleanclass)
471       # The sed commands below are a bit scary. Here is what they do:
472       # 1-3: remove the \DeclareFOO macro and add the correct boolean
473       #      at the end of the line telling whether the class is
474       #      available
475       # 4: if the macro had an optional argument with several
476       #    parameters, only keep the first one
477       # 5: if the macro did not have an optional argument, provide one
478       #    (equal to the class name)
479       # 6: remove brackets and replace with correctly quoted entries
480       #     grep '\\Declare\(LaTeX\|DocBook\|LinuxDoc\)Class' "$file" \
481       #      | sed -e 's/^.*\DeclareLaTeXClass *\(.*\)/\1 "false"/' \
482       #     -e 's/^.*\DeclareDocBookClass *\(.*\)/\1 "'$bool_docbook'"/' \
483       #     -e 's/^.*\DeclareLinuxDocClass *\(.*\)/\1 "'$bool_linuxdoc'"/' \
484       #     -e 's/\[\([^,]*\),[^]]*\]/[\1]/' \
485       #     -e 's/^{/['$class']{/' \
486       #     -e 's/\[\([^]]*\)\] *{\([^}]*\)}/"'$class'" "\1" "\2"/' \
487       #                   >>textclass.lst
488       for line in open(file).readlines():
489         if p1.search(line) == None:
490           continue
491         line = p2.sub(r'\1 "false"', line)
492         line = p3.sub(r'\1 "' + bool_docbook + '"', line)
493         line = p4.sub(r'\1 "' + bool_linuxdoc + '"', line)
494         line = p5.sub(r'[\1]', line)
495         line = p6.sub("[" + classname + "]{", line)
496         line = p7.sub( "'" + classname + "'" + r'"\1" "\2"', line)
497         tx.write(line)
498         break       # one file, one line.
499   tx.close()
500   print '\tdone'
501 else:
502   print '\tauto'
503   removeFiles(['wrap_chkconfig.ltx', 'chkconfig.vars', \
504     'chkconfig.classes', 'chklayouts.tex'])
505   rmcopy = False
506   if not os.path.isfile( 'chkconfig.ltx' ):
507     shutil.copy( os.path.join(srcdir, 'chkconfig.ltx'),  'chkconfig.ltx' )
508     rmcopy = True
509   writeToFile('wrap_chkconfig.ltx', '%s\n%s\n\\input{chkconfig.ltx}\n' \
510     % (linuxdoc_cmd, docbook_cmd) )
511   ## Construct the list of classes to test for.
512   # build the list of available layout files and convert it to commands
513   # for chkconfig.ltx
514   p1 = re.compile(r'\Declare(LaTeX|DocBook|LinuxDoc)Class')
515   testclasses = list()
516   for file in glob.glob( os.path.join('layouts', '*.layout') ) + \
517     glob.glob( os.path.join(srcdir, 'layouts', '*.layout' ) ) :
518     if not os.path.isfile(file): continue
519     classname = file.split(os.sep)[-1].split('.')[0]
520     for line in open(file).readlines():
521       if p1.search(line) == None:
522         continue
523       if line[0] != '#':
524         print "Wrong input layout file with line '" + line
525         sys.exit(3)
526       testclasses.append("\\TestDocClass{%s}{%s}" % (classname, line[1:].strip()))
527       break
528   testclasses.sort()
529   cl = open('chklayouts.tex', 'w')
530   for line in testclasses:
531     cl.write(line + '\n')
532   cl.close()
533   #
534   # we have chklayouts.tex, then process it
535   for line in cmdOutput(LATEX + ' wrap_chkconfig.ltx').splitlines():
536     if re.match('^\+', line):
537       print line
538   #
539   #  evalulate lines in chkconfig.vars?
540   # is it really necessary?
541   for line in open('chkconfig.vars').readlines():
542     exec( re.sub('-', '_', line) )
543   if rmcopy:   # remove the copied file
544     removeFiles( [ 'chkconfig.ltx' ] )
545
546 ### Do we have all the files we need? Useful if latex did not run
547
548 ### if chkconfig.sed does not exist (because LaTeX did not run),
549 ### then provide a standard version.
550 if not os.path.isfile('chkconfig.sed'):
551   writeToFile('chkconfig.sed', '##s/@.*@/???/g\n')
552
553 print "creating packages.lst"
554 ### if packages.lst does not exist (because LaTeX did not run),
555 ### then provide a standard version.
556 if not os.path.isfile('packages.lst'):
557   writeToFile('packages.lst', '''
558 ### This file should contain the list of LaTeX packages that have been
559 ### recognized by LyX. Unfortunately, since configure could not find
560 ### your LaTeX2e program, the tests have not been run. Run ./configure
561 ### if you need to update it after a configuration change.
562 ''')
563
564 print 'creating doc/LaTeXConfig.lyx'
565 #
566 # This is originally done by sed, using a
567 # tex-generated file chkconfig.sed
568 ##sed -f chkconfig.sed ${srcdir}/doc/LaTeXConfig.lyx.in
569 ##  >doc/LaTeXConfig.lyx
570 # Now, we have to do it by hand (python).
571 #
572 # add to chekconfig.sed
573 writeToFile('chkconfig.sed', '''s!@chk_linuxdoc@!%s!g
574 s!@chk_docbook@!%s!g
575 ''' % (chk_linuxdoc, chk_docbook) , append=True)
576 # process this sed file!!!!
577 lyxin = open( os.path.join(srcdir, 'doc', 'LaTeXConfig.lyx.in')).readlines()
578 # get the rules
579 p = re.compile(r's!(.*)!(.*)!g')
580 # process each sed replace.
581 for sed in open('chkconfig.sed').readlines():
582   try:
583     fr, to = p.match(sed).groups()
584     for line in range(len(lyxin)):
585       lyxin[line] = lyxin[line].replace(fr, to)
586   except:  # wrong sed entry?
587     print "Wrong sed entry in chkconfig.sed:", sed
588     sys.exit(4)
589
590 writeToFile( os.path.join('doc', 'LaTeXConfig.lyx'),
591   ''.join(lyxin))
592
593 ### Let's check whether spaces are allowed in TeX file names
594 tex_allows_spaces = 'false'
595 if lyx_check_config:
596   print "Checking whether TeX allows spaces in file names... ",
597   writeToFile('a b.tex', r'\message{working^^J}' )
598   # FIXME: the bsh version uses < /dev/null which is not portable.
599   # Can anyone confirm if this option (-interaction) is available
600   # at other flavor of latex as well? (MikTex/win, Web2C/linux are fine.) 
601   if ''.join(cmdOutput(LATEX + ' -interaction=nonstopmode "a b"')).find('working') != -1:
602     print 'yes'
603     tex_allows_spaces = 'true'
604   else:
605     print 'no'
606     tex_allows_spaces = 'false'
607   removeFiles( [ 'a b.tex', 'a b.log', 'texput.log' ])
608
609 checkProg('a FIG -> EPS/PPM converter', ['fig2dev'],
610   rc_entry = [
611     r'''\converter fig        eps        "fig2dev -L eps $$i $$o"       ""
612 \converter fig        ppm        "fig2dev -L ppm $$i $$o"       ""
613 \converter fig        png        "fig2dev -L png $$i $$o"       ""''',
614     ''])
615
616 checkProg('a TIFF -> PS converter', ['tiff2ps $$i > $$o'],
617   rc_entry = [ r'\converter tiff       eps        "%%"  ""', ''])
618
619 checkProg('a TGIF -> EPS/PPM converter', ['tgif'],
620   rc_entry = [
621     r'''\converter tgif       eps        "tgif -stdout -print -color -eps $$i > $$o"    ""
622 \converter tgif       pdf        "tgif -stdout -print -color -pdf $$i > $$o"    ""''',
623     ''])
624
625 checkProg('a EPS -> PDF converter', ['epstopdf'],
626   rc_entry = [ r'\converter eps        pdf        "epstopdf --outfile=$$o $$i"  ""', ''])
627
628 path, GRACE = checkProg('a Grace -> Image converter', ['gracebat'],
629   rc_entry = [
630     r'''\converter agr        eps        "gracebat -hardcopy -printfile $$o -hdevice EPS $$i 2>/dev/null"       ""
631 \converter agr        png        "gracebat -hardcopy -printfile $$o -hdevice PNG $$i 2>/dev/null"       ""
632 \converter agr        jpg        "gracebat -hardcopy -printfile $$o -hdevice JPEG $$i 2>/dev/null"      ""
633 \converter agr        ppm        "gracebat -hardcopy -printfile $$o -hdevice PNM $$i 2>/dev/null"       ""''',
634     ''])
635
636 # chk_fontenc may not exist 
637 try:
638   addToRC(r'\font_encoding "%s"' % chk_fontenc)
639 except:
640   pass
641 addToRC(r'\tex_allows_spaces ' + tex_allows_spaces)
642
643 if use_cygwin_path_fix == 'true':
644   addToRC(r'\cygwin_path_fix_needed ' + use_cygwin_path_fix)
645
646 # Remove superfluous files if we are not writing in the main lib
647 # directory
648 for file in [outfile, 'textclass.lst', 'packages.lst', \
649   'doc/LaTeXConfig.lyx']:
650   try:
651     # we rename the file first, so that we avoid comparing a file with itself
652     os.rename(file, file + '.new')
653     syscfg = open( os.path.join(srcdir, file) ).read()
654     mycfg = open( file + '.new').read()
655     if mycfg == syscfg:
656       print "removing ", file, " which is identical to the system global version"
657       removeFiles( [file + '.new'] )
658     else:
659       os.rename( file + '.new', file )
660   except:  # use local version if anthing goes wrong.
661     os.rename( file + '.new', file )
662     pass
663
664 # Final clean-up
665 if not lyx_keep_temps:
666   removeFiles(['chkconfig.sed', 'chkconfig.vars',  \
667     'wrap_chkconfig.ltx', 'wrap_chkconfig.log', \
668     'chklayouts.tex', 'missfont.log'])
669