]> git.lyx.org Git - lyx.git/blob - lib/configure.py
revert recent change to development/FORMAT (don't change history)
[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. 
12
13 import sys, os, re, shutil, glob
14
15
16 class Tee:
17     ''' Writing to a Tee object will write to all file objects it keeps.
18         That is to say, writing to Tee(sys.stdout, open(logfile, 'w')) will
19         write to sys.stdout as well as a log file.
20     '''
21     def __init__(self, *args):
22         self.files = args
23
24     def write(self, data):
25         for f in self.files:
26             result = f.write(data)
27         return result
28
29     def writelines(self, seq):
30         for i in seq:
31             self.write(i)
32
33
34 def writeToFile(filename, lines, append = False):
35     " utility function: write or append lines to filename "
36     if append:
37         file = open(filename, 'a')
38     else:
39         file = open(filename, 'w')
40     file.write(lines)
41     file.close()
42
43
44 def addToRC(lines):
45     ''' utility function: shortcut for appending lines to outfile
46         add newline at the end of lines.
47     '''
48     if lines.strip() != '':
49         writeToFile(outfile, lines + '\n', append = True)
50
51
52 def removeFiles(filenames):
53     '''utility function: 'rm -f'
54         ignore errors when file does not exist, or is a directory.
55     '''
56     for file in filenames:
57         try:
58             os.remove(file)
59         except:
60             pass
61
62
63 def cmdOutput(cmd):
64     '''utility function: run a command and get its output as a string
65         cmd: command to run
66     '''
67     fout = os.popen(cmd)
68     output = fout.read()
69     fout.close()
70     return output.strip()
71
72
73 def setEnviron():
74     ''' I do not really know why this is useful, but we might as well keep it.
75         NLS nuisances.
76         Only set these to C if already set.  These must not be set unconditionally
77         because not all systems understand e.g. LANG=C (notably SCO).
78         Fixing LC_MESSAGES prevents Solaris sh from translating var values in `set'!
79         Non-C LC_CTYPE values break the ctype check.
80     '''
81     os.environ['LANG'] = os.getenv('LANG', 'C')
82     os.environ['LC'] = os.getenv('LC_ALL', 'C')
83     os.environ['LC_MESSAGE'] = os.getenv('LC_MESSAGE', 'C')
84     os.environ['LC_CTYPE'] = os.getenv('LC_CTYPE', 'C')
85
86
87 def createDirectories():
88     ''' Create the build directories if necessary '''
89     for dir in ['bind', 'clipart', 'doc', 'examples', 'images', 'kbd', \
90         'layouts', 'scripts', 'templates', 'ui' ]:
91         if not os.path.isdir( dir ):
92             try:
93                 os.mkdir( dir)
94             except:
95                 print "Failed to create directory ", dir
96                 sys.exit(1)
97
98
99 def checkTeXPaths():
100     ''' Determine the path-style needed by the TeX engine on Win32 (Cygwin) '''
101     windows_style_tex_paths = ''
102     if os.name == 'nt' or sys.platform == 'cygwin':
103         from tempfile import mkstemp
104         fd, tmpfname = mkstemp(suffix='.ltx')
105         if os.name == 'nt':
106             inpname = tmpfname.replace('\\', '/')
107         else:
108             inpname = cmdOutput('cygpath -m ' + tmpfname)
109         inpname = inpname.replace('~', '\\string~')
110         os.write(fd, r'\relax')
111         os.close(fd)
112         latex_out = cmdOutput(r'latex "\nonstopmode\input{%s}"' % inpname)
113         if 'Error' in latex_out:
114             print "configure: TeX engine needs posix-style paths in latex files"
115             windows_style_tex_paths = 'false'
116         else:
117             print "configure: TeX engine needs windows-style paths in latex files"
118             windows_style_tex_paths = 'true'
119         removeFiles([tmpfname, 'texput.log'])
120     return windows_style_tex_paths
121
122
123 ## Searching some useful programs
124 def checkProg(description, progs, rc_entry = [], path = [], not_found = ''):
125     '''
126         This function will search a program in $PATH plus given path
127         If found, return directory and program name (not the options).
128
129         description: description of the program
130
131         progs: check programs, for each prog, the first word is used
132             for searching but the whole string is used to replace
133             %% for a rc_entry. So, feel free to add '$$i' etc for programs.
134
135         path: additional pathes
136
137         rc_entry: entry to outfile, can be
138             1. emtpy: no rc entry will be added
139             2. one pattern: %% will be replaced by the first found program,
140                 or '' if no program is found.
141             3. several patterns for each prog and not_found. This is used 
142                 when different programs have different usages. If you do not 
143                 want not_found entry to be added to the RC file, you can specify 
144                 an entry for each prog and use '' for the not_found entry.
145
146         not_found: the value that should be used instead of '' if no program
147             was found
148
149     '''
150     # one rc entry for each progs plus not_found entry
151     if len(rc_entry) > 1 and len(rc_entry) != len(progs) + 1:
152         print "rc entry should have one item or item for each prog and not_found."
153         sys.exit(2)
154     print 'checking for ' + description + '...'
155     ## print '(' + ','.join(progs) + ')',
156     for idx in range(len(progs)):
157         # ac_prog may have options, ac_word is the command name
158         ac_prog = progs[idx]
159         ac_word = ac_prog.split(' ')[0]
160         print '+checking for "' + ac_word + '"... ',
161         path = os.environ["PATH"].split(os.pathsep) + path
162         for ac_dir in path:
163             # check both ac_word and ac_word.exe (for windows system)
164             if os.path.isfile( os.path.join(ac_dir, ac_word) ) or \
165                 os.path.isfile( os.path.join(ac_dir, ac_word + ".exe") ):
166                 print ' yes'
167                 # write rc entries for this command
168                 if len(rc_entry) == 1:
169                     addToRC(rc_entry[0].replace('%%', ac_prog))
170                 elif len(rc_entry) > 1:
171                     addToRC(rc_entry[idx].replace('%%', ac_prog))
172                 return [ac_dir, ac_word]
173         # if not successful
174         print ' no'
175     # write rc entries for 'not found'
176     if len(rc_entry) > 0:  # the last one.
177         addToRC(rc_entry[-1].replace('%%', not_found))
178     return ['', not_found]
179
180
181 def checkViewer(description, progs, rc_entry = [], path = []):
182     ''' The same as checkProg, but for viewers and editors '''
183     return checkProg(description, progs, rc_entry, path, not_found = 'auto')
184
185
186 def checkLatex():
187     ''' Check latex, return lyx_check_config '''
188     # Find programs! Returned path is not used now
189     if ((os.name == 'nt' or sys.platform == 'cygwin') and
190             checkProg('DVI to DTL converter', ['dv2dt']) != ['', ''] and
191             checkProg('DTL to DVI converter', ['dt2dv']) != ['', '']):
192         # Windows only: DraftDVI
193         converter_entry = r'''\converter latex      dvi2       "%%"     "latex"
194 \converter dvi2       dvi        "python -tt $$s/scripts/clean_dvi.py $$i $$o"  ""'''
195     else:
196         converter_entry = r'\converter latex      dvi        "%%"       "latex"'
197     path, LATEX = checkProg('a Latex2e program', ['pplatex $$i', 'latex $$i', 'latex2e $$i'],
198         rc_entry = [converter_entry])
199     # no latex
200     if LATEX != '':
201         # Check if latex is usable
202         writeToFile('chklatex.ltx', '''
203 \\nonstopmode\\makeatletter
204 \\ifx\\undefined\\documentclass\\else
205   \\message{ThisIsLaTeX2e}
206 \\fi
207 \\@@end
208 ''')
209         # run latex on chklatex.ltx and check result
210         if cmdOutput(LATEX + ' chklatex.ltx').find('ThisIsLaTeX2e') != -1:
211             # valid latex2e
212             return LATEX
213         else:
214             print "Latex not usable (not LaTeX2e) "
215         # remove temporary files
216         removeFiles(['chklatex.ltx', 'chklatex.log'])
217     return ''
218
219
220 def checkFormatEntries():  
221     ''' Check all formats (\Format entries) '''
222     checkViewer('a Tgif viewer and editor', ['tgif'],
223         rc_entry = [r'\Format tgif       obj     Tgif                   "" "%%" "%%"    ""'])
224     #
225     checkViewer('a FIG viewer and editor', ['xfig'],
226         rc_entry = [r'\Format fig        fig     FIG                    "" "%%" "%%"    ""'])
227     #
228     checkViewer('a Grace viewer and editor', ['xmgrace'],
229         rc_entry = [r'\Format agr        agr     Grace                  "" "%%" "%%"    ""'])
230     #
231     checkViewer('a FEN viewer and editor', ['xboard -lpf $$i -mode EditPosition'],
232         rc_entry = [r'\Format fen        fen     FEN                    "" "%%" "%%"    ""'])
233     #
234     path, iv = checkViewer('a raster image viewer', ['xv', 'kview', 'gimp'])
235     path, ie = checkViewer('a raster image editor', ['gimp'])
236     addToRC(r'''\Format bmp        bmp     BMP                    "" "%s"       "%s"    ""
237 \Format gif        gif     GIF                    "" "%s"       "%s"    ""
238 \Format jpg        jpg     JPEG                   "" "%s"       "%s"    ""
239 \Format pbm        pbm     PBM                    "" "%s"       "%s"    ""
240 \Format pgm        pgm     PGM                    "" "%s"       "%s"    ""
241 \Format png        png     PNG                    "" "%s"       "%s"    ""
242 \Format ppm        ppm     PPM                    "" "%s"       "%s"    ""
243 \Format tiff       tif     TIFF                   "" "%s"       "%s"    ""
244 \Format xbm        xbm     XBM                    "" "%s"       "%s"    ""
245 \Format xpm        xpm     XPM                    "" "%s"       "%s"    ""''' % \
246         (iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie) )
247     #
248     checkViewer('a text editor', ['xemacs', 'gvim', 'kedit', 'kwrite', 'kate', \
249         'nedit', 'gedit', 'notepad'],
250         rc_entry = [r'''\Format asciichess asc    "Plain text (chess output)"  "" ""    "%%"    ""
251 \Format asciiimage asc    "Plain text (image)"         "" ""    "%%"    ""
252 \Format asciixfig  asc    "Plain text (Xfig output)"   "" ""    "%%"    ""
253 \Format dateout    tmp    "date (output)"         "" "" "%%"    ""
254 \Format docbook    sgml    DocBook                B  "" "%%"    "document"
255 \Format docbook-xml xml   "Docbook (XML)"         "" "" "%%"    "document"
256 \Format literate   nw      NoWeb                  N  "" "%%"    "document"
257 \Format latex      tex    "LaTeX (plain)"         L  "" "%%"    "document"
258 \Format linuxdoc   sgml    LinuxDoc               x  "" "%%"    "document"
259 \Format pdflatex   tex    "LaTeX (pdflatex)"      "" "" "%%"    "document"
260 \Format text       txt    "Plain text"            a  "" "%%"    "document"
261 \Format text2      txt    "Plain text (pstotext)" "" "" "%%"    "document"
262 \Format text3      txt    "Plain text (ps2ascii)" "" "" "%%"    "document"
263 \Format text4      txt    "Plain text (catdvi)"   "" "" "%%"    "document"
264 \Format textparagraph txt "Plain text (paragraphs)"    "" ""    "%%"    "document"''' ])
265     #
266     #checkProg('a Postscript interpreter', ['gs'],
267     #  rc_entry = [ r'\ps_command "%%"' ])
268     checkViewer('a Postscript previewer', ['gv', 'ghostview -swap', 'kghostview'],
269         rc_entry = [r'''\Format eps        eps     EPS                    "" "%%"       ""      ""
270 \Format ps         ps      Postscript             t  "%%"       ""      "document"'''])
271     #
272     checkViewer('a PDF previewer', ['acrobat', 'acroread', 'gv', 'ghostview', \
273                             'xpdf', 'kpdf', 'kghostview'],
274         rc_entry = [r'''\Format pdf        pdf    "PDF (ps2pdf)"          P  "%%"       ""      "document"
275 \Format pdf2       pdf    "PDF (pdflatex)"        F  "%%"       ""      "document"
276 \Format pdf3       pdf    "PDF (dvipdfm)"         m  "%%"       ""      "document"'''])
277     #
278     checkViewer('a DVI previewer', ['xdvi', 'kdvi'],
279         rc_entry = [r'\Format dvi        dvi     DVI                    D  "%%" ""      "document"'])
280     if ((os.name == 'nt' or sys.platform == 'cygwin') and
281             checkProg('DVI to DTL converter', ['dv2dt']) != ['', ''] and
282             checkProg('DTL to DVI converter', ['dt2dv']) != ['', '']):
283         # Windows only: DraftDVI
284         addToRC(r'\Format dvi2       dvi     DraftDVI               ""  ""      "document"')
285     #
286     checkViewer('a HTML previewer', ['mozilla file://$$p$$i', 'netscape'],
287         rc_entry = [r'\Format html       html    HTML                   H  "%%" ""      "document"'])
288     #
289     # entried that do not need checkProg
290     addToRC(r'''\Format date       ""     "date command"          "" "" ""      ""
291 \Format fax        ""      Fax                    "" "" ""      "document"
292 \Format lyx        lyx     LyX                    "" "" ""      ""
293 \Format lyx13x     lyx13  "LyX 1.3.x"             "" "" ""      "document"
294 \Format lyxpreview lyxpreview "LyX Preview"       "" "" ""      ""
295 \Format pdftex     pdftex_t PDFTEX                "" "" ""      ""
296 \Format program    ""      Program                "" "" ""      ""
297 \Format pstex      pstex_t PSTEX                  "" "" ""      ""
298 \Format sxw        sxw    "OpenOffice.Org Writer" O  "" ""      "document"
299 \Format word       doc    "MS Word"               W  "" ""      "document"
300 \Format wordhtml   html   "MS Word (HTML)"        "" ""        ""       "document"
301 ''')
302
303
304 def checkConverterEntries():
305     ''' Check all converters (\converter entries) '''
306     checkProg('the pdflatex program', ['pdflatex $$i'],
307         rc_entry = [ r'\converter pdflatex   pdf2       "%%"    "latex"' ])
308     
309     ''' If we're running LyX in-place then tex2lyx will be found in
310             ../src/tex2lyx. Add this directory to the PATH temporarily and
311             search for tex2lyx.
312             Use PATH to avoid any problems with paths-with-spaces.
313     '''
314     path_orig = os.environ["PATH"]
315     os.environ["PATH"] = os.path.join('..', 'src', 'tex2lyx') + \
316         os.pathsep + path_orig
317
318     checkProg('a LaTeX/Noweb -> LyX converter', ['tex2lyx', 'tex2lyx' + version_suffix],
319         rc_entry = [r'''\converter latex      lyx        "%% -f $$i $$o"        ""
320 \converter literate   lyx        "%% -n -f $$i $$o"     ""'''])
321
322     os.environ["PATH"] = path_orig
323
324     #
325     checkProg('a Noweb -> LaTeX converter', ['noweave -delay -index $$i > $$o'],
326         rc_entry = [ r'\converter literate   latex      "%%"    ""' ])
327     #
328     checkProg('a HTML -> LaTeX converter', ['html2latex $$i'],
329         rc_entry = [ r'\converter html       latex      "%%"    ""' ])
330     #
331     checkProg('a MSWord -> LaTeX converter', ['wvCleanLatex $$i $$o'],
332         rc_entry = [ r'\converter word       latex      "%%"    ""' ])
333     #
334     checkProg('a LaTeX -> MS Word converter', ["htlatex $$i 'html,word' 'symbol/!' '-cvalidate'"],
335         rc_entry = [ r'\converter latex      wordhtml   "%%"    ""' ])
336     #
337     checkProg('an OpenOffice.org -> LaTeX converter', ['w2l -clean $$i'],
338         rc_entry = [ r'\converter sxw        latex      "%%"    ""' ])
339     #
340     checkProg('a LaTeX -> OpenOffice.org converter', ['oolatex $$i', 'oolatex.sh $$i'],
341         rc_entry = [ r'\converter latex      sxw        "%%"    "latex"' ])
342     #
343     checkProg('a PS to PDF converter', ['ps2pdf13 $$i $$o'],
344         rc_entry = [ r'\converter ps         pdf        "%%"    ""' ])
345     #
346     checkProg('a PS to TXT converter', ['pstotext $$i > $$o'],
347         rc_entry = [ r'\converter ps         text2      "%%"    ""' ])
348     #
349     checkProg('a PS to TXT converter', ['ps2ascii $$i $$o'],
350         rc_entry = [ r'\converter ps         text3      "%%"    ""' ])
351     #
352     checkProg('a DVI to TXT converter', ['catdvi $$i > $$o'],
353         rc_entry = [ r'\converter dvi        text4      "%%"    ""' ])
354     #
355     checkProg('a DVI to PS converter', ['dvips -o $$o $$i'],
356         rc_entry = [ r'\converter dvi        ps         "%%"    ""' ])
357     #
358     checkProg('a DVI to PDF converter', ['dvipdfmx -o $$o $$i', 'dvipdfm -o $$o $$i'],
359         rc_entry = [ r'\converter dvi        pdf3       "%%"    ""' ])
360     #
361     path, dvipng = checkProg('dvipng', ['dvipng'])
362     if dvipng == "dvipng":
363         addToRC(r'\converter lyxpreview png        "python -tt $$s/scripts/lyxpreview2bitmap.py"        ""')
364     else:
365         addToRC(r'\converter lyxpreview png        ""   ""')
366     #  
367     checkProg('a fax program', ['kdeprintfax $$i', 'ksendfax $$i'],
368         rc_entry = [ r'\converter ps         fax        "%%"    ""'])
369     #
370     checkProg('a FIG -> EPS/PPM converter', ['fig2dev'],
371         rc_entry = [
372             r'''\converter fig        eps        "fig2dev -L eps $$i $$o"       ""
373 \converter fig        ppm        "fig2dev -L ppm $$i $$o"       ""
374 \converter fig        png        "fig2dev -L png $$i $$o"       ""''',
375             ''])
376     #
377     checkProg('a TIFF -> PS converter', ['tiff2ps $$i > $$o'],
378         rc_entry = [ r'\converter tiff       eps        "%%"    ""', ''])
379     #
380     checkProg('a TGIF -> EPS/PPM converter', ['tgif'],
381         rc_entry = [
382             r'''\converter tgif       eps        "tgif -stdout -print -color -eps $$i > $$o"    ""
383 \converter tgif       ppm        "tgif -stdout -print -color -ppm $$i > $$o"    ""
384 \converter tgif       png        "tgif -stdout -print -color -png $$i > $$o"    ""
385 \converter tgif       pdf        "tgif -stdout -print -color -pdf $$i > $$o"    ""''',
386             ''])
387     #
388     checkProg('a EPS -> PDF converter', ['epstopdf'],
389         rc_entry = [ r'\converter eps        pdf        "epstopdf --outfile=$$o $$i"    ""', ''])
390     #
391     checkProg('a Grace -> Image converter', ['gracebat'],
392         rc_entry = [
393             r'''\converter agr        eps        "gracebat -hardcopy -printfile $$o -hdevice EPS $$i 2>/dev/null"       ""
394 \converter agr        png        "gracebat -hardcopy -printfile $$o -hdevice PNG $$i 2>/dev/null"       ""
395 \converter agr        jpg        "gracebat -hardcopy -printfile $$o -hdevice JPEG $$i 2>/dev/null"      ""
396 \converter agr        ppm        "gracebat -hardcopy -printfile $$o -hdevice PNM $$i 2>/dev/null"       ""''',
397             ''])
398     #
399     checkProg('a LaTeX -> HTML converter', ['htlatex $$i', 'tth  -t -e2 -L$$b < $$i > $$o', \
400         'latex2html -no_subdir -split 0 -show_section_numbers $$i', 'hevea -s $$i'],
401         rc_entry = [ r'\converter latex      html       "%%"    "originaldir,needaux"' ])
402     #
403     # FIXME: no rc_entry? comment it out
404     # checkProg('Image converter', ['convert $$i $$o'])
405     #
406     # Entried that do not need checkProg
407     addToRC(r'''\converter lyxpreview ppm        "python -tt $$s/scripts/lyxpreview2bitmap.py"  ""
408 \converter date       dateout    "date +%d-%m-%Y > $$o" ""
409 \converter docbook    docbook-xml "cp $$i $$o"  "xml"
410 \converter fen        asciichess "python -tt $$s/scripts/fen2ascii.py $$i $$o"  ""
411 \converter fig        pdftex     "python -tt $$s/scripts/fig2pdftex.py $$i $$o" ""
412 \converter fig        pstex      "python -tt $$s/scripts/fig2pstex.py $$i $$o"  ""
413 \converter lyx        lyx13x     "python -tt $$s/lyx2lyx/lyx2lyx -t 221 $$i > $$o"      ""
414 ''')
415
416
417 def checkLinuxDoc():
418     ''' Check linuxdoc '''
419     #
420     path, LINUXDOC = checkProg('SGML-tools 1.x (LinuxDoc)', ['sgml2lyx'],
421         rc_entry = [
422         r'''\converter linuxdoc   lyx        "sgml2lyx $$i"     ""
423 \converter linuxdoc   latex      "sgml2latex $$i"       ""
424 \converter linuxdoc   dvi        "sgml2latex -o dvi $$i"        ""
425 \converter linuxdoc   html       "sgml2html $$i"        ""''',
426         r'''\converter linuxdoc   lyx        "" ""
427 \converter linuxdoc   latex      ""     ""
428 \converter linuxdoc   dvi        ""     ""
429 \converter linuxdoc   html       ""     ""''' ])
430     if LINUXDOC != '':
431         return ('yes', 'true', '\\def\\haslinuxdoc{yes}')
432     else:
433         return ('no', 'false', '')
434
435
436 def checkDocBook():
437     ''' Check docbook '''
438     path, DOCBOOK = checkProg('SGML-tools 2.x (DocBook) or db2x scripts', ['sgmltools', 'db2dvi'],
439         rc_entry = [
440             r'''\converter docbook    dvi        "sgmltools -b dvi $$i" ""
441 \converter docbook    html       "sgmltools -b html $$i"        ""''',
442             r'''\converter docbook    dvi        "db2dvi $$i"   ""
443 \converter docbook    html       "db2html $$i"  ""''',
444             r'''\converter docbook    dvi        ""     ""
445 \converter docbook    html       ""     ""'''])
446     #
447     if DOCBOOK != '':
448         return ('yes', 'true', '\\def\\hasdocbook{yes}')
449     else:
450         return ('no', 'false', '')
451
452
453 def checkOtherEntries():
454     ''' entries other than Format and Converter '''
455     checkProg('a *roff formatter', ['groff', 'nroff'],
456         rc_entry = [
457             r'\ascii_roff_command "groff -t -Tlatin1 $$FName"',
458             r'\ascii_roff_command "tbl $$FName | nroff"',
459             r'\ascii_roff_command ""' ])
460     checkProg('ChkTeX', ['chktex -n1 -n3 -n6 -n9 -n22 -n25 -n30 -n38'],
461         rc_entry = [ r'\chktex_command "%%"' ])
462     checkProg('a spellchecker', ['ispell'],
463         rc_entry = [ r'\spell_command "%%"' ])
464     ## FIXME: OCTAVE is not used anywhere
465     # path, OCTAVE = checkProg('Octave', ['octave'])
466     ## FIXME: MAPLE is not used anywhere
467     # path, MAPLE = checkProg('Maple', ['maple'])
468     checkProg('a spool command', ['lp', 'lpr'],
469         rc_entry = [
470             r'''\print_spool_printerprefix "-d "
471 \print_spool_command "lp"''',
472             r'''\print_spool_printerprefix "-P",
473 \print_spool_command "lpr"''',
474             ''])
475     # Add the rest of the entries (no checkProg is required)
476     addToRC(r'''\copier    fig        "python -tt $$s/scripts/fig_copy.py $$i $$o"
477 \copier    pstex      "python -tt $$s/scripts/tex_copy.py $$i $$o $$l"
478 \copier    pdftex     "python -tt $$s/scripts/tex_copy.py $$i $$o $$l"
479 ''')
480
481
482 def processLayoutFile(file, bool_docbook, bool_linuxdoc):
483     ''' process layout file and get a line of result
484         
485         Declear line are like this: (article.layout, scrbook.layout, svjog.layout)
486         
487         \DeclareLaTeXClass{article}
488         \DeclareLaTeXClass[scrbook]{book (koma-script)}
489         \DeclareLaTeXClass[svjour,svjog.clo]{article (Springer - svjour/jog)}
490
491         we expect output:
492         
493         "article" "article" "article" "false"
494         "scrbook" "scrbook" "book (koma-script)" "false"
495         "svjog" "svjour" "article (Springer - svjour/jog)" "false"
496     '''
497     classname = file.split(os.sep)[-1].split('.')[0]
498     # return ('LaTeX', '[a,b]', 'a', ',b,c', 'article') for \DeclearLaTeXClass[a,b,c]{article}
499     p = re.compile(r'\Declare(LaTeX|DocBook)Class\s*(\[([^,]*)(,.*)*\])*\s*{(.*)}')
500     for line in open(file).readlines():
501         res = p.search(line)
502         if res != None:
503             (classtype, optAll, opt, opt1, desc) = res.groups()
504             avai = {'LaTeX':'false', 'DocBook':bool_docbook, 'LinuxDoc':bool_linuxdoc}[classtype]
505             if opt == None:
506                 opt = classname
507             return '"%s" "%s" "%s" "%s"\n' % (classname, opt, desc, avai)
508     print "Layout file without \DeclearXXClass line. "
509     sys.exit(2)
510
511     
512 def checkLatexConfig(check_config, bool_docbook, bool_linuxdoc):
513     ''' Explore the LaTeX configuration '''
514     print 'checking LaTeX configuration... ',
515     # First, remove the files that we want to re-create
516     removeFiles(['textclass.lst', 'packages.lst', 'chkconfig.sed'])
517     #
518     if not check_config:
519         print ' default values'
520         print '+checking list of textclasses... '
521         tx = open('textclass.lst', 'w')
522         tx.write('''
523 # This file declares layouts and their associated definition files
524 # (include dir. relative to the place where this file is).
525 # It contains only default values, since chkconfig.ltx could not be run
526 # for some reason. Run ./configure.py if you need to update it after a
527 # configuration change.
528 ''')
529         # build the list of available layout files and convert it to commands
530         # for chkconfig.ltx
531         foundClasses = []
532         for file in glob.glob( os.path.join('layouts', '*.layout') ) + \
533             glob.glob( os.path.join(srcdir, 'layouts', '*.layout' ) ) :
534             # valid file?
535             if not os.path.isfile(file): 
536                 continue
537             # get stuff between /xxxx.layout .
538             classname = file.split(os.sep)[-1].split('.')[0]
539             #  tr ' -' '__'`
540             cleanclass = classname.replace(' ', '_')
541             cleanclass = cleanclass.replace('-', '_')
542             # make sure the same class is not considered twice
543             if foundClasses.count(cleanclass) == 0: # not found before
544                 foundClasses.append(cleanclass)
545                 tx.write(processLayoutFile(file, bool_docbook, bool_linuxdoc))
546         tx.close()
547         print '\tdone'
548     else:
549         print '\tauto'
550         removeFiles(['wrap_chkconfig.ltx', 'chkconfig.vars', \
551             'chkconfig.classes', 'chklayouts.tex'])
552         rmcopy = False
553         if not os.path.isfile( 'chkconfig.ltx' ):
554             shutil.copy( os.path.join(srcdir, 'chkconfig.ltx'),  'chkconfig.ltx' )
555             rmcopy = True
556         writeToFile('wrap_chkconfig.ltx', '%s\n%s\n\\input{chkconfig.ltx}\n' \
557             % (linuxdoc_cmd, docbook_cmd) )
558         # Construct the list of classes to test for.
559         # build the list of available layout files and convert it to commands
560         # for chkconfig.ltx
561         p1 = re.compile(r'\Declare(LaTeX|DocBook)Class')
562         testclasses = list()
563         for file in glob.glob( os.path.join('layouts', '*.layout') ) + \
564             glob.glob( os.path.join(srcdir, 'layouts', '*.layout' ) ) :
565             if not os.path.isfile(file):
566                 continue
567             classname = file.split(os.sep)[-1].split('.')[0]
568             for line in open(file).readlines():
569                 if p1.search(line) == None:
570                     continue
571                 if line[0] != '#':
572                     print "Wrong input layout file with line '" + line
573                     sys.exit(3)
574                 testclasses.append("\\TestDocClass{%s}{%s}" % (classname, line[1:].strip()))
575                 break
576         testclasses.sort()
577         cl = open('chklayouts.tex', 'w')
578         for line in testclasses:
579             cl.write(line + '\n')
580         cl.close()
581         #
582         # we have chklayouts.tex, then process it
583         fout = os.popen(LATEX + ' wrap_chkconfig.ltx')
584         while True:
585             line = fout.readline()
586             if not line:
587                 break;
588             if re.match('^\+', line):
589                 print line,
590         fout.close()
591         #
592         # currently, values in chhkconfig are only used to set
593         # \font_encoding
594         values = {}
595         for line in open('chkconfig.vars').readlines():
596             key, val = re.sub('-', '_', line).split('=')
597             val = val.strip()
598             values[key] = val.strip("'")
599         # chk_fontenc may not exist 
600         try:
601             addToRC(r'\font_encoding "%s"' % values["chk_fontenc"])
602         except:
603             pass
604         if rmcopy:   # remove the copied file
605             removeFiles( [ 'chkconfig.ltx' ] )
606
607
608 def createLaTeXConfig():
609     ''' create LaTeXConfig.lyx '''
610     # if chkconfig.sed does not exist (because LaTeX did not run),
611     # then provide a standard version.
612     if not os.path.isfile('chkconfig.sed'):
613         writeToFile('chkconfig.sed', 's!@.*@!???!g\n')
614     print "creating packages.lst"
615     # if packages.lst does not exist (because LaTeX did not run),
616     # then provide a standard version.
617     if not os.path.isfile('packages.lst'):
618         writeToFile('packages.lst', '''
619 ### This file should contain the list of LaTeX packages that have been
620 ### recognized by LyX. Unfortunately, since configure could not find
621 ### your LaTeX2e program, the tests have not been run. Run ./configure.py
622 ### if you need to update it after a configuration change.
623 ''')
624     print 'creating doc/LaTeXConfig.lyx'
625     #
626     # This is originally done by sed, using a
627     # tex-generated file chkconfig.sed
628     ##sed -f chkconfig.sed ${srcdir}/doc/LaTeXConfig.lyx.in
629     ##  >doc/LaTeXConfig.lyx
630     # Now, we have to do it by hand (python).
631     #
632     # add to chekconfig.sed
633     writeToFile('chkconfig.sed', '''s!@chk_linuxdoc@!%s!g
634 s!@chk_docbook@!%s!g
635     ''' % (chk_linuxdoc, chk_docbook) , append=True)
636     # process this sed file!!!!
637     lyxin = open( os.path.join(srcdir, 'doc', 'LaTeXConfig.lyx.in')).readlines()
638     # get the rules
639     p = re.compile(r's!(.*)!(.*)!g')
640     # process each sed replace.
641     for sed in open('chkconfig.sed').readlines():
642         if sed.strip() == '':
643             continue
644         try:
645             fr, to = p.match(sed).groups()
646             # if latex did not run, change all @name@ to '???'
647             if fr == '@.*@':
648                 for line in range(len(lyxin)):
649                     lyxin[line] = re.sub('@.*@', to, lyxin[line])
650             else:
651                 for line in range(len(lyxin)):
652                     lyxin[line] = lyxin[line].replace(fr, to)
653         except:  # wrong sed entry?
654             print "Wrong sed entry in chkconfig.sed: '" + sed + "'"
655             sys.exit(4)
656     # 
657     writeToFile( os.path.join('doc', 'LaTeXConfig.lyx'),
658         ''.join(lyxin))
659
660
661 def checkTeXAllowSpaces():
662     ''' Let's check whether spaces are allowed in TeX file names '''
663     tex_allows_spaces = 'false'
664     if lyx_check_config:
665         print "Checking whether TeX allows spaces in file names... ",
666         writeToFile('a b.tex', r'\message{working^^J}' )
667         if os.name == 'nt':
668             latex_out = cmdOutput(LATEX + r""" "\nonstopmode\input{\"a b\"}" """)
669         else:
670             latex_out = cmdOutput(LATEX + r""" '\nonstopmode\input{"a b"}' """)
671         if 'working' in latex_out:
672             print 'yes'
673             tex_allows_spaces = 'true'
674         else:
675             print 'no'
676             tex_allows_spaces = 'false'
677         addToRC(r'\tex_allows_spaces ' + tex_allows_spaces)
678         removeFiles( [ 'a b.tex', 'a b.log', 'texput.log' ])
679
680
681 def removeTempFiles():
682     # Final clean-up
683     if not lyx_keep_temps:
684         removeFiles(['chkconfig.sed', 'chkconfig.vars',  \
685             'wrap_chkconfig.ltx', 'wrap_chkconfig.log', \
686             'chklayouts.tex', 'missfont.log', 
687             'chklatex.ltx', 'chklatex.log'])
688
689
690 if __name__ == '__main__':
691     lyx_check_config = True
692     outfile = 'lyxrc.defaults'
693     rc_entries = ''
694     lyx_keep_temps = False
695     version_suffix = ''
696     logfile = 'configure.log'
697     ## Parse the command line
698     for op in sys.argv[1:]:   # default shell/for list is $*, the options
699         if op in [ '-help', '--help', '-h' ]:
700             print '''Usage: configure [options]
701 Options:
702     --help                   show this help lines
703     --keep-temps             keep temporary files (for debug. purposes)
704     --without-latex-config   do not run LaTeX to determine configuration
705     --with-version-suffix=suffix suffix of binary installed files
706 '''
707             sys.exit(0)
708         elif op == '--without-latex-config':
709             lyx_check_config = False
710         elif op == '--keep-temps':
711             lyx_keep_temps = True
712         elif op[0:22] == '--with-version-suffix=':  # never mind if op is not long enough
713             version_suffix = op[22:]
714         else:
715             print "Unknown option", op
716             sys.exit(1)
717     #
718     # set up log file for stdout and stderr
719     log = open(logfile, 'w')
720     sys.stdout = Tee(sys.stdout, log)
721     sys.stderr = Tee(sys.stderr, log)
722     # check if we run from the right directory
723     srcdir = os.path.dirname(sys.argv[0])
724     if srcdir == '':
725         srcdir = '.'
726     if not os.path.isfile( os.path.join(srcdir, 'chkconfig.ltx') ):
727         print "configure: error: cannot find chkconfig.ltx script"
728         sys.exit(1)
729     setEnviron()
730     createDirectories()
731     windows_style_tex_paths = checkTeXPaths()
732     ## Write the first part of outfile
733     writeToFile(outfile, '''# This file has been automatically generated by LyX' lib/configure.py
734 # script. It contains default settings that have been determined by
735 # examining your system. PLEASE DO NOT MODIFY ANYTHING HERE! If you
736 # want to customize LyX, use LyX' Preferences dialog or modify directly 
737 # the "preferences" file instead. Any setting in that file will
738 # override the values given here.
739 ''')
740     # check latex
741     LATEX = checkLatex()
742     checkFormatEntries()
743     checkConverterEntries()
744     (chk_linuxdoc, bool_linuxdoc, linuxdoc_cmd) = checkLinuxDoc()
745     (chk_docbook, bool_docbook, docbook_cmd) = checkDocBook()
746     checkTeXAllowSpaces()
747     if windows_style_tex_paths != '':
748         addToRC(r'\tex_expects_windows_paths %s' % windows_style_tex_paths)
749     checkOtherEntries()
750     # --without-latex-config can disable lyx_check_config
751     checkLatexConfig( lyx_check_config and LATEX != '', bool_docbook, bool_linuxdoc)
752     createLaTeXConfig()
753     removeTempFiles()