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