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