]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/LyX.py
*** Support for generic sideways floats ***
[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,313), minor_versions("1.6" , 0))] # JSpitzm: rotfloat support
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     # python does not know the alias latin9
136     if inputencoding == "latin9":
137         return "iso-8859-15"
138     return inputencoding
139
140 ##
141 # Class
142 #
143 class LyX_base:
144     """This class carries all the information of the LyX file."""
145     
146     def __init__(self, end_format = 0, input = "", output = "", error = "",
147                  debug = default_debug__, try_hard = 0, cjk_encoding = '',
148                  language = "english", encoding = "auto"):
149
150         """Arguments:
151         end_format: final format that the file should be converted. (integer)
152         input: the name of the input source, if empty resort to standard input.
153         output: the name of the output file, if empty use the standard output.
154         error: the name of the error file, if empty use the standard error.
155         debug: debug level, O means no debug, as its value increases be more verbose.
156         """
157         self.choose_io(input, output)
158
159         if error:
160             self.err = open(error, "w")
161         else:
162             self.err = sys.stderr
163
164         self.debug = debug
165         self.try_hard = try_hard
166         self.cjk_encoding = cjk_encoding
167
168         if end_format:
169             self.end_format = self.lyxformat(end_format)
170         else:
171             self.end_format = get_end_format()
172
173         self.backend = "latex"
174         self.textclass = "article"
175         # This is a hack: We use '' since we don't know the default
176         # layout of the text class. LyX will parse it as default layout.
177         # FIXME: Read the layout file and use the real default layout
178         self.default_layout = ''
179         self.header = []
180         self.preamble = []
181         self.body = []
182         self.status = 0
183         self.encoding = encoding
184         self.language = language
185
186
187     def warning(self, message, debug_level= default_debug__):
188         """ Emits warning to self.error, if the debug_level is less
189         than the self.debug."""
190         if debug_level <= self.debug:
191             self.err.write("Warning: " + message + "\n")
192
193
194     def error(self, message):
195         " Emits a warning and exits if not in try_hard mode."
196         self.warning(message)
197         if not self.try_hard:
198             self.warning("Quiting.")
199             sys.exit(1)
200
201         self.status = 2
202
203
204     def read(self):
205         """Reads a file into the self.header and
206         self.body parts, from self.input."""
207
208         while True:
209             line = self.input.readline()
210             if not line:
211                 self.error("Invalid LyX file.")
212
213             line = trim_eol(line)
214             if check_token(line, '\\begin_preamble'):
215                 while 1:
216                     line = self.input.readline()
217                     if not line:
218                         self.error("Invalid LyX file.")
219
220                     line = trim_eol(line)
221                     if check_token(line, '\\end_preamble'):
222                         break
223                     
224                     if line.split()[:0] in ("\\layout",
225                                             "\\begin_layout", "\\begin_body"):
226                         
227                         self.warning("Malformed LyX file:"
228                                      "Missing '\\end_preamble'."
229                                      "\nAdding it now and hoping"
230                                      "for the best.")
231
232                     self.preamble.append(line)
233
234             if check_token(line, '\\end_preamble'):
235                 continue
236
237             line = line.strip()
238             if not line:
239                 continue
240
241             if line.split()[0] in ("\\layout", "\\begin_layout",
242                                    "\\begin_body", "\\begin_deeper"):
243                 self.body.append(line)
244                 break
245
246             self.header.append(line)
247
248         self.textclass = get_value(self.header, "\\textclass", 0)
249         self.backend = get_backend(self.textclass)
250         self.format  = self.read_format()
251         self.language = get_value(self.header, "\\language", 0,
252                                   default = "english")
253         self.inputencoding = get_value(self.header, "\\inputencoding",
254                                        0, default = "auto")
255         self.encoding = get_encoding(self.language,
256                                      self.inputencoding, self.format,
257                                      self.cjk_encoding)
258         self.initial_version = self.read_version()
259
260         # Second pass over header and preamble, now we know the file encoding
261         for i in range(len(self.header)):
262             self.header[i] = self.header[i].decode(self.encoding)
263         for i in range(len(self.preamble)):
264             self.preamble[i] = self.preamble[i].decode(self.encoding)
265
266         # Read document body
267         while 1:
268             line = self.input.readline().decode(self.encoding)
269             if not line:
270                 break
271             self.body.append(trim_eol(line))
272
273
274     def write(self):
275         " Writes the LyX file to self.output."
276         self.set_version()
277         self.set_format()
278         self.set_textclass()
279         if self.encoding == "auto":
280             self.encoding = get_encoding(self.language, self.encoding,
281                                          self.format, self.cjk_encoding)
282         if self.preamble:
283             i = find_token(self.header, '\\textclass', 0) + 1
284             preamble = ['\\begin_preamble'] + self.preamble + ['\\end_preamble']
285             if i == 0:
286                 self.error("Malformed LyX file: Missing '\\textclass'.")
287             else:
288                 header = self.header[:i] + preamble + self.header[i:]
289         else:
290             header = self.header
291
292         for line in header + [''] + self.body:
293             self.output.write(line.encode(self.encoding)+"\n")
294
295
296     def choose_io(self, input, output):
297         """Choose input and output streams, dealing transparently with
298         compressed files."""
299
300         if output:
301             self.output = open(output, "wb")
302         else:
303             self.output = sys.stdout
304
305         if input and input != '-':
306             self.dir = os.path.dirname(os.path.abspath(input))
307             try:
308                 gzip.open(input).readline()
309                 self.input = gzip.open(input)
310                 self.output = gzip.GzipFile(mode="wb", fileobj=self.output) 
311             except:
312                 self.input = open(input)
313         else:
314             self.dir = ''
315             self.input = sys.stdin
316
317
318     def lyxformat(self, format):
319         " Returns the file format representation, an integer."
320         result = format_re.match(format)
321         if result:
322             format = int(result.group(1) + result.group(2))
323         elif format == '2':
324             format = 200
325         else:
326             self.error(str(format) + ": " + "Invalid LyX file.")
327
328         if format in formats_list():
329             return format
330
331         self.error(str(format) + ": " + "Format not supported.")
332         return None
333
334
335     def read_version(self):
336         """ Searchs for clues of the LyX version used to write the
337         file, returns the most likely value, or None otherwise."""
338
339         for line in self.header:
340             if line[0] != "#":
341                 return None
342
343             line = line.replace("fix",".")
344             result = original_version.match(line)
345             if result:
346                 # Special know cases: reLyX and KLyX
347                 if line.find("reLyX") != -1 or line.find("KLyX") != -1:
348                     return "0.12"
349
350                 res = result.group(1)
351                 if not res:
352                     self.warning(line)
353                 #self.warning("Version %s" % result.group(1))
354                 return res
355         self.warning(str(self.header[:2]))
356         return None
357
358
359     def set_version(self):
360         " Set the header with the version used."
361         self.header[0] = " ".join(["#LyX %s created this file." % version__,
362                                   "For more info see http://www.lyx.org/"])
363         if self.header[1][0] == '#':
364             del self.header[1]
365
366
367     def read_format(self):
368         " Read from the header the fileformat of the present LyX file."
369         for line in self.header:
370             result = fileformat.match(line)
371             if result:
372                 return self.lyxformat(result.group(1))
373         else:
374             self.error("Invalid LyX File.")
375         return None
376
377
378     def set_format(self):
379         " Set the file format of the file, in the header."
380         if self.format <= 217:
381             format = str(float(self.format)/100)
382         else:
383             format = str(self.format)
384         i = find_token(self.header, "\\lyxformat", 0)
385         self.header[i] = "\\lyxformat %s" % format
386
387
388     def set_textclass(self):
389         i = find_token(self.header, "\\textclass", 0)
390         self.header[i] = "\\textclass %s" % self.textclass
391
392
393     #Note that the module will be added at the END of the extant ones
394     def add_module(self, module):
395       i = find_token(self.header, "\\begin_modules", 0)
396       if i == -1:
397         #No modules yet included
398         i = find_token(self.header, "\\textclass", 0)
399         if i == -1:
400           self.warning("Malformed LyX document: No \\textclass!!")
401           return
402         modinfo = ["\\begin_modules", module, "\\end_modules"]
403         self.header[i + 1: i + 1] = modinfo
404         return
405       j = find_token(self.header, "\\end_modules", i)
406       if j == -1:
407         self.warning("Malformed LyX document: No \\end_modules.")
408         return
409       k = find_token(self.header, module, i)
410       if k != -1 and k < j:
411         return
412       self.header.insert(j, module)
413
414
415     def set_parameter(self, param, value):
416         " Set the value of the header parameter."
417         i = find_token(self.header, '\\' + param, 0)
418         if i == -1:
419             self.warning('Parameter not found in the header: %s' % param, 3)
420             return
421         self.header[i] = '\\%s %s' % (param, str(value))
422
423
424     def is_default_layout(self, layout):
425         " Check whether a layout is the default layout of this class."
426         # FIXME: Check against the real text class default layout
427         if layout == 'Standard' or layout == self.default_layout:
428             return 1
429         return 0
430
431
432     def convert(self):
433         "Convert from current (self.format) to self.end_format."
434         mode, convertion_chain = self.chain()
435         self.warning("convertion chain: " + str(convertion_chain), 3)
436
437         for step in convertion_chain:
438             steps = getattr(__import__("lyx_" + step), mode)
439
440             self.warning("Convertion step: %s - %s" % (step, mode),
441                          default_debug__ + 1)
442             if not steps:
443                 self.error("The convertion to an older "
444                 "format (%s) is not implemented." % self.format)
445
446             multi_conv = len(steps) != 1
447             for version, table in steps:
448                 if multi_conv and \
449                    (self.format >= version and mode == "convert") or\
450                    (self.format <= version and mode == "revert"):
451                     continue
452
453                 for conv in table:
454                     init_t = time.time()
455                     try:
456                         conv(self)
457                     except:
458                         self.warning("An error ocurred in %s, %s" %
459                                      (version, str(conv)),
460                                      default_debug__)
461                         if not self.try_hard:
462                             raise
463                         self.status = 2
464                     else:
465                         self.warning("%lf: Elapsed time on %s" %
466                                      (time.time() - init_t,
467                                       str(conv)), default_debug__ +
468                                      1)
469                 self.format = version
470                 if self.end_format == self.format:
471                     return
472
473
474     def chain(self):
475         """ This is where all the decisions related with the
476         convertion are taken.  It returns a list of modules needed to
477         convert the LyX file from self.format to self.end_format"""
478
479         self.start =  self.format
480         format = self.format
481         correct_version = 0
482
483         for rel in format_relation:
484             if self.initial_version in rel[2]:
485                 if format in rel[1]:
486                     initial_step = rel[0]
487                     correct_version = 1
488                     break
489
490         if not correct_version:
491             if format <= 215:
492                 self.warning("Version does not match file format, "
493                              "discarding it. (Version %s, format %d)" %
494                              (self.initial_version, self.format))
495             for rel in format_relation:
496                 if format in rel[1]:
497                     initial_step = rel[0]
498                     break
499             else:
500                 # This should not happen, really.
501                 self.error("Format not supported.")
502
503         # Find the final step
504         for rel in format_relation:
505             if self.end_format in rel[1]:
506                 final_step = rel[0]
507                 break
508         else:
509             self.error("Format not supported.")
510
511         # Convertion mode, back or forth
512         steps = []
513         if (initial_step, self.start) < (final_step, self.end_format):
514             mode = "convert"
515             first_step = 1
516             for step in format_relation:
517                 if  initial_step <= step[0] <= final_step:
518                     if first_step and len(step[1]) == 1:
519                         first_step = 0
520                         continue
521                     steps.append(step[0])
522         else:
523             mode = "revert"
524             relation_format = format_relation[:]
525             relation_format.reverse()
526             last_step = None
527
528             for step in relation_format:
529                 if  final_step <= step[0] <= initial_step:
530                     steps.append(step[0])
531                     last_step = step
532
533             if last_step[1][-1] == self.end_format:
534                 steps.pop()
535
536         self.warning("Convertion mode: %s\tsteps%s" %(mode, steps), 10)
537         return mode, steps
538
539
540     def get_toc(self, depth = 4):
541         " Returns the TOC of this LyX document."
542         paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2,
543                              'Subsection' : 3, 'Subsubsection': 4}
544         allowed_insets = ['Quotes']
545         allowed_parameters = ('\\paragraph_spacing', '\\noindent',
546                               '\\align', '\\labelwidthstring',
547                               "\\start_of_appendix", "\\leftindent")
548         sections = []
549         for section in paragraphs_filter.keys():
550             sections.append('\\begin_layout %s' % section)
551
552         toc_par = []
553         i = 0
554         while 1:
555             i = find_tokens(self.body, sections, i)
556             if i == -1:
557                 break
558
559             j = find_end_of(self.body,  i + 1, '\\begin_layout', '\\end_layout')
560             if j == -1:
561                 self.warning('Incomplete file.', 0)
562                 break
563
564             section = self.body[i].split()[1]
565             if section[-1] == '*':
566                 section = section[:-1]
567
568             par = []
569
570             k = i + 1
571             # skip paragraph parameters
572             while not self.body[k].strip() or self.body[k].split()[0] \
573                       in allowed_parameters:
574                 k += 1 
575
576             while k < j:
577                 if check_token(self.body[k], '\\begin_inset'):
578                     inset = self.body[k].split()[1]
579                     end = find_end_of_inset(self.body, k)
580                     if end == -1 or end > j:
581                         self.warning('Malformed file.', 0)
582
583                     if inset in allowed_insets:
584                         par.extend(self.body[k: end+1])
585                     k = end + 1
586                 else:
587                     par.append(self.body[k])
588                     k += 1
589
590             # trim empty lines in the end.
591             while par and par[-1].strip() == '':
592                 par.pop()
593
594             toc_par.append(Paragraph(section, par))
595
596             i = j + 1
597
598         return toc_par
599
600
601 class File(LyX_base):
602     " This class reads existing LyX files."
603
604     def __init__(self, end_format = 0, input = "", output = "", error = "",
605                  debug = default_debug__, try_hard = 0, cjk_encoding = ''):
606         LyX_base.__init__(self, end_format, input, output, error,
607                           debug, try_hard, cjk_encoding)
608         self.read()
609
610
611 class NewFile(LyX_base):
612     " This class is to create new LyX files."
613     def set_header(self, **params):
614         # set default values
615         self.header.extend([
616             "#LyX xxxx created this file."
617             "For more info see http://www.lyx.org/",
618             "\\lyxformat xxx",
619             "\\begin_document",
620             "\\begin_header",
621             "\\textclass article",
622             "\\language english",
623             "\\inputencoding auto",
624             "\\font_roman default",
625             "\\font_sans default",
626             "\\font_typewriter default",
627             "\\font_default_family default",
628             "\\font_sc false",
629             "\\font_osf false",
630             "\\font_sf_scale 100",
631             "\\font_tt_scale 100",
632             "\\graphics default",
633             "\\paperfontsize default",
634             "\\papersize default",
635             "\\use_geometry false",
636             "\\use_amsmath 1",
637             "\\cite_engine basic",
638             "\\use_bibtopic false",
639             "\\paperorientation portrait",
640             "\\secnumdepth 3",
641             "\\tocdepth 3",
642             "\\paragraph_separation indent",
643             "\\defskip medskip",
644             "\\quotes_language english",
645             "\\papercolumns 1",
646             "\\papersides 1",
647             "\\paperpagestyle default",
648             "\\tracking_changes false",
649             "\\end_header"])
650
651         self.format = get_end_format()
652         for param in params:
653             self.set_parameter(param, params[param])
654
655
656     def set_body(self, paragraphs):
657         self.body.extend(['\\begin_body',''])
658
659         for par in paragraphs:
660             self.body.extend(par.asLines())
661
662         self.body.extend(['','\\end_body', '\\end_document'])
663
664
665 class Paragraph:
666     # unfinished implementation, it is missing the Text and Insets
667     # representation.
668     " This class represents the LyX paragraphs."
669     def __init__(self, name, body=[], settings = [], child = []):
670         """ Parameters:
671         name: paragraph name.
672         body: list of lines of body text.
673         child: list of paragraphs that descend from this paragraph.
674         """
675         self.name = name
676         self.body = body
677         self.settings = settings
678         self.child = child
679
680     def asLines(self):
681         """ Converts the paragraph to a list of strings, representing
682         it in the LyX file."""
683
684         result = ['','\\begin_layout %s' % self.name]
685         result.extend(self.settings)
686         result.append('')
687         result.extend(self.body)
688         result.append('\\end_layout')
689
690         if not self.child:
691             return result
692
693         result.append('\\begin_deeper')
694         for node in self.child:
695             result.extend(node.asLines())
696         result.append('\\end_deeper')
697
698         return result