]> git.lyx.org Git - lyx.git/blob - lib/configure.py
* LFUNs.lyx
[lyx.git] / lib / configure.py
1 #! /usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # file configure.py
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
7
8 # \author Bo Peng
9 # Full author contact details are available in file CREDITS.
10
11 import sys, os, re, shutil, glob, logging
12
13 # set up logging
14 logging.basicConfig(level = logging.DEBUG,
15     format = '%(levelname)s: %(message)s', # ignore application name
16     filename = 'configure.log',
17     filemode = 'w')
18 #
19 # Add a handler to log to console
20 console = logging.StreamHandler()
21 console.setLevel(logging.INFO) # the console only print out general information
22 formatter = logging.Formatter('%(message)s') # only print out the message itself
23 console.setFormatter(formatter)
24 logger = logging.getLogger('LyX')
25 logger.addHandler(console)
26
27 def writeToFile(filename, lines, append = False):
28     " utility function: write or append lines to filename "
29     if append:
30         file = open(filename, 'a')
31     else:
32         file = open(filename, 'w')
33     file.write(lines)
34     file.close()
35
36
37 def addToRC(lines):
38     ''' utility function: shortcut for appending lines to outfile
39         add newline at the end of lines.
40     '''
41     if lines.strip() != '':
42         writeToFile(outfile, lines + '\n', append = True)
43         logger.debug('Add to RC:\n' + lines + '\n\n')
44
45
46 def removeFiles(filenames):
47     '''utility function: 'rm -f'
48         ignore errors when file does not exist, or is a directory.
49     '''
50     for file in filenames:
51         try:
52             os.remove(file)
53             logger.debug('Removing file %s' % file)
54         except:
55             logger.debug('Failed to remove file %s' % file)
56             pass
57
58
59 def cmdOutput(cmd):
60     '''utility function: run a command and get its output as a string
61         cmd: command to run
62     '''
63     fout = os.popen(cmd)
64     output = fout.read()
65     fout.close()
66     return output.strip()
67
68
69 def setEnviron():
70     ''' I do not really know why this is useful, but we might as well keep it.
71         NLS nuisances.
72         Only set these to C if already set.  These must not be set unconditionally
73         because not all systems understand e.g. LANG=C (notably SCO).
74         Fixing LC_MESSAGES prevents Solaris sh from translating var values in set!
75         Non-C LC_CTYPE values break the ctype check.
76     '''
77     os.environ['LANG'] = os.getenv('LANG', 'C')
78     os.environ['LC'] = os.getenv('LC_ALL', 'C')
79     os.environ['LC_MESSAGE'] = os.getenv('LC_MESSAGE', 'C')
80     os.environ['LC_CTYPE'] = os.getenv('LC_CTYPE', 'C')
81
82
83 def createDirectories():
84     ''' Create the build directories if necessary '''
85     for dir in ['bind', 'clipart', 'doc', 'examples', 'images', 'kbd', \
86         'layouts', 'scripts', 'templates', 'ui' ]:
87         if not os.path.isdir( dir ):
88             try:
89                 os.mkdir( dir)
90                 logger.debug('Create directory %s.' % dir)
91             except:
92                 logger.error('Failed to create directory %s.' % 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         logname = os.path.basename(inpname.replace('.ltx', '.log'))
107         inpname = inpname.replace('~', '\\string~')
108         os.write(fd, r'\relax')
109         os.close(fd)
110         latex_out = cmdOutput(r'latex "\nonstopmode\input{%s}"' % inpname)
111         if 'Error' in latex_out:
112             logger.warning("configure: TeX engine needs posix-style paths in latex files")
113             windows_style_tex_paths = 'false'
114         else:
115             logger.info("configure: TeX engine needs windows-style paths in latex files")
116             windows_style_tex_paths = 'true'
117         removeFiles([tmpfname, logname, 'texput.log'])
118     return windows_style_tex_paths
119
120
121 ## Searching some useful programs
122 def checkProg(description, progs, rc_entry = [], path = [], not_found = ''):
123     '''
124         This function will search a program in $PATH plus given path
125         If found, return directory and program name (not the options).
126
127         description: description of the program
128
129         progs: check programs, for each prog, the first word is used
130             for searching but the whole string is used to replace
131             %% for a rc_entry. So, feel free to add '$$i' etc for programs.
132
133         path: additional pathes
134
135         rc_entry: entry to outfile, can be
136             1. emtpy: no rc entry will be added
137             2. one pattern: %% will be replaced by the first found program,
138                 or '' if no program is found.
139             3. several patterns for each prog and not_found. This is used 
140                 when different programs have different usages. If you do not 
141                 want not_found entry to be added to the RC file, you can specify 
142                 an entry for each prog and use '' for the not_found entry.
143
144         not_found: the value that should be used instead of '' if no program
145             was found
146
147     '''
148     # one rc entry for each progs plus not_found entry
149     if len(rc_entry) > 1 and len(rc_entry) != len(progs) + 1:
150         logger.error("rc entry should have one item or item for each prog and not_found.")
151         sys.exit(2)
152     logger.info('checking for ' + description + '...')
153     ## print '(' + ','.join(progs) + ')',
154     for idx in range(len(progs)):
155         # ac_prog may have options, ac_word is the command name
156         ac_prog = progs[idx]
157         ac_word = ac_prog.split(' ')[0]
158         msg = '+checking for "' + ac_word + '"... '
159         path = os.environ["PATH"].split(os.pathsep) + path
160         extlist = ['']
161         if os.environ.has_key("PATHEXT"):
162             extlist = extlist + os.environ["PATHEXT"].split(os.pathsep)
163         for ac_dir in path:
164             for ext in extlist:
165                 if os.path.isfile( os.path.join(ac_dir, ac_word + ext) ):
166                     logger.info(msg + ' yes')
167                     # write rc entries for this command
168                     if len(rc_entry) == 1:
169                         addToRC(rc_entry[0].replace('%%', ac_prog))
170                     elif len(rc_entry) > 1:
171                         addToRC(rc_entry[idx].replace('%%', ac_prog))
172                     return [ac_dir, ac_word]
173         # if not successful
174         logger.info(msg + ' no')
175     # write rc entries for 'not found'
176     if len(rc_entry) > 0:  # the last one.
177         addToRC(rc_entry[-1].replace('%%', not_found))
178     return ['', not_found]
179
180
181 def checkViewer(description, progs, rc_entry = [], path = []):
182     ''' The same as checkProg, but for viewers and editors '''
183     return checkProg(description, progs, rc_entry, path, not_found = 'auto')
184
185
186 def checkDTLtools():
187     ''' Check whether DTL tools are available (Windows only) '''
188     # Find programs! Returned path is not used now
189     if ((os.name == 'nt' or sys.platform == 'cygwin') and
190             checkProg('DVI to DTL converter', ['dv2dt']) != ['', ''] and
191             checkProg('DTL to DVI converter', ['dt2dv']) != ['', '']):
192         dtl_tools = True
193     else:
194         dtl_tools = False
195     return dtl_tools
196
197
198 def checkLatex(dtl_tools):
199     ''' Check latex, return lyx_check_config '''
200     path, LATEX = checkProg('a Latex2e program', ['latex $$i', 'platex $$i', 'latex2e $$i'])
201     path, PPLATEX = checkProg('a DVI postprocessing program', ['pplatex $$i'])
202     #-----------------------------------------------------------------
203     path, PLATEX = checkProg('pLaTeX, the Japanese LaTeX', ['platex $$i'])
204     if PLATEX != '':
205         # check if PLATEX is pLaTeX2e
206         writeToFile('chklatex.ltx', '''
207 \\nonstopmode
208 \\@@end
209 ''')
210         # run platex on chklatex.ltx and check result
211         if cmdOutput(PLATEX + ' chklatex.ltx').find('pLaTeX2e') != -1:
212             # We have the Japanese pLaTeX2e
213             addToRC(r'\converter platex   dvi       "%s"   "latex"' % PLATEX)
214             LATEX = PLATEX
215         else:
216             PLATEX = ''
217             removeFiles(['chklatex.ltx', 'chklatex.log'])
218     #-----------------------------------------------------------------
219     # use LATEX to convert from latex to dvi if PPLATEX is not available    
220     if PPLATEX == '':
221         PPLATEX = LATEX
222     if dtl_tools:
223         # Windows only: DraftDVI
224         addToRC(r'''\converter latex      dvi2       "%s"       "latex"
225 \converter dvi2       dvi        "python -tt $$s/scripts/clean_dvi.py $$i $$o"  ""''' % PPLATEX)
226     else:
227         addToRC(r'\converter latex      dvi        "%s" "latex"' % PPLATEX)
228     # no latex
229     if LATEX != '':
230         # Check if latex is usable
231         writeToFile('chklatex.ltx', '''
232 \\nonstopmode\\makeatletter
233 \\ifx\\undefined\\documentclass\\else
234   \\message{ThisIsLaTeX2e}
235 \\fi
236 \\@@end
237 ''')
238         # run latex on chklatex.ltx and check result
239         if cmdOutput(LATEX + ' chklatex.ltx').find('ThisIsLaTeX2e') != -1:
240             # valid latex2e
241             return LATEX
242         else:
243             logger.warning("Latex not usable (not LaTeX2e) ")
244         # remove temporary files
245         removeFiles(['chklatex.ltx', 'chklatex.log'])
246     return ''
247
248
249 def checkFormatEntries(dtl_tools):  
250     ''' Check all formats (\Format entries) '''
251     checkViewer('a Tgif viewer and editor', ['tgif'],
252         rc_entry = [r'\Format tgif       obj     Tgif                   "" "%%" "%%"    "vector"'])
253     #
254     checkViewer('a FIG viewer and editor', ['xfig', 'jfig3-itext.jar', 'jfig3.jar'],
255         rc_entry = [r'\Format fig        fig     FIG                    "" "%%" "%%"    "vector"'])
256     #
257     checkViewer('a Dia viewer and editor', ['dia'],
258         rc_entry = [r'\Format dia        dia     DIA                    "" "%%" "%%"    "vector"'])
259     #
260     checkViewer('a Grace viewer and editor', ['xmgrace'],
261         rc_entry = [r'\Format agr        agr     Grace                  "" "%%" "%%"    "vector"'])
262     #
263     checkViewer('a FEN viewer and editor', ['xboard -lpf $$i -mode EditPosition'],
264         rc_entry = [r'\Format fen        fen     FEN                    "" "%%" "%%"    ""'])
265     #
266     path, iv = checkViewer('a raster image viewer', ['xv', 'kview', 'gimp-remote', 'gimp'])
267     path, ie = checkViewer('a raster image editor', ['gimp-remote', 'gimp'])
268     addToRC(r'''\Format bmp        bmp     BMP                    "" "%s"       "%s"    ""
269 \Format gif        gif     GIF                    "" "%s"       "%s"    ""
270 \Format jpg        jpg     JPEG                   "" "%s"       "%s"    ""
271 \Format pbm        pbm     PBM                    "" "%s"       "%s"    ""
272 \Format pgm        pgm     PGM                    "" "%s"       "%s"    ""
273 \Format png        png     PNG                    "" "%s"       "%s"    ""
274 \Format ppm        ppm     PPM                    "" "%s"       "%s"    ""
275 \Format tiff       tif     TIFF                   "" "%s"       "%s"    ""
276 \Format xbm        xbm     XBM                    "" "%s"       "%s"    ""
277 \Format xpm        xpm     XPM                    "" "%s"       "%s"    ""''' % \
278         (iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie, iv, ie) )
279     #
280     checkViewer('a text editor', ['sensible-editor', 'xemacs', 'gvim', 'kedit', 'kwrite', 'kate', \
281         'nedit', 'gedit', 'notepad'],
282         rc_entry = [r'''\Format asciichess asc    "Plain text (chess output)"  "" ""    "%%"    ""
283 \Format asciiimage asc    "Plain text (image)"         "" ""    "%%"    ""
284 \Format asciixfig  asc    "Plain text (Xfig output)"   "" ""    "%%"    ""
285 \Format dateout    tmp    "date (output)"         "" "" "%%"    ""
286 \Format docbook    sgml    DocBook                B  "" "%%"    "document"
287 \Format docbook-xml xml   "Docbook (XML)"         "" "" "%%"    "document"
288 \Format dot        dot    "Graphviz Dot"          "" "" "%%"    "vector"
289 \Format platex     tex    "LaTeX (pLaTeX)"        "" "" "%%"    "document"
290 \Format literate   nw      NoWeb                  N  "" "%%"    "document"
291 \Format lilypond   ly     "LilyPond music"        "" "" "%%"    "vector"
292 \Format latex      tex    "LaTeX (plain)"         L  "" "%%"    "document"
293 \Format pdflatex   tex    "LaTeX (pdflatex)"      "" "" "%%"    "document"
294 \Format xetex      tex    "LaTeX (XeTeX)"         "" "" "%%"    "document"
295 \Format text       txt    "Plain text"            a  "" "%%"    "document"
296 \Format text2      txt    "Plain text (pstotext)" "" "" "%%"    "document"
297 \Format text3      txt    "Plain text (ps2ascii)" "" "" "%%"    "document"
298 \Format text4      txt    "Plain text (catdvi)"   "" "" "%%"    "document"
299 \Format textparagraph txt "Plain Text, Join Lines" "" ""        "%%"    "document"''' ])
300  #
301     checkViewer('a BibTeX editor', ['sensible-editor', 'jabref', 'JabRef', \
302         'pybliographic', 'bibdesk', 'gbib', 'kbib', \
303         'kbibtex', 'sixpack', 'bibedit', 'tkbibtex' \
304         'xemacs', 'gvim', 'kedit', 'kwrite', 'kate', \
305         'nedit', 'gedit', 'notepad'],
306         rc_entry = [r'''\Format bibtex bib    "BibTeX"         "" ""    "%%"    ""''' ])
307     #
308     #checkProg('a Postscript interpreter', ['gs'],
309     #  rc_entry = [ r'\ps_command "%%"' ])
310     checkViewer('a Postscript previewer', ['kghostview', 'evince', 'gv', 'ghostview -swap'],
311         rc_entry = [r'''\Format eps        eps     EPS                    "" "%%"       ""      "vector"
312 \Format ps         ps      Postscript             t  "%%"       ""      "document,vector"'''])
313     #
314     checkViewer('a PDF previewer', ['kpdf', 'evince', 'kghostview', 'xpdf', 'acrobat', 'acroread', \
315                     'gv', 'ghostview'],
316         rc_entry = [r'''\Format pdf        pdf    "PDF (ps2pdf)"          P  "%%"       ""      "document,vector"
317 \Format pdf2       pdf    "PDF (pdflatex)"        F  "%%"       ""      "document,vector"
318 \Format pdf3       pdf    "PDF (dvipdfm)"         m  "%%"       ""      "document,vector"
319 \Format pdf4       pdf    "PDF (XeTeX)"           X  "%%"       ""      "document,vector"'''])
320     #
321     checkViewer('a DVI previewer', ['xdvi', 'kdvi'],
322         rc_entry = [r'\Format dvi        dvi     DVI                    D  "%%" ""      "document,vector"'])
323     if dtl_tools:
324         # Windows only: DraftDVI
325         addToRC(r'\Format dvi2       dvi     DraftDVI               ""  ""      ""      "vector"')
326     #
327     checkViewer('an HTML previewer', ['firefox', 'mozilla file://$$p$$i', 'netscape'],
328         rc_entry = [r'\Format html       html    HTML                   H  "%%" ""      "document"'])
329     #
330     checkViewer('Noteedit', ['noteedit'],
331         rc_entry = [r'\Format noteedit   not     Noteedit               "" "%%" "%%"    "vector"'])
332     #
333     checkViewer('an OpenDocument viewer', ['swriter', 'oowriter'],
334         rc_entry = [r'\Format odt        odt     OpenDocument           "" "%%" "%%"    "document,vector"'])
335     #
336     # entried that do not need checkProg
337     addToRC(r'''\Format date       ""     "date command"          "" "" ""      ""
338 \Format csv        csv    "Table (CSV)"  "" ""  ""      "document"
339 \Format fax        ""      Fax                    "" "" ""      "document"
340 \Format lyx        lyx     LyX                    "" "" ""      ""
341 \Format lyx13x     lyx13  "LyX 1.3.x"             "" "" ""      "document"
342 \Format lyx14x     lyx14  "LyX 1.4.x"             "" "" ""      "document"
343 \Format lyx15x     lyx15  "LyX 1.5.x"             "" "" ""      "document"
344 \Format lyx16x     lyx16  "LyX 1.6.x"             "" "" ""      "document"
345 \Format clyx       cjklyx "CJK LyX 1.4.x (big5)"  "" "" ""      "document"
346 \Format jlyx       cjklyx "CJK LyX 1.4.x (euc-jp)" "" ""        ""      "document"
347 \Format klyx       cjklyx "CJK LyX 1.4.x (euc-kr)" "" ""        ""      "document"
348 \Format lyxpreview lyxpreview "LyX Preview"       "" "" ""      ""
349 \Format lyxpreview-platex lyxpreview-platex "LyX Preview (pLaTeX)"       "" ""  ""      ""
350 \Format pdftex     pdftex_t PDFTEX                "" "" ""      ""
351 \Format program    ""      Program                "" "" ""      ""
352 \Format pstex      pstex_t PSTEX                  "" "" ""      ""
353 \Format rtf        rtf    "Rich Text Format"      "" "" ""      "document,vector"
354 \Format sxw        sxw    "OpenOffice.Org (sxw)"  ""  ""        ""      "document,vector"
355 \Format wmf        wmf    "Windows Metafile"      "" "" ""      "vector"
356 \Format emf        emf    "Enhanced Metafile"     "" "" ""      "vector"
357 \Format word       doc    "MS Word"               W  "" ""      "document,vector"
358 \Format wordhtml   html   "HTML (MS Word)"        "" ""        ""       "document"
359 ''')
360
361
362 def checkConverterEntries():
363     ''' Check all converters (\converter entries) '''
364     checkProg('the pdflatex program', ['pdflatex $$i'],
365         rc_entry = [ r'\converter pdflatex   pdf2       "%%"    "latex"' ])
366
367     checkProg('XeTeX', ['xelatex $$i'],
368         rc_entry = [ r'\converter xetex      pdf4       "%%"    "latex"' ])
369     
370     ''' If we're running LyX in-place then tex2lyx will be found in
371             ../src/tex2lyx. Add this directory to the PATH temporarily and
372             search for tex2lyx.
373             Use PATH to avoid any problems with paths-with-spaces.
374     '''
375     path_orig = os.environ["PATH"]
376     os.environ["PATH"] = os.path.join('..', 'src', 'tex2lyx') + \
377         os.pathsep + path_orig
378
379     checkProg('a LaTeX/Noweb -> LyX converter', ['tex2lyx', 'tex2lyx' + version_suffix],
380         rc_entry = [r'''\converter latex      lyx        "%% -f $$i $$o"        ""
381 \converter literate   lyx        "%% -n -f $$i $$o"     ""'''])
382
383     os.environ["PATH"] = path_orig
384
385     #
386     checkProg('a Noweb -> LaTeX converter', ['noweave -delay -index $$i > $$o'],
387         rc_entry = [r'''\converter literate   latex      "%%"   ""
388 \converter literate   pdflatex      "%%"        ""'''])
389     #
390     checkProg('an HTML -> LaTeX converter', ['html2latex $$i', 'gnuhtml2latex $$i', \
391         'htmltolatex -input $$i -output $$o', 'java -jar htmltolatex.jar -input $$i -output $$o'],
392         rc_entry = [ r'\converter html       latex      "%%"    ""' ])
393     #
394     checkProg('an MS Word -> LaTeX converter', ['wvCleanLatex $$i $$o'],
395         rc_entry = [ r'\converter word       latex      "%%"    ""' ])
396     # On SuSE the scripts have a .sh suffix, and on debian they are in /usr/share/tex4ht/
397     path, htmlconv = checkProg('a LaTeX -> HTML converter', ['htlatex $$i', 'htlatex.sh $$i', \
398         '/usr/share/tex4ht/htlatex $$i', 'tth  -t -e2 -L$$b < $$i > $$o', \
399         'latex2html -no_subdir -split 0 -show_section_numbers $$i', 'hevea -s $$i'],
400         rc_entry = [ r'\converter latex      html       "%%"    "needaux"' ])
401     if htmlconv.find('htlatex') >= 0 or htmlconv == 'latex2html':
402       addToRC(r'''\copier    html       "python -tt $$s/scripts/ext_copy.py -e html,png,css $$i $$o"''')
403     else:
404       addToRC(r'''\copier    html       "python -tt $$s/scripts/ext_copy.py $$i $$o"''')
405
406     # On SuSE the scripts have a .sh suffix, and on debian they are in /usr/share/tex4ht/
407     path, htmlconv = checkProg('a LaTeX -> MS Word converter', ["htlatex $$i 'html,word' 'symbol/!' '-cvalidate'", \
408         "htlatex.sh $$i 'html,word' 'symbol/!' '-cvalidate'", \
409         "/usr/share/tex4ht/htlatex $$i 'html,word' 'symbol/!' '-cvalidate'"],
410         rc_entry = [ r'\converter latex      wordhtml   "%%"    "needaux"' ])
411     if htmlconv.find('htlatex') >= 0:
412       addToRC(r'''\copier    wordhtml       "python -tt $$s/scripts/ext_copy.py -e html,png,css $$i $$o"''')
413     #
414     checkProg('an OpenOffice.org -> LaTeX converter', ['w2l -clean $$i'],
415         rc_entry = [ r'\converter sxw        latex      "%%"    ""' ])
416     #
417     checkProg('an OpenDocument -> LaTeX converter', ['w2l -clean $$i'],
418         rc_entry = [ r'\converter odt        latex      "%%"    ""' ])
419     # According to http://www.tug.org/applications/tex4ht/mn-commands.html
420     # the command mk4ht oolatex $$i has to be used as default,
421     # but as this would require to have Perl installed, in MiKTeX oolatex is
422     # directly available as application.
423     # On SuSE the scripts have a .sh suffix, and on debian they are in /usr/share/tex4ht/
424     # Both SuSE and debian have oolatex
425     checkProg('a LaTeX -> Open Document converter', [
426         'oolatex $$i', 'mk4ht oolatex $$i', 'oolatex.sh $$i', '/usr/share/tex4ht/oolatex $$i',
427         'htlatex $$i \'xhtml,ooffice\' \'ooffice/! -cmozhtf\' \'-coo\' \'-cvalidate\''],
428         rc_entry = [ r'\converter latex      odt        "%%"    "needaux"' ])
429     # On windows it is called latex2rt.exe
430     checkProg('a LaTeX -> RTF converter', ['latex2rtf -p -S -o $$o $$i', 'latex2rt -p -S -o $$o $$i'],
431         rc_entry = [ r'\converter latex      rtf        "%%"    "needaux"' ])
432     #
433     checkProg('a RTF -> HTML converter', ['unrtf --html  $$i > $$o'],
434         rc_entry = [ r'\converter rtf      html        "%%"     ""' ])
435     #
436     checkProg('a PS to PDF converter', ['ps2pdf13 $$i $$o'],
437         rc_entry = [ r'\converter ps         pdf        "%%"    ""' ])
438     #
439     checkProg('a PS to TXT converter', ['pstotext $$i > $$o'],
440         rc_entry = [ r'\converter ps         text2      "%%"    ""' ])
441     #
442     checkProg('a PS to TXT converter', ['ps2ascii $$i $$o'],
443         rc_entry = [ r'\converter ps         text3      "%%"    ""' ])
444     #
445     checkProg('a PS to EPS converter', ['ps2eps $$i'],
446         rc_entry = [ r'\converter ps         eps      "%%"      ""' ])
447     #
448     checkProg('a PDF to PS converter', ['pdf2ps $$i $$o', 'pdftops $$i $$o'],
449         rc_entry = [ r'\converter pdf         ps        "%%"    ""' ])
450     #
451     checkProg('a PDF to EPS converter', ['pdftops -eps -f 1 -l 1 $$i $$o'],
452         rc_entry = [ r'\converter pdf         eps        "%%"   ""' ])
453     #
454     checkProg('a DVI to TXT converter', ['catdvi $$i > $$o'],
455         rc_entry = [ r'\converter dvi        text4      "%%"    ""' ])
456     #
457     checkProg('a DVI to PS converter', ['dvips -o $$o $$i'],
458         rc_entry = [ r'\converter dvi        ps         "%%"    ""' ])
459     #
460     checkProg('a DVI to PDF converter', ['dvipdfmx -o $$o $$i', 'dvipdfm -o $$o $$i'],
461         rc_entry = [ r'\converter dvi        pdf3       "%%"    ""' ])
462     #
463     path, dvipng = checkProg('dvipng', ['dvipng'])
464     if dvipng == "dvipng":
465         addToRC(r'\converter lyxpreview png        "python -tt $$s/scripts/lyxpreview2bitmap.py"        ""')
466     else:
467         addToRC(r'\converter lyxpreview png        ""   ""')
468     #  
469     checkProg('a fax program', ['kdeprintfax $$i', 'ksendfax $$i'],
470         rc_entry = [ r'\converter ps         fax        "%%"    ""'])
471     #
472     checkProg('a FIG -> EPS/PPM converter', ['fig2dev'],
473         rc_entry = [
474             r'''\converter fig        eps        "fig2dev -L eps $$i $$o"       ""
475 \converter fig        ppm        "fig2dev -L ppm $$i $$o"       ""
476 \converter fig        png        "fig2dev -L png $$i $$o"       ""''',
477             ''])
478     #
479     checkProg('a TIFF -> PS converter', ['tiff2ps $$i > $$o'],
480         rc_entry = [ r'\converter tiff       eps        "%%"    ""', ''])
481     #
482     checkProg('a TGIF -> EPS/PPM converter', ['tgif'],
483         rc_entry = [
484             r'''\converter tgif       eps        "tgif -print -color -eps -stdout $$i > $$o"    ""
485 \converter tgif       png        "tgif -print -color -png -o $$d $$i"   ""
486 \converter tgif       pdf        "tgif -print -color -pdf -stdout $$i > $$o"    ""''',
487             ''])
488     #
489     checkProg('a WMF -> EPS converter', ['metafile2eps $$i $$o', 'wmf2eps -o $$o $$i'],
490         rc_entry = [ r'\converter wmf        eps        "%%"    ""'])
491     #
492     checkProg('an EMF -> EPS converter', ['metafile2eps $$i $$o', 'wmf2eps -o $$o $$i'],
493         rc_entry = [ r'\converter emf        eps        "%%"    ""'])
494     #
495     checkProg('an EPS -> PDF converter', ['epstopdf'],
496         rc_entry = [ r'\converter eps        pdf        "epstopdf --outfile=$$o $$i"    ""', ''])
497     #
498     # no agr -> pdf converter, since the pdf library used by gracebat is not
499     # free software and therefore not compiled in in many installations.
500     # Fortunately, this is not a big problem, because we will use epstopdf to
501     # convert from agr to pdf via eps without loss of quality.
502     checkProg('a Grace -> Image converter', ['gracebat'],
503         rc_entry = [
504             r'''\converter agr        eps        "gracebat -hardcopy -printfile $$o -hdevice EPS $$i 2>/dev/null"       ""
505 \converter agr        png        "gracebat -hardcopy -printfile $$o -hdevice PNG $$i 2>/dev/null"       ""
506 \converter agr        jpg        "gracebat -hardcopy -printfile $$o -hdevice JPEG $$i 2>/dev/null"      ""
507 \converter agr        ppm        "gracebat -hardcopy -printfile $$o -hdevice PNM $$i 2>/dev/null"       ""''',
508             ''])
509     #
510     checkProg('a Dot -> PDF converter', ['dot -Tpdf $$i -o $$o'],
511         rc_entry = [ r'\converter dot        pdf        "%%"    ""'])
512     #
513     checkProg('a Dia -> PNG converter', ['dia -e $$o -t png $$i'],
514         rc_entry = [ r'\converter dia        png        "%%"    ""'])
515     #
516     checkProg('a Dia -> EPS converter', ['dia -e $$o -t eps $$i'],
517         rc_entry = [ r'\converter dia        eps        "%%"    ""'])
518     #
519     #
520     path, lilypond = checkProg('a LilyPond -> EPS/PDF/PNG converter', ['lilypond'])
521     if (lilypond != ''):
522         version_string = cmdOutput("lilypond --version")
523         match = re.match('GNU LilyPond (\S+)', version_string)
524         if match:
525             version_number = match.groups()[0]
526             version = version_number.split('.')
527             if int(version[0]) > 2 or (len(version) > 1 and int(version[0]) == 2 and int(version[1]) >= 11):
528                 addToRC(r'''\converter lilypond   eps        "lilypond -dbackend=eps --ps $$i"  ""
529 \converter lilypond   png        "lilypond -dbackend=eps --png $$i"     ""''')
530                 addToRC(r'\converter lilypond   pdf        "lilypond -dbackend=eps --pdf $$i"   ""')
531                 print '+  found LilyPond version %s.' % version_number
532             elif int(version[0]) > 2 or (len(version) > 1 and int(version[0]) == 2 and int(version[1]) >= 6):
533                 addToRC(r'''\converter lilypond   eps        "lilypond -b eps --ps $$i" ""
534 \converter lilypond   png        "lilypond -b eps --png $$i"    ""''')
535                 if int(version[0]) > 2 or (len(version) > 1 and int(version[0]) == 2 and int(version[1]) >= 9):
536                     addToRC(r'\converter lilypond   pdf        "lilypond -b eps --pdf $$i"      ""')
537                 logger.info('+  found LilyPond version %s.' % version_number)
538             else:
539                 logger.info('+  found LilyPond, but version %s is too old.' % version_number)
540         else:
541             logger.info('+  found LilyPond, but could not extract version number.')
542     #
543     checkProg('a Noteedit -> LilyPond converter', ['noteedit --export-lilypond $$i'],
544         rc_entry = [ r'\converter noteedit   lilypond   "%%"    ""', ''])
545     #
546     # FIXME: no rc_entry? comment it out
547     # checkProg('Image converter', ['convert $$i $$o'])
548     #
549     # Entries that do not need checkProg
550     addToRC(r'''\converter lyxpreview ppm        "python -tt $$s/scripts/lyxpreview2bitmap.py"  ""
551 \converter lyxpreview-platex ppm        "python -tt $$s/scripts/lyxpreview-platex2bitmap.py"    ""
552 \converter csv        lyx        "python -tt $$s/scripts/csv2lyx.py $$i $$o"    ""
553 \converter date       dateout    "python -tt $$s/scripts/date.py %d-%m-%Y > $$o"        ""
554 \converter docbook    docbook-xml "cp $$i $$o"  "xml"
555 \converter fen        asciichess "python -tt $$s/scripts/fen2ascii.py $$i $$o"  ""
556 \converter fig        pdftex     "python -tt $$s/scripts/fig2pdftex.py $$i $$o" ""
557 \converter fig        pstex      "python -tt $$s/scripts/fig2pstex.py $$i $$o"  ""
558 \converter lyx        lyx13x     "python -tt $$s/lyx2lyx/lyx2lyx -t 221 $$i > $$o"      ""
559 \converter lyx        lyx14x     "python -tt $$s/lyx2lyx/lyx2lyx -t 245 $$i > $$o"      ""
560 \converter lyx        lyx15x     "python -tt $$s/lyx2lyx/lyx2lyx -t 276 $$i > $$o"      ""
561 \converter lyx        lyx16x     "python -tt $$s/lyx2lyx/lyx2lyx -t 345 $$i > $$o"      ""
562 \converter lyx        clyx       "python -tt $$s/lyx2lyx/lyx2lyx -c big5 -t 245 $$i > $$o"      ""
563 \converter lyx        jlyx       "python -tt $$s/lyx2lyx/lyx2lyx -c euc_jp -t 245 $$i > $$o"    ""
564 \converter lyx        klyx       "python -tt $$s/lyx2lyx/lyx2lyx -c euc_kr -t 245 $$i > $$o"    ""
565 \converter clyx       lyx        "python -tt $$s/lyx2lyx/lyx2lyx -c big5 $$i > $$o"     ""
566 \converter jlyx       lyx        "python -tt $$s/lyx2lyx/lyx2lyx -c euc_jp $$i > $$o"   ""
567 \converter klyx       lyx        "python -tt $$s/lyx2lyx/lyx2lyx -c euc_kr $$i > $$o"   ""
568 ''')
569
570
571 def checkDocBook():
572     ''' Check docbook '''
573     path, DOCBOOK = checkProg('SGML-tools 2.x (DocBook), db2x scripts or xsltproc', ['sgmltools', 'db2dvi', 'xsltproc'],
574         rc_entry = [
575             r'''\converter docbook    dvi        "sgmltools -b dvi $$i" ""
576 \converter docbook    html       "sgmltools -b html $$i"        ""''',
577             r'''\converter docbook    dvi        "db2dvi $$i"   ""
578 \converter docbook    html       "db2html $$i"  ""''',
579             r'''\converter docbook    dvi        ""     ""
580 \converter docbook    html       "" ""''',
581             r'''\converter docbook    dvi        ""     ""
582 \converter docbook    html       ""     ""'''])
583     #
584     if DOCBOOK != '':
585         return ('yes', 'true', '\\def\\hasdocbook{yes}')
586     else:
587         return ('no', 'false', '')
588
589
590 def checkOtherEntries():
591     ''' entries other than Format and Converter '''
592     checkProg('ChkTeX', ['chktex -n1 -n3 -n6 -n9 -n22 -n25 -n30 -n38'],
593         rc_entry = [ r'\chktex_command "%%"' ])
594     checkProg('BibTeX', ['jbibtex', 'bibtex'],
595         rc_entry = [ r'\bibtex_command "%%"' ])
596     checkProg('an index processor', ['texindy', 'makeindex -c -q'],
597         rc_entry = [ r'\index_command "%%"' ])
598     checkProg('a nomenclature processor', ['makeindex'],
599         rc_entry = [ r'\nomencl_command "makeindex -s nomencl.ist"' ])
600     ## FIXME: OCTAVE is not used anywhere
601     # path, OCTAVE = checkProg('Octave', ['octave'])
602     ## FIXME: MAPLE is not used anywhere
603     # path, MAPLE = checkProg('Maple', ['maple'])
604     checkProg('a spool command', ['lp', 'lpr'],
605         rc_entry = [
606             r'''\print_spool_printerprefix "-d "
607 \print_spool_command "lp"''',
608             r'''\print_spool_printerprefix "-P",
609 \print_spool_command "lpr"''',
610             ''])
611     # Add the rest of the entries (no checkProg is required)
612     addToRC(r'''\copier    fig        "python -tt $$s/scripts/fig_copy.py $$i $$o"
613 \copier    pstex      "python -tt $$s/scripts/tex_copy.py $$i $$o $$l"
614 \copier    pdftex     "python -tt $$s/scripts/tex_copy.py $$i $$o $$l"
615 \copier    program    "python -tt $$s/scripts/ext_copy.py $$i $$o"
616 ''')
617
618
619 def processLayoutFile(file, bool_docbook):
620     ''' process layout file and get a line of result
621         
622         Declare lines look like this: (article.layout, scrbook.layout, svjog.layout)
623         
624         \DeclareLaTeXClass{article}
625         \DeclareLaTeXClass[scrbook]{book (koma-script)}
626         \DeclareLaTeXClass[svjour,svjog.clo]{article (Springer - svjour/jog)}
627
628         we expect output:
629         
630         "article" "article" "article" "false"
631         "scrbook" "scrbook" "book (koma-script)" "false"
632         "svjog" "svjour" "article (Springer - svjour/jog)" "false"
633     '''
634     classname = file.split(os.sep)[-1].split('.')[0]
635     # return ('LaTeX', '[a,b]', 'a', ',b,c', 'article') for \DeclareLaTeXClass[a,b,c]{article}
636     p = re.compile(r'\Declare(LaTeX|DocBook)Class\s*(\[([^,]*)(,.*)*\])*\s*{(.*)}')
637     for line in open(file).readlines():
638         res = p.search(line)
639         if res != None:
640             (classtype, optAll, opt, opt1, desc) = res.groups()
641             avai = {'LaTeX':'false', 'DocBook':bool_docbook}[classtype]
642             if opt == None:
643                 opt = classname
644             return '"%s" "%s" "%s" "%s"\n' % (classname, opt, desc, avai)
645     logger.warning("Layout file " + file + " has no \DeclareXXClass line. ")
646     return ""
647
648
649 def checkLatexConfig(check_config, bool_docbook):
650     ''' Explore the LaTeX configuration 
651         Return None (will be passed to sys.exit()) for success.
652     '''
653     msg = 'checking LaTeX configuration... '
654     # if --without-latex-config is forced, or if there is no previous 
655     # version of textclass.lst, re-generate a default file.
656     if not os.path.isfile('textclass.lst') or not check_config:
657         # remove the files only if we want to regenerate
658         removeFiles(['textclass.lst', 'packages.lst'])
659         #
660         # Then, generate a default textclass.lst. In case configure.py
661         # fails, we still have something to start lyx.
662         logger.info(msg + ' default values')
663         logger.info('+checking list of textclasses... ')
664         tx = open('textclass.lst', 'w')
665         tx.write('''
666 # This file declares layouts and their associated definition files
667 # (include dir. relative to the place where this file is).
668 # It contains only default values, since chkconfig.ltx could not be run
669 # for some reason. Run ./configure.py if you need to update it after a
670 # configuration change.
671 ''')
672         # build the list of available layout files and convert it to commands
673         # for chkconfig.ltx
674         foundClasses = []
675         for file in glob.glob( os.path.join('layouts', '*.layout') ) + \
676             glob.glob( os.path.join(srcdir, 'layouts', '*.layout' ) ) :
677             # valid file?
678             if not os.path.isfile(file): 
679                 continue
680             # get stuff between /xxxx.layout .
681             classname = file.split(os.sep)[-1].split('.')[0]
682             #  tr ' -' '__'`
683             cleanclass = classname.replace(' ', '_')
684             cleanclass = cleanclass.replace('-', '_')
685             # make sure the same class is not considered twice
686             if foundClasses.count(cleanclass) == 0: # not found before
687                 foundClasses.append(cleanclass)
688                 retval = processLayoutFile(file, bool_docbook)
689                 if retval != "":
690                     tx.write(retval)
691         tx.close()
692         logger.info('\tdone')
693     if not check_config:
694         return None
695     # the following will generate textclass.lst.tmp, and packages.lst.tmp
696     else:
697         logger.info(msg + '\tauto')
698         removeFiles(['wrap_chkconfig.ltx', 'chkconfig.vars', \
699             'chkconfig.classes', 'chklayouts.tex'])
700         rmcopy = False
701         if not os.path.isfile( 'chkconfig.ltx' ):
702             shutil.copyfile( os.path.join(srcdir, 'chkconfig.ltx'), 'chkconfig.ltx' )
703             rmcopy = True
704         writeToFile('wrap_chkconfig.ltx', '%s\n\\input{chkconfig.ltx}\n' % docbook_cmd)
705         # Construct the list of classes to test for.
706         # build the list of available layout files and convert it to commands
707         # for chkconfig.ltx
708         p1 = re.compile(r'\Declare(LaTeX|DocBook)Class')
709         testclasses = list()
710         for file in glob.glob( os.path.join('layouts', '*.layout') ) + \
711             glob.glob( os.path.join(srcdir, 'layouts', '*.layout' ) ) :
712             if not os.path.isfile(file):
713                 continue
714             classname = file.split(os.sep)[-1].split('.')[0]
715             for line in open(file).readlines():
716                 if p1.search(line) == None:
717                     continue
718                 if line[0] != '#':
719                     logger.error("Wrong input layout file with line '" + line)
720                     sys.exit(3)
721                 testclasses.append("\\TestDocClass{%s}{%s}" % (classname, line[1:].strip()))
722                 break
723         testclasses.sort()
724         cl = open('chklayouts.tex', 'w')
725         for line in testclasses:
726             cl.write(line + '\n')
727         cl.close()
728         #
729         # we have chklayouts.tex, then process it
730         fout = os.popen(LATEX + ' wrap_chkconfig.ltx')
731         while True:
732             line = fout.readline()
733             if not line:
734                 break;
735             if re.match('^\+', line):
736                 logger.info(line.strip())
737         # if the command succeeds, None will be returned
738         ret = fout.close()
739         #
740         # currently, values in chhkconfig are only used to set
741         # \font_encoding
742         values = {}
743         for line in open('chkconfig.vars').readlines():
744             key, val = re.sub('-', '_', line).split('=')
745             val = val.strip()
746             values[key] = val.strip("'")
747         # chk_fontenc may not exist 
748         try:
749             addToRC(r'\font_encoding "%s"' % values["chk_fontenc"])
750         except:
751             pass
752         if rmcopy:   # remove the copied file
753             removeFiles( [ 'chkconfig.ltx' ] )
754         # if configure successed, move textclass.lst.tmp to textclass.lst
755         # and packages.lst.tmp to packages.lst
756         if os.path.isfile('textclass.lst.tmp') and len(open('textclass.lst.tmp').read()) > 0 \
757             and os.path.isfile('packages.lst.tmp') and len(open('packages.lst.tmp').read()) > 0:
758             shutil.move('textclass.lst.tmp', 'textclass.lst')
759             shutil.move('packages.lst.tmp', 'packages.lst')
760         return ret
761
762
763 def checkModulesConfig():
764   removeFiles(['lyxmodules.lst'])
765
766   logger.info('+checking list of modules... ')
767   tx = open('lyxmodules.lst', 'w')
768   tx.write('''## This file declares modules and their associated definition files.
769 ## It has been automatically generated by configure
770 ## Use "Options/Reconfigure" if you need to update it after a
771 ## configuration change. 
772 ''')
773   # build the list of available modules
774   foundClasses = []
775   for file in glob.glob( os.path.join('layouts', '*.module') ) + \
776       glob.glob( os.path.join(srcdir, 'layouts', '*.module' ) ) :
777       # valid file?
778       logger.info(file)
779       if not os.path.isfile(file): 
780           continue
781       retval = processModuleFile(file, bool_docbook)
782       if retval != "":
783           tx.write(retval)
784   tx.close()
785   logger.info('\tdone')
786
787
788 def processModuleFile(file, bool_docbook):
789     ''' process module file and get a line of result
790
791         The top of a module file should look like this:
792           #\DeclareLyXModule[LaTeX Packages]{ModuleName}
793           #BeginDescription
794           #...body of description...
795           #EndDescription
796           #Requires: [list of required modules]
797           #Excludes: [list of excluded modules]
798         The last two lines are optional
799         We expect output:
800           "ModuleName" "filename" "Description" "Packages" "Requires" "Excludes"
801     '''
802     p = re.compile(r'\DeclareLyXModule\s*(?:\[([^]]*?)\])?{(.*)}')
803     r = re.compile(r'#+\s*Requires: (.*)')
804     x = re.compile(r'#+\s*Excludes: (.*)')
805     b = re.compile(r'#+\s*DescriptionBegin\s*$')
806     e = re.compile(r'#+\s*DescriptionEnd\s*$')
807
808     modname = desc = pkgs = req = excl = ""
809     readingDescription = False
810     descLines = []
811     filename = file.split(os.sep)[-1]
812     filename = filename[:-7]
813
814     for line in open(file).readlines():
815       if readingDescription:
816         res = e.search(line)
817         if res != None:
818           readingDescription = False
819           desc = " ".join(descLines)
820           continue
821         descLines.append(line[1:].strip())
822         continue
823       res = b.search(line)
824       if res != None:
825         readingDescription = True
826         continue
827       res = p.search(line)
828       if res != None:
829           (pkgs, modname) = res.groups()
830           if pkgs == None:
831             pkgs = ""
832           else:
833             tmp = [s.strip() for s in pkgs.split(",")]
834             pkgs = ",".join(tmp)
835           continue
836       res = r.search(line)
837       if res != None:
838         req = res.group(1)
839         tmp = [s.strip() for s in req.split("|")]
840         req = "|".join(tmp)
841         continue
842       res = x.search(line)
843       if res != None:
844         excl = res.group(1)
845         tmp = [s.strip() for s in excl.split("|")]
846         excl = "|".join(tmp)
847         continue
848     if modname != "":
849         return '"%s" "%s" "%s" "%s" "%s" "%s"\n' % (modname, filename, desc, pkgs, req, excl)
850     logger.warning("Module file without \DeclareLyXModule line. ")
851     return ""
852
853
854 def checkTeXAllowSpaces():
855     ''' Let's check whether spaces are allowed in TeX file names '''
856     tex_allows_spaces = 'false'
857     if lyx_check_config:
858         msg = "Checking whether TeX allows spaces in file names... "
859         writeToFile('a b.tex', r'\message{working^^J}' )
860         if os.name == 'nt':
861             latex_out = cmdOutput(LATEX + r""" "\nonstopmode\input{\"a b\"}" """)
862         else:
863             latex_out = cmdOutput(LATEX + r""" '\nonstopmode\input{"a b"}' """)
864         if 'working' in latex_out:
865             logger.info(msg + 'yes')
866             tex_allows_spaces = 'true'
867         else:
868             logger.info(msg + 'no')
869             tex_allows_spaces = 'false'
870         addToRC(r'\tex_allows_spaces ' + tex_allows_spaces)
871         removeFiles( [ 'a b.tex', 'a b.log', 'texput.log' ])
872
873
874 def removeTempFiles():
875     # Final clean-up
876     if not lyx_keep_temps:
877         removeFiles(['chkconfig.vars',  \
878             'wrap_chkconfig.ltx', 'wrap_chkconfig.log', \
879             'chklayouts.tex', 'missfont.log', 
880             'chklatex.ltx', 'chklatex.log'])
881
882
883 if __name__ == '__main__':
884     lyx_check_config = True
885     outfile = 'lyxrc.defaults'
886     rc_entries = ''
887     lyx_keep_temps = False
888     version_suffix = ''
889     ## Parse the command line
890     for op in sys.argv[1:]:   # default shell/for list is $*, the options
891         if op in [ '-help', '--help', '-h' ]:
892             print '''Usage: configure [options]
893 Options:
894     --help                   show this help lines
895     --keep-temps             keep temporary files (for debug. purposes)
896     --without-latex-config   do not run LaTeX to determine configuration
897     --with-version-suffix=suffix suffix of binary installed files
898 '''
899             sys.exit(0)
900         elif op == '--without-latex-config':
901             lyx_check_config = False
902         elif op == '--keep-temps':
903             lyx_keep_temps = True
904         elif op[0:22] == '--with-version-suffix=':  # never mind if op is not long enough
905             version_suffix = op[22:]
906         else:
907             print "Unknown option", op
908             sys.exit(1)
909     #
910     # check if we run from the right directory
911     srcdir = os.path.dirname(sys.argv[0])
912     if srcdir == '':
913         srcdir = '.'
914     if not os.path.isfile( os.path.join(srcdir, 'chkconfig.ltx') ):
915         logger.error("configure: error: cannot find chkconfig.ltx script")
916         sys.exit(1)
917     setEnviron()
918     createDirectories()
919     windows_style_tex_paths = checkTeXPaths()
920     dtl_tools = checkDTLtools()
921     ## Write the first part of outfile
922     writeToFile(outfile, '''# This file has been automatically generated by LyX' lib/configure.py
923 # script. It contains default settings that have been determined by
924 # examining your system. PLEASE DO NOT MODIFY ANYTHING HERE! If you
925 # want to customize LyX, use LyX' Preferences dialog or modify directly 
926 # the "preferences" file instead. Any setting in that file will
927 # override the values given here.
928 ''')
929     # check latex
930     LATEX = checkLatex(dtl_tools)
931     checkFormatEntries(dtl_tools)
932     checkConverterEntries()
933     (chk_docbook, bool_docbook, docbook_cmd) = checkDocBook()
934     checkTeXAllowSpaces()
935     if windows_style_tex_paths != '':
936         addToRC(r'\tex_expects_windows_paths %s' % windows_style_tex_paths)
937     checkOtherEntries()
938     # --without-latex-config can disable lyx_check_config
939     ret = checkLatexConfig(lyx_check_config and LATEX != '', bool_docbook)
940     checkModulesConfig() #lyx_check_config and LATEX != '')
941     removeTempFiles()
942     # The return error code can be 256. Because most systems expect an error code
943     # in the range 0-127, 256 can be interpretted as 'success'. Because we expect
944     # a None for success, 'ret is not None' is used to exit.
945     sys.exit(ret is not None)