]> git.lyx.org Git - lyx.git/blob - lib/configure.py
6e71430229334068eb960a41509825169fb0e7c1
[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 pdflatex   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    "TeX (latex)"           l  "" "%%"
266 \Format linuxdoc   sgml    LinuxDoc               x  "" "%%"
267 \Format pdflatex   tex    "TeX (pdflatex)"        "" "" "%%"
268 \Format text       txt    "Plain text"            a  "" "%%"
269 \Format textparagraph txt "Plain text (paragraphs)"    "" ""    "%%"''' ])
270
271 checkProg('a LaTeX -> LyX converter', [os.path.join('..','src','tex2lyx','tex2lyx') + ' -f $$i $$o', \
272   'tex2lyx' +  version_suffix + ' -f $$i $$o' ],
273   rc_entry = [ r'\converter latex      lyx        "%%"  ""' ])
274
275 checkProg('a Noweb -> LyX converter', ['noweb2lyx' + version_suffix + ' $$i $$o'], path = ['./reLyX'],
276   rc_entry = [ r'\converter literate   lyx        "%%"  ""' ])
277
278 checkProg('a Noweb -> LaTeX converter', ['noweave -delay -index $$i > $$o'],
279   rc_entry = [ r'\converter literate   latex      "%%"  ""' ])
280
281 checkProg('a HTML -> LaTeX converter', ['html2latex $$i'],
282   rc_entry = [ r'\converter html       latex      "%%"  ""' ])
283
284 checkProg('a MSWord -> LaTeX converter', ['wvCleanLatex $$i $$o'],
285   rc_entry = [ r'\converter word       latex      "%%"  ""' ])
286
287 checkProg('a LaTeX -> MS Word converter', ["htlatex $$i 'html,word' 'symbol/!' '-cvalidate'"],
288   rc_entry = [ r'\converter latex      wordhtml   "%%"  ""' ])
289
290 # FIXME: image_command is not used anywhere.
291 checkProg('Image converter', ['convert $$i $$o'])
292
293 checkProg('an OpenOffice.org -> LaTeX converter', ['w2l -clean $$i'],
294   rc_entry = [ r'\converter sxw        latex      "%%"  ""' ])
295
296 checkProg('an LaTeX -> OpenOffice.org LaTeX converter', ['oolatex $$i', 'oolatex.sh $$i'],
297   rc_entry = [ r'\converter latex      sxw        "%%"  "latex"' ])
298
299 #checkProg('a Postscript interpreter', ['gs'],
300 #  rc_entry = [ r'\ps_command "%%"' ])
301
302 checkProg('a Postscript previewer', ['gsview32', 'gv', 'ghostview -swap', 'kghostview'],
303   rc_entry = [
304     r'''\Format eps        eps     EPS                    "" "%%"       ""
305 \Format ps         ps      Postscript             t  "%%"       ""''' ])
306
307 checkProg('a PDF previewer', ['acrobat', 'acrord32', 'gsview32', \
308   'acroread', 'gv', 'ghostview', 'xpdf', 'kpdf', 'kghostview'],
309   rc_entry = [ r'''\Format pdf        pdf    "PDF (ps2pdf)"          P  "%%"    ""
310 \Format pdf2       pdf    "PDF (pdflatex)"        F  "%%"       ""
311 \Format pdf3       pdf    "PDF (dvipdfm)"         m  "%%"       ""''' ])
312
313 checkProg('a DVI previewer', ['xdvi', 'windvi', 'yap', 'kdvi'],
314   rc_entry = [ r'\Format dvi        dvi     DVI                    D  "%%"      ""' ])
315
316 checkProg('a HTML previewer', ['mozilla file://$$p$$i', 'netscape'],
317   rc_entry = [ r'\Format html       html    HTML                   H  "%%"      ""' ])
318
319 checkProg('a PS to PDF converter', ['ps2pdf13 $$i'],
320   rc_entry = [ r'\converter ps         pdf        "%%"  ""' ])
321
322 checkProg('a DVI to PS converter', ['dvips -o $$o $$i'],
323   rc_entry = [ r'\converter dvi        ps         "%%"  ""' ])
324
325 checkProg('a DVI to PDF converter', ['dvipdfm $$i'],
326   rc_entry = [ r'\converter dvi        pdf3       "%%"  ""' ])
327
328 ### We have a script to convert previewlyx to ppm
329 addToRC(r'\converter lyxpreview ppm        "python $$s/scripts/lyxpreview2bitmap.py"    ""')
330
331 path, dvipng = checkProg('dvipng', ['dvipng'])
332 if dvipng == "dvipng":
333   addToRC(r'\converter lyxpreview png        "python $$s/scripts/lyxpreview2bitmap.py"  ""')
334 else:
335   addToRC(r'\converter lyxpreview png        "" ""')
336
337 checkProg('a *roff formatter', ['groff', 'nroff'],
338   rc_entry = [
339     r'\ascii_roff_command "groff -t -Tlatin1 $$FName"',
340     r'\ascii_roff_command "tbl $$FName | nroff"',
341     r'\ascii_roff_command "none"' ])
342
343 checkProg('ChkTeX', ['chktex -n1 -n3 -n6 -n9 -n22 -n25 -n30 -n38'],
344   rc_entry = [ r'\chktex_command "%%"' ])
345
346 checkProg('a spellchecker', ['ispell'],
347   rc_entry = [ r'\spell_command "%%"' ])
348
349 ## FIXME: OCTAVE is not used anywhere
350 path, OCTAVE = checkProg('Octave', ['octave'])
351
352 ## FIXME: MAPLE is not used anywhere
353 path, MAPLE = checkProg('Maple', ['maple'])
354
355 checkProg('a fax program', ['kdeprintfax $$i', 'ksendfax $$i'],
356   rc_entry = [ r'\converter ps         fax        "%%"  ""'])
357
358 path, LINUXDOC = checkProg('SGML-tools 1.x (LinuxDoc)', ['sgml2lyx'],
359   rc_entry = [
360     r'''\converter linuxdoc   lyx        "sgml2lyx $$i" ""
361 \converter linuxdoc   latex      "sgml2latex $$i"       ""
362 \converter linuxdoc   dvi        "sgml2latex -o dvi $$i"        ""
363 \converter linuxdoc   html       "sgml2html $$i"        ""''',
364     r'''\converter linuxdoc   lyx        "none" ""
365 \converter linuxdoc   latex      "none" ""
366 \converter linuxdoc   dvi        "none" ""
367 \converter linuxdoc   html       "none" ""''' ])
368
369 if LINUXDOC != 'none':
370   chk_linuxdoc = 'yes'
371   bool_linuxdoc = 'true'
372   linuxdoc_cmd = '\\def\\haslinuxdoc{yes}'
373 else:
374   chk_linuxdoc = 'no'
375   bool_linuxdoc = 'false'
376   linuxdoc_cmd = ''
377
378 path, DOCBOOK = checkProg('SGML-tools 2.x (DocBook) or db2x scripts', ['sgmltools', 'db2dvi'],
379   rc_entry = [
380     r'''\converter docbook    dvi        "sgmltools -b dvi $$i" ""
381 \converter docbook    html       "sgmltools -b html $$i"        ""''',
382     r'''\converter docbook    dvi        "db2dvi $$i"   ""
383 \converter docbook    html       "db2html $$i"  ""''',
384     r'''\converter docbook    dvi        "none" ""
385 \converter docbook    html       "none" ""'''])
386
387 if DOCBOOK != 'none':
388   chk_docbook = 'yes'
389   bool_docbook = 'true'
390   docbook_cmd = '\\def\\hasdocbook{yes}'
391 else:
392   chk_docbook = 'no'
393   bool_docbook = 'false'
394   docbook_cmd = ''
395
396 checkProg('a spool command', ['lp', 'lpr'],
397   rc_entry = [
398     r'''\print_spool_printerprefix "-d "
399 \print_spool_command "lp"''',
400     r'''\print_spool_printerprefix "-P",
401 \print_spool_command "lpr"''',
402     ''])
403
404 checkProg('a LaTeX -> HTML converter', ['htlatex $$i', 'tth  -t -e2 -L$$b < $$i > $$o', \
405   'latex2html -no_subdir -split 0 -show_section_numbers $$i', 'hevea -s $$i'],
406   rc_entry = [ r'\converter latex      html       "%%"  "originaldir,needaux"' ])
407
408 # Add the rest of the entries (no checkProg is required)
409 addToRC(r'''\Format date       ""     "date command"          "" ""     ""
410 \Format fax        ""      Fax                    "" "" ""
411 \Format lyx        lyx     LyX                    "" "" ""
412 \Format lyx13x     lyx13  "LyX 1.3.x"             "" "" ""
413 \Format lyxpreview lyxpreview "LyX Preview"       "" "" ""
414 \Format pdftex     pdftex_t PDFTEX                "" "" ""
415 \Format program    ""      Program                "" "" ""
416 \Format pstex      pstex_t PSTEX                  "" "" ""
417 \Format sxw        sxw    "OpenOffice.Org Writer" O  "" ""
418 \Format word       doc    "MS Word"               W  "" ""
419 \Format wordhtml   html   "MS Word (HTML)"        "" ""        ""
420 \converter date       dateout    "date +%d-%m-%Y > $$o" ""
421 \converter docbook    docbook-xml "cp $$i $$o"  "xml"
422 \converter fen        asciichess "python $$s/scripts/fen2ascii.py $$i $$o"      ""
423 \converter fig        pdftex     "sh $$s/scripts/fig2pdftex.sh $$i $$o" ""
424 \converter fig        pstex      "sh $$s/scripts/fig2pstex.sh $$i $$o"  ""
425 \converter lyx        lyx13x     "python $$s/lyx2lyx/lyx2lyx -t 221 $$i > $$o"  ""
426 \copier    fig        "sh $$s/scripts/fig_copy.sh $$i $$o"
427 \copier    pstex      "python $$s/scripts/tex_copy.py $$i $$o $$l"
428 \copier    pdftex     "python $$s/scripts/tex_copy.py $$i $$o $$l"
429 ''')
430
431 ## Explore the LaTeX configuration
432 print 'checking LaTeX configuration... ',
433 ## First, remove the files that we want to re-create
434 removeFiles(['textclass.lst', 'packages.lst', 'chkconfig.sed'])
435
436 if not lyx_check_config:
437   print ' default values'
438   print '+checking list of textclasses... '
439   tx = open('textclass.lst', 'w')
440   tx.write('''
441 # This file declares layouts and their associated definition files
442 # (include dir. relative to the place where this file is).
443 # It contains only default values, since chkconfig.ltx could not be run
444 # for some reason. Run ./configure if you need to update it after a
445 # configuration change.
446 ''')
447   # build the list of available layout files and convert it to commands
448   # for chkconfig.ltx
449   foundClasses = []
450   # sed filters
451   # FIXME: this is a direct translation of the sed commands
452   # There may be more efficient methods
453   p1 = re.compile(r'\Declare(LaTeX|DocBook|LinuxDoc)Class')
454   p2 = re.compile(r'^.*\DeclareLaTeXClass *(.*)')
455   p3 = re.compile(r'^.*\DeclareDocBookClass *(.*)')
456   p4 = re.compile(r'^.*\DeclareLinuxDocClass *(.*)')
457   p5 = re.compile(r'\[([^,]*),[^]]*\]')
458   p6 = re.compile('^{')
459   p7 = re.compile(r'\[([^]]*)\] *{([^}]*)}')
460   for file in glob.glob( os.path.join('layouts', '*.layout') ) + \
461     glob.glob( os.path.join(srcdir, 'layouts', '*.layout' ) ) :
462     # valid file?
463     if not os.path.isfile(file): continue
464     # get stuff between /xxxx.layout .
465     classname = file.split(os.sep)[-1].split('.')[0]
466     #  tr ' -' '__'`
467     cleanclass = classname.replace(' ', '_')
468     cleanclass = cleanclass.replace('-', '_')
469     # make sure the same class is not considered twice
470     if foundClasses.count(cleanclass) == 0: # not found before
471       foundClasses.append(cleanclass)
472       # The sed commands below are a bit scary. Here is what they do:
473       # 1-3: remove the \DeclareFOO macro and add the correct boolean
474       #      at the end of the line telling whether the class is
475       #      available
476       # 4: if the macro had an optional argument with several
477       #    parameters, only keep the first one
478       # 5: if the macro did not have an optional argument, provide one
479       #    (equal to the class name)
480       # 6: remove brackets and replace with correctly quoted entries
481       #     grep '\\Declare\(LaTeX\|DocBook\|LinuxDoc\)Class' "$file" \
482       #      | sed -e 's/^.*\DeclareLaTeXClass *\(.*\)/\1 "false"/' \
483       #     -e 's/^.*\DeclareDocBookClass *\(.*\)/\1 "'$bool_docbook'"/' \
484       #     -e 's/^.*\DeclareLinuxDocClass *\(.*\)/\1 "'$bool_linuxdoc'"/' \
485       #     -e 's/\[\([^,]*\),[^]]*\]/[\1]/' \
486       #     -e 's/^{/['$class']{/' \
487       #     -e 's/\[\([^]]*\)\] *{\([^}]*\)}/"'$class'" "\1" "\2"/' \
488       #                   >>textclass.lst
489       for line in open(file).readlines():
490         if p1.search(line) == None:
491           continue
492         line = p2.sub(r'\1 "false"', line)
493         line = p3.sub(r'\1 "' + bool_docbook + '"', line)
494         line = p4.sub(r'\1 "' + bool_linuxdoc + '"', line)
495         line = p5.sub(r'[\1]', line)
496         line = p6.sub("[" + classname + "]{", line)
497         line = p7.sub( "'" + classname + "'" + r'"\1" "\2"', line)
498         tx.write(line)
499         break       # one file, one line.
500   tx.close()
501   print '\tdone'
502 else:
503   print '\tauto'
504   removeFiles(['wrap_chkconfig.ltx', 'chkconfig.vars', \
505     'chkconfig.classes', 'chklayouts.tex'])
506   rmcopy = False
507   if not os.path.isfile( 'chkconfig.ltx' ):
508     shutil.copy( os.path.join(srcdir, 'chkconfig.ltx'),  'chkconfig.ltx' )
509     rmcopy = True
510   writeToFile('wrap_chkconfig.ltx', '%s\n%s\n\\input{chkconfig.ltx}\n' \
511     % (linuxdoc_cmd, docbook_cmd) )
512   ## Construct the list of classes to test for.
513   # build the list of available layout files and convert it to commands
514   # for chkconfig.ltx
515   p1 = re.compile(r'\Declare(LaTeX|DocBook|LinuxDoc)Class')
516   testclasses = list()
517   for file in glob.glob( os.path.join('layouts', '*.layout') ) + \
518     glob.glob( os.path.join(srcdir, 'layouts', '*.layout' ) ) :
519     if not os.path.isfile(file): continue
520     classname = file.split(os.sep)[-1].split('.')[0]
521     for line in open(file).readlines():
522       if p1.search(line) == None:
523         continue
524       if line[0] != '#':
525         print "Wrong input layout file with line '" + line
526         sys.exit(3)
527       testclasses.append("\\TestDocClass{%s}{%s}" % (classname, line[1:].strip()))
528       break
529   testclasses.sort()
530   cl = open('chklayouts.tex', 'w')
531   for line in testclasses:
532     cl.write(line + '\n')
533   cl.close()
534   #
535   # we have chklayouts.tex, then process it
536   for line in cmdOutput(LATEX + ' wrap_chkconfig.ltx').splitlines():
537     if re.match('^\+', line):
538       print line
539   #
540   #  evalulate lines in chkconfig.vars?
541   # is it really necessary?
542   for line in open('chkconfig.vars').readlines():
543     exec( re.sub('-', '_', line) )
544   if rmcopy:   # remove the copied file
545     removeFiles( [ 'chkconfig.ltx' ] )
546
547 ### Do we have all the files we need? Useful if latex did not run
548
549 ### if chkconfig.sed does not exist (because LaTeX did not run),
550 ### then provide a standard version.
551 if not os.path.isfile('chkconfig.sed'):
552   writeToFile('chkconfig.sed', '##s/@.*@/???/g\n')
553
554 print "creating packages.lst"
555 ### if packages.lst does not exist (because LaTeX did not run),
556 ### then provide a standard version.
557 if not os.path.isfile('packages.lst'):
558   writeToFile('packages.lst', '''
559 ### This file should contain the list of LaTeX packages that have been
560 ### recognized by LyX. Unfortunately, since configure could not find
561 ### your LaTeX2e program, the tests have not been run. Run ./configure
562 ### if you need to update it after a configuration change.
563 ''')
564
565 print 'creating doc/LaTeXConfig.lyx'
566 #
567 # This is originally done by sed, using a
568 # tex-generated file chkconfig.sed
569 ##sed -f chkconfig.sed ${srcdir}/doc/LaTeXConfig.lyx.in
570 ##  >doc/LaTeXConfig.lyx
571 # Now, we have to do it by hand (python).
572 #
573 # add to chekconfig.sed
574 writeToFile('chkconfig.sed', '''s!@chk_linuxdoc@!%s!g
575 s!@chk_docbook@!%s!g
576 ''' % (chk_linuxdoc, chk_docbook) , append=True)
577 # process this sed file!!!!
578 lyxin = open( os.path.join(srcdir, 'doc', 'LaTeXConfig.lyx.in')).readlines()
579 # get the rules
580 p = re.compile(r's!(.*)!(.*)!g')
581 # process each sed replace.
582 for sed in open('chkconfig.sed').readlines():
583   try:
584     fr, to = p.match(sed).groups()
585     for line in range(len(lyxin)):
586       lyxin[line] = lyxin[line].replace(fr, to)
587   except:  # wrong sed entry?
588     print "Wrong sed entry in chkconfig.sed:", sed
589     sys.exit(4)
590
591 writeToFile( os.path.join('doc', 'LaTeXConfig.lyx'),
592   ''.join(lyxin))
593
594 ### Let's check whether spaces are allowed in TeX file names
595 tex_allows_spaces = 'false'
596 if lyx_check_config:
597   print "Checking whether TeX allows spaces in file names... ",
598   writeToFile('a b.tex', r'\message{working^^J}' )
599   # FIXME: the bsh version uses < /dev/null which is not portable.
600   # Can anyone confirm if this option (-interaction) is available
601   # at other flavor of latex as well? (MikTex/win, Web2C/linux are fine.) 
602   if ''.join(cmdOutput(LATEX + ' -interaction=nonstopmode "a b"')).find('working') != -1:
603     print 'yes'
604     tex_allows_spaces = 'true'
605   else:
606     print 'no'
607     tex_allows_spaces = 'false'
608   removeFiles( [ 'a b.tex', 'a b.log', 'texput.log' ])
609
610 checkProg('a FIG -> EPS/PPM converter', ['fig2dev'],
611   rc_entry = [
612     r'''\converter fig        eps        "fig2dev -L eps $$i $$o"       ""
613 \converter fig        ppm        "fig2dev -L ppm $$i $$o"       ""
614 \converter fig        png        "fig2dev -L png $$i $$o"       ""''',
615     ''])
616
617 checkProg('a TIFF -> PS converter', ['tiff2ps $$i > $$o'],
618   rc_entry = [ r'\converter tiff       eps        "%%"  ""', ''])
619
620 checkProg('a TGIF -> EPS/PPM converter', ['tgif'],
621   rc_entry = [
622     r'''\converter tgif       eps        "tgif -stdout -print -color -eps $$i > $$o"    ""
623 \converter tgif       pdf        "tgif -stdout -print -color -pdf $$i > $$o"    ""''',
624     ''])
625
626 checkProg('a EPS -> PDF converter', ['epstopdf'],
627   rc_entry = [ r'\converter eps        pdf        "epstopdf --outfile=$$o $$i"  ""', ''])
628
629 path, GRACE = checkProg('a Grace -> Image converter', ['gracebat'],
630   rc_entry = [
631     r'''\converter agr        eps        "gracebat -hardcopy -printfile $$o -hdevice EPS $$i 2>/dev/null"       ""
632 \converter agr        png        "gracebat -hardcopy -printfile $$o -hdevice PNG $$i 2>/dev/null"       ""
633 \converter agr        jpg        "gracebat -hardcopy -printfile $$o -hdevice JPEG $$i 2>/dev/null"      ""
634 \converter agr        ppm        "gracebat -hardcopy -printfile $$o -hdevice PNM $$i 2>/dev/null"       ""''',
635     ''])
636
637 # chk_fontenc may not exist 
638 try:
639   addToRC(r'\font_encoding "%s"' % chk_fontenc)
640 except:
641   pass
642 addToRC(r'\tex_allows_spaces ' + tex_allows_spaces)
643
644 if use_cygwin_path_fix == 'true':
645   addToRC(r'\cygwin_path_fix_needed ' + use_cygwin_path_fix)
646
647 # Remove superfluous files if we are not writing in the main lib
648 # directory
649 for file in [outfile, 'textclass.lst', 'packages.lst', \
650   'doc/LaTeXConfig.lyx']:
651   try:
652     # we rename the file first, so that we avoid comparing a file with itself
653     os.rename(file, file + '.new')
654     syscfg = open( os.path.join(srcdir, file) ).read()
655     mycfg = open( file + '.new').read()
656     if mycfg == syscfg:
657       print "removing ", file, " which is identical to the system global version"
658       removeFiles( [file + '.new'] )
659     else:
660       os.rename( file + '.new', file )
661   except:  # use local version if anthing goes wrong.
662     os.rename( file + '.new', file )
663     pass
664
665 # Final clean-up
666 if not lyx_keep_temps:
667   removeFiles(['chkconfig.sed', 'chkconfig.vars',  \
668     'wrap_chkconfig.ltx', 'wrap_chkconfig.log', \
669     'chklayouts.tex', 'missfont.log'])
670