]> git.lyx.org Git - features.git/blob - lib/lyx2lyx/LyX.py
4bb101fda83e52602174c597360baf015b986167
[features.git] / lib / lyx2lyx / LyX.py
1 # This file is part of lyx2lyx
2 # -*- coding: utf-8 -*-
3 # Copyright (C) 2002-2004 Dekel Tsur <dekel@lyx.org>
4 # Copyright (C) 2002-2006 José Matos <jamatos@lyx.org>
5 #
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19
20 from parser_tools import get_value, check_token, find_token,\
21      find_tokens, find_end_of
22 import os.path
23 import gzip
24 import locale
25 import sys
26 import re
27 import time
28
29 try:
30     import lyx2lyx_version
31     version_lyx2lyx = lyx2lyx_version.version
32 except: # we are running from build directory so assume the last version
33     version_lyx2lyx = '1.6.0svn'
34
35 default_debug_level = 2
36
37 ####################################################################
38 # Private helper functions
39
40 def find_end_of_inset(lines, i):
41     " Find beginning of inset, where lines[i] is included."
42     return find_end_of(lines, i, "\\begin_inset", "\\end_inset")
43
44 def generate_minor_versions(major, last_minor_version):
45     """ Generate minor versions, using major as prefix and minor
46     versions from 0 until last_minor_version, plus the generic version.
47
48     Example:
49
50       generate_minor_versions("1.2", 4) ->
51       [ "1.2", "1.2.0", "1.2.1", "1.2.2", "1.2.3"]
52     """
53     return [major] + [major + ".%d" % i for i in range(last_minor_version + 1)]
54
55
56 # End of helper functions
57 ####################################################################
58
59
60 # Regular expressions used
61 format_re = re.compile(r"(\d)[\.,]?(\d\d)")
62 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
63 original_version = re.compile(r".*?LyX ([\d.]*)")
64
65 ##
66 # file format information:
67 #  file, supported formats, stable release versions
68 format_relation = [("0_06",    [200], generate_minor_versions("0.6" , 4)),
69                    ("0_08",    [210], generate_minor_versions("0.8" , 6) + ["0.7"]),
70                    ("0_10",    [210], generate_minor_versions("0.10", 7) + ["0.9"]),
71                    ("0_12",    [215], generate_minor_versions("0.12", 1) + ["0.11"]),
72                    ("1_0",     [215], generate_minor_versions("1.0" , 4)),
73                    ("1_1",     [215], generate_minor_versions("1.1" , 4)),
74                    ("1_1_5",   [216], ["1.1.5","1.1.5.1","1.1.5.2","1.1"]),
75                    ("1_1_6_0", [217], ["1.1.6","1.1.6.1","1.1.6.2","1.1"]),
76                    ("1_1_6_3", [218], ["1.1.6.3","1.1.6.4","1.1"]),
77                    ("1_2",     [220], generate_minor_versions("1.2" , 4)),
78                    ("1_3",     [221], generate_minor_versions("1.3" , 7)),
79                    ("1_4", range(222,246), generate_minor_versions("1.4" , 5)),
80                    ("1_5", range(246,277), generate_minor_versions("1.5" , 1)),
81                    ("1_6", range(277,286), generate_minor_versions("1.6" , 0))]
82
83
84 def formats_list():
85     " Returns a list with supported file formats."
86     formats = []
87     for version in format_relation:
88         for format in version[1]:
89             if format not in formats:
90                 formats.append(format)
91     return formats
92
93
94 def get_end_format():
95     " Returns the more recent file format available."
96     return format_relation[-1][1][-1]
97
98
99 def get_backend(textclass):
100     " For _textclass_ returns its backend."
101     if textclass == "linuxdoc" or textclass == "manpage":
102         return "linuxdoc"
103     if textclass[:7] == "docbook":
104         return "docbook"
105     return "latex"
106
107
108 def trim_eol(line):
109     " Remove end of line char(s)."
110     if line[-2:-1] == '\r':
111         return line[:-2]
112     else:
113         return line[:-1]
114
115
116 def get_encoding(language, inputencoding, format, cjk_encoding):
117     if format > 248:
118         return "utf8"
119     # CJK-LyX encodes files using the current locale encoding.
120     # This means that files created by CJK-LyX can only be converted using
121     # the correct locale settings unless the encoding is given as commandline
122     # argument.
123     if cjk_encoding == 'auto':
124         return locale.getpreferredencoding()
125     elif cjk_encoding != '':
126         return cjk_encoding
127     from lyx2lyx_lang import lang
128     if inputencoding == "auto" or inputencoding == "default":
129         return lang[language][3]
130     if inputencoding == "":
131         return "latin1"
132     # python does not know the alias latin9
133     if inputencoding == "latin9":
134         return "iso-8859-15"
135     return inputencoding
136
137 ##
138 # Class
139 #
140 class LyX_Base:
141     """This class carries all the information of the LyX file."""
142     
143     def __init__(self, end_format = 0, input = "", output = "", error
144                  = "", debug = default_debug_level, try_hard = 0, cjk_encoding = '',
145                  language = "english", encoding = "auto"):
146
147         """Arguments:
148         end_format: final format that the file should be converted. (integer)
149         input: the name of the input source, if empty resort to standard input.
150         output: the name of the output file, if empty use the standard output.
151         error: the name of the error file, if empty use the standard error.
152         debug: debug level, O means no debug, as its value increases be more verbose.
153         """
154         self.choose_io(input, output)
155
156         if error:
157             self.err = open(error, "w")
158         else:
159             self.err = sys.stderr
160
161         self.debug = debug
162         self.try_hard = try_hard
163         self.cjk_encoding = cjk_encoding
164
165         if end_format:
166             self.end_format = self.lyxformat(end_format)
167         else:
168             self.end_format = get_end_format()
169
170         self.backend = "latex"
171         self.textclass = "article"
172         # This is a hack: We use '' since we don't know the default
173         # layout of the text class. LyX will parse it as default layout.
174         # FIXME: Read the layout file and use the real default layout
175         self.default_layout = ''
176         self.header = []
177         self.preamble = []
178         self.manifest = []
179         self.body = []
180         self.status = 0
181         self.encoding = encoding
182         self.language = language
183
184
185     def warning(self, message, debug_level= default_debug_level):
186         " Emits warning to self.error, if the debug_level is less than the self.debug."
187         if debug_level <= self.debug:
188             self.err.write("Warning: " + message + "\n")
189
190
191     def error(self, message):
192         " Emits a warning and exits if not in try_hard mode."
193         self.warning(message)
194         if not self.try_hard:
195             self.warning("Quiting.")
196             sys.exit(1)
197
198         self.status = 2
199
200
201     def read(self):
202         """Reads a file into the self.header, self.manifest and self.body parts, from self.input."""
203
204         while 1:
205             line = self.input.readline()
206             if not line:
207                 self.error("Invalid LyX file.")
208
209             line = trim_eol(line)
210             if check_token(line, '\\begin_preamble'):
211                 while 1:
212                     line = self.input.readline()
213                     if not line:
214                         self.error("Invalid LyX file.")
215
216                     line = trim_eol(line)
217                     if check_token(line, '\\end_preamble'):
218                         break
219                     
220                     if line.split()[:0] in ("\\layout", "\\begin_layout", "\\begin_body"):
221                         self.warning("Malformed LyX file: Missing '\\end_preamble'.")
222                         self.warning("Adding it now and hoping for the best.")
223
224                     self.preamble.append(line)
225
226             if check_token(line, '\\end_preamble'):
227                 continue
228
229             if check_token(line, '\\begin_manifest'):
230                 while 1:
231                     line = self.input.readline()
232                     if not line:
233                         self.error("Invalid LyX file.")
234
235                     line = trim_eol(line)
236                     if check_token(line, "\\end_manifest"):
237                         break
238
239                     if not line.startswith('\\filename') and not line.startswith('\\inzipName') \
240                             and not line.startswith('\\embed'):
241                         self.warning("Malformed LyX file: Missing '\\end_manifest'.")
242
243                     self.manifest.append(line)
244             
245             if check_token(line, '\\end_manifest'):
246                 continue
247
248             line = line.strip()
249             if not line:
250                 continue
251
252             if line.split()[0] in ("\\layout", "\\begin_layout", "\\begin_body", "\\begin_deeper"):
253                 self.body.append(line)
254                 break
255
256             self.header.append(line)
257
258         self.textclass = get_value(self.header, "\\textclass", 0)
259         self.backend = get_backend(self.textclass)
260         self.format  = self.read_format()
261         self.language = get_value(self.header, "\\language", 0, default = "english")
262         self.inputencoding = get_value(self.header, "\\inputencoding", 0, default = "auto")
263         self.encoding = get_encoding(self.language, self.inputencoding, self.format, self.cjk_encoding)
264         self.initial_version = self.read_version()
265
266         # Second pass over header and preamble, now we know the file encoding
267         for i in range(len(self.header)):
268             self.header[i] = self.header[i].decode(self.encoding)
269         for i in range(len(self.preamble)):
270             self.preamble[i] = self.preamble[i].decode(self.encoding)
271
272         # Read document body
273         while 1:
274             line = self.input.readline().decode(self.encoding)
275             if not line:
276                 break
277             self.body.append(trim_eol(line))
278
279
280     def write(self):
281         " Writes the LyX file to self.output."
282         self.set_version()
283         self.set_format()
284         self.set_textclass()
285         if self.encoding == "auto":
286             self.encoding = get_encoding(self.language, self.encoding, self.format, self.cjk_encoding)
287
288         if self.preamble:
289             i = find_token(self.header, '\\textclass', 0) + 1
290             preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
291             if i == 0:
292                 self.error("Malformed LyX file: Missing '\\textclass'.")
293             else:
294                 header = self.header[:i] + preamble + self.header[i:]
295         else:
296             header = self.header
297
298         # LyX file format <= 284 does not have a manifest section
299         # so this section is set to None
300         if self.manifest is None:
301             manifest = []
302         else:
303             manifest = ['\\begin_manifest'] + self.manifest + ['\\end_manifest', '']
304
305         for line in header + [''] + manifest + self.body:
306             self.output.write(line.encode(self.encoding)+"\n")
307
308
309     def choose_io(self, input, output):
310         """Choose input and output streams, dealing transparently with
311         compressed files."""
312
313         if output:
314             self.output = open(output, "wb")
315         else:
316             self.output = sys.stdout
317
318         if input and input != '-':
319             self.dir = os.path.dirname(os.path.abspath(input))
320             try:
321                 gzip.open(input).readline()
322                 self.input = gzip.open(input)
323                 self.output = gzip.GzipFile(mode="wb", fileobj=self.output) 
324             except:
325                 self.input = open(input)
326         else:
327             self.dir = ''
328             self.input = sys.stdin
329
330
331     def lyxformat(self, format):
332         " Returns the file format representation, an integer."
333         result = format_re.match(format)
334         if result:
335             format = int(result.group(1) + result.group(2))
336         elif format == '2':
337             format = 200
338         else:
339             self.error(str(format) + ": " + "Invalid LyX file.")
340
341         if format in formats_list():
342             return format
343
344         self.error(str(format) + ": " + "Format not supported.")
345         return None
346
347
348     def read_version(self):
349         """ Searchs for clues of the LyX version used to write the file, returns the
350         most likely value, or None otherwise."""
351         for line in self.header:
352             if line[0] != "#":
353                 return None
354
355             line = line.replace("fix",".")
356             result = original_version.match(line)
357             if result:
358                 # Special know cases: reLyX and KLyX
359                 if line.find("reLyX") != -1 or line.find("KLyX") != -1:
360                     return "0.12"
361
362                 res = result.group(1)
363                 if not res:
364                     self.warning(line)
365                 #self.warning("Version %s" % result.group(1))
366                 return res
367         self.warning(str(self.header[:2]))
368         return None
369
370
371     def set_version(self):
372         " Set the header with the version used."
373         self.header[0] = "#LyX %s created this file. For more info see http://www.lyx.org/" % version_lyx2lyx
374         if self.header[1][0] == '#':
375             del self.header[1]
376
377
378     def read_format(self):
379         " Read from the header the fileformat of the present LyX file."
380         for line in self.header:
381             result = fileformat.match(line)
382             if result:
383                 return self.lyxformat(result.group(1))
384         else:
385             self.error("Invalid LyX File.")
386         return None
387
388
389     def set_format(self):
390         " Set the file format of the file, in the header."
391         if self.format <= 217:
392             format = str(float(self.format)/100)
393         else:
394             format = str(self.format)
395         i = find_token(self.header, "\\lyxformat", 0)
396         self.header[i] = "\\lyxformat %s" % format
397
398
399     def set_textclass(self):
400         i = find_token(self.header, "\\textclass", 0)
401         self.header[i] = "\\textclass %s" % self.textclass
402
403
404     def set_parameter(self, param, value):
405         " Set the value of the header parameter."
406         i = find_token(self.header, '\\' + param, 0)
407         if i == -1:
408             self.warning('Parameter not found in the header: %s' % param, 3)
409             return
410         self.header[i] = '\\%s %s' % (param, str(value))
411
412
413     def is_default_layout(self, layout):
414         " Check whether a layout is the default layout of this class."
415         # FIXME: Check against the real text class default layout
416         if layout == 'Standard' or layout == self.default_layout:
417             return 1
418         return 0
419
420
421     def convert(self):
422         "Convert from current (self.format) to self.end_format."
423         mode, convertion_chain = self.chain()
424         self.warning("convertion chain: " + str(convertion_chain), 3)
425
426         for step in convertion_chain:
427             steps = getattr(__import__("lyx_" + step), mode)
428
429             self.warning("Convertion step: %s - %s" % (step, mode), default_debug_level + 1)
430             if not steps:
431                     self.error("The convertion to an older format (%s) is not implemented." % self.format)
432
433             multi_conv = len(steps) != 1
434             for version, table in steps:
435                 if multi_conv and \
436                    (self.format >= version and mode == "convert") or\
437                    (self.format <= version and mode == "revert"):
438                     continue
439
440                 for conv in table:
441                     init_t = time.time()
442                     try:
443                         conv(self)
444                     except:
445                         self.warning("An error ocurred in %s, %s" % (version, str(conv)),
446                                      default_debug_level)
447                         if not self.try_hard:
448                             raise
449                         self.status = 2
450                     else:
451                         self.warning("%lf: Elapsed time on %s"  % (time.time() - init_t, str(conv)),
452                                      default_debug_level + 1)
453
454                 self.format = version
455                 if self.end_format == self.format:
456                     return
457
458
459     def chain(self):
460         """ This is where all the decisions related with the convertion are taken.
461         It returns a list of modules needed to convert the LyX file from
462         self.format to self.end_format"""
463
464         self.start =  self.format
465         format = self.format
466         correct_version = 0
467
468         for rel in format_relation:
469             if self.initial_version in rel[2]:
470                 if format in rel[1]:
471                     initial_step = rel[0]
472                     correct_version = 1
473                     break
474
475         if not correct_version:
476             if format <= 215:
477                 self.warning("Version does not match file format, discarding it. (Version %s, format %d)" %(self.initial_version, self.format))
478             for rel in format_relation:
479                 if format in rel[1]:
480                     initial_step = rel[0]
481                     break
482             else:
483                 # This should not happen, really.
484                 self.error("Format not supported.")
485
486         # Find the final step
487         for rel in format_relation:
488             if self.end_format in rel[1]:
489                 final_step = rel[0]
490                 break
491         else:
492             self.error("Format not supported.")
493
494         # Convertion mode, back or forth
495         steps = []
496         if (initial_step, self.start) < (final_step, self.end_format):
497             mode = "convert"
498             first_step = 1
499             for step in format_relation:
500                 if  initial_step <= step[0] <= final_step:
501                     if first_step and len(step[1]) == 1:
502                         first_step = 0
503                         continue
504                     steps.append(step[0])
505         else:
506             mode = "revert"
507             relation_format = format_relation[:]
508             relation_format.reverse()
509             last_step = None
510
511             for step in relation_format:
512                 if  final_step <= step[0] <= initial_step:
513                     steps.append(step[0])
514                     last_step = step
515
516             if last_step[1][-1] == self.end_format:
517                 steps.pop()
518
519         self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10)
520         return mode, steps
521
522
523     def get_toc(self, depth = 4):
524         " Returns the TOC of this LyX document."
525         paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2, 'Subsection' : 3, 'Subsubsection': 4}
526         allowed_insets = ['Quotes']
527         allowed_parameters = '\\paragraph_spacing', '\\noindent', '\\align', '\\labelwidthstring', "\\start_of_appendix", "\\leftindent"
528
529         sections = []
530         for section in paragraphs_filter.keys():
531             sections.append('\\begin_layout %s' % section)
532
533         toc_par = []
534         i = 0
535         while 1:
536             i = find_tokens(self.body, sections, i)
537             if i == -1:
538                 break
539
540             j = find_end_of(self.body,  i + 1, '\\begin_layout', '\\end_layout')
541             if j == -1:
542                 self.warning('Incomplete file.', 0)
543                 break
544
545             section = self.body[i].split()[1]
546             if section[-1] == '*':
547                 section = section[:-1]
548
549             par = []
550
551             k = i + 1
552             # skip paragraph parameters
553             while not self.body[k].strip() or self.body[k].split()[0] in allowed_parameters:
554                 k = k +1
555
556             while k < j:
557                 if check_token(self.body[k], '\\begin_inset'):
558                     inset = self.body[k].split()[1]
559                     end = find_end_of_inset(self.body, k)
560                     if end == -1 or end > j:
561                         self.warning('Malformed file.', 0)
562
563                     if inset in allowed_insets:
564                         par.extend(self.body[k: end+1])
565                     k = end + 1
566                 else:
567                     par.append(self.body[k])
568                     k = k + 1
569
570             # trim empty lines in the end.
571             while par and par[-1].strip() == '':
572                 par.pop()
573
574             toc_par.append(Paragraph(section, par))
575
576             i = j + 1
577
578         return toc_par
579
580
581 class File(LyX_Base):
582     " This class reads existing LyX files."
583     def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level, try_hard = 0, cjk_encoding = ''):
584         LyX_Base.__init__(self, end_format, input, output, error, debug, try_hard, cjk_encoding)
585         self.read()
586
587
588 class NewFile(LyX_Base):
589     " This class is to create new LyX files."
590     def set_header(self, **params):
591         # set default values
592         self.header.extend([
593             "#LyX xxxx created this file. For more info see http://www.lyx.org/",
594             "\\lyxformat xxx",
595             "\\begin_document",
596             "\\begin_header",
597             "\\textclass article",
598             "\\language english",
599             "\\inputencoding auto",
600             "\\font_roman default",
601             "\\font_sans default",
602             "\\font_typewriter default",
603             "\\font_default_family default",
604             "\\font_sc false",
605             "\\font_osf false",
606             "\\font_sf_scale 100",
607             "\\font_tt_scale 100",
608             "\\graphics default",
609             "\\paperfontsize default",
610             "\\papersize default",
611             "\\use_geometry false",
612             "\\use_amsmath 1",
613             "\\cite_engine basic",
614             "\\use_bibtopic false",
615             "\\paperorientation portrait",
616             "\\secnumdepth 3",
617             "\\tocdepth 3",
618             "\\paragraph_separation indent",
619             "\\defskip medskip",
620             "\\quotes_language english",
621             "\\papercolumns 1",
622             "\\papersides 1",
623             "\\paperpagestyle default",
624             "\\tracking_changes false",
625             "\\end_header"])
626
627         self.format = get_end_format()
628         for param in params:
629             self.set_parameter(param, params[param])
630
631
632     def set_body(self, paragraphs):
633         self.body.extend(['\\begin_body',''])
634
635         for par in paragraphs:
636             self.body.extend(par.asLines())
637
638         self.body.extend(['','\\end_body', '\\end_document'])
639
640
641 class Paragraph:
642     # unfinished implementation, it is missing the Text and Insets representation.
643     " This class represents the LyX paragraphs."
644     def __init__(self, name, body=[], settings = [], child = []):
645         """ Parameters:
646         name: paragraph name.
647         body: list of lines of body text.
648         child: list of paragraphs that descend from this paragraph.
649         """
650         self.name = name
651         self.body = body
652         self.settings = settings
653         self.child = child
654
655     def asLines(self):
656         " Converts the paragraph to a list of strings, representing it in the LyX file."
657         result = ['','\\begin_layout %s' % self.name]
658         result.extend(self.settings)
659         result.append('')
660         result.extend(self.body)
661         result.append('\\end_layout')
662
663         if not self.child:
664             return result
665
666         result.append('\\begin_deeper')
667         for node in self.child:
668             result.extend(node.asLines())
669         result.append('\\end_deeper')
670
671         return result
672
673
674 class Inset:
675     " This class represents the LyX insets."
676     pass
677
678
679 class Text:
680     " This class represents simple chuncks of text."
681     pass