]> git.lyx.org Git - lyx.git/blob - lib/configure.py
Use booleans True and False and fix a typo in configure.py
[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 checkDTLtools():
187     ''' Check whether DTL tools are available (Windows only) '''
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         dtl_tools = True
193     else:
194         dtl_tools = False
195     return dtl_tools
196
197
198 def checkLatex(dtl_tools):
199     ''' Check latex, return lyx_check_config '''
200     if dtl_tools:
201         # Windows only: DraftDVI
202         converter_entry = r'''\converter latex      dvi2       "%%"     "latex"
203 \converter dvi2       dvi        "python -tt $$s/scripts/clean_dvi.py $$i $$o"  ""'''
204     else:
205         converter_entry = r'\converter latex      dvi        "%%"       "latex"'
206     path, LATEX = checkProg('a Latex2e program', ['pplatex $$i', 'latex $$i', 'latex2e $$i'],
207         rc_entry = [converter_entry])
208     # no latex
209     if LATEX != '':
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             # valid latex2e
221             return LATEX
222         else:
223             print "Latex not usable (not LaTeX2e) "
224         # remove temporary files
225         removeFiles(['chklatex.ltx', 'chklatex.log'])
226     return ''
227
228
229 def checkFormatEntries(dtl_tools):  
230     ''' Check all formats (\Format entries) '''
231     checkViewer('a Tgif viewer and editor', ['tgif'],
232         rc_entry = [r'\Format tgif       obj     Tgif                   "" "%%" "%%"    "vector"'])
233     #
234     checkViewer('a FIG viewer and editor', ['xfig'],
235         rc_entry = [r'\Format fig        fig     FIG                    "" "%%" "%%"    "vector"'])
236     #
237     checkViewer('a Grace viewer and editor', ['xmgrace'],
238         rc_entry = [r'\Format agr        agr     Grace                  "" "%%" "%%"    "vector"'])
239     #
240     checkViewer('a FEN viewer and editor', ['xboard -lpf $$i -mode EditPosition'],
241         rc_entry = [r'\Format fen        fen     FEN                    "" "%%" "%%"    ""'])
242     #
243     path, iv = checkViewer('a raster image viewer', ['xv', 'kview', 'gimp'])
244     path, ie = checkViewer('a raster image editor', ['gimp'])
245     addToRC(r'''\Format bmp        bmp     BMP                    "" "%s"       "%s"    ""
246 \Format gif        gif     GIF                    "" "%s"       "%s"    ""
247 \Format jpg        jpg     JPEG                   "" "%s"       "%s"    ""
248 \Format pbm        pbm     PBM                    "" "%s"       "%s"    ""
249 \Format pgm        pgm     PGM                    "" "%s"       "%s"    ""
250 \Format png        png     PNG                    "" "%s"       "%s"    ""
251 \Format ppm        ppm     PPM                    "" "%s"       "%s"    ""
252 \Format tiff       tif     TIFF                   "" "%s"       "%s"    ""
253 \Format xbm        xbm     XBM                    "" "%s"       "%s"    ""
254 \Format xpm        xpm     XPM                    "" "%s"       "%s"    ""''' % \
255         (iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie) )
256     #
257     checkViewer('a text editor', ['xemacs', 'gvim', 'kedit', 'kwrite', 'kate', \
258         'nedit', 'gedit', 'notepad'],
259         rc_entry = [r'''\Format asciichess asc    "Plain text (chess output)"  "" ""    "%%"    ""
260 \Format asciiimage asc    "Plain text (image)"         "" ""    "%%"    ""
261 \Format asciixfig  asc    "Plain text (Xfig output)"   "" ""    "%%"    ""
262 \Format dateout    tmp    "date (output)"         "" "" "%%"    ""
263 \Format docbook    sgml    DocBook                B  "" "%%"    "document"
264 \Format docbook-xml xml   "Docbook (XML)"         "" "" "%%"    "document"
265 \Format literate   nw      NoWeb                  N  "" "%%"    "document"
266 \Format lilypond   ly     "LilyPond music"        "" "" "%%"    "vector"
267 \Format latex      tex    "LaTeX (plain)"         L  "" "%%"    "document"
268 \Format linuxdoc   sgml    LinuxDoc               x  "" "%%"    "document"
269 \Format pdflatex   tex    "LaTeX (pdflatex)"      "" "" "%%"    "document"
270 \Format text       txt    "Plain text"            a  "" "%%"    "document"
271 \Format text2      txt    "Plain text (pstotext)" "" "" "%%"    "document"
272 \Format text3      txt    "Plain text (ps2ascii)" "" "" "%%"    "document"
273 \Format text4      txt    "Plain text (catdvi)"   "" "" "%%"    "document"
274 \Format textparagraph txt "Plain text (paragraphs)"    "" ""    "%%"    "document"''' ])
275     #
276     #checkProg('a Postscript interpreter', ['gs'],
277     #  rc_entry = [ r'\ps_command "%%"' ])
278     checkViewer('a Postscript previewer', ['gv', 'ghostview -swap', 'kghostview'],
279         rc_entry = [r'''\Format eps        eps     EPS                    "" "%%"       ""      "vector"
280 \Format ps         ps      Postscript             t  "%%"       ""      "document,vector"'''])
281     #
282     checkViewer('a PDF previewer', ['acrobat', 'acroread', 'gv', 'ghostview', \
283                             'xpdf', 'kpdf', 'kghostview'],
284         rc_entry = [r'''\Format pdf        pdf    "PDF (ps2pdf)"          P  "%%"       ""      "document,vector"
285 \Format pdf2       pdf    "PDF (pdflatex)"        F  "%%"       ""      "document,vector"
286 \Format pdf3       pdf    "PDF (dvipdfm)"         m  "%%"       ""      "document,vector"'''])
287     #
288     checkViewer('a DVI previewer', ['xdvi', 'kdvi'],
289         rc_entry = [r'\Format dvi        dvi     DVI                    D  "%%" ""      "document,vector"'])
290     if dtl_tools:
291         # Windows only: DraftDVI
292         addToRC(r'\Format dvi2       dvi     DraftDVI               ""  ""      "document,vector"')
293     #
294     checkViewer('a HTML previewer', ['mozilla file://$$p$$i', 'netscape'],
295         rc_entry = [r'\Format html       html    HTML                   H  "%%" ""      "document"'])
296     #
297     # entried that do not need checkProg
298     addToRC(r'''\Format date       ""     "date command"          "" "" ""      ""
299 \Format fax        ""      Fax                    "" "" ""      "document"
300 \Format lyx        lyx     LyX                    "" "" ""      ""
301 \Format lyx13x     lyx13  "LyX 1.3.x"             "" "" ""      "document"
302 \Format lyxpreview lyxpreview "LyX Preview"       "" "" ""      ""
303 \Format pdftex     pdftex_t PDFTEX                "" "" ""      ""
304 \Format program    ""      Program                "" "" ""      ""
305 \Format pstex      pstex_t PSTEX                  "" "" ""      ""
306 \Format rtf        rtf    "Rich Text Format"      "" "" ""      "document,vector"
307 \Format sxw        sxw    "OpenOffice.Org Writer" O  "" ""      "document,vector"
308 \Format wmf        wmf    "Windows Meta File"     "" "" ""      "vector"
309 \Format word       doc    "MS Word"               W  "" ""      "document,vector"
310 \Format wordhtml   html   "MS Word (HTML)"        "" ""        ""       "document"
311 ''')
312
313
314 def checkConverterEntries():
315     ''' Check all converters (\converter entries) '''
316     checkProg('the pdflatex program', ['pdflatex $$i'],
317         rc_entry = [ r'\converter pdflatex   pdf2       "%%"    "latex"' ])
318     
319     ''' If we're running LyX in-place then tex2lyx will be found in
320             ../src/tex2lyx. Add this directory to the PATH temporarily and
321             search for tex2lyx.
322             Use PATH to avoid any problems with paths-with-spaces.
323     '''
324     path_orig = os.environ["PATH"]
325     os.environ["PATH"] = os.path.join('..', 'src', 'tex2lyx') + \
326         os.pathsep + path_orig
327
328     checkProg('a LaTeX/Noweb -> LyX converter', ['tex2lyx', 'tex2lyx' + version_suffix],
329         rc_entry = [r'''\converter latex      lyx        "%% -f $$i $$o"        ""
330 \converter literate   lyx        "%% -n -f $$i $$o"     ""'''])
331
332     os.environ["PATH"] = path_orig
333
334     #
335     checkProg('a Noweb -> LaTeX converter', ['noweave -delay -index $$i > $$o'],
336         rc_entry = [ r'\converter literate   latex      "%%"    ""' ])
337     #
338     checkProg('a HTML -> LaTeX converter', ['html2latex $$i'],
339         rc_entry = [ r'\converter html       latex      "%%"    ""' ])
340     #
341     checkProg('a MSWord -> LaTeX converter', ['wvCleanLatex $$i $$o'],
342         rc_entry = [ r'\converter word       latex      "%%"    ""' ])
343     #
344     checkProg('a LaTeX -> MS Word converter', ["htlatex $$i 'html,word' 'symbol/!' '-cvalidate'"],
345         rc_entry = [ r'\converter latex      wordhtml   "%%"    ""' ])
346     #
347     checkProg('an OpenOffice.org -> LaTeX converter', ['w2l -clean $$i'],
348         rc_entry = [ r'\converter sxw        latex      "%%"    ""' ])
349     #
350     checkProg('a LaTeX -> OpenOffice.org converter', ['oolatex $$i', 'oolatex.sh $$i'],
351         rc_entry = [ r'\converter latex      sxw        "%%"    "latex"' ])
352     # On windows it is called latex2rt.exe
353     checkProg('a LaTeX -> RTF converter', ['latex2rtf -p -S -o $$o $$i', 'latex2rt -p -S -o $$o $$i'],
354         rc_entry = [ r'\converter latex      rtf        "%%"    "needaux"' ])
355     #
356     checkProg('a PS to PDF converter', ['ps2pdf13 $$i $$o'],
357         rc_entry = [ r'\converter ps         pdf        "%%"    ""' ])
358     #
359     checkProg('a PS to TXT converter', ['pstotext $$i > $$o'],
360         rc_entry = [ r'\converter ps         text2      "%%"    ""' ])
361     #
362     checkProg('a PS to TXT converter', ['ps2ascii $$i $$o'],
363         rc_entry = [ r'\converter ps         text3      "%%"    ""' ])
364     #
365     checkProg('a DVI to TXT converter', ['catdvi $$i > $$o'],
366         rc_entry = [ r'\converter dvi        text4      "%%"    ""' ])
367     #
368     checkProg('a DVI to PS converter', ['dvips -o $$o $$i'],
369         rc_entry = [ r'\converter dvi        ps         "%%"    ""' ])
370     #
371     checkProg('a DVI to PDF converter', ['dvipdfmx -o $$o $$i', 'dvipdfm -o $$o $$i'],
372         rc_entry = [ r'\converter dvi        pdf3       "%%"    ""' ])
373     #
374     path, dvipng = checkProg('dvipng', ['dvipng'])
375     if dvipng == "dvipng":
376         addToRC(r'\converter lyxpreview png        "python -tt $$s/scripts/lyxpreview2bitmap.py"        ""')
377     else:
378         addToRC(r'\converter lyxpreview png        ""   ""')
379     #  
380     checkProg('a fax program', ['kdeprintfax $$i', 'ksendfax $$i'],
381         rc_entry = [ r'\converter ps         fax        "%%"    ""'])
382     #
383     checkProg('a FIG -> EPS/PPM converter', ['fig2dev'],
384         rc_entry = [
385             r'''\converter fig        eps        "fig2dev -L eps $$i $$o"       ""
386 \converter fig        ppm        "fig2dev -L ppm $$i $$o"       ""
387 \converter fig        png        "fig2dev -L png $$i $$o"       ""''',
388             ''])
389     #
390     checkProg('a TIFF -> PS converter', ['tiff2ps $$i > $$o'],
391         rc_entry = [ r'\converter tiff       eps        "%%"    ""', ''])
392     #
393     checkProg('a TGIF -> EPS/PPM converter', ['tgif'],
394         rc_entry = [
395             r'''\converter tgif       eps        "tgif -stdout -print -color -eps $$i > $$o"    ""
396 \converter tgif       ppm        "tgif -stdout -print -color -ppm $$i > $$o"    ""
397 \converter tgif       png        "tgif -stdout -print -color -png $$i > $$o"    ""
398 \converter tgif       pdf        "tgif -stdout -print -color -pdf $$i > $$o"    ""''',
399             ''])
400     #
401     checkProg('a WMF -> EPS converter', ['wmf2eps -o $$o $$i'],
402         rc_entry = [ r'\converter wmf        eps        "%%"    ""', ''])
403     #
404     checkProg('a EPS -> PDF converter', ['epstopdf'],
405         rc_entry = [ r'\converter eps        pdf        "epstopdf --outfile=$$o $$i"    ""', ''])
406     #
407     checkProg('a Grace -> Image converter', ['gracebat'],
408         rc_entry = [
409             r'''\converter agr        eps        "gracebat -hardcopy -printfile $$o -hdevice EPS $$i 2>/dev/null"       ""
410 \converter agr        png        "gracebat -hardcopy -printfile $$o -hdevice PNG $$i 2>/dev/null"       ""
411 \converter agr        jpg        "gracebat -hardcopy -printfile $$o -hdevice JPEG $$i 2>/dev/null"      ""
412 \converter agr        ppm        "gracebat -hardcopy -printfile $$o -hdevice PNM $$i 2>/dev/null"       ""''',
413             ''])
414     #
415     checkProg('a LaTeX -> HTML converter', ['htlatex $$i', 'tth  -t -e2 -L$$b < $$i > $$o', \
416         'latex2html -no_subdir -split 0 -show_section_numbers $$i', 'hevea -s $$i'],
417         rc_entry = [ r'\converter latex      html       "%%"    "originaldir,needaux"' ])
418     #
419     path, lilypond = checkProg('a LilyPond -> EPS/PDF/PNG converter', ['lilypond'])
420     if (lilypond != ''):
421         version_string = cmdOutput("lilypond --version")
422         match = re.match('GNU LilyPond (\S+)', version_string)
423         if match:
424             version_number = match.groups()[0]
425             version = version_number.split('.')
426             if int(version[0]) > 2 or (len(version) > 1 and int(version[0]) == 2 and int(version[1]) >= 6):
427                 addToRC(r'''\converter lilypond   eps        "lilypond -b eps --ps $$i" ""
428 \converter lilypond   png        "lilypond -b eps --png $$i"    ""''')
429                 if int(version[0]) > 2 or (len(version) > 1 and int(version[0]) == 2 and int(version[1]) >= 9):
430                     addToRC(r'\converter lilypond   pdf        "lilypond -b eps --pdf $$i"      ""')
431                 print '+  found LilyPond version %s.' % version_number
432             else:
433                 print '+  found LilyPond, but version %s is too old.' % version_number
434         else:
435             print '+  found LilyPond, but could not extract version number.'
436     #
437     # FIXME: no rc_entry? comment it out
438     # checkProg('Image converter', ['convert $$i $$o'])
439     #
440     # Entried that do not need checkProg
441     addToRC(r'''\converter lyxpreview ppm        "python -tt $$s/scripts/lyxpreview2bitmap.py"  ""
442 \converter date       dateout    "date +%d-%m-%Y > $$o" ""
443 \converter docbook    docbook-xml "cp $$i $$o"  "xml"
444 \converter fen        asciichess "python -tt $$s/scripts/fen2ascii.py $$i $$o"  ""
445 \converter fig        pdftex     "python -tt $$s/scripts/fig2pdftex.py $$i $$o" ""
446 \converter fig        pstex      "python -tt $$s/scripts/fig2pstex.py $$i $$o"  ""
447 \converter lyx        lyx13x     "python -tt $$s/lyx2lyx/lyx2lyx -t 221 $$i > $$o"      ""
448 ''')
449
450
451 def checkLinuxDoc():
452     ''' Check linuxdoc '''
453     #
454     path, LINUXDOC = checkProg('SGML-tools 1.x (LinuxDoc)', ['sgml2lyx'],
455         rc_entry = [
456         r'''\converter linuxdoc   lyx        "sgml2lyx $$i"     ""
457 \converter linuxdoc   latex      "sgml2latex $$i"       ""
458 \converter linuxdoc   dvi        "sgml2latex -o dvi $$i"        ""
459 \converter linuxdoc   html       "sgml2html $$i"        ""''',
460         r'''\converter linuxdoc   lyx        "" ""
461 \converter linuxdoc   latex      ""     ""
462 \converter linuxdoc   dvi        ""     ""
463 \converter linuxdoc   html       ""     ""''' ])
464     if LINUXDOC != '':
465         return ('yes', 'true', '\\def\\haslinuxdoc{yes}')
466     else:
467         return ('no', 'false', '')
468
469
470 def checkDocBook():
471     ''' Check docbook '''
472     path, DOCBOOK = checkProg('SGML-tools 2.x (DocBook) or db2x scripts', ['sgmltools', 'db2dvi'],
473         rc_entry = [
474             r'''\converter docbook    dvi        "sgmltools -b dvi $$i" ""
475 \converter docbook    html       "sgmltools -b html $$i"        ""''',
476             r'''\converter docbook    dvi        "db2dvi $$i"   ""
477 \converter docbook    html       "db2html $$i"  ""''',
478             r'''\converter docbook    dvi        ""     ""
479 \converter docbook    html       ""     ""'''])
480     #
481     if DOCBOOK != '':
482         return ('yes', 'true', '\\def\\hasdocbook{yes}')
483     else:
484         return ('no', 'false', '')
485
486
487 def checkOtherEntries():
488     ''' entries other than Format and Converter '''
489     checkProg('a *roff formatter', ['groff', 'nroff'],
490         rc_entry = [
491             r'\ascii_roff_command "groff -t -Tlatin1 $$FName"',
492             r'\ascii_roff_command "tbl $$FName | nroff"',
493             r'\ascii_roff_command ""' ])
494     checkProg('ChkTeX', ['chktex -n1 -n3 -n6 -n9 -n22 -n25 -n30 -n38'],
495         rc_entry = [ r'\chktex_command "%%"' ])
496     checkProg('a spellchecker', ['ispell'],
497         rc_entry = [ r'\spell_command "%%"' ])
498     ## FIXME: OCTAVE is not used anywhere
499     # path, OCTAVE = checkProg('Octave', ['octave'])
500     ## FIXME: MAPLE is not used anywhere
501     # path, MAPLE = checkProg('Maple', ['maple'])
502     checkProg('a spool command', ['lp', 'lpr'],
503         rc_entry = [
504             r'''\print_spool_printerprefix "-d "
505 \print_spool_command "lp"''',
506             r'''\print_spool_printerprefix "-P",
507 \print_spool_command "lpr"''',
508             ''])
509     # Add the rest of the entries (no checkProg is required)
510     addToRC(r'''\copier    fig        "python -tt $$s/scripts/fig_copy.py $$i $$o"
511 \copier    pstex      "python -tt $$s/scripts/tex_copy.py $$i $$o $$l"
512 \copier    pdftex     "python -tt $$s/scripts/tex_copy.py $$i $$o $$l"
513 ''')
514
515
516 def processLayoutFile(file, bool_docbook, bool_linuxdoc):
517     ''' process layout file and get a line of result
518         
519         Declear line are like this: (article.layout, scrbook.layout, svjog.layout)
520         
521         \DeclareLaTeXClass{article}
522         \DeclareLaTeXClass[scrbook]{book (koma-script)}
523         \DeclareLaTeXClass[svjour,svjog.clo]{article (Springer - svjour/jog)}
524
525         we expect output:
526         
527         "article" "article" "article" "false"
528         "scrbook" "scrbook" "book (koma-script)" "false"
529         "svjog" "svjour" "article (Springer - svjour/jog)" "false"
530     '''
531     classname = file.split(os.sep)[-1].split('.')[0]
532     # return ('LaTeX', '[a,b]', 'a', ',b,c', 'article') for \DeclearLaTeXClass[a,b,c]{article}
533     p = re.compile(r'\Declare(LaTeX|DocBook)Class\s*(\[([^,]*)(,.*)*\])*\s*{(.*)}')
534     for line in open(file).readlines():
535         res = p.search(line)
536         if res != None:
537             (classtype, optAll, opt, opt1, desc) = res.groups()
538             avai = {'LaTeX':'false', 'DocBook':bool_docbook, 'LinuxDoc':bool_linuxdoc}[classtype]
539             if opt == None:
540                 opt = classname
541             return '"%s" "%s" "%s" "%s"\n' % (classname, opt, desc, avai)
542     print "Layout file without \DeclearXXClass line. "
543     sys.exit(2)
544
545     
546 def checkLatexConfig(check_config, bool_docbook, bool_linuxdoc):
547     ''' Explore the LaTeX configuration '''
548     print 'checking LaTeX configuration... ',
549     # First, remove the files that we want to re-create
550     removeFiles(['textclass.lst', 'packages.lst', 'chkconfig.sed'])
551     #
552     if not check_config:
553         print ' default values'
554         print '+checking list of textclasses... '
555         tx = open('textclass.lst', 'w')
556         tx.write('''
557 # This file declares layouts and their associated definition files
558 # (include dir. relative to the place where this file is).
559 # It contains only default values, since chkconfig.ltx could not be run
560 # for some reason. Run ./configure.py if you need to update it after a
561 # configuration change.
562 ''')
563         # build the list of available layout files and convert it to commands
564         # for chkconfig.ltx
565         foundClasses = []
566         for file in glob.glob( os.path.join('layouts', '*.layout') ) + \
567             glob.glob( os.path.join(srcdir, 'layouts', '*.layout' ) ) :
568             # valid file?
569             if not os.path.isfile(file): 
570                 continue
571             # get stuff between /xxxx.layout .
572             classname = file.split(os.sep)[-1].split('.')[0]
573             #  tr ' -' '__'`
574             cleanclass = classname.replace(' ', '_')
575             cleanclass = cleanclass.replace('-', '_')
576             # make sure the same class is not considered twice
577             if foundClasses.count(cleanclass) == 0: # not found before
578                 foundClasses.append(cleanclass)
579                 tx.write(processLayoutFile(file, bool_docbook, bool_linuxdoc))
580         tx.close()
581         print '\tdone'
582     else:
583         print '\tauto'
584         removeFiles(['wrap_chkconfig.ltx', 'chkconfig.vars', \
585             'chkconfig.classes', 'chklayouts.tex'])
586         rmcopy = False
587         if not os.path.isfile( 'chkconfig.ltx' ):
588             shutil.copy( os.path.join(srcdir, 'chkconfig.ltx'),  'chkconfig.ltx' )
589             rmcopy = True
590         writeToFile('wrap_chkconfig.ltx', '%s\n%s\n\\input{chkconfig.ltx}\n' \
591             % (linuxdoc_cmd, docbook_cmd) )
592         # Construct the list of classes to test for.
593         # build the list of available layout files and convert it to commands
594         # for chkconfig.ltx
595         p1 = re.compile(r'\Declare(LaTeX|DocBook)Class')
596         testclasses = list()
597         for file in glob.glob( os.path.join('layouts', '*.layout') ) + \
598             glob.glob( os.path.join(srcdir, 'layouts', '*.layout' ) ) :
599             if not os.path.isfile(file):
600                 continue
601             classname = file.split(os.sep)[-1].split('.')[0]
602             for line in open(file).readlines():
603                 if p1.search(line) == None:
604                     continue
605                 if line[0] != '#':
606                     print "Wrong input layout file with line '" + line
607                     sys.exit(3)
608                 testclasses.append("\\TestDocClass{%s}{%s}" % (classname, line[1:].strip()))
609                 break
610         testclasses.sort()
611         cl = open('chklayouts.tex', 'w')
612         for line in testclasses:
613             cl.write(line + '\n')
614         cl.close()
615         #
616         # we have chklayouts.tex, then process it
617         fout = os.popen(LATEX + ' wrap_chkconfig.ltx')
618         while True:
619             line = fout.readline()
620             if not line:
621                 break;
622             if re.match('^\+', line):
623                 print line,
624         fout.close()
625         #
626         # currently, values in chhkconfig are only used to set
627         # \font_encoding
628         values = {}
629         for line in open('chkconfig.vars').readlines():
630             key, val = re.sub('-', '_', line).split('=')
631             val = val.strip()
632             values[key] = val.strip("'")
633         # chk_fontenc may not exist 
634         try:
635             addToRC(r'\font_encoding "%s"' % values["chk_fontenc"])
636         except:
637             pass
638         if rmcopy:   # remove the copied file
639             removeFiles( [ 'chkconfig.ltx' ] )
640
641
642 def createLaTeXConfig():
643     ''' create LaTeXConfig.lyx '''
644     # if chkconfig.sed does not exist (because LaTeX did not run),
645     # then provide a standard version.
646     if not os.path.isfile('chkconfig.sed'):
647         writeToFile('chkconfig.sed', 's!@.*@!???!g\n')
648     print "creating packages.lst"
649     # if packages.lst does not exist (because LaTeX did not run),
650     # then provide a standard version.
651     if not os.path.isfile('packages.lst'):
652         writeToFile('packages.lst', '''
653 ### This file should contain the list of LaTeX packages that have been
654 ### recognized by LyX. Unfortunately, since configure could not find
655 ### your LaTeX2e program, the tests have not been run. Run ./configure.py
656 ### if you need to update it after a configuration change.
657 ''')
658     print 'creating doc/LaTeXConfig.lyx'
659     #
660     # This is originally done by sed, using a
661     # tex-generated file chkconfig.sed
662     ##sed -f chkconfig.sed ${srcdir}/doc/LaTeXConfig.lyx.in
663     ##  >doc/LaTeXConfig.lyx
664     # Now, we have to do it by hand (python).
665     #
666     # add to chekconfig.sed
667     writeToFile('chkconfig.sed', '''s!@chk_linuxdoc@!%s!g
668 s!@chk_docbook@!%s!g
669     ''' % (chk_linuxdoc, chk_docbook) , append=True)
670     # process this sed file!!!!
671     lyxin = open( os.path.join(srcdir, 'doc', 'LaTeXConfig.lyx.in')).readlines()
672     # get the rules
673     p = re.compile(r's!(.*)!(.*)!g')
674     # process each sed replace.
675     for sed in open('chkconfig.sed').readlines():
676         if sed.strip() == '':
677             continue
678         try:
679             fr, to = p.match(sed).groups()
680             # if latex did not run, change all @name@ to '???'
681             if fr == '@.*@':
682                 for line in range(len(lyxin)):
683                     lyxin[line] = re.sub('@.*@', to, lyxin[line])
684             else:
685                 for line in range(len(lyxin)):
686                     lyxin[line] = lyxin[line].replace(fr, to)
687         except:  # wrong sed entry?
688             print "Wrong sed entry in chkconfig.sed: '" + sed + "'"
689             sys.exit(4)
690     # 
691     writeToFile( os.path.join('doc', 'LaTeXConfig.lyx'),
692         ''.join(lyxin))
693
694
695 def checkTeXAllowSpaces():
696     ''' Let's check whether spaces are allowed in TeX file names '''
697     tex_allows_spaces = 'false'
698     if lyx_check_config:
699         print "Checking whether TeX allows spaces in file names... ",
700         writeToFile('a b.tex', r'\message{working^^J}' )
701         if os.name == 'nt':
702             latex_out = cmdOutput(LATEX + r""" "\nonstopmode\input{\"a b\"}" """)
703         else:
704             latex_out = cmdOutput(LATEX + r""" '\nonstopmode\input{"a b"}' """)
705         if 'working' in latex_out:
706             print 'yes'
707             tex_allows_spaces = 'true'
708         else:
709             print 'no'
710             tex_allows_spaces = 'false'
711         addToRC(r'\tex_allows_spaces ' + tex_allows_spaces)
712         removeFiles( [ 'a b.tex', 'a b.log', 'texput.log' ])
713
714
715 def removeTempFiles():
716     # Final clean-up
717     if not lyx_keep_temps:
718         removeFiles(['chkconfig.sed', 'chkconfig.vars',  \
719             'wrap_chkconfig.ltx', 'wrap_chkconfig.log', \
720             'chklayouts.tex', 'missfont.log', 
721             'chklatex.ltx', 'chklatex.log'])
722
723
724 if __name__ == '__main__':
725     lyx_check_config = True
726     outfile = 'lyxrc.defaults'
727     rc_entries = ''
728     lyx_keep_temps = False
729     version_suffix = ''
730     logfile = 'configure.log'
731     ## Parse the command line
732     for op in sys.argv[1:]:   # default shell/for list is $*, the options
733         if op in [ '-help', '--help', '-h' ]:
734             print '''Usage: configure [options]
735 Options:
736     --help                   show this help lines
737     --keep-temps             keep temporary files (for debug. purposes)
738     --without-latex-config   do not run LaTeX to determine configuration
739     --with-version-suffix=suffix suffix of binary installed files
740 '''
741             sys.exit(0)
742         elif op == '--without-latex-config':
743             lyx_check_config = False
744         elif op == '--keep-temps':
745             lyx_keep_temps = True
746         elif op[0:22] == '--with-version-suffix=':  # never mind if op is not long enough
747             version_suffix = op[22:]
748         else:
749             print "Unknown option", op
750             sys.exit(1)
751     #
752     # set up log file for stdout and stderr
753     log = open(logfile, 'w')
754     sys.stdout = Tee(sys.stdout, log)
755     sys.stderr = Tee(sys.stderr, log)
756     # check if we run from the right directory
757     srcdir = os.path.dirname(sys.argv[0])
758     if srcdir == '':
759         srcdir = '.'
760     if not os.path.isfile( os.path.join(srcdir, 'chkconfig.ltx') ):
761         print "configure: error: cannot find chkconfig.ltx script"
762         sys.exit(1)
763     setEnviron()
764     createDirectories()
765     windows_style_tex_paths = checkTeXPaths()
766     dtl_tools = checkDTLtools()
767     ## Write the first part of outfile
768     writeToFile(outfile, '''# This file has been automatically generated by LyX' lib/configure.py
769 # script. It contains default settings that have been determined by
770 # examining your system. PLEASE DO NOT MODIFY ANYTHING HERE! If you
771 # want to customize LyX, use LyX' Preferences dialog or modify directly 
772 # the "preferences" file instead. Any setting in that file will
773 # override the values given here.
774 ''')
775     # check latex
776     LATEX = checkLatex(dtl_tools)
777     checkFormatEntries(dtl_tools)
778     checkConverterEntries()
779     (chk_linuxdoc, bool_linuxdoc, linuxdoc_cmd) = checkLinuxDoc()
780     (chk_docbook, bool_docbook, docbook_cmd) = checkDocBook()
781     checkTeXAllowSpaces()
782     if windows_style_tex_paths != '':
783         addToRC(r'\tex_expects_windows_paths %s' % windows_style_tex_paths)
784     checkOtherEntries()
785     # --without-latex-config can disable lyx_check_config
786     checkLatexConfig( lyx_check_config and LATEX != '', bool_docbook, bool_linuxdoc)
787     createLaTeXConfig()
788     removeTempFiles()