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