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