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