]> git.lyx.org Git - lyx.git/blob - lib/configure.py
move README.Documentation to attic
[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 from __future__ import print_function
12 import glob, logging, os, errno, re, shutil, subprocess, sys, stat
13
14 # set up logging
15 logging.basicConfig(level = logging.DEBUG,
16     format = '%(levelname)s: %(message)s', # ignore application name
17     filename = 'configure.log',
18     filemode = 'w')
19 #
20 # Add a handler to log to console
21 console = logging.StreamHandler()
22 console.setLevel(logging.INFO) # the console only print out general information
23 formatter = logging.Formatter('%(message)s') # only print out the message itself
24 console.setFormatter(formatter)
25 logger = logging.getLogger('LyX')
26 logger.addHandler(console)
27
28 def writeToFile(filename, lines, append = False):
29     " utility function: write or append lines to filename "
30     if append:
31         file = open(filename, 'a')
32     else:
33         file = open(filename, 'w')
34     file.write(lines)
35     file.close()
36
37
38 def addToRC(lines):
39     ''' utility function: shortcut for appending lines to outfile
40         add newline at the end of lines.
41     '''
42     if lines.strip() != '':
43         writeToFile(outfile, lines + '\n', append = True)
44         logger.debug('Add to RC:\n' + lines + '\n\n')
45
46
47 def removeFiles(filenames):
48     '''utility function: 'rm -f'
49         ignore errors when file does not exist, or is a directory.
50     '''
51     for file in filenames:
52         try:
53             os.remove(file)
54             logger.debug('Removing file %s' % file)
55         except OSError as e:
56             if e.errno == errno.ENOENT: # no such file or directory
57                 logger.debug('No need to remove file %s (it does not exists)' % file)
58             elif e.errno == errno.EISDIR: # is a directory
59                 logger.debug('Failed to remove file %s (it is a directory)' % file)
60             else:
61                 logger.debug('Failed to remove file %s' % file)
62             pass
63
64
65 def cmdOutput(cmd, async = False):
66     '''utility function: run a command and get its output as a string
67         cmd: command to run
68         async: if False, return whole output as a string, otherwise
69                return the stdout handle from which the output can be
70                read (the caller is then responsible for closing it)
71     '''
72     if os.name == 'nt':
73         b = False
74         if sys.version_info[0] < 3:
75             cmd = 'cmd /d /c pushd ' + shortPath(os.getcwdu()) + '&' + cmd
76         else:
77             cmd = 'cmd /d /c pushd ' + shortPath(os.getcwd()) + '&' + cmd
78     else:
79         b = True
80     pipe = subprocess.Popen(cmd, shell=b, close_fds=b, stdin=subprocess.PIPE,
81                             stdout=subprocess.PIPE, universal_newlines=True)
82     pipe.stdin.close()
83     if async:
84         return pipe.stdout
85     output = pipe.stdout.read()
86     pipe.stdout.close()
87     return output.strip()
88
89
90 def shortPath(path):
91     ''' On Windows, return the short version of "path" if possible '''
92     if os.name == 'nt':
93         from ctypes import windll, create_unicode_buffer
94         GetShortPathName = windll.kernel32.GetShortPathNameW
95         shortlen = GetShortPathName(path, 0, 0)
96         shortpath = create_unicode_buffer(shortlen)
97         if GetShortPathName(path, shortpath, shortlen):
98             return shortpath.value
99     return path
100
101
102 def setEnviron():
103     ''' I do not really know why this is useful, but we might as well keep it.
104         NLS nuisances.
105         Only set these to C if already set.  These must not be set unconditionally
106         because not all systems understand e.g. LANG=C (notably SCO).
107         Fixing LC_MESSAGES prevents Solaris sh from translating var values in set!
108         Non-C LC_CTYPE values break the ctype check.
109     '''
110     os.environ['LANG'] = os.getenv('LANG', 'C')
111     os.environ['LC'] = os.getenv('LC_ALL', 'C')
112     os.environ['LC_MESSAGE'] = os.getenv('LC_MESSAGE', 'C')
113     os.environ['LC_CTYPE'] = os.getenv('LC_CTYPE', 'C')
114
115
116 def copy_tree(src, dst, preserve_symlinks=False, level=0):
117     ''' Copy an entire directory tree 'src' to a new location 'dst'.
118
119     Code inspired from distutils.copy_tree.
120          Copying ignores non-regular files and the cache directory.
121     Pipes may be present as leftovers from LyX for lyx-server.
122
123     If 'preserve_symlinks' is true, symlinks will be
124     copied as symlinks (on platforms that support them!); otherwise
125     (the default), the destination of the symlink will be copied.
126     '''
127
128     if not os.path.isdir(src):
129         raise FileError("cannot copy tree '%s': not a directory" % src)
130     try:
131         names = os.listdir(src)
132     except os.error as oserror:
133         (errno, errstr) = oserror.args
134         raise FileError("error listing files in '%s': %s" % (src, errstr))
135
136     if not os.path.isdir(dst):
137         os.makedirs(dst)
138
139     outputs = []
140
141     for name in names:
142         src_name = os.path.join(src, name)
143         dst_name = os.path.join(dst, name)
144         if preserve_symlinks and os.path.islink(src_name):
145             link_dest = os.readlink(src_name)
146             os.symlink(link_dest, dst_name)
147             outputs.append(dst_name)
148         elif level == 0 and name == 'cache':
149             logger.info("Skip cache %s", src_name)
150         elif os.path.isdir(src_name):
151             outputs.extend(
152                 copy_tree(src_name, dst_name, preserve_symlinks, level=(level + 1)))
153         elif stat.S_ISREG(os.stat(src_name).st_mode) or os.path.islink(src_name):
154             shutil.copy2(src_name, dst_name)
155             outputs.append(dst_name)
156         else:
157             logger.info("Ignore non-regular file %s", src_name)
158
159     return outputs
160
161
162 def checkUpgrade():
163     ''' Check for upgrade from previous version '''
164     cwd = os.getcwd()
165     basename = os.path.basename( cwd )
166     lyxrc = os.path.join(cwd, outfile)
167     if not os.path.isfile( lyxrc ) and basename.endswith( version_suffix ) :
168         logger.info('Checking for upgrade from previous version.')
169         parent = os.path.dirname(cwd)
170         appname = basename[:(-len(version_suffix))]
171         for version in ['-2.1', '-2.0', '-1.6' ]:
172             logger.debug('Checking for upgrade from previous version ' + version)
173             previous = os.path.join(parent, appname + version)
174             logger.debug('previous = ' + previous)
175             if os.path.isdir( previous ):
176                 logger.info('Found directory "%s".', previous)
177                 copy_tree( previous, cwd, True )
178                 logger.info('Content copied to directory "%s".', cwd)
179                 return
180
181
182 def createDirectories():
183     ''' Create the build directories if necessary '''
184     for dir in ['bind', 'clipart', 'doc', 'examples', 'images', 'kbd',
185         'layouts', 'scripts', 'templates', 'ui' ]:
186         if not os.path.isdir( dir ):
187             try:
188                 os.mkdir( dir)
189                 logger.debug('Create directory %s.' % dir)
190             except:
191                 logger.error('Failed to create directory %s.' % dir)
192                 sys.exit(1)
193
194
195 def checkTeXPaths():
196     ''' Determine the path-style needed by the TeX engine on Win32 (Cygwin) '''
197     windows_style_tex_paths = ''
198     if LATEX == '':
199         return windows_style_tex_paths
200     if os.name == 'nt' or sys.platform == 'cygwin':
201         from tempfile import mkstemp
202         fd, tmpfname = mkstemp(suffix='.ltx')
203         if os.name == 'nt':
204             encoding = sys.getfilesystemencoding()
205             if sys.version_info[0] < 3:
206                 inpname = shortPath(unicode(tmpfname, encoding)).replace('\\', '/')
207             else:
208                 inpname = shortPath(tmpfname).replace('\\', '/') 
209         else:
210             inpname = cmdOutput('cygpath -m ' + tmpfname)
211         logname = os.path.basename(re.sub("(?i).ltx", ".log", inpname))
212         inpname = inpname.replace('~', '\\string~')
213         os.write(fd, b'\\relax')
214         os.close(fd)
215         latex_out = cmdOutput(r'latex "\nonstopmode\input{%s}\makeatletter\@@end"'
216                               % inpname)
217         if 'Error' in latex_out:
218             latex_out = cmdOutput(r'latex "\nonstopmode\input{\"%s\"}\makeatletter\@@end"'
219                                   % inpname)
220         if 'Error' in latex_out:
221             logger.warning("configure: TeX engine needs posix-style paths in latex files")
222             windows_style_tex_paths = 'false'
223         else:
224             logger.info("configure: TeX engine needs windows-style paths in latex files")
225             windows_style_tex_paths = 'true'
226         removeFiles([tmpfname, logname, 'texput.log'])
227     return windows_style_tex_paths
228
229
230 ## Searching some useful programs
231 def checkProg(description, progs, rc_entry = [], path = [], not_found = ''):
232     '''
233         This function will search a program in $PATH plus given path
234         If found, return directory and program name (not the options).
235
236         description: description of the program
237
238         progs: check programs, for each prog, the first word is used
239             for searching but the whole string is used to replace
240             %% for a rc_entry. So, feel free to add '$$i' etc for programs.
241
242         path: additional paths (will be prepended to the program name)
243
244         rc_entry: entry to outfile, can be
245             1. emtpy: no rc entry will be added
246             2. one pattern: %% will be replaced by the first found program,
247                 or '' if no program is found.
248             3. several patterns for each prog and not_found. This is used
249                 when different programs have different usages. If you do not
250                 want not_found entry to be added to the RC file, you can specify
251                 an entry for each prog and use '' for the not_found entry.
252
253         not_found: the value that should be used instead of '' if no program
254             was found
255
256     '''
257     # one rc entry for each progs plus not_found entry
258     if len(rc_entry) > 1 and len(rc_entry) != len(progs) + 1:
259         logger.error("rc entry should have one item or item "
260                      "for each prog and not_found.")
261         sys.exit(2)
262     logger.info('checking for ' + description + '...')
263     ## print '(' + ','.join(progs) + ')',
264     additional_path = path
265     path = os.environ["PATH"].split(os.pathsep) + additional_path
266     extlist = ['']
267     if "PATHEXT" in os.environ:
268         extlist = extlist + os.environ["PATHEXT"].split(os.pathsep)
269     global java, perl
270     for idx in range(len(progs)):
271         # ac_prog may have options, ac_word is the command name
272         ac_prog = progs[idx]
273         ac_word = ac_prog.split(' ')[0]
274         if (ac_word.endswith('.class') or ac_word.endswith('.jar')) and java == '':
275             continue
276         if ac_word.endswith('.pl') and perl == '':
277             continue
278         msg = '+checking for "' + ac_word + '"... '
279         for ac_dir in path:
280             if hasattr(os, "access") and not os.access(ac_dir, os.F_OK):
281                 continue
282             for ext in extlist:
283                 if os.path.isfile( os.path.join(ac_dir, ac_word + ext) ):
284                     logger.info(msg + ' yes')
285                     # deal with java and perl
286                     if ac_word.endswith('.class'):
287                         ac_prog = ac_prog.replace(ac_word, r'%s \"%s\"'
288                                     % (java, os.path.join(ac_dir, ac_word[:-6])))
289                     elif ac_word.endswith('.jar'):
290                         ac_prog = ac_prog.replace(ac_word, r'%s -jar \"%s\"'
291                                     % (java, os.path.join(ac_dir, ac_word)))
292                     elif ac_word.endswith('.pl'):
293                         ac_prog = ac_prog.replace(ac_word, r'%s -w \"%s\"'
294                                     % (perl, os.path.join(ac_dir, ac_word)))
295                     elif ac_dir in additional_path:
296                         ac_prog = ac_prog.replace(ac_word, r'\"%s\"'
297                                     % (os.path.join(ac_dir, ac_word)))
298                     # write rc entries for this command
299                     if len(rc_entry) == 1:
300                         addToRC(rc_entry[0].replace('%%', ac_prog))
301                     elif len(rc_entry) > 1:
302                         addToRC(rc_entry[idx].replace('%%', ac_prog))
303                     return [ac_dir, ac_word]
304         # if not successful
305         logger.info(msg + ' no')
306     # write rc entries for 'not found'
307     if len(rc_entry) > 0:  # the last one.
308         addToRC(rc_entry[-1].replace('%%', not_found))
309     return ['', not_found]
310
311
312 def checkProgAlternatives(description, progs, rc_entry = [],
313                           alt_rc_entry = [], path = [], not_found = ''):
314     '''
315         The same as checkProg, but additionally, all found programs will be added
316         as alt_rc_entries
317     '''
318     # one rc entry for each progs plus not_found entry
319     if len(rc_entry) > 1 and len(rc_entry) != len(progs) + 1:
320         logger.error("rc entry should have one item or item for each prog and not_found.")
321         sys.exit(2)
322     logger.info('checking for ' + description + '...')
323     ## print '(' + ','.join(progs) + ')',
324     additional_path = path
325     path = os.environ["PATH"].split(os.pathsep) + additional_path
326     extlist = ['']
327     if "PATHEXT" in os.environ:
328         extlist = extlist + os.environ["PATHEXT"].split(os.pathsep)
329     found_prime = False
330     real_ac_dir = ''
331     real_ac_word = not_found
332     global java, perl
333     for idx in range(len(progs)):
334         # ac_prog may have options, ac_word is the command name
335         ac_prog = progs[idx]
336         ac_word = ac_prog.split(' ')[0]
337         if (ac_word.endswith('.class') or ac_word.endswith('.jar')) and java == '':
338             continue
339         if ac_word.endswith('.pl') and perl == '':
340             continue
341         msg = '+checking for "' + ac_word + '"... '
342         found_alt = False
343         for ac_dir in path:
344             if hasattr(os, "access") and not os.access(ac_dir, os.F_OK):
345                 continue
346             for ext in extlist:
347                 if os.path.isfile( os.path.join(ac_dir, ac_word + ext) ):
348                     logger.info(msg + ' yes')
349                     pr = re.compile(r'(\\\S+)(.*)$')
350                     m = None
351                     # deal with java and perl
352                     if ac_word.endswith('.class'):
353                         ac_prog = ac_prog.replace(ac_word, r'%s \"%s\"'
354                                     % (java, os.path.join(ac_dir, ac_word[:-6])))
355                     elif ac_word.endswith('.jar'):
356                         ac_prog = ac_prog.replace(ac_word, r'%s -jar \"%s\"'
357                                     % (java, os.path.join(ac_dir, ac_word)))
358                     elif ac_word.endswith('.pl'):
359                         ac_prog = ac_prog.replace(ac_word, r'%s -w \"%s\"'
360                                     % (perl, os.path.join(ac_dir, ac_word)))
361                     elif ac_dir in additional_path:
362                         ac_prog = ac_prog.replace(ac_word, r'\"%s\"'
363                                     % (os.path.join(ac_dir, ac_word)))
364                     # write rc entries for this command
365                     if found_prime == False:
366                         if len(rc_entry) == 1:
367                             addToRC(rc_entry[0].replace('%%', ac_prog))
368                         elif len(rc_entry) > 1:
369                             addToRC(rc_entry[idx].replace('%%', ac_prog))
370                         real_ac_dir = ac_dir
371                         real_ac_word = ac_word
372                         found_prime = True
373                     if len(alt_rc_entry) == 1:
374                         alt_rc = alt_rc_entry[0]
375                         if alt_rc == "":
376                             # if no explicit alt_rc is given, construct one
377                             m = pr.match(rc_entry[0])
378                             if m:
379                                 alt_rc = m.group(1) + "_alternatives" + m.group(2)
380                         addToRC(alt_rc.replace('%%', ac_prog))
381                     elif len(alt_rc_entry) > 1:
382                         alt_rc = alt_rc_entry[idx]
383                         if alt_rc == "":
384                             # if no explicit alt_rc is given, construct one
385                             m = pr.match(rc_entry[idx])
386                             if m:
387                                 alt_rc = m.group(1) + "_alternatives" + m.group(2)
388                         addToRC(alt_rc.replace('%%', ac_prog))
389                     found_alt = True
390                     break
391             if found_alt:
392                 break
393         if found_alt == False:
394             # if not successful
395             logger.info(msg + ' no')
396     if found_prime:
397         return [real_ac_dir, real_ac_word]
398     # write rc entries for 'not found'
399     if len(rc_entry) > 0:  # the last one.
400         addToRC(rc_entry[-1].replace('%%', not_found))
401     return ['', not_found]
402
403
404 def addAlternatives(rcs, alt_type):
405     '''
406         Returns a \\prog_alternatives string to be used as an alternative
407         rc entry.  alt_type can be a string or a list of strings.
408     '''
409     r = re.compile(r'\\Format (\S+).*$')
410     m = None
411     alt = ''
412     alt_token = '\\%s_alternatives '
413     if isinstance(alt_type, str):
414         alt_tokens = [alt_token % alt_type]
415     else:
416         alt_tokens = [alt_token % s for s in alt_type]
417     for idxx in range(len(rcs)):
418         if len(rcs) == 1:
419             m = r.match(rcs[0])
420             if m:
421                 alt = '\n'.join([s + m.group(1) + ' "%%"' for s in alt_tokens])
422         elif len(rcs) > 1:
423             m = r.match(rcs[idxx])
424             if m:
425                 if idxx > 0:
426                     alt += '\n'
427                 alt += '\n'.join([s + m.group(1) + ' "%%"' for s in alt_tokens])
428     return alt
429
430
431 def listAlternatives(progs, alt_type, rc_entry = []):
432     '''
433         Returns a list of \\prog_alternatives strings to be used as alternative
434         rc entries.  alt_type can be a string or a list of strings.
435     '''
436     if len(rc_entry) > 1 and len(rc_entry) != len(progs) + 1:
437         logger.error("rc entry should have one item or item for each prog and not_found.")
438         sys.exit(2)
439     alt_rc_entry = []
440     for idx in range(len(progs)):
441         if len(rc_entry) == 1:
442             rcs = rc_entry[0].split('\n')
443             alt = addAlternatives(rcs, alt_type)
444             alt_rc_entry.insert(0, alt)
445         elif len(rc_entry) > 1:
446             rcs = rc_entry[idx].split('\n')
447             alt = addAlternatives(rcs, alt_type)
448             alt_rc_entry.insert(idx, alt)
449     return alt_rc_entry
450
451
452 def checkViewer(description, progs, rc_entry = [], path = []):
453     ''' The same as checkProgAlternatives, but for viewers '''
454     alt_rc_entry = listAlternatives(progs, 'viewer', rc_entry)
455     return checkProgAlternatives(description, progs, rc_entry,
456                                  alt_rc_entry, path, not_found = 'auto')
457
458
459 def checkEditor(description, progs, rc_entry = [], path = []):
460     ''' The same as checkProgAlternatives, but for editors '''
461     alt_rc_entry = listAlternatives(progs, 'editor', rc_entry)
462     return checkProgAlternatives(description, progs, rc_entry,
463                                  alt_rc_entry, path, not_found = 'auto')
464
465
466 def checkViewerNoRC(description, progs, rc_entry = [], path = []):
467     ''' The same as checkViewer, but do not add rc entry '''
468     alt_rc_entry = listAlternatives(progs, 'viewer', rc_entry)
469     rc_entry = []
470     return checkProgAlternatives(description, progs, rc_entry,
471                                  alt_rc_entry, path, not_found = 'auto')
472
473
474 def checkEditorNoRC(description, progs, rc_entry = [], path = []):
475     ''' The same as checkViewer, but do not add rc entry '''
476     alt_rc_entry = listAlternatives(progs, 'editor', rc_entry)
477     rc_entry = []
478     return checkProgAlternatives(description, progs, rc_entry,
479                                  alt_rc_entry, path, not_found = 'auto')
480
481
482 def checkViewerEditor(description, progs, rc_entry = [], path = []):
483     ''' The same as checkProgAlternatives, but for viewers and editors '''
484     alt_rc_entry = listAlternatives(progs, ['editor', 'viewer'], rc_entry)
485     return checkProgAlternatives(description, progs, rc_entry,
486                                  alt_rc_entry, path, not_found = 'auto')
487
488
489 def checkDTLtools():
490     ''' Check whether DTL tools are available (Windows only) '''
491     # Find programs! Returned path is not used now
492     if ((os.name == 'nt' or sys.platform == 'cygwin') and
493             checkProg('DVI to DTL converter', ['dv2dt']) != ['', ''] and
494             checkProg('DTL to DVI converter', ['dt2dv']) != ['', '']):
495         dtl_tools = True
496     else:
497         dtl_tools = False
498     return dtl_tools
499
500 def checkInkscape():
501     ''' Check whether Inkscape is available and return the full path (Windows only) '''
502     ''' On Mac OS (darwin) a wrapper is used - therefore the version is checked '''
503     ''' The answer of the real inkscape is validated and a fake binary used if this fails '''
504     if sys.platform == 'darwin':
505         version_string = cmdOutput("inkscape --version")
506         if version_string.startswith('Inkscape'):
507             return 'inkscape'
508         else:
509             return 'inkscape-binary'
510     elif os.name != 'nt':
511         return 'inkscape'
512     if sys.version_info[0] < 3:
513         import _winreg as winreg
514     else:
515         import winreg
516     aReg = winreg.ConnectRegistry(None, winreg.HKEY_CLASSES_ROOT)
517     try:
518         aKey = winreg.OpenKey(aReg, r"inkscape.svg\DefaultIcon")
519         val = winreg.QueryValueEx(aKey, "")
520         return str(val[0]).split('"')[1]
521     except EnvironmentError:
522         try:
523             aKey = winreg.OpenKey(aReg, r"Applications\inkscape.exe\shell\open\command")
524             val = winreg.QueryValueEx(aKey, "")
525             return str(val[0]).split('"')[1]
526         except EnvironmentError:
527             return 'inkscape'
528
529 def checkLatex(dtl_tools):
530     ''' Check latex, return lyx_check_config '''
531     path, LATEX = checkProg('a Latex2e program', ['latex $$i', 'latex2e $$i'])
532     path, PPLATEX = checkProg('a DVI postprocessing program', ['pplatex $$i'])
533     #-----------------------------------------------------------------
534     path, PLATEX = checkProg('pLaTeX, the Japanese LaTeX', ['platex $$i'])
535     if PLATEX != '':
536         # check if PLATEX is pLaTeX2e
537         writeToFile('chklatex.ltx', r'\nonstopmode\makeatletter\@@end')
538         # run platex on chklatex.ltx and check result
539         if cmdOutput(PLATEX + ' chklatex.ltx').find('pLaTeX2e') != -1:
540             # We have the Japanese pLaTeX2e
541             addToRC(r'\converter platex   dvi       "%s"   "latex=platex"' % PLATEX)
542         else:
543             PLATEX = ''
544             removeFiles(['chklatex.ltx', 'chklatex.log'])
545     #-----------------------------------------------------------------
546     # use LATEX to convert from latex to dvi if PPLATEX is not available
547     if PPLATEX == '':
548         PPLATEX = LATEX
549     if dtl_tools:
550         # Windows only: DraftDVI
551         addToRC(r'''\converter latex      dvi2       "%s"       "latex"
552 \converter dvi2       dvi        "python -tt $$s/scripts/clean_dvi.py $$i $$o"  ""''' % PPLATEX)
553     else:
554         addToRC(r'\converter latex      dvi        "%s" "latex"' % PPLATEX)
555     # no latex
556     if LATEX != '':
557         # Check if latex is usable
558         writeToFile('chklatex.ltx', r'''
559 \nonstopmode
560 \ifx\undefined\documentclass\else
561   \message{ThisIsLaTeX2e}
562 \fi
563 \makeatletter
564 \@@end
565 ''')
566         # run latex on chklatex.ltx and check result
567         if cmdOutput(LATEX + ' chklatex.ltx').find('ThisIsLaTeX2e') != -1:
568             # valid latex2e
569             return LATEX
570         else:
571             logger.warning("Latex not usable (not LaTeX2e) ")
572         # remove temporary files
573         removeFiles(['chklatex.ltx', 'chklatex.log'])
574     return ''
575
576
577 def checkLuatex():
578     ''' Check if luatex is there '''
579     path, LUATEX = checkProg('LuaTeX', ['lualatex $$i'])
580     path, DVILUATEX = checkProg('LuaTeX (DVI)', ['dvilualatex $$i'])
581     if LUATEX != '':
582         addToRC(r'\converter luatex      pdf5       "%s"        "latex=lualatex"' % LUATEX)
583     if DVILUATEX != '':
584         addToRC(r'\converter dviluatex   dvi3        "%s"       "latex=dvilualatex"' % DVILUATEX)
585
586
587 def checkModule(module):
588     ''' Check for a Python module, return the status '''
589     msg = 'checking for "' + module + ' module"... '
590     try:
591       __import__(module)
592       logger.info(msg + ' yes')
593       return True
594     except ImportError:
595       logger.info(msg + ' no')
596       return False
597
598
599 texteditors = ['xemacs', 'gvim', 'kedit', 'kwrite', 'kate',
600                'nedit', 'gedit', 'geany', 'leafpad', 'mousepad',
601                'xed', 'notepad', 'WinEdt', 'WinShell', 'PSPad']
602
603 def checkFormatEntries(dtl_tools):
604     ''' Check all formats (\Format entries) '''
605     checkViewerEditor('a Tgif viewer and editor', ['tgif'],
606         rc_entry = [r'\Format tgif      "obj, tgo" Tgif                 "" "%%" "%%"    "vector"        "application/x-tgif"'])
607     #
608     checkViewerEditor('a FIG viewer and editor', ['xfig', 'jfig3-itext.jar', 'jfig3.jar'],
609         rc_entry = [r'\Format fig        fig     FIG                    "" "%%" "%%"    "vector"        "application/x-xfig"'])
610     #
611     checkViewerEditor('a Dia viewer and editor', ['dia'],
612         rc_entry = [r'\Format dia        dia     DIA                    "" "%%" "%%"    "vector,zipped=native", "application/x-dia-diagram"'])
613     #
614     checkViewerEditor('an OpenDocument drawing viewer and editor', ['libreoffice', 'lodraw', 'ooffice', 'oodraw', 'soffice'],
615         rc_entry = [r'\Format odg        "odg, sxd" "OpenDocument drawing"   "" "%%"    "%%"    "vector,zipped=native"  "application/vnd.oasis.opendocument.graphics"'])
616     #
617     checkViewerEditor('a Grace viewer and editor', ['xmgrace'],
618         rc_entry = [r'\Format agr        agr     Grace                  "" "%%" "%%"    "vector"        ""'])
619     #
620     checkViewerEditor('a FEN viewer and editor', ['xboard -lpf $$i -mode EditPosition'],
621         rc_entry = [r'\Format fen        fen     FEN                    "" "%%" "%%"    ""      ""'])
622     #
623     checkViewerEditor('a SVG viewer and editor', [inkscape_gui],
624         rc_entry = [r'''\Format svg        "svg" SVG                "" "%%" "%%"        "vector"        "image/svg+xml"
625 \Format svgz       "svgz" "SVG (compressed)" "" "%%" "%%"       "vector,zipped=native"  ""'''],
626         path = [inkscape_path])
627     #
628     imageformats = r'''\Format bmp        bmp     BMP                    "" "%s"        "%s"    ""      "image/x-bmp"
629 \Format gif        gif     GIF                    "" "%s"       "%s"    ""      "image/gif"
630 \Format jpg       "jpg, jpeg" JPEG                "" "%s"       "%s"    ""      "image/jpeg"
631 \Format pbm        pbm     PBM                    "" "%s"       "%s"    ""      "image/x-portable-bitmap"
632 \Format pgm        pgm     PGM                    "" "%s"       "%s"    ""      "image/x-portable-graymap"
633 \Format png        png     PNG                    "" "%s"       "%s"    ""      "image/x-png"
634 \Format ppm        ppm     PPM                    "" "%s"       "%s"    ""      "image/x-portable-pixmap"
635 \Format tiff       tif     TIFF                   "" "%s"       "%s"    ""      "image/tiff"
636 \Format xbm        xbm     XBM                    "" "%s"       "%s"    ""      "image/x-xbitmap"
637 \Format xpm        xpm     XPM                    "" "%s"       "%s"    ""      "image/x-xpixmap"'''
638     path, iv = checkViewerNoRC('a raster image viewer',
639         ['xv', 'gwenview', 'kview',
640          'eog', 'xviewer', 'ristretto', 'gpicview', 'lximage-qt',
641          'xdg-open', 'gimp-remote', 'gimp'],
642         rc_entry = [imageformats])
643     path, ie = checkEditorNoRC('a raster image editor',
644         ['gimp-remote', 'gimp'], rc_entry = [imageformats])
645     addToRC(imageformats % ((iv, ie)*10))
646     #
647     checkViewerEditor('a text editor', texteditors,
648         rc_entry = [r'''\Format asciichess asc    "Plain text (chess output)"  "" ""    "%%"    ""      ""
649 \Format docbook    sgml    DocBook                B  "" "%%"    "document,menu=export"  ""
650 \Format docbook-xml xml   "DocBook (XML)"         "" "" "%%"    "document,menu=export"  "application/docbook+xml"
651 \Format dot        dot    "Graphviz Dot"          "" "" "%%"    "vector"        "text/vnd.graphviz"
652 \Format dviluatex  tex    "LaTeX (dviluatex)"     "" "" "%%"    "document,menu=export"  ""
653 \Format platex     tex    "LaTeX (pLaTeX)"        "" "" "%%"    "document,menu=export"  ""
654 \Format literate   nw      NoWeb                  N  "" "%%"    "document,menu=export"  ""
655 \Format sweave     Rnw    "Sweave"                S  "" "%%"    "document,menu=export"  ""
656 \Format sweave-ja  Rnw    "Sweave (Japanese)"     S  "" "%%"    "document,menu=export"  ""
657 \Format r          R      "R/S code"              "" "" "%%"    "document,menu=export"  ""
658 \Format knitr      Rnw    "Rnw (knitr)"           "" "" "%%"    "document,menu=export"  ""
659 \Format knitr-ja   Rnw    "Rnw (knitr, Japanese)" "" "" "%%"    "document,menu=export"  ""
660 \Format lilypond-book    lytex "LilyPond book (LaTeX)"   "" ""  "%%"    "document,menu=export"  ""
661 \Format lilypond-book-ja lytex "LilyPond book (pLaTeX)"   "" "" "%%"    "document,menu=export"  ""
662 \Format latex      tex    "LaTeX (plain)"         L  "" "%%"    "document,menu=export"  "text/x-tex"
663 \Format luatex     tex    "LaTeX (LuaTeX)"        "" "" "%%"    "document,menu=export"  ""
664 \Format pdflatex   tex    "LaTeX (pdflatex)"      "" "" "%%"    "document,menu=export"  ""
665 \Format xetex      tex    "LaTeX (XeTeX)"         "" "" "%%"    "document,menu=export"  ""
666 \Format latexclipboard tex "LaTeX (clipboard)"    "" "" "%%"    ""      ""
667 \Format text       txt    "Plain text"            a  "" "%%"    "document,menu=export"  "text/plain"
668 \Format text2      txt    "Plain text (pstotext)" "" "" "%%"    "document"      ""
669 \Format text3      txt    "Plain text (ps2ascii)" "" "" "%%"    "document"      ""
670 \Format text4      txt    "Plain text (catdvi)"   "" "" "%%"    "document"      ""
671 \Format textparagraph txt "Plain Text, Join Lines" "" ""        "%%"    "document"      ""
672 \Format beamer.info pdf.info   "Info (Beamer)"         "" ""   "%%"    "document,menu=export"   ""''' ])
673    #Lilypond files have special editors, but fall back to plain text editors
674     checkViewerEditor('a lilypond editor',
675         ['frescobaldi'] + texteditors,
676         rc_entry = [r'''\Format lilypond   ly     "LilyPond music"        "" "" "%%"    "vector"        "text/x-lilypond"''' ])
677    #Spreadsheets using ssconvert from gnumeric
678     checkViewer('gnumeric spreadsheet software', ['gnumeric'],
679       rc_entry = [r'''\Format gnumeric gnumeric "Gnumeric spreadsheet" "" ""    "%%"   "document"       "application/x-gnumeric"
680 \Format excel      xls    "Excel spreadsheet"      "" "" "%%"    "document"     "application/vnd.ms-excel"
681 \Format excel2     xlsx   "MS Excel Office Open XML" "" "" "%%" "document"      "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
682 \Format html_table html   "HTML Table (for spreadsheets)"      "" "" "%%"    "document" "text/html"
683 \Format oocalc     ods    "OpenDocument spreadsheet" "" "" "%%"    "document"   "application/vnd.oasis.opendocument.spreadsheet"'''])
684  #
685     checkViewer('an HTML previewer', ['firefox', 'mozilla file://$$p$$i', 'netscape'],
686         rc_entry = [r'\Format xhtml      xhtml   "LyXHTML"              y "%%" ""    "document,menu=export"     "application/xhtml+xml"'])
687  #
688     checkEditor('a BibTeX editor', ['jabref', 'JabRef',
689         'pybliographic', 'bibdesk', 'gbib', 'kbib',
690         'kbibtex', 'sixpack', 'bibedit', 'tkbibtex', 'TeXnicCenter'] +
691         texteditors,
692         rc_entry = [r'''\Format bibtex bib    "BibTeX"         "" ""    "%%"    ""      "text/x-bibtex"''' ])
693     #
694     #checkProg('a Postscript interpreter', ['gs'],
695     #  rc_entry = [ r'\ps_command "%%"' ])
696     checkViewer('a Postscript previewer',
697                 ['kghostview', 'okular', 'qpdfview --unique',
698                  'evince', 'xreader',
699                  'gv', 'ghostview -swap', 'gsview64', 'gsview32'],
700         rc_entry = [r'''\Format eps        eps     EPS                    "" "%%"       ""      "vector"        "image/x-eps"
701 \Format eps2       eps    "EPS (uncropped)"       "" "%%"       ""      "vector"        ""
702 \Format eps3       eps    "EPS (cropped)"         "" "%%"       ""      "document"      ""
703 \Format ps         ps      Postscript             t  "%%"       ""      "document,vector,menu=export"   "application/postscript"'''])
704     # for xdg-open issues look here: http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg151818.html
705     # maybe use "bestApplication()" from https://github.com/jleclanche/python-mime
706     # the MIME type is set for pdf6, because that one needs to be autodetectable by libmime
707     checkViewer('a PDF previewer',
708                 ['pdfview', 'kpdf', 'okular', 'qpdfview --unique',
709                  'evince', 'xreader', 'kghostview', 'xpdf', 'SumatraPDF',
710                  'acrobat', 'acroread', 'mupdf',
711                  'gv', 'ghostview', 'AcroRd32', 'gsview64', 'gsview32'],
712         rc_entry = [r'''\Format pdf        pdf    "PDF (ps2pdf)"          P  "%%"       ""      "document,vector,menu=export"   ""
713 \Format pdf2       pdf    "PDF (pdflatex)"        F  "%%"       ""      "document,vector,menu=export"   ""
714 \Format pdf3       pdf    "PDF (dvipdfm)"         m  "%%"       ""      "document,vector,menu=export"   ""
715 \Format pdf4       pdf    "PDF (XeTeX)"           X  "%%"       ""      "document,vector,menu=export"   ""
716 \Format pdf5       pdf    "PDF (LuaTeX)"          u  "%%"       ""      "document,vector,menu=export"   ""
717 \Format pdf6       pdf    "PDF (graphics)"        "" "%%"       ""      "vector"        "application/pdf"
718 \Format pdf7       pdf    "PDF (cropped)"         "" "%%"       ""      "document,vector"       ""
719 \Format pdf8       pdf    "PDF (lower resolution)"         "" "%%"      ""      "document,vector"       ""'''])
720     #
721     checkViewer('a DVI previewer', ['xdvi', 'kdvi', 'okular',
722                                     'evince', 'xreader',
723                                     'yap', 'dviout -Set=!m'],
724         rc_entry = [r'''\Format dvi        dvi     DVI                    D  "%%"       ""      "document,vector,menu=export"   "application/x-dvi"
725 \Format dvi3       dvi     "DVI (LuaTeX)"          V  "%%"      ""      "document,vector,menu=export"   ""'''])
726     if dtl_tools:
727         # Windows only: DraftDVI
728         addToRC(r'\Format dvi2       dvi     DraftDVI               ""  ""      ""      "vector"        ""')
729     #
730     checkViewer('an HTML previewer', ['firefox', 'mozilla file://$$p$$i', 'netscape'],
731         rc_entry = [r'\Format html      "html, htm" HTML                H  "%%" ""      "document,menu=export"  "text/html"'])
732     #
733     checkViewerEditor('Noteedit', ['noteedit'],
734         rc_entry = [r'\Format noteedit   not     Noteedit               "" "%%" "%%"    "vector"        ""'])
735     #
736     checkViewerEditor('an OpenDocument viewer', ['libreoffice', 'lwriter', 'lowriter', 'oowriter', 'swriter', 'abiword'],
737         rc_entry = [r'''\Format odt        odt     "OpenDocument (tex4ht)"  "" "%%"     "%%"    "document,vector,menu=export"   "application/vnd.oasis.opendocument.text"
738 \Format odt2       odt    "OpenDocument (eLyXer)"  "" "%%"      "%%"    "document,vector,menu=export"   "application/vnd.oasis.opendocument.text"
739 \Format odt3       odt    "OpenDocument (Pandoc)"  "" "%%"      "%%"    "document,vector,menu=export"   "application/vnd.oasis.opendocument.text"
740 \Format sxw        sxw    "OpenOffice.Org (sxw)"  "" "" ""      "document,vector"       "application/vnd.sun.xml.writer"'''])
741     #
742     checkViewerEditor('a Rich Text and Word viewer', ['libreoffice', 'lwriter', 'lowriter', 'oowriter', 'swriter', 'abiword'],
743         rc_entry = [r'''\Format rtf        rtf    "Rich Text Format"      "" "%%"       "%%"    "document,vector,menu=export"   "application/rtf"
744 \Format word       doc    "MS Word"               W  "%%"       "%%"    "document,vector,menu=export"   "application/msword"
745 \Format word2      docx    "MS Word Office Open XML"               O  "%%"      "%%"    "document,vector,menu=export"   "application/vnd.openxmlformats-officedocument.wordprocessingml.document"'''])
746     #
747     # entries that do not need checkProg
748     addToRC(r'''\Format csv        csv    "Table (CSV)"           "" "" ""      "document"      "text/csv"
749 \Format fax        ""      Fax                    "" "" ""      "document"      ""
750 \Format lyx        lyx     LyX                    "" "" ""      ""      "application/x-lyx"
751 \Format lyx13x     13.lyx "LyX 1.3.x"             "" "" ""      "document"      ""
752 \Format lyx14x     14.lyx "LyX 1.4.x"             "" "" ""      "document"      ""
753 \Format lyx15x     15.lyx "LyX 1.5.x"             "" "" ""      "document"      ""
754 \Format lyx16x     16.lyx "LyX 1.6.x"             "" "" ""      "document"      ""
755 \Format lyx20x     20.lyx "LyX 2.0.x"             "" "" ""      "document"      ""
756 \Format lyx21x     21.lyx "LyX 2.1.x"             "" "" ""      "document"      ""
757 \Format lyx22x     22.lyx "LyX 2.2.x"             "" "" ""      "document,menu=export"  ""
758 \Format clyx       cjklyx "CJK LyX 1.4.x (big5)"  "" "" ""      "document"      ""
759 \Format jlyx       cjklyx "CJK LyX 1.4.x (euc-jp)" "" ""        ""      "document"      ""
760 \Format klyx       cjklyx "CJK LyX 1.4.x (euc-kr)" "" ""        ""      "document"      ""
761 \Format lyxpreview lyxpreview "LyX Preview"       "" "" ""      ""      ""
762 \Format pdftex     "pdftex_t, pdf_tex" PDFTEX                "" ""      ""      ""      ""
763 \Format program    ""      Program                "" "" ""      ""      ""
764 \Format pstex      "pstex_t, ps_tex" PSTEX                  "" ""       ""      ""      ""
765 \Format wmf        wmf    "Windows Metafile"      "" "" ""      "vector"        "image/x-wmf"
766 \Format emf        emf    "Enhanced Metafile"     "" "" ""      "vector"        "image/x-emf"
767 \Format wordhtml  "html, htm" "HTML (MS Word)"    "" "" ""      "document"      ""
768 ''')
769
770
771 def checkConverterEntries():
772     ''' Check all converters (\converter entries) '''
773     checkProg('the pdflatex program', ['pdflatex $$i'],
774         rc_entry = [ r'\converter pdflatex   pdf2       "%%"    "latex=pdflatex"' ])
775
776     checkProg('XeTeX', ['xelatex $$i'],
777         rc_entry = [ r'\converter xetex      pdf4       "%%"    "latex=xelatex"' ])
778
779     checkLuatex()
780
781     # Look for tex2lyx in this order (see bugs #3308 and #6986):
782     #   1)  If we're building LyX with autotools then tex2lyx is found
783     #       in the subdirectory tex2lyx with respect to the binary dir.
784     #   2)  If we're building LyX with cmake then tex2lyx is found
785     #       in the binary dir.
786     #   3)  If LyX was configured with a version suffix then tex2lyx
787     #       will also have this version suffix.
788     #   4)  Otherwise always use tex2lyx.
789     in_binary_subdir = os.path.join(lyx_binary_dir, 'tex2lyx', 'tex2lyx')
790     in_binary_subdir = os.path.abspath(in_binary_subdir).replace('\\', '/')
791
792     in_binary_dir = os.path.join(lyx_binary_dir, 'tex2lyx')
793     in_binary_dir = os.path.abspath(in_binary_dir).replace('\\', '/')
794
795     path, t2l = checkProg('a LaTeX/Noweb -> LyX converter', [in_binary_subdir, in_binary_subdir + version_suffix, in_binary_dir, in_binary_dir + version_suffix, 'tex2lyx' + version_suffix, 'tex2lyx'],
796         rc_entry = [r'''\converter latex      lyx        "%% -f $$i $$o"        ""
797 \converter latexclipboard lyx        "%% -fixedenc utf8 -f $$i $$o"     ""
798 \converter literate   lyx        "%% -n -m noweb -f $$i $$o"    ""
799 \converter sweave   lyx        "%% -n -m sweave -f $$i $$o"     "needauth"
800 \converter knitr   lyx        "%% -n -m knitr -f $$i $$o"       "needauth"'''], not_found = 'tex2lyx')
801     if path == '':
802         logger.warning("Failed to find tex2lyx on your system.")
803
804     #
805     checkProg('a Noweb -> LaTeX converter', ['noweave -delay -index $$i > $$o'],
806         rc_entry = [r'''\converter literate   latex      "%%"   ""
807 \converter literate   pdflatex      "%%"        ""
808 \converter literate   xetex         "%%"        ""
809 \converter literate   luatex        "%%"        ""
810 \converter literate   dviluatex     "%%"        ""'''])
811     #
812     checkProg('a Sweave -> LaTeX converter', ['Rscript --verbose --no-save --no-restore $$s/scripts/lyxsweave.R $$p$$i $$p$$o $$e $$r'],
813         rc_entry = [r'''\converter sweave   latex      "%%"     "needauth"
814 \converter sweave   pdflatex   "%%"     "needauth"
815 \converter sweave-ja   platex     "%%"  "needauth"
816 \converter sweave   xetex      "%%"     "needauth"
817 \converter sweave   luatex     "%%"     "needauth"
818 \converter sweave   dviluatex  "%%"     "needauth"'''])
819     #
820     checkProg('a knitr -> LaTeX converter', ['Rscript --verbose --no-save --no-restore $$s/scripts/lyxknitr.R $$p$$i $$p$$o $$e $$r'],
821         rc_entry = [r'''\converter knitr   latex      "%%"      "needauth"
822 \converter knitr   pdflatex   "%%"      "needauth"
823 \converter knitr-ja   platex     "%%"   "needauth"
824 \converter knitr   xetex      "%%"      "needauth"
825 \converter knitr   luatex     "%%"      "needauth"
826 \converter knitr   dviluatex  "%%"      "needauth"'''])
827     #
828     checkProg('a Sweave -> R/S code converter', ['Rscript --verbose --no-save --no-restore $$s/scripts/lyxstangle.R $$i $$e $$r'],
829         rc_entry = [ r'\converter sweave      r      "%%"    "needauth"',
830                      r'\converter sweave-ja   r      "%%"    "needauth"' ])
831     #
832     checkProg('a knitr -> R/S code converter', ['Rscript --verbose --no-save --no-restore $$s/scripts/lyxknitr.R $$p$$i $$p$$o $$e $$r tangle'],
833         rc_entry = [ r'\converter knitr      r      "%%"    "needauth"',
834                      r'\converter knitr-ja   r      "%%"    "needauth"' ])
835     #
836     checkProg('an HTML -> LaTeX converter', ['html2latex $$i', 'gnuhtml2latex',
837         'htmltolatex -input $$i -output $$o', 'htmltolatex.jar -input $$i -output $$o'],
838         rc_entry = [ r'\converter html       latex      "%%"    ""',
839                      r'\converter html       latex      "python -tt $$s/scripts/html2latexwrapper.py %% $$i $$o"        ""',
840                      r'\converter html       latex      "%%"    ""',
841                      r'\converter html       latex      "%%"    ""', '' ])
842     #
843     checkProg('an MS Word -> LaTeX converter', ['wvCleanLatex $$i $$o'],
844         rc_entry = [ r'\converter word       latex      "%%"    ""' ])
845
846     # eLyXer: search as an executable (elyxer.py, elyxer)
847     path, elyxer = checkProg('a LyX -> HTML converter',
848         ['elyxer.py --nofooter --directory $$r $$i $$o', 'elyxer --nofooter --directory $$r $$i $$o'],
849         rc_entry = [ r'\converter lyx      html       "%%"      ""' ])
850     path, elyxer = checkProg('a LyX -> HTML (MS Word) converter',
851         ['elyxer.py --nofooter --html --directory $$r $$i $$o', 'elyxer --nofooter --html --directory $$r $$i $$o'],
852         rc_entry = [ r'\converter lyx      wordhtml       "%%"  ""' ])
853     path, elyxer = checkProg('a LyX -> OpenDocument (eLyXer) converter',
854         ['elyxer.py --html --nofooter --unicode --directory $$r $$i $$o', 'elyxer --html --nofooter --unicode --directory $$r $$i $$o'],
855         rc_entry = [ r'\converter lyx      odt2       "%%"      ""' ])
856     path, elyxer = checkProg('a LyX -> Word converter',
857         ['elyxer.py --html --nofooter --unicode --directory $$r $$i $$o', 'elyxer --html --nofooter --unicode --directory $$r $$i $$o'],
858         rc_entry = [ r'\converter lyx      word      "%%"       ""' ])
859     if elyxer.find('elyxer') >= 0:
860       addToRC(r'''\copier    html       "python -tt $$s/scripts/ext_copy.py -e html,png,jpg,jpeg,css $$i $$o"''')
861       addToRC(r'''\copier    wordhtml       "python -tt $$s/scripts/ext_copy.py -e html,png,jpg,jpeg,css $$i $$o"''')
862     else:
863       # search for HTML converters other than eLyXer
864       # On SuSE the scripts have a .sh suffix, and on debian they are in /usr/share/tex4ht/
865       path, htmlconv = checkProg('a LaTeX -> HTML converter', ['htlatex $$i', 'htlatex.sh $$i',
866           '/usr/share/tex4ht/htlatex $$i', 'tth  -t -e2 -L$$b < $$i > $$o',
867           'latex2html -no_subdir -split 0 -show_section_numbers $$i', 'hevea -s $$i'],
868           rc_entry = [ r'\converter latex      html       "%%"  "needaux"' ])
869       if htmlconv.find('htlatex') >= 0 or htmlconv == 'latex2html':
870         addToRC(r'''\copier    html       "python -tt $$s/scripts/ext_copy.py -e html,png,css $$i $$o"''')
871       else:
872         addToRC(r'''\copier    html       "python -tt $$s/scripts/ext_copy.py $$i $$o"''')
873       path, htmlconv = checkProg('a LaTeX -> HTML (MS Word) converter', ["htlatex $$i 'html,word' 'symbol/!' '-cvalidate'",
874           "htlatex.sh $$i 'html,word' 'symbol/!' '-cvalidate'",
875           "/usr/share/tex4ht/htlatex $$i 'html,word' 'symbol/!' '-cvalidate'"],
876           rc_entry = [ r'\converter latex      wordhtml   "%%"  "needaux"' ])
877       if htmlconv.find('htlatex') >= 0:
878         addToRC(r'''\copier    wordhtml       "python -tt $$s/scripts/ext_copy.py -e html,png,css $$i $$o"''')
879       else:
880         addToRC(r'''\copier    wordhtml       "python -tt $$s/scripts/ext_copy.py $$i $$o"''')
881
882
883     # Check if LyXBlogger is installed
884     lyxblogger_found = checkModule('lyxblogger')
885     if lyxblogger_found:
886       addToRC(r'\Format    blog       blog       "LyXBlogger"           "" "" ""  "document"  ""')
887       addToRC(r'\converter xhtml      blog       "python -m lyxblogger $$i"       ""')
888
889     #
890     checkProg('an OpenOffice.org -> LaTeX converter', ['w2l -clean $$i'],
891         rc_entry = [ r'\converter sxw        latex      "%%"    ""' ])
892     #
893     checkProg('an OpenDocument -> LaTeX converter', ['w2l -clean $$i'],
894         rc_entry = [ r'\converter odt        latex      "%%"    ""' ])
895     #
896     checkProg('an Open Document (Pandoc) -> LaTeX converter', ['pandoc -s -f odt -o $$o -t latex $$i'],
897         rc_entry = [ r'\converter odt3        latex      "%%"   ""' ])
898     #
899     checkProg('a MS Word Office Open XML converter -> LaTeX', ['pandoc -s -f docx -o $$o -t latex $$i'],
900         rc_entry = [ r'\converter word2      latex      "%%"    ""' ])
901     # Only define a converter to pdf6, otherwise the odt format could be
902     # used as an intermediate step for export to pdf, which is not wanted.
903     checkProg('an OpenDocument -> PDF converter', ['unoconv -f pdf --stdout $$i > $$o'],
904         rc_entry = [ r'\converter odt        pdf6       "%%"    ""' ])
905     # According to http://www.tug.org/applications/tex4ht/mn-commands.html
906     # the command mk4ht oolatex $$i has to be used as default,
907     # but as this would require to have Perl installed, in MiKTeX oolatex is
908     # directly available as application.
909     # On SuSE the scripts have a .sh suffix, and on debian they are in /usr/share/tex4ht/
910     # Both SuSE and debian have oolatex
911     checkProg('a LaTeX -> Open Document (tex4ht) converter', [
912         'oolatex $$i', 'mk4ht oolatex $$i', 'oolatex.sh $$i', '/usr/share/tex4ht/oolatex $$i',
913         'htlatex $$i \'xhtml,ooffice\' \'ooffice/! -cmozhtf\' \'-coo\' \'-cvalidate\''],
914         rc_entry = [ r'\converter latex      odt        "%%"    "needaux"' ])
915     # On windows it is called latex2rt.exe
916     checkProg('a LaTeX -> RTF converter', ['latex2rtf -p -S -o $$o $$i', 'latex2rt -p -S -o $$o $$i'],
917         rc_entry = [ r'\converter latex      rtf        "%%"    "needaux"' ])
918     #
919     checkProg('a LaTeX -> Open Document (Pandoc) converter', ['pandoc -s -f latex -o $$o -t odt $$i'],
920         rc_entry = [ r'\converter latex      odt3        "%%"   ""' ])
921     #
922     checkProg('a LaTeX -> MS Word Office Open XML converter', ['pandoc -s -f latex -o $$o -t docx $$i'],
923         rc_entry = [ r'\converter latex      word2       "%%"   ""' ])
924     #
925     checkProg('a RTF -> HTML converter', ['unrtf --html  $$i > $$o'],
926         rc_entry = [ r'\converter rtf      html        "%%"     ""' ])
927     # Do not define a converter to pdf6, ps is a pure export format
928     checkProg('a PS to PDF converter', ['ps2pdf $$i $$o'],
929         rc_entry = [ r'\converter ps         pdf        "%%"    ""' ])
930     #
931     checkProg('a PS to TXT converter', ['pstotext $$i > $$o'],
932         rc_entry = [ r'\converter ps         text2      "%%"    ""' ])
933     #
934     checkProg('a PS to TXT converter', ['ps2ascii $$i $$o'],
935         rc_entry = [ r'\converter ps         text3      "%%"    ""' ])
936     # Need to call ps2eps in a pipe, otherwise it would name the output file
937     # depending on the extension of the input file. We do not know the input
938     # file extension in general, so the resultfile= flag would not help.
939     # Since ps2eps crops the image, we do not use it to convert from ps->eps.
940     # This would create additional paths in the converter graph with unwanted
941     # side effects (e.g. ps->pdf via ps2pdf would create a different result
942     # than ps->eps->pdf via ps2eps and epstopdf).
943     checkProg('a PS to EPS converter', ['ps2eps -- < $$i > $$o'],
944         rc_entry = [ r'\converter eps2       eps      "%%"      ""' ])
945     #
946     checkProg('a PDF to PS converter', ['pdftops $$i $$o', 'pdf2ps $$i $$o'],
947         rc_entry = [ r'\converter pdf         ps        "%%"    ""' ])
948     # Only define a converter from pdf6 for graphics
949     checkProg('a PDF to EPS converter', ['pdftops -eps -f 1 -l 1 $$i $$o'],
950         rc_entry = [ r'\converter pdf6        eps        "%%"   ""' ])
951     # Define a converter from pdf6 to png for Macs where pdftops is missing.
952     # The converter utility sips allows to force the dimensions of the resulting
953     # png image. The value of 800 pixel for the width is arbitrary and not
954     # related to the current screen resolution or width.
955     # There is no converter parameter for this information.
956     checkProg('a PDF to PNG converter',
957         ['sips --resampleWidth 800 --setProperty format png $$i --out $$o'],
958         rc_entry = [ r'\converter pdf6        png        "%%" ""' ])
959     # Create one converter for a PDF produced using TeX fonts and one for a
960     # PDF produced using non-TeX fonts. This does not produce non-unique
961     # conversion paths, since a given document either uses TeX fonts or not.
962     checkProg('a PDF cropping tool', ['pdfcrop $$i $$o'],
963         rc_entry = [ r'''\converter pdf2   pdf7       "%%"      ""
964 \converter pdf4   pdf7       "%%"       ""''' ])
965     # Create one converter for a PDF produced using TeX fonts and one for a
966     # PDF produced using non-TeX fonts. This does not produce non-unique
967     # conversion paths, since a given document either uses TeX fonts or not.
968     checkProg('Ghostscript', ["gswin32c", "gswin64c", "gs"],
969         rc_entry = [ r'''\converter pdf2   pdf8       "python -tt $$s/scripts/convert_pdf.py $$i $$o ebook"     ""
970 \converter pdf4   pdf8       "python -tt $$s/scripts/convert_pdf.py $$i $$o ebook"      ""''' ])
971     #
972     checkProg('a Beamer info extractor', ['makebeamerinfo -p $$i'],
973         rc_entry = [ r'\converter pdf2         beamer.info        "%%"  ""' ])
974     #
975     checkProg('a DVI to TXT converter', ['catdvi $$i > $$o'],
976         rc_entry = [ r'\converter dvi        text4      "%%"    ""' ])
977     #
978     checkProg('a DVI to PS converter', ['dvips -o $$o $$i'],
979         rc_entry = [ r'\converter dvi        ps         "%%"    ""' ])
980     #
981     checkProg('a DVI to cropped EPS converter', ['dvips -E -o $$o $$i'],
982         rc_entry = [ r'\converter dvi        eps3         "%%"  ""' ])
983     #
984     checkProg('a DVI to PDF converter', ['dvipdfmx -o $$o $$i', 'dvipdfm -o $$o $$i'],
985         rc_entry = [ r'\converter dvi        pdf3       "%%"    ""' ])
986     #
987     checkProg('a fax program', ['kdeprintfax $$i', 'ksendfax $$i', 'hylapex $$i'],
988         rc_entry = [ r'\converter ps         fax        "%%"    ""'])
989     #
990     path, fig2dev = checkProg('a FIG -> Image converter', ['fig2dev'])
991     if fig2dev == "fig2dev":
992         addToRC(r'''\converter fig        eps        "fig2dev -L eps $$i $$o"   ""
993 \converter fig        ppm        "fig2dev -L ppm $$i $$o"       ""
994 \converter fig        svg        "fig2dev -L svg $$i $$o"       ""
995 \converter fig        png        "fig2dev -L png $$i $$o"       ""
996 \converter fig        pdftex     "python -tt $$s/scripts/fig2pdftex.py $$i $$o" ""
997 \converter fig        pstex      "python -tt $$s/scripts/fig2pstex.py $$i $$o"  ""''')
998     #
999     checkProg('a SVG -> PDFTeX converter', [inkscape_cl],
1000         rc_entry = [ r'\converter svg        pdftex     "python -tt $$s/scripts/svg2pdftex.py %% $$p$$i $$p$$o" ""'],
1001         path = [inkscape_path])
1002     #
1003     checkProg('a SVG -> PSTeX converter', [inkscape_cl],
1004         rc_entry = [ r'\converter svg        pstex     "python -tt $$s/scripts/svg2pstex.py %% $$p$$i $$p$$o" ""'],
1005         path = [inkscape_path])
1006     #
1007     checkProg('a TIFF -> PS converter', ['tiff2ps $$i > $$o'],
1008         rc_entry = [ r'\converter tiff       eps        "%%"    ""'])
1009     #
1010     checkProg('a TGIF -> EPS/PPM converter', ['tgif'],
1011         rc_entry = [
1012             r'''\converter tgif       eps        "tgif -print -color -eps -stdout $$i > $$o"    ""
1013 \converter tgif       png        "tgif -print -color -png -o $$d $$i"   ""
1014 \converter tgif       pdf6       "tgif -print -color -pdf -stdout $$i > $$o"    ""'''])
1015     #
1016     checkProg('a WMF -> EPS converter', ['metafile2eps $$i $$o', 'wmf2eps -o $$o $$i', inkscape_cl + ' --file=%s$$i --export-area-drawing --without-gui --export-eps=%s$$o'
1017                % (inkscape_fileprefix, inkscape_fileprefix)],
1018         rc_entry = [ r'\converter wmf        eps        "%%"    ""'])
1019     #
1020     checkProg('an EMF -> EPS converter', ['metafile2eps $$i $$o', inkscape_cl + ' --file=%s$$i --export-area-drawing --without-gui --export-eps=%s$$o'
1021                % (inkscape_fileprefix, inkscape_fileprefix)],
1022         rc_entry = [ r'\converter emf        eps        "%%"    ""'])
1023     #
1024     checkProg('a WMF -> PDF converter', [inkscape_cl + ' --file=%s$$i --export-area-drawing --without-gui --export-pdf=%s$$o' % (inkscape_fileprefix, inkscape_fileprefix)],
1025         rc_entry = [ r'\converter wmf        pdf6        "%%"   ""'])
1026     #
1027     checkProg('an EMF -> PDF converter', [inkscape_cl + ' --file=%s$$i --export-area-drawing --without-gui --export-pdf=%s$$o' % (inkscape_fileprefix, inkscape_fileprefix)],
1028         rc_entry = [ r'\converter emf        pdf6        "%%"   ""'])
1029     # Only define a converter to pdf6 for graphics
1030     checkProg('an EPS -> PDF converter', ['epstopdf'],
1031         rc_entry = [ r'\converter eps        pdf6       "epstopdf --outfile=$$o $$i"    ""'])
1032     #
1033     checkProg('an EPS -> PNG converter', ['magick $$i $$o', 'convert $$i $$o'],
1034         rc_entry = [ r'\converter eps        png        "%%"    ""'])
1035     #
1036     # no agr -> pdf6 converter, since the pdf library used by gracebat is not
1037     # free software and therefore not compiled in in many installations.
1038     # Fortunately, this is not a big problem, because we will use epstopdf to
1039     # convert from agr to pdf6 via eps without loss of quality.
1040     checkProg('a Grace -> Image converter', ['gracebat'],
1041         rc_entry = [
1042             r'''\converter agr        eps        "gracebat -hardcopy -printfile $$o -hdevice EPS $$i 2>/dev/null"       ""
1043 \converter agr        png        "gracebat -hardcopy -printfile $$o -hdevice PNG $$i 2>/dev/null"       ""
1044 \converter agr        jpg        "gracebat -hardcopy -printfile $$o -hdevice JPEG $$i 2>/dev/null"      ""
1045 \converter agr        ppm        "gracebat -hardcopy -printfile $$o -hdevice PNM $$i 2>/dev/null"       ""'''])
1046     #
1047     checkProg('a Dot -> Image converter', ['dot'],
1048         rc_entry = [
1049             r'''\converter dot        eps        "dot -Teps $$i -o $$o" ""
1050 \converter dot        png        "dot -Tpng $$i -o $$o" ""'''])
1051     #
1052     path, dia = checkProg('a Dia -> Image converter', ['dia'])
1053     if dia == 'dia':
1054         addToRC(r'''\converter dia        png        "dia -e $$o -t png $$i"    ""
1055 \converter dia        eps        "dia -e $$o -t eps $$i"        ""
1056 \converter dia        svg        "dia -e $$o -t svg $$i"        ""''')
1057
1058     #
1059     # Actually, this produces EPS, but with a wrong bounding box (usually A4 or letter).
1060     # The eps2->eps converter then fixes the bounding box by cropping.
1061     # Although unoconv can convert to png and pdf as well, do not define
1062     # odg->png and odg->pdf converters, since the bb would be too large as well.
1063     checkProg('an OpenDocument -> EPS converter', ['libreoffice --headless --nologo --convert-to eps $$i', 'unoconv -f eps --stdout $$i > $$o'],
1064         rc_entry = [ r'\converter odg        eps2       "%%"    ""'])
1065     #
1066     checkProg('a SVG (compressed) -> SVG converter', ['gunzip -c $$i > $$o'],
1067         rc_entry = [ r'\converter svgz       svg        "%%"    ""'])
1068     #
1069     checkProg('a SVG -> SVG (compressed) converter', ['gzip -c $$i > $$o'],
1070         rc_entry = [ r'\converter svg        svgz       "%%"    ""'])
1071     # Only define a converter to pdf6 for graphics
1072     # Prefer rsvg-convert over inkscape since it is faster (see http://www.lyx.org/trac/ticket/9891)
1073     checkProg('a SVG -> PDF converter', ['rsvg-convert -f pdf -o $$o $$i', inkscape_cl + ' --file=%s$$i --export-area-drawing --without-gui --export-pdf=%s$$o'
1074                % (inkscape_fileprefix, inkscape_fileprefix)],
1075         rc_entry = [ r'''\converter svg        pdf6       "%%"    ""
1076 \converter svgz       pdf6       "%%"    ""'''],
1077         path = ['', inkscape_path])
1078     #
1079     checkProg('a SVG -> EPS converter', ['rsvg-convert -f ps -o $$o $$i', inkscape_cl + ' --file=%s$$i --export-area-drawing --without-gui --export-eps=%s$$o'
1080                % (inkscape_fileprefix, inkscape_fileprefix)],
1081         rc_entry = [ r'''\converter svg        eps        "%%"    ""
1082 \converter svgz       eps        "%%"    ""'''],
1083         path = ['', inkscape_path])
1084     #
1085     checkProg('a SVG -> PNG converter', ['rsvg-convert -f png -o $$o $$i', inkscape_cl + ' --without-gui --file=%s$$i --export-png=%s$$o'
1086                % (inkscape_fileprefix, inkscape_fileprefix)],
1087         rc_entry = [ r'''\converter svg        png        "%%"    "",
1088 \converter svgz       png        "%%"    ""'''],
1089         path = ['', inkscape_path])
1090     #
1091     checkProg('Gnuplot', ['gnuplot'], 
1092         rc_entry = [ r'''\Format gnuplot     "gp, gnuplot"    "Gnuplot"     "" "" ""  "vector"  "text/plain"
1093 \converter gnuplot      pdf6      "python -tt $$s/scripts/gnuplot2pdf.py $$i $$o"    "needauth"''' ])
1094     #
1095     # gnumeric/xls/ods to tex
1096     checkProg('a spreadsheet -> latex converter', ['ssconvert'],
1097        rc_entry = [ r'''\converter gnumeric latex "ssconvert --export-type=Gnumeric_html:latex $$i $$o" ""
1098 \converter oocalc latex "ssconvert --export-type=Gnumeric_html:latex $$i $$o" ""
1099 \converter excel  latex "ssconvert --export-type=Gnumeric_html:latex $$i $$o" ""
1100 \converter excel2 latex "ssconvert --export-type=Gnumeric_html:latex $$i $$o" ""
1101 \converter gnumeric html_table "ssconvert --export-type=Gnumeric_html:html40frag $$i $$o" ""
1102 \converter oocalc html_table "ssconvert --export-type=Gnumeric_html:html40frag $$i $$o" ""
1103 \converter excel  html_table "ssconvert --export-type=Gnumeric_html:html40frag $$i $$o" ""
1104 \converter excel2 html_table "ssconvert --export-type=Gnumeric_html:html40frag $$i $$o" ""
1105 '''])
1106
1107     path, lilypond = checkProg('a LilyPond -> EPS/PDF/PNG converter', ['lilypond'])
1108     if (lilypond != ''):
1109         version_string = cmdOutput("lilypond --version")
1110         match = re.match('GNU LilyPond (\S+)', version_string)
1111         if match:
1112             version_number = match.groups()[0]
1113             version = version_number.split('.')
1114             if int(version[0]) > 2 or (len(version) > 1 and int(version[0]) == 2 and int(version[1]) >= 11):
1115                 addToRC(r'''\converter lilypond   eps        "lilypond -dbackend=eps -dsafe --ps $$i"   ""
1116 \converter lilypond   png        "lilypond -dbackend=eps -dsafe --png $$i"      ""''')
1117                 addToRC(r'\converter lilypond   pdf6       "lilypond -dbackend=eps -dsafe --pdf $$i"    ""')
1118                 logger.info('+  found LilyPond version %s.' % version_number)
1119             elif int(version[0]) > 2 or (len(version) > 1 and int(version[0]) == 2 and int(version[1]) >= 6):
1120                 addToRC(r'''\converter lilypond   eps        "lilypond -b eps --ps --safe $$i"  ""
1121 \converter lilypond   png        "lilypond -b eps --png $$i"    ""''')
1122                 if int(version[0]) > 2 or (len(version) > 1 and int(version[0]) == 2 and int(version[1]) >= 9):
1123                     addToRC(r'\converter lilypond   pdf6       "lilypond -b eps --pdf --safe $$i"       ""')
1124                 logger.info('+  found LilyPond version %s.' % version_number)
1125             else:
1126                 logger.info('+  found LilyPond, but version %s is too old.' % version_number)
1127         else:
1128             logger.info('+  found LilyPond, but could not extract version number.')
1129     #
1130     path, lilypond_book = checkProg('a LilyPond book (LaTeX) -> LaTeX converter', ['lilypond-book'])
1131     if (lilypond_book != ''):
1132         version_string = cmdOutput("lilypond-book --version")
1133         match = re.match('(\S+)$', version_string)
1134         if match:
1135             version_number = match.groups()[0]
1136             version = version_number.split('.')
1137             if int(version[0]) > 2 or (len(version) > 1 and int(version[0]) == 2 and int(version[1]) >= 13):
1138                 # Note: The --lily-output-dir flag is required because lilypond-book
1139                 #       does not process input again unless the input has changed,
1140                 #       even if the output format being requested is different. So
1141                 #       once a .eps file exists, lilypond-book won't create a .pdf
1142                 #       even when requested with --pdf. This is a problem if a user
1143                 #       clicks View PDF after having done a View DVI. To circumvent
1144                 #       this, use different output folders for eps and pdf outputs.
1145                 addToRC(r'\converter lilypond-book latex    "lilypond-book --safe --lily-output-dir=ly-eps $$i"                                ""')
1146                 addToRC(r'\converter lilypond-book pdflatex "lilypond-book --safe --pdf --latex-program=pdflatex --lily-output-dir=ly-pdf $$i" ""')
1147                 addToRC(r'\converter lilypond-book-ja platex "lilypond-book --safe --pdf --latex-program=platex --lily-output-dir=ly-pdf $$i" ""')
1148                 addToRC(r'\converter lilypond-book xetex    "lilypond-book --safe --pdf --latex-program=xelatex --lily-output-dir=ly-pdf $$i"  ""')
1149                 addToRC(r'\converter lilypond-book luatex   "lilypond-book --safe --pdf --latex-program=lualatex --lily-output-dir=ly-pdf $$i" ""')
1150                 addToRC(r'\converter lilypond-book dviluatex "lilypond-book --safe --latex-program=dvilualatex --lily-output-dir=ly-eps $$i" ""')
1151                 logger.info('+  found LilyPond-book version %s.' % version_number)
1152             else:
1153                 logger.info('+  found LilyPond-book, but version %s is too old.' % version_number)
1154         else:
1155             logger.info('+  found LilyPond-book, but could not extract version number.')
1156     #
1157     checkProg('a Noteedit -> LilyPond converter', ['noteedit --export-lilypond $$i'],
1158         rc_entry = [ r'\converter noteedit   lilypond   "%%"    ""' ])
1159     #
1160     # Currently, lyxpak outputs a gzip compressed tar archive on *nix
1161     # and a zip archive on Windows.
1162     # So, we configure the appropriate version according to the platform.
1163     cmd = r'\converter lyx %s "python -tt $$s/scripts/lyxpak.py $$r/$$f" ""'
1164     if os.name == 'nt':
1165         addToRC(r'\Format lyxzip     zip    "LyX Archive (zip)"     "" "" ""  "document,menu=export"    ""')
1166         addToRC(cmd % "lyxzip")
1167     else:
1168         addToRC(r'\Format lyxgz      gz     "LyX Archive (tar.gz)"  "" "" ""  "document,menu=export"    ""')
1169         addToRC(cmd % "lyxgz")
1170
1171     #
1172     # FIXME: no rc_entry? comment it out
1173     # checkProg('Image converter', ['convert $$i $$o'])
1174     #
1175     # Entries that do not need checkProg
1176     addToRC(r'''
1177 \converter csv        lyx        "python -tt $$s/scripts/csv2lyx.py $$i $$o"    ""
1178 \converter docbook    docbook-xml "cp $$i $$o"  "xml"
1179 \converter fen        asciichess "python -tt $$s/scripts/fen2ascii.py $$i $$o"  ""
1180 \converter lyx        lyx13x     "python -tt $$s/lyx2lyx/lyx2lyx -V 1.3 -o $$o $$i"     ""
1181 \converter lyx        lyx14x     "python -tt $$s/lyx2lyx/lyx2lyx -V 1.4 -o $$o $$i"     ""
1182 \converter lyx        lyx15x     "python -tt $$s/lyx2lyx/lyx2lyx -V 1.5 -o $$o $$i"     ""
1183 \converter lyx        lyx16x     "python -tt $$s/lyx2lyx/lyx2lyx -V 1.6 -o $$o $$i"     ""
1184 \converter lyx        lyx20x     "python -tt $$s/lyx2lyx/lyx2lyx -V 2.0 -o $$o $$i"     ""
1185 \converter lyx        lyx21x     "python -tt $$s/lyx2lyx/lyx2lyx -V 2.1 -o $$o $$i"     ""
1186 \converter lyx        lyx22x     "python -tt $$s/lyx2lyx/lyx2lyx -V 2.2 -o $$o $$i"     ""
1187 \converter lyx        clyx       "python -tt $$s/lyx2lyx/lyx2lyx -V 1.4 -o $$o -c big5   $$i"   ""
1188 \converter lyx        jlyx       "python -tt $$s/lyx2lyx/lyx2lyx -V 1.4 -o $$o -c euc_jp $$i"   ""
1189 \converter lyx        klyx       "python -tt $$s/lyx2lyx/lyx2lyx -V 1.4 -o $$o -c euc_kr $$i"   ""
1190 \converter clyx       lyx        "python -tt $$s/lyx2lyx/lyx2lyx -c big5   -o $$o $$i"  ""
1191 \converter jlyx       lyx        "python -tt $$s/lyx2lyx/lyx2lyx -c euc_jp -o $$o $$i"  ""
1192 \converter klyx       lyx        "python -tt $$s/lyx2lyx/lyx2lyx -c euc_kr -o $$o $$i"  ""
1193 \converter lyxpreview png        "python -tt $$s/scripts/lyxpreview2bitmap.py --png"    ""
1194 \converter lyxpreview ppm        "python -tt $$s/scripts/lyxpreview2bitmap.py --ppm"    ""
1195 ''')
1196
1197
1198 def checkDocBook():
1199     ''' Check docbook '''
1200     path, DOCBOOK = checkProg('SGML-tools 2.x (DocBook), db2x scripts or xsltproc', ['sgmltools', 'db2dvi', 'xsltproc'],
1201         rc_entry = [
1202             r'''\converter docbook    dvi        "sgmltools -b dvi $$i" ""
1203 \converter docbook    html       "sgmltools -b html $$i"        ""
1204 \converter docbook    ps         "sgmltools -b ps $$i"  ""''',
1205             r'''\converter docbook    dvi        "db2dvi $$i"   ""
1206 \converter docbook    html       "db2html $$i"  ""''',
1207             r'''\converter docbook    dvi        ""     ""
1208 \converter docbook    html       "" ""''',
1209             r'''\converter docbook    dvi        ""     ""
1210 \converter docbook    html       ""     ""'''])
1211     #
1212     if DOCBOOK != '':
1213         return ('yes', 'true', '\\def\\hasdocbook{yes}')
1214     else:
1215         return ('no', 'false', '')
1216
1217
1218 def checkOtherEntries():
1219     ''' entries other than Format and Converter '''
1220     checkProg('ChkTeX', ['chktex -n1 -n3 -n6 -n9 -n22 -n25 -n30 -n38'],
1221         rc_entry = [ r'\chktex_command "%%"' ])
1222     checkProgAlternatives('BibTeX or alternative programs',
1223         ['bibtex', 'bibtex8', 'biber'],
1224         rc_entry = [ r'\bibtex_command "automatic"' ],
1225         alt_rc_entry = [ r'\bibtex_alternatives "%%"' ])
1226     checkProgAlternatives('a specific Japanese BibTeX variant',
1227         ['pbibtex', 'upbibtex', 'jbibtex', 'bibtex', 'biber'],
1228         rc_entry = [ r'\jbibtex_command "automatic"' ],
1229         alt_rc_entry = [ r'\jbibtex_alternatives "%%"' ])
1230     checkProgAlternatives('available index processors',
1231         ['texindy', 'makeindex -c -q', 'xindy'],
1232         rc_entry = [ r'\index_command "%%"' ],
1233         alt_rc_entry = [ r'\index_alternatives "%%"' ])
1234     checkProg('an index processor appropriate to Japanese',
1235         ['mendex -c -q', 'jmakeindex -c -q', 'makeindex -c -q'],
1236         rc_entry = [ r'\jindex_command "%%"' ])
1237     checkProg('the splitindex processor', ['splitindex.pl', 'splitindex',
1238         'splitindex.class'], rc_entry = [ r'\splitindex_command "%%"' ])
1239     checkProg('a nomenclature processor', ['makeindex'],
1240         rc_entry = [ r'\nomencl_command "makeindex -s nomencl.ist"' ])
1241     checkProg('a python-pygments driver command', ['pygmentize'],
1242         rc_entry = [ r'\pygmentize_command "%%"' ])
1243     ## FIXME: OCTAVE is not used anywhere
1244     # path, OCTAVE = checkProg('Octave', ['octave'])
1245     ## FIXME: MAPLE is not used anywhere
1246     # path, MAPLE = checkProg('Maple', ['maple'])
1247     # Add the rest of the entries (no checkProg is required)
1248     addToRC(r'''\copier    fig        "python -tt $$s/scripts/fig_copy.py $$i $$o"
1249 \copier    pstex      "python -tt $$s/scripts/tex_copy.py $$i $$o $$l"
1250 \copier    pdftex     "python -tt $$s/scripts/tex_copy.py $$i $$o $$l"
1251 \copier    program    "python -tt $$s/scripts/ext_copy.py $$i $$o"
1252 ''')
1253
1254
1255 def processLayoutFile(file, bool_docbook):
1256     ''' process layout file and get a line of result
1257
1258         Declare lines look like this:
1259
1260         \DeclareLaTeXClass[<requirements>]{<description>}
1261
1262         Optionally, a \DeclareCategory line follows:
1263
1264         \DeclareCategory{<category>}
1265
1266         So for example (article.layout, scrbook.layout, svjog.layout)
1267
1268         \DeclareLaTeXClass{article}
1269         \DeclareCategory{Articles}
1270
1271         \DeclareLaTeXClass[scrbook]{book (koma-script)}
1272         \DeclareCategory{Books}
1273
1274         \DeclareLaTeXClass[svjour,svjog.clo]{article (Springer - svjour/jog)}
1275
1276         we'd expect this output:
1277
1278         "article" "article" "article" "false" "article.cls" "Articles"
1279         "scrbook" "scrbook" "book (koma-script)" "false" "scrbook.cls" "Books"
1280         "svjog" "svjour" "article (Springer - svjour/jog)" "false" "svjour.cls,svjog.clo" ""
1281     '''
1282     def checkForClassExtension(x):
1283         '''if the extension for a latex class is not
1284            provided, add .cls to the classname'''
1285         if not b'.' in x:
1286             return x.strip() + b'.cls'
1287         else:
1288             return x.strip()
1289     classname = file.split(os.sep)[-1].split('.')[0]
1290     # return ('LaTeX', '[a,b]', 'a', ',b,c', 'article') for \DeclareLaTeXClass[a,b,c]{article}
1291     p = re.compile(b'\s*#\s*\\\\Declare(LaTeX|DocBook)Class\s*(\[([^,]*)(,.*)*\])*\s*{(.*)}\s*$')
1292     q = re.compile(b'\s*#\s*\\\\DeclareCategory{(.*)}\s*$')
1293     classdeclaration = b""
1294     categorydeclaration = b'""'
1295     for line in open(file, 'rb').readlines():
1296         res = p.match(line)
1297         qres = q.match(line)
1298         if res != None:
1299             (classtype, optAll, opt, opt1, desc) = res.groups()
1300             avai = {b'LaTeX':b'false', b'DocBook':bool_docbook.encode('ascii')}[classtype]
1301             if opt == None:
1302                 opt = classname.encode('ascii')
1303                 prereq_latex = checkForClassExtension(classname.encode('ascii'))
1304             else:
1305                 prereq_list = optAll[1:-1].split(b',')
1306                 prereq_list = list(map(checkForClassExtension, prereq_list))
1307                 prereq_latex = b','.join(prereq_list)
1308             prereq_docbook = {'true':b'', 'false':b'docbook'}[bool_docbook]
1309             prereq = {b'LaTeX':prereq_latex, b'DocBook':prereq_docbook}[classtype]
1310             classdeclaration = (b'"%s" "%s" "%s" "%s" "%s"'
1311                                % (classname, opt, desc, avai, prereq))
1312             if categorydeclaration != b'""':
1313                 return classdeclaration + b" " + categorydeclaration
1314         if qres != None:
1315              categorydeclaration = b'"%s"' % (qres.groups()[0])
1316              if classdeclaration != b"":
1317                  return classdeclaration + b" " + categorydeclaration
1318     if classdeclaration != b"":
1319         return classdeclaration + b" " + categorydeclaration
1320     logger.warning("Layout file " + file + " has no \DeclareXXClass line. ")
1321     return b""
1322
1323
1324 def checkLatexConfig(check_config, bool_docbook):
1325     ''' Explore the LaTeX configuration
1326         Return None (will be passed to sys.exit()) for success.
1327     '''
1328     msg = 'checking LaTeX configuration... '
1329     # if --without-latex-config is forced, or if there is no previous
1330     # version of textclass.lst, re-generate a default file.
1331     if not os.path.isfile('textclass.lst') or not check_config:
1332         # remove the files only if we want to regenerate
1333         removeFiles(['textclass.lst', 'packages.lst'])
1334         #
1335         # Then, generate a default textclass.lst. In case configure.py
1336         # fails, we still have something to start lyx.
1337         logger.info(msg + ' default values')
1338         logger.info('+checking list of textclasses... ')
1339         tx = open('textclass.lst', 'wb')
1340         tx.write(b'''
1341 # This file declares layouts and their associated definition files
1342 # (include dir. relative to the place where this file is).
1343 # It contains only default values, since chkconfig.ltx could not be run
1344 # for some reason. Run ./configure.py if you need to update it after a
1345 # configuration change.
1346 ''')
1347         # build the list of available layout files and convert it to commands
1348         # for chkconfig.ltx
1349         foundClasses = []
1350         for file in (glob.glob(os.path.join('layouts', '*.layout'))
1351                      + glob.glob(os.path.join(srcdir, 'layouts', '*.layout'))):
1352             # valid file?
1353             if not os.path.isfile(file):
1354                 continue
1355             # get stuff between /xxxx.layout .
1356             classname = file.split(os.sep)[-1].split('.')[0]
1357             #  tr ' -' '__'`
1358             cleanclass = classname.replace(' ', '_')
1359             cleanclass = cleanclass.replace('-', '_')
1360             # make sure the same class is not considered twice
1361             if foundClasses.count(cleanclass) == 0: # not found before
1362                 foundClasses.append(cleanclass)
1363                 retval = processLayoutFile(file, bool_docbook)
1364                 if retval != b"":
1365                     tx.write(retval + os.linesep)
1366         tx.close()
1367         logger.info('\tdone')
1368     if not os.path.isfile('packages.lst') or not check_config:
1369         logger.info('+generating default list of packages... ')
1370         removeFiles(['packages.lst'])
1371         tx = open('packages.lst', 'w')
1372         tx.close()
1373         logger.info('\tdone')
1374     if not check_config:
1375         return None
1376     # the following will generate textclass.lst.tmp, and packages.lst.tmp
1377     logger.info(msg + '\tauto')
1378     removeFiles(['chkconfig.classes', 'chkconfig.vars', 'chklayouts.tex',
1379         'wrap_chkconfig.ltx'])
1380     rmcopy = False
1381     if not os.path.isfile( 'chkconfig.ltx' ):
1382         shutil.copyfile( os.path.join(srcdir, 'chkconfig.ltx'), 'chkconfig.ltx' )
1383         rmcopy = True
1384     writeToFile('wrap_chkconfig.ltx', '%s\n\\input{chkconfig.ltx}\n' % docbook_cmd)
1385     # Construct the list of classes to test for.
1386     # build the list of available layout files and convert it to commands
1387     # for chkconfig.ltx
1388     declare = re.compile(b'\\s*#\\s*\\\\Declare(LaTeX|DocBook)Class\\s*(\[([^,]*)(,.*)*\])*\\s*{(.*)}\\s*$')
1389     category = re.compile(b'\\s*#\\s*\\\\DeclareCategory{(.*)}\\s*$')
1390     empty = re.compile(b'\\s*$')
1391     testclasses = list()
1392     for file in (glob.glob( os.path.join('layouts', '*.layout') )
1393                  + glob.glob( os.path.join(srcdir, 'layouts', '*.layout' ) ) ):
1394         nodeclaration = False
1395         if not os.path.isfile(file):
1396             continue
1397         classname = file.split(os.sep)[-1].split('.')[0]
1398         decline = b""
1399         catline = b""
1400         for line in open(file, 'rb').readlines():
1401             if not empty.match(line) and line[0] != b'#'[0]:
1402                 if decline == b"":
1403                     logger.warning("Failed to find valid \Declare line "
1404                         "for layout file `%s'.\n\t=> Skipping this file!" % file)
1405                     nodeclaration = True
1406                 # A class, but no category declaration. Just break.
1407                 break
1408             if declare.match(line) != None:
1409                 decline = b"\\TestDocClass{%s}{%s}" \
1410                            % (classname.encode('ascii'), line[1:].strip())
1411                 testclasses.append(decline)
1412             elif category.match(line) != None:
1413                 catline = (b"\\DeclareCategory{%s}{%s}"
1414                            % (classname.encode('ascii'),
1415                               category.match(line).groups()[0]))
1416                 testclasses.append(catline)
1417             if catline == b"" or decline == b"":
1418                 continue
1419             break
1420         if nodeclaration:
1421             continue
1422     testclasses.sort()
1423     cl = open('chklayouts.tex', 'wb')
1424     for line in testclasses:
1425         cl.write(line + b'\n')
1426     cl.close()
1427     #
1428     # we have chklayouts.tex, then process it
1429     latex_out = cmdOutput(LATEX + ' wrap_chkconfig.ltx', True)
1430     while True:
1431         line = latex_out.readline()
1432         if not line:
1433             break;
1434         if line.startswith('+'):
1435             logger.info(line.strip())
1436     # if the command succeeds, None will be returned
1437     ret = latex_out.close()
1438     #
1439     # remove the copied file
1440     if rmcopy:
1441         removeFiles( [ 'chkconfig.ltx' ] )
1442     #
1443     # currently, values in chkconfig are only used to set
1444     # \font_encoding
1445     values = {}
1446     for line in open('chkconfig.vars').readlines():
1447         key, val = re.sub('-', '_', line).split('=')
1448         val = val.strip()
1449         values[key] = val.strip("'")
1450     # chk_fontenc may not exist
1451     try:
1452         addToRC(r'\font_encoding "%s"' % values["chk_fontenc"])
1453     except:
1454         pass
1455     # if configure successed, move textclass.lst.tmp to textclass.lst
1456     # and packages.lst.tmp to packages.lst
1457     if (os.path.isfile('textclass.lst.tmp')
1458           and len(open('textclass.lst.tmp').read()) > 0
1459         and os.path.isfile('packages.lst.tmp')
1460           and len(open('packages.lst.tmp').read()) > 0):
1461         shutil.move('textclass.lst.tmp', 'textclass.lst')
1462         shutil.move('packages.lst.tmp', 'packages.lst')
1463     return ret
1464
1465
1466 def checkModulesConfig():
1467   removeFiles(['lyxmodules.lst', 'chkmodules.tex'])
1468
1469   logger.info('+checking list of modules... ')
1470   tx = open('lyxmodules.lst', 'wb')
1471   tx.write(b'''## This file declares modules and their associated definition files.
1472 ## It has been automatically generated by configure
1473 ## Use "Options/Reconfigure" if you need to update it after a
1474 ## configuration change.
1475 ## "ModuleName" "filename" "Description" "Packages" "Requires" "Excludes" "Category"
1476 ''')
1477
1478   # build the list of available modules
1479   seen = []
1480   # note that this searches the local directory first, then the
1481   # system directory. that way, we pick up the user's version first.
1482   for file in (glob.glob( os.path.join('layouts', '*.module') )
1483                + glob.glob( os.path.join(srcdir, 'layouts', '*.module' ) ) ):
1484       # valid file?
1485       logger.info(file)
1486       if not os.path.isfile(file):
1487           continue
1488
1489       filename = file.split(os.sep)[-1]
1490       filename = filename[:-7]
1491       if seen.count(filename):
1492           continue
1493
1494       seen.append(filename)
1495       retval = processModuleFile(file, filename.encode('ascii'), bool_docbook)
1496       if retval != b"":
1497           tx.write(retval)
1498   tx.close()
1499   logger.info('\tdone')
1500
1501
1502 def processModuleFile(file, filename, bool_docbook):
1503     ''' process module file and get a line of result
1504
1505         The top of a module file should look like this:
1506           #\DeclareLyXModule[LaTeX Packages]{ModuleName}
1507           #DescriptionBegin
1508           #...body of description...
1509           #DescriptionEnd
1510           #Requires: [list of required modules]
1511           #Excludes: [list of excluded modules]
1512           #Category: [category name]
1513         The last three lines are optional (though do give a category).
1514         We expect output:
1515           "ModuleName" "filename" "Description" "Packages" "Requires" "Excludes" "Category"
1516     '''
1517     remods = re.compile(b'\s*#\s*\\\\DeclareLyXModule\s*(?:\[([^]]*?)\])?{(.*)}')
1518     rereqs = re.compile(b'\s*#+\s*Requires: (.*)')
1519     reexcs = re.compile(b'\s*#+\s*Excludes: (.*)')
1520     recaty = re.compile(b'\s*#+\s*Category: (.*)')
1521     redbeg = re.compile(b'\s*#+\s*DescriptionBegin\s*$')
1522     redend = re.compile(b'\s*#+\s*DescriptionEnd\s*$')
1523
1524     modname = desc = pkgs = req = excl = catgy = b""
1525     readingDescription = False
1526     descLines = []
1527
1528     for line in open(file, 'rb').readlines():
1529       if readingDescription:
1530         res = redend.match(line)
1531         if res != None:
1532           readingDescription = False
1533           desc = b" ".join(descLines)
1534           # Escape quotes.
1535           desc = desc.replace(b'"', b'\\"')
1536           continue
1537         descLines.append(line[1:].strip())
1538         continue
1539       res = redbeg.match(line)
1540       if res != None:
1541         readingDescription = True
1542         continue
1543       res = remods.match(line)
1544       if res != None:
1545           (pkgs, modname) = res.groups()
1546           if pkgs == None:
1547             pkgs = b""
1548           else:
1549             tmp = [s.strip() for s in pkgs.split(b",")]
1550             pkgs = b",".join(tmp)
1551           continue
1552       res = rereqs.match(line)
1553       if res != None:
1554         req = res.group(1)
1555         tmp = [s.strip() for s in req.split(b"|")]
1556         req = b"|".join(tmp)
1557         continue
1558       res = reexcs.match(line)
1559       if res != None:
1560         excl = res.group(1)
1561         tmp = [s.strip() for s in excl.split(b"|")]
1562         excl = b"|".join(tmp)
1563         continue
1564       res = recaty.match(line)
1565       if res != None:
1566         catgy = res.group(1)
1567         continue
1568
1569     if modname == b"":
1570       logger.warning("Module file without \DeclareLyXModule line. ")
1571       return b""
1572
1573     if pkgs != b"":
1574         # this module has some latex dependencies:
1575         # append the dependencies to chkmodules.tex,
1576         # which is \input'ed by chkconfig.ltx
1577         testpackages = list()
1578         for pkg in pkgs.split(b","):
1579             if b"->" in pkg:
1580                 # this is a converter dependency: skip
1581                 continue
1582             if pkg.endswith(b".sty"):
1583                 pkg = pkg[:-4]
1584             testpackages.append("\\TestPackage{%s}" % (pkg.decode('ascii'),))
1585         cm = open('chkmodules.tex', 'a')
1586         for line in testpackages:
1587             cm.write(line + '\n')
1588         cm.close()
1589
1590     return (b'"%s" "%s" "%s" "%s" "%s" "%s" "%s"\n'
1591             % (modname, filename, desc, pkgs, req, excl, catgy))
1592
1593
1594 def checkCiteEnginesConfig():
1595   removeFiles(['lyxciteengines.lst', 'chkciteengines.tex'])
1596
1597   logger.info('+checking list of cite engines... ')
1598   tx = open('lyxciteengines.lst', 'wb')
1599   tx.write(b'''## This file declares cite engines and their associated definition files.
1600 ## It has been automatically generated by configure
1601 ## Use "Options/Reconfigure" if you need to update it after a
1602 ## configuration change.
1603 ## "CiteEngineName" "filename" "CiteEngineType" "CiteFramework" "DefaultBiblio" "Description" "Packages"
1604 ''')
1605
1606   # build the list of available modules
1607   seen = []
1608   # note that this searches the local directory first, then the
1609   # system directory. that way, we pick up the user's version first.
1610   for file in glob.glob( os.path.join('citeengines', '*.citeengine') ) + \
1611       glob.glob( os.path.join(srcdir, 'citeengines', '*.citeengine' ) ) :
1612       # valid file?
1613       logger.info(file)
1614       if not os.path.isfile(file):
1615           continue
1616
1617       filename = file.split(os.sep)[-1]
1618       filename = filename[:-11]
1619       if seen.count(filename):
1620           continue
1621
1622       seen.append(filename)
1623       retval = processCiteEngineFile(file, filename.encode('ascii'), bool_docbook)
1624       if retval != b"":
1625           tx.write(retval)
1626   tx.close()
1627   logger.info('\tdone')
1628
1629
1630 def processCiteEngineFile(file, filename, bool_docbook):
1631     ''' process cite engines file and get a line of result
1632
1633         The top of a cite engine file should look like this:
1634           #\DeclareLyXCiteEngine[LaTeX Packages]{CiteEngineName}
1635           #DescriptionBegin
1636           #...body of description...
1637           #DescriptionEnd
1638         We expect output:
1639           "CiteEngineName" "filename" "CiteEngineType" "CiteFramework" "DefaultBiblio" "Description" "Packages"
1640     '''
1641     remods = re.compile(b'\s*#\s*\\\\DeclareLyXCiteEngine\s*(?:\[([^]]*?)\])?{(.*)}')
1642     redbeg = re.compile(b'\s*#+\s*DescriptionBegin\s*$')
1643     redend = re.compile(b'\s*#+\s*DescriptionEnd\s*$')
1644     recet = re.compile(b'\s*CiteEngineType\s*(.*)')
1645     redb = re.compile(b'\s*DefaultBiblio\s*(.*)')
1646     resfm = re.compile(b'\s*CiteFramework\s*(.*)')
1647
1648     modname = desc = pkgs = cet = db = cfm = ""
1649     readingDescription = False
1650     descLines = []
1651
1652     for line in open(file, 'rb').readlines():
1653       if readingDescription:
1654         res = redend.match(line)
1655         if res != None:
1656           readingDescription = False
1657           desc = b" ".join(descLines)
1658           # Escape quotes.
1659           desc = desc.replace(b'"', b'\\"')
1660           continue
1661         descLines.append(line[1:].strip())
1662         continue
1663       res = redbeg.match(line)
1664       if res != None:
1665         readingDescription = True
1666         continue
1667       res = remods.match(line)
1668       if res != None:
1669           (pkgs, modname) = res.groups()
1670           if pkgs == None:
1671             pkgs = b""
1672           else:
1673             tmp = [s.strip() for s in pkgs.split(b",")]
1674             pkgs = b",".join(tmp)
1675           continue
1676       res = recet.match(line)
1677       if res != None:
1678         cet = res.group(1)
1679         continue
1680       res = redb.match(line)
1681       if res != None:
1682         db = res.group(1)
1683         continue
1684       res = resfm.match(line)
1685       if res != None:
1686         cfm = res.group(1)
1687         continue
1688
1689     if modname == b"":
1690       logger.warning("Cite Engine File file without \DeclareLyXCiteEngine line. ")
1691       return b""
1692
1693     if pkgs != b"":
1694         # this cite engine has some latex dependencies:
1695         # append the dependencies to chkciteengines.tex,
1696         # which is \input'ed by chkconfig.ltx
1697         testpackages = list()
1698         for pkg in pkgs.split(b","):
1699             if b"->" in pkg:
1700                 # this is a converter dependency: skip
1701                 continue
1702             if pkg.endswith(b".sty"):
1703                 pkg = pkg[:-4]
1704             testpackages.append("\\TestPackage{%s}" % (pkg.decode('ascii'),))
1705         cm = open('chkciteengines.tex', 'a')
1706         for line in testpackages:
1707             cm.write(line + '\n')
1708         cm.close()
1709
1710     return (b'"%s" "%s" "%s" "%s" "%s" "%s" "%s"\n' % (modname, filename, cet, cfm, db, desc, pkgs))
1711
1712
1713 def checkXTemplates():
1714   removeFiles(['xtemplates.lst'])
1715
1716   logger.info('+checking list of external templates... ')
1717   tx = open('xtemplates.lst', 'w')
1718   tx.write('''## This file lists external templates.
1719 ## It has been automatically generated by configure
1720 ## Use "Options/Reconfigure" if you need to update it after a
1721 ## configuration change.
1722 ''')
1723
1724   # build the list of available templates
1725   seen = []
1726   # note that this searches the local directory first, then the
1727   # system directory. that way, we pick up the user's version first.
1728   for file in glob.glob( os.path.join('xtemplates', '*.xtemplate') ) + \
1729       glob.glob( os.path.join(srcdir, 'xtemplates', '*.xtemplate' ) ) :
1730       # valid file?
1731       logger.info(file)
1732       if not os.path.isfile(file):
1733           continue
1734
1735       filename = file.split(os.sep)[-1]
1736       if seen.count(filename):
1737           continue
1738
1739       seen.append(filename)
1740       if filename != "":
1741           tx.write(filename + "\n")
1742   tx.close()
1743   logger.info('\tdone')
1744
1745
1746 def checkTeXAllowSpaces():
1747     ''' Let's check whether spaces are allowed in TeX file names '''
1748     tex_allows_spaces = 'false'
1749     if lyx_check_config:
1750         msg = "Checking whether TeX allows spaces in file names... "
1751         writeToFile('a b.tex', r'\message{working^^J}' )
1752         if LATEX != '':
1753             if os.name == 'nt' or sys.platform == 'cygwin':
1754                 latex_out = cmdOutput(LATEX + r""" "\nonstopmode\input{\"a b\"}\makeatletter\@@end" """)
1755             else:
1756                 latex_out = cmdOutput(LATEX + r""" '\nonstopmode\input{"a b"}\makeatletter\@@end' """)
1757         else:
1758             latex_out = ''
1759         if 'working' in latex_out:
1760             logger.info(msg + 'yes')
1761             tex_allows_spaces = 'true'
1762         else:
1763             logger.info(msg + 'no')
1764             tex_allows_spaces = 'false'
1765         addToRC(r'\tex_allows_spaces ' + tex_allows_spaces)
1766         removeFiles( [ 'a b.tex', 'a b.log', 'texput.log' ])
1767
1768
1769 def rescanTeXFiles():
1770     ''' Run kpsewhich to update information about TeX files '''
1771     logger.info("+Indexing TeX files... ")
1772     if not os.path.isfile( os.path.join(srcdir, 'scripts', 'TeXFiles.py') ):
1773         logger.error("configure: error: cannot find TeXFiles.py script")
1774         sys.exit(1)
1775     interpreter = sys.executable
1776     if interpreter == '':
1777         interpreter = "python"
1778     tfp = cmdOutput(interpreter + " -tt " + '"'
1779                     + os.path.join(srcdir, 'scripts', 'TeXFiles.py') + '"')
1780     logger.info(tfp)
1781     logger.info("\tdone")
1782
1783
1784 def removeTempFiles():
1785     # Final clean-up
1786     if not lyx_keep_temps:
1787         removeFiles(['chkconfig.vars', 'chklatex.ltx', 'chklatex.log',
1788             'chklayouts.tex', 'chkmodules.tex', 'chkciteengines.tex',
1789             'missfont.log', 'wrap_chkconfig.ltx', 'wrap_chkconfig.log'])
1790
1791
1792 if __name__ == '__main__':
1793     lyx_check_config = True
1794     lyx_kpsewhich = True
1795     outfile = 'lyxrc.defaults'
1796     lyxrc_fileformat = 25
1797     rc_entries = ''
1798     lyx_keep_temps = False
1799     version_suffix = ''
1800     lyx_binary_dir = ''
1801     ## Parse the command line
1802     for op in sys.argv[1:]:   # default shell/for list is $*, the options
1803         if op in [ '-help', '--help', '-h' ]:
1804             print('''Usage: configure [options]
1805 Options:
1806     --help                   show this help lines
1807     --keep-temps             keep temporary files (for debug. purposes)
1808     --without-kpsewhich      do not update TeX files information via kpsewhich
1809     --without-latex-config   do not run LaTeX to determine configuration
1810     --with-version-suffix=suffix suffix of binary installed files
1811     --binary-dir=directory   directory of binary installed files
1812 ''')
1813             sys.exit(0)
1814         elif op == '--without-kpsewhich':
1815             lyx_kpsewhich = False
1816         elif op == '--without-latex-config':
1817             lyx_check_config = False
1818         elif op == '--keep-temps':
1819             lyx_keep_temps = True
1820         elif op[0:22] == '--with-version-suffix=':  # never mind if op is not long enough
1821             version_suffix = op[22:]
1822         elif op[0:13] == '--binary-dir=':
1823             lyx_binary_dir = op[13:]
1824         else:
1825             print("Unknown option %s" % op)
1826             sys.exit(1)
1827     #
1828     # check if we run from the right directory
1829     srcdir = os.path.dirname(sys.argv[0])
1830     if srcdir == '':
1831         srcdir = '.'
1832     if not os.path.isfile( os.path.join(srcdir, 'chkconfig.ltx') ):
1833         logger.error("configure: error: cannot find chkconfig.ltx script")
1834         sys.exit(1)
1835     setEnviron()
1836     if sys.platform == 'darwin' and len(version_suffix) > 0:
1837         checkUpgrade()
1838     createDirectories()
1839     dtl_tools = checkDTLtools()
1840     ## Write the first part of outfile
1841     writeToFile(outfile, '''# This file has been automatically generated by LyX' lib/configure.py
1842 # script. It contains default settings that have been determined by
1843 # examining your system. PLEASE DO NOT MODIFY ANYTHING HERE! If you
1844 # want to customize LyX, use LyX' Preferences dialog or modify directly
1845 # the "preferences" file instead. Any setting in that file will
1846 # override the values given here.
1847
1848 Format %i
1849
1850 ''' % lyxrc_fileformat)
1851     # check latex
1852     LATEX = checkLatex(dtl_tools)
1853     # check java and perl before any checkProg that may require them
1854     java = checkProg('a java interpreter', ['java'])[1]
1855     perl = checkProg('a perl interpreter', ['perl'])[1]
1856     (inkscape_path, inkscape_gui) = os.path.split(checkInkscape())
1857     # On Windows, we need to call the "inkscape.com" wrapper
1858     # for command line purposes. Other OSes do not differentiate.
1859     inkscape_cl = inkscape_gui
1860     if os.name == 'nt':
1861         inkscape_cl = inkscape_gui.replace('.exe', '.com')
1862     # On MacOSX, Inkscape requires full path file arguments. This
1863     # is not needed on Linux and Win and even breaks the latter.
1864     inkscape_fileprefix = ""
1865     if sys.platform == 'darwin':
1866         inkscape_fileprefix = "$$p"
1867     checkFormatEntries(dtl_tools)
1868     checkConverterEntries()
1869     (chk_docbook, bool_docbook, docbook_cmd) = checkDocBook()
1870     checkTeXAllowSpaces()
1871     windows_style_tex_paths = checkTeXPaths()
1872     if windows_style_tex_paths != '':
1873         addToRC(r'\tex_expects_windows_paths %s' % windows_style_tex_paths)
1874     checkOtherEntries()
1875     if lyx_kpsewhich:
1876         rescanTeXFiles()
1877     checkModulesConfig()
1878     checkCiteEnginesConfig()
1879     checkXTemplates()
1880     # --without-latex-config can disable lyx_check_config
1881     ret = checkLatexConfig(lyx_check_config and LATEX != '', bool_docbook)
1882     removeTempFiles()
1883     # The return error code can be 256. Because most systems expect an error code
1884     # in the range 0-127, 256 can be interpretted as 'success'. Because we expect
1885     # a None for success, 'ret is not None' is used to exit.
1886     sys.exit(ret is not None)