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