]> git.lyx.org Git - lyx.git/blob - lib/configure.py
From Joost Verburg: Put the clean_dvi.py script into the main distribution
[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 checkCygwinPath(srcdir):
82   ''' Adjust PATH for Win32 (Cygwin) '''
83   cygwin_path_fix = ''
84   if sys.platform == 'cygwin':
85     from tempfile import mkstemp
86     fd, tmpfname = mkstemp(suffix='.ltx', dir='/tmp')
87     os.write(fd, r'''
88 \documentstyle{article}
89 \begin{document}\end{document}
90   ''')
91     os.close(fd)
92     inpname = cmdOutput('cygpath -m ' + tmpfname)
93     # a wrapper file
94     wfd, wtmpfname = mkstemp(suffix='.ltx', dir='/tmp')
95     wtmpfname = cmdOutput('cygpath -m ' + wtmpfname)
96     os.write(wfd, r'\input{' + inpname + '}' )
97     os.close(wfd)
98     if cmdOutput('latex ' + wtmpfname).find('Error') != -1:
99       print "configure: cygwin detected; path correction is not needed"
100       cygwin_path_fix = 'false'
101     else:
102       print "configure: cygwin detected; path correction"
103       srcdir = cmdOutput('cygpath -m ' + srcdir)
104       print "srcdir = ", srcdir
105       cygwin_path_fix = 'true'
106     tmpbname,ext = os.path.splitext(os.path.basename(tmpfname))
107     wtmpbname,ext = os.path.splitext(os.path.basename(wtmpfname))
108     removeFiles( [ tmpfname, wtmpfname, tmpbname + '.log', \
109             tmpbname + '.aux', wtmpbname + '.log', wtmpbname + '.aux' ] )
110   return cygwin_path_fix
111
112
113 ## Searching some useful programs
114 def checkProg(description, progs, rc_entry = [], path = [] ):
115   '''
116     This function will search a program in $PATH plus given path
117     If found, return directory and program name (not the options).
118
119     description: description of the program
120
121     progs: check programs, for each prog, the first word is used
122       for searching but the whole string is used to replace
123       %% for a rc_entry. So, feel free to add '$$i' etc for programs.
124
125     path: additional pathes
126
127     rc_entry: entry to outfile, can be
128       1. emtpy: no rc entry will be added
129       2. one pattern: %% will be replaced by the first found program,
130          or 'none' is no program is found.
131       3. several patterns for each prog and 'none'. This is used 
132          when different programs have different usages. If you do not 
133          want 'none' entry to be added to the RC file, you can specify 
134          an entry for each prog and use '' for the 'none' entry.
135
136   '''
137   # one rc entry for each progs plus none entry
138   if len(rc_entry) > 1 and len(rc_entry) != len(progs) + 1:
139     print "rc entry should have one item or item for each prog and none."
140     sys.exit(2)
141   print 'checking for ' + description + '...'
142   ## print '(' + ','.join(progs) + ')',
143   for idx in range(len(progs)):
144     # ac_prog may have options, ac_word is the command name
145     ac_prog = progs[idx]
146     ac_word = ac_prog.split(' ')[0]
147     print '+checking for "' + ac_word + '"... ',
148     path = os.environ["PATH"].split(os.pathsep) + path
149     for ac_dir in path:
150       # check both ac_word and ac_word.exe (for windows system)
151       if os.path.isfile( os.path.join(ac_dir, ac_word) ) or \
152          os.path.isfile( os.path.join(ac_dir, ac_word + ".exe") ):
153         print ' yes'
154         # write rc entries for this command
155         if len(rc_entry) == 1:
156           addToRC(rc_entry[0].replace('%%', ac_prog))
157         elif len(rc_entry) > 1:
158           addToRC(rc_entry[idx].replace('%%', ac_prog))
159         return [ac_dir, ac_word]
160     # if not successful
161     print ' no'
162   # write rc entries for 'not found'
163   if len(rc_entry) > 0:  # the last one.
164     addToRC(rc_entry[-1].replace('%%', 'none'))
165   return ['', 'none']
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':
172     # Windows only: DraftDVI
173     if checkProg('DVI to DTL converter', ['dv2dt']) != ['', 'none'] and checkProg('DTL to DVI converter', ['dt2dv']) != ['', 'none']:
174       converter_entry = r'''\converter latex      dvi2       "%%"       "latex"
175 \converter dvi2       dvi        "python $$s/scripts/clean_dvi.py $$i $$o"      ""'''
176     else:
177       converter_entry = r'\converter latex      dvi        "%%" "latex"'
178   else:
179     converter_entry = r'\converter latex      dvi        "%%"   "latex"'
180   path, LATEX = checkProg('a Latex2e program', ['pplatex $$i', 'latex $$i', 'latex2e $$i'],
181     rc_entry = [converter_entry])
182   # no latex
183   if LATEX != 'none':
184     # Check if latex is usable
185     writeToFile('chklatex.ltx', '''
186 \\nonstopmode\\makeatletter
187 \\ifx\\undefined\\documentclass\\else
188   \\message{ThisIsLaTeX2e}
189 \\fi
190 \\@@end
191 ''')
192     # run latex on chklatex.ltx and check result
193     if cmdOutput(LATEX + ' chklatex.ltx').find('ThisIsLaTeX2e') != -1:
194       # valid latex2e
195       return LATEX
196     else:
197       print "Latex not usable (not LaTeX2e) "
198     # remove temporary files
199     removeFiles(['chklatex.ltx', 'chklatex.log'])
200   return ''
201
202
203 def checkFormatEntries():  
204   ''' Check all formats (\Format entries) '''
205   checkProg('a Tgif viewer and editor', ['tgif'],
206     rc_entry = [ r'\Format tgif       obj     Tgif                   "" "%%"    "%%"    ""'])
207   #
208   checkProg('a FIG viewer and editor', ['xfig'],
209     rc_entry = [ r'\Format fig        fig     FIG                    "" "%%"    "%%"    ""'] )
210   #
211   checkProg('a Grace viewer and editor', ['xmgrace'],
212     rc_entry = [ r'\Format agr        agr     Grace                  "" "%%"    "%%"    ""'] )
213   #
214   checkProg('a FEN viewer and editor', ['xboard -lpf $$i -mode EditPosition'],
215     rc_entry = [ r'\Format fen        fen     FEN                    "" "%%"    "%%"    ""' ])
216   #
217   path, iv = checkProg('a raster image viewer', ['xv', 'kview', 'gimp'])
218   path, ie = checkProg('a raster image editor', ['gimp'])
219   addToRC(r'''\Format bmp        bmp     BMP                    "" "%s" "%s"    ""
220 \Format gif        gif     GIF                    "" "%s"       "%s"    ""
221 \Format jpg        jpg     JPEG                   "" "%s"       "%s"    ""
222 \Format pbm        pbm     PBM                    "" "%s"       "%s"    ""
223 \Format pgm        pgm     PGM                    "" "%s"       "%s"    ""
224 \Format png        png     PNG                    "" "%s"       "%s"    ""
225 \Format ppm        ppm     PPM                    "" "%s"       "%s"    ""
226 \Format tiff       tif     TIFF                   "" "%s"       "%s"    ""
227 \Format xbm        xbm     XBM                    "" "%s"       "%s"    ""
228 \Format xpm        xpm     XPM                    "" "%s"       "%s"    ""''' % \
229     (iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie) )
230   #
231   checkProg('a text editor', ['xemacs', 'gvim', 'kedit', 'kwrite', 'kate', \
232     'nedit', 'gedit', 'notepad'],
233     rc_entry = [ r'''\Format asciichess asc    "Plain text (chess output)"  "" ""       "%%"    ""
234 \Format asciiimage asc    "Plain text (image)"         "" ""    "%%"    ""
235 \Format asciixfig  asc    "Plain text (Xfig output)"   "" ""    "%%"    ""
236 \Format dateout    tmp    "date (output)"         "" "" "%%"    ""
237 \Format docbook    sgml    DocBook                B  "" "%%"    "document"
238 \Format docbook-xml xml   "Docbook (XML)"         "" "" "%%"    "document"
239 \Format literate   nw      NoWeb                  N  "" "%%"    "document"
240 \Format latex      tex    "LaTeX (plain)"         L  "" "%%"    "document"
241 \Format linuxdoc   sgml    LinuxDoc               x  "" "%%"    "document"
242 \Format pdflatex   tex    "LaTeX (pdflatex)"      "" "" "%%"    "document"
243 \Format text       txt    "Plain text"            a  "" "%%"    "document"
244 \Format textparagraph txt "Plain text (paragraphs)"    "" ""    "%%"    "document"''' ])
245   #
246   #checkProg('a Postscript interpreter', ['gs'],
247   #  rc_entry = [ r'\ps_command "%%"' ])
248   checkProg('a Postscript previewer', ['gv', 'ghostview -swap', 'kghostview'],
249     rc_entry = [ r'''\Format eps        eps     EPS                    "" "%%"  ""      ""
250 \Format ps         ps      Postscript             t  "%%"       ""      "document"''' ])
251   #
252   checkProg('a PDF previewer', ['acrobat', 'acroread', 'gv', 'ghostview', \
253               'xpdf', 'kpdf', 'kghostview'],
254     rc_entry = [ r'''\Format pdf        pdf    "PDF (ps2pdf)"          P  "%%"  ""      "document"
255 \Format pdf2       pdf    "PDF (pdflatex)"        F  "%%"       ""      "document"
256 \Format pdf3       pdf    "PDF (dvipdfm)"         m  "%%"       ""      "document"''' ])
257   #
258   checkProg('a DVI previewer', ['xdvi', 'kdvi'],
259     rc_entry = [ r'\Format dvi        dvi     DVI                    D  "%%"    ""      "document"' ])
260   if os.name == 'nt' or sys.platform == 'cygwin':
261     # Windows only: DraftDVI
262     if checkProg('DVI to DTL converter', ['dv2dt']) != ['', 'none'] and checkProg('DTL to DVI converter', ['dt2dv']) != ['', 'none']:
263       addToRC(r'\Format dvi2       dvi     DraftDVI               "" "" "document"')
264   #
265   checkProg('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'],
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', ['dvipdfm $$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 $$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       pdf        "tgif -stdout -print -color -pdf $$i > $$o"    ""''',
357       ''])
358   #
359   checkProg('a EPS -> PDF converter', ['epstopdf'],
360     rc_entry = [ r'\converter eps        pdf        "epstopdf --outfile=$$o $$i"        ""', ''])
361   #
362   checkProg('a Grace -> Image converter', ['gracebat'],
363     rc_entry = [
364       r'''\converter agr        eps        "gracebat -hardcopy -printfile $$o -hdevice EPS $$i 2>/dev/null"     ""
365 \converter agr        png        "gracebat -hardcopy -printfile $$o -hdevice PNG $$i 2>/dev/null"       ""
366 \converter agr        jpg        "gracebat -hardcopy -printfile $$o -hdevice JPEG $$i 2>/dev/null"      ""
367 \converter agr        ppm        "gracebat -hardcopy -printfile $$o -hdevice PNM $$i 2>/dev/null"       ""''',
368       ''])
369   #
370   checkProg('a LaTeX -> HTML converter', ['htlatex $$i', 'tth  -t -e2 -L$$b < $$i > $$o', \
371     'latex2html -no_subdir -split 0 -show_section_numbers $$i', 'hevea -s $$i'],
372     rc_entry = [ r'\converter latex      html       "%%"        "originaldir,needaux"' ])
373   #
374   # FIXME: no rc_entry? comment it out
375   # checkProg('Image converter', ['convert $$i $$o'])
376   #
377   # Entried that do not need checkProg
378   addToRC(r'''\converter lyxpreview ppm        "python $$s/scripts/lyxpreview2bitmap.py"        ""
379 \converter date       dateout    "date +%d-%m-%Y > $$o" ""
380 \converter docbook    docbook-xml "cp $$i $$o"  "xml"
381 \converter fen        asciichess "python $$s/scripts/fen2ascii.py $$i $$o"      ""
382 \converter fig        pdftex     "sh $$s/scripts/fig2pdftex.sh $$i $$o" ""
383 \converter fig        pstex      "sh $$s/scripts/fig2pstex.sh $$i $$o"  ""
384 \converter lyx        lyx13x     "python $$s/lyx2lyx/lyx2lyx -t 221 $$i > $$o"  ""
385 ''')
386
387
388 def checkLinuxDoc():
389   ''' Check linuxdoc '''
390   #
391   path, LINUXDOC = checkProg('SGML-tools 1.x (LinuxDoc)', ['sgml2lyx'],
392     rc_entry = [
393     r'''\converter linuxdoc   lyx        "sgml2lyx $$i" ""
394 \converter linuxdoc   latex      "sgml2latex $$i"       ""
395 \converter linuxdoc   dvi        "sgml2latex -o dvi $$i"        ""
396 \converter linuxdoc   html       "sgml2html $$i"        ""''',
397     r'''\converter linuxdoc   lyx        "none" ""
398 \converter linuxdoc   latex      "none" ""
399 \converter linuxdoc   dvi        "none" ""
400 \converter linuxdoc   html       "none" ""''' ])
401   if LINUXDOC != 'none':
402     return ('yes', 'true', '\\def\\haslinuxdoc{yes}')
403   else:
404     return ('no', 'false', '')
405
406
407 def checkDocBook():
408   ''' Check docbook '''
409   path, DOCBOOK = checkProg('SGML-tools 2.x (DocBook) or db2x scripts', ['sgmltools', 'db2dvi'],
410     rc_entry = [
411       r'''\converter docbook    dvi        "sgmltools -b dvi $$i"       ""
412 \converter docbook    html       "sgmltools -b html $$i"        ""''',
413       r'''\converter docbook    dvi        "db2dvi $$i" ""
414 \converter docbook    html       "db2html $$i"  ""''',
415       r'''\converter docbook    dvi        "none"       ""
416 \converter docbook    html       "none" ""'''])
417   #
418   if DOCBOOK != 'none':
419     return ('yes', 'true', '\\def\\hasdocbook{yes}')
420   else:
421     return ('no', 'false', '')
422
423
424 def checkOtherEntries():
425   ''' entries other than Format and Converter '''
426   checkProg('a *roff formatter', ['groff', 'nroff'],
427     rc_entry = [
428       r'\ascii_roff_command "groff -t -Tlatin1 $$FName"',
429       r'\ascii_roff_command "tbl $$FName | nroff"',
430       r'\ascii_roff_command "none"' ])
431   checkProg('ChkTeX', ['chktex -n1 -n3 -n6 -n9 -n22 -n25 -n30 -n38'],
432     rc_entry = [ r'\chktex_command "%%"' ])
433   checkProg('a spellchecker', ['ispell'],
434     rc_entry = [ r'\spell_command "%%"' ])
435   ## FIXME: OCTAVE is not used anywhere
436   # path, OCTAVE = checkProg('Octave', ['octave'])
437   ## FIXME: MAPLE is not used anywhere
438   # path, MAPLE = checkProg('Maple', ['maple'])
439   checkProg('a spool command', ['lp', 'lpr'],
440     rc_entry = [
441       r'''\print_spool_printerprefix "-d "
442 \print_spool_command "lp"''',
443       r'''\print_spool_printerprefix "-P",
444 \print_spool_command "lpr"''',
445       ''])
446   # Add the rest of the entries (no checkProg is required)
447   addToRC(r'''\copier    fig        "sh $$s/scripts/fig_copy.sh $$i $$o"
448 \copier    pstex      "python $$s/scripts/tex_copy.py $$i $$o $$l"
449 \copier    pdftex     "python $$s/scripts/tex_copy.py $$i $$o $$l"
450 ''')
451
452
453 def processLayoutFile(file, bool_docbook, bool_linuxdoc):
454   ''' process layout file and get a line of result
455     
456     Declear line are like this: (article.layout, scrbook.layout, svjog.layout)
457     
458     \DeclareLaTeXClass{article}
459     \DeclareLaTeXClass[scrbook]{book (koma-script)}
460     \DeclareLaTeXClass[svjour,svjog.clo]{article (Springer - svjour/jog)}
461
462     we expect output:
463     
464     "article" "article" "article" "false"
465     "scrbook" "scrbook" "book (koma-script)" "false"
466     "svjog" "svjour" "article (Springer - svjour/jog)" "false"
467   '''
468   classname = file.split(os.sep)[-1].split('.')[0]
469   # return ('LaTeX', '[a,b]', 'a', ',b,c', 'article') for \DeclearLaTeXClass[a,b,c]{article}
470   p = re.compile(r'\Declare(LaTeX|DocBook|LinuxDoc)Class\s*(\[([^,]*)(,.*)*\])*\s*{(.*)}')
471   for line in open(file).readlines():
472     res = p.search(line)
473     if res != None:
474       (classtype, optAll, opt, opt1, desc) = res.groups()
475       avai = {'LaTeX':'false', 'DocBook':bool_docbook, 'LinuxDoc':bool_linuxdoc}[classtype]
476       if opt == None:
477         opt = classname
478       return '"%s" "%s" "%s" "%s"\n' % (classname, opt, desc, avai)
479   print "Layout file without \DeclearXXClass line. "
480   sys.exit(2)
481
482   
483 def checkLatexConfig(check_config, bool_docbook, bool_linuxdoc):
484   ''' Explore the LaTeX configuration '''
485   print 'checking LaTeX configuration... ',
486   # First, remove the files that we want to re-create
487   removeFiles(['textclass.lst', 'packages.lst', 'chkconfig.sed'])
488   #
489   if not check_config:
490     print ' default values'
491     print '+checking list of textclasses... '
492     tx = open('textclass.lst', 'w')
493     tx.write('''
494 # This file declares layouts and their associated definition files
495 # (include dir. relative to the place where this file is).
496 # It contains only default values, since chkconfig.ltx could not be run
497 # for some reason. Run ./configure if you need to update it after a
498 # configuration change.
499 ''')
500     # build the list of available layout files and convert it to commands
501     # for chkconfig.ltx
502     foundClasses = []
503     for file in glob.glob( os.path.join('layouts', '*.layout') ) + \
504       glob.glob( os.path.join(srcdir, 'layouts', '*.layout' ) ) :
505       # valid file?
506       if not os.path.isfile(file): 
507         continue
508       # get stuff between /xxxx.layout .
509       classname = file.split(os.sep)[-1].split('.')[0]
510       #  tr ' -' '__'`
511       cleanclass = classname.replace(' ', '_')
512       cleanclass = cleanclass.replace('-', '_')
513       # make sure the same class is not considered twice
514       if foundClasses.count(cleanclass) == 0: # not found before
515         foundClasses.append(cleanclass)
516         tx.write(processLayoutFile(file, bool_docbook, bool_linuxdoc))
517     tx.close()
518     print '\tdone'
519   else:
520     print '\tauto'
521     removeFiles(['wrap_chkconfig.ltx', 'chkconfig.vars', \
522       'chkconfig.classes', 'chklayouts.tex'])
523     rmcopy = False
524     if not os.path.isfile( 'chkconfig.ltx' ):
525       shutil.copy( os.path.join(srcdir, 'chkconfig.ltx'),  'chkconfig.ltx' )
526       rmcopy = True
527     writeToFile('wrap_chkconfig.ltx', '%s\n%s\n\\input{chkconfig.ltx}\n' \
528       % (linuxdoc_cmd, docbook_cmd) )
529     # Construct the list of classes to test for.
530     # build the list of available layout files and convert it to commands
531     # for chkconfig.ltx
532     p1 = re.compile(r'\Declare(LaTeX|DocBook|LinuxDoc)Class')
533     testclasses = list()
534     for file in glob.glob( os.path.join('layouts', '*.layout') ) + \
535       glob.glob( os.path.join(srcdir, 'layouts', '*.layout' ) ) :
536       if not os.path.isfile(file):
537         continue
538       classname = file.split(os.sep)[-1].split('.')[0]
539       for line in open(file).readlines():
540         if p1.search(line) == None:
541           continue
542         if line[0] != '#':
543           print "Wrong input layout file with line '" + line
544           sys.exit(3)
545         testclasses.append("\\TestDocClass{%s}{%s}" % (classname, line[1:].strip()))
546         break
547     testclasses.sort()
548     cl = open('chklayouts.tex', 'w')
549     for line in testclasses:
550       cl.write(line + '\n')
551     cl.close()
552     #
553     # we have chklayouts.tex, then process it
554     for line in cmdOutput(LATEX + ' wrap_chkconfig.ltx').splitlines():
555       if re.match('^\+', line):
556         print line
557     #
558     # currently, values in chhkconfig are only used to set
559     # \font_encoding
560     values = {}
561     for line in open('chkconfig.vars').readlines():
562       key, val = re.sub('-', '_', line).split('=')
563       val = val.strip()
564       values[key] = val.strip("'")
565     # chk_fontenc may not exist 
566     try:
567       addToRC(r'\font_encoding "%s"' % values["chk_fontenc"])
568     except:
569       pass
570     if rmcopy:   # remove the copied file
571       removeFiles( [ 'chkconfig.ltx' ] )
572
573
574 def createLaTeXConfig():
575   ''' create LaTeXConfig.lyx '''
576   # if chkconfig.sed does not exist (because LaTeX did not run),
577   # then provide a standard version.
578   if not os.path.isfile('chkconfig.sed'):
579     writeToFile('chkconfig.sed', 's!@.*@!???!g\n')
580   print "creating packages.lst"
581   # if packages.lst does not exist (because LaTeX did not run),
582   # then provide a standard version.
583   if not os.path.isfile('packages.lst'):
584     writeToFile('packages.lst', '''
585 ### This file should contain the list of LaTeX packages that have been
586 ### recognized by LyX. Unfortunately, since configure could not find
587 ### your LaTeX2e program, the tests have not been run. Run ./configure
588 ### if you need to update it after a configuration change.
589 ''')
590   print 'creating doc/LaTeXConfig.lyx'
591   #
592   # This is originally done by sed, using a
593   # tex-generated file chkconfig.sed
594   ##sed -f chkconfig.sed ${srcdir}/doc/LaTeXConfig.lyx.in
595   ##  >doc/LaTeXConfig.lyx
596   # Now, we have to do it by hand (python).
597   #
598   # add to chekconfig.sed
599   writeToFile('chkconfig.sed', '''s!@chk_linuxdoc@!%s!g
600 s!@chk_docbook@!%s!g
601   ''' % (chk_linuxdoc, chk_docbook) , append=True)
602   # process this sed file!!!!
603   lyxin = open( os.path.join(srcdir, 'doc', 'LaTeXConfig.lyx.in')).readlines()
604   # get the rules
605   p = re.compile(r's!(.*)!(.*)!g')
606   # process each sed replace.
607   for sed in open('chkconfig.sed').readlines():
608     if sed.strip() == '':
609       continue
610     try:
611       fr, to = p.match(sed).groups()
612       # if latex did not run, change all @name@ to '???'
613       if fr == '@.*@':
614         for line in range(len(lyxin)):
615           lyxin[line] = re.sub('@.*@', to, lyxin[line])
616       else:
617         for line in range(len(lyxin)):
618           lyxin[line] = lyxin[line].replace(fr, to)
619     except:  # wrong sed entry?
620       print "Wrong sed entry in chkconfig.sed: '" + sed + "'"
621       sys.exit(4)
622   # 
623   writeToFile( os.path.join('doc', 'LaTeXConfig.lyx'),
624     ''.join(lyxin))
625
626
627 def checkTeXAllowSpaces():
628   ''' Let's check whether spaces are allowed in TeX file names '''
629   tex_allows_spaces = 'false'
630   if lyx_check_config:
631     print "Checking whether TeX allows spaces in file names... ",
632     writeToFile('a b.tex', r'\message{working^^J}' )
633     # FIXME: the bsh version uses < /dev/null which is not portable.
634     # Can anyone confirm if this option (-interaction) is available
635     # at other flavor of latex as well? (MikTex/win, Web2C/linux are fine.) 
636     if ''.join(cmdOutput(LATEX + ' -interaction=nonstopmode "a b"')).find('working') != -1:
637       print 'yes'
638       tex_allows_spaces = 'true'
639     else:
640       print 'no'
641       tex_allows_spaces = 'false'
642     addToRC(r'\tex_allows_spaces ' + tex_allows_spaces)
643     removeFiles( [ 'a b.tex', 'a b.log', 'texput.log' ])
644
645
646 def removeTempFiles():
647   # Final clean-up
648   if not lyx_keep_temps:
649     removeFiles(['chkconfig.sed', 'chkconfig.vars',  \
650       'wrap_chkconfig.ltx', 'wrap_chkconfig.log', \
651       'chklayouts.tex', 'missfont.log', 
652       'chklatex.ltx', 'chklatex.log'])
653
654
655 if __name__ == '__main__':
656   lyx_check_config = True
657   outfile = 'lyxrc.defaults'
658   rc_entries = ''
659   lyx_keep_temps = False
660   version_suffix = ''
661   ## Parse the command line
662   for op in sys.argv[1:]:   # default shell/for list is $*, the options
663     if op in [ '-help', '--help', '-h' ]:
664       print '''Usage: configure [options]
665 Options:
666   --help                   show this help lines
667   --keep-temps             keep temporary files (for debug. purposes)
668   --without-latex-config   do not run LaTeX to determine configuration
669   --with-version-suffix=suffix suffix of binary installed files
670 '''
671       sys.exit(0)
672     elif op == '--without-latex-config':
673       lyx_check_config = False
674     elif op == '--keep-temps':
675       lyx_keep_temps = True
676     elif op[0:22] == '--with-version-suffix=':  # never mind if op is not long enough
677       version_suffix = op[22:]
678     else:
679       print "Unknown option", op
680       sys.exit(1)
681   #    
682   # check if we run from the right directory
683   srcdir = os.path.dirname(sys.argv[0])
684   if srcdir == '':
685     srcdir = '.'
686   if not os.path.isfile( os.path.join(srcdir, 'chkconfig.ltx') ):
687     print "configure: error: cannot find chkconfig.ltx script"
688     sys.exit(1)
689   setEnviron()
690   createDirectories()
691   cygwin_path_fix = checkCygwinPath(srcdir)
692   ## Write the first part of outfile
693   writeToFile(outfile, '''# This file has been automatically generated by LyX' lib/configure.py
694 # script. It contains default settings that have been determined by
695 # examining your system. PLEASE DO NOT MODIFY ANYTHING HERE! If you
696 # want to customize LyX, make a copy of the file LYXDIR/lyxrc as
697 # ~/.lyx/lyxrc and edit this file instead. Any setting in lyxrc will
698 # override the values given here.
699 ''')
700   # check latex
701   LATEX = checkLatex()
702   checkFormatEntries()
703   checkConverterEntries()
704   (chk_linuxdoc, bool_linuxdoc, linuxdoc_cmd) = checkLinuxDoc()
705   (chk_docbook, bool_docbook, docbook_cmd) = checkDocBook()
706   checkTeXAllowSpaces()
707   checkOtherEntries()
708   if cygwin_path_fix != '':
709     addToRC(r'\cygwin_path_fix_needed %s' % cygwin_path_fix)
710   # --without-latex-config can disable lyx_check_config
711   checkLatexConfig( lyx_check_config and LATEX != '', bool_docbook, bool_linuxdoc)
712   createLaTeXConfig()
713   removeTempFiles()