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