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