]> git.lyx.org Git - lyx.git/blob - lib/lyx2lyx/LyX.py
clean up french language handling
[lyx.git] / lib / lyx2lyx / LyX.py
1 # This file is part of lyx2lyx
2 # -*- coding: iso-8859-1 -*-
3 # Copyright (C) 2002-2004 Dekel Tsur <dekel@lyx.org>, José Matos <jamatos@lyx.org>
4 #
5 # This program is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU General Public License
7 # as published by the Free Software Foundation; either version 2
8 # of the License, or (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
18
19 from parser_tools import get_value, check_token, find_token,\
20      find_tokens, find_end_of, find_end_of_inset
21 import os.path
22 import gzip
23 import sys
24 import re
25 import string
26 import time
27
28 version_lyx2lyx = "1.4.0cvs"
29 default_debug_level = 2
30
31 # Regular expressions used
32 format_re = re.compile(r"(\d)[\.,]?(\d\d)")
33 fileformat = re.compile(r"\\lyxformat\s*(\S*)")
34 original_version = re.compile(r"\#LyX (\S*)")
35
36 ##
37 # file format information:
38 #  file, supported formats, stable release versions
39 format_relation = [("0_10",  [210], ["0.10.7","0.10"]),
40                    ("0_12",  [215], ["0.12","0.12.1","0.12"]),
41                    ("1_0_0", [215], ["1.0.0","1.0"]),
42                    ("1_0_1", [215], ["1.0.1","1.0.2","1.0.3","1.0.4", "1.1.2","1.1"]),
43                    ("1_1_4", [215], ["1.1.4","1.1"]),
44                    ("1_1_5", [216], ["1.1.5","1.1.5fix1","1.1.5fix2","1.1"]),
45                    ("1_1_6", [217], ["1.1.6","1.1.6fix1","1.1.6fix2","1.1"]),
46                    ("1_1_6fix3", [218], ["1.1.6fix3","1.1.6fix4","1.1"]),
47                    ("1_2", [220], ["1.2.0","1.2.1","1.2.3","1.2.4","1.2"]),
48                    ("1_3", [221], ["1.3.0","1.3.1","1.3.2","1.3.3","1.3.4","1.3.5","1.3"]),
49                    ("1_4", range(223,243), ["1.4.0cvs","1.4"])]
50
51
52 def formats_list():
53     " Returns a list with supported file formats."
54     formats = []
55     for version in format_relation:
56         for format in version[1]:
57             if format not in formats:
58                 formats.append(format)
59     return formats
60
61
62 def get_end_format():
63     " Returns the more recent file format available."
64     return format_relation[-1][1][-1]
65
66
67 def get_backend(textclass):
68     " For _textclass_ returns its backend."
69     if textclass == "linuxdoc" or textclass == "manpage":
70         return "linuxdoc"
71     if textclass[:7] == "docbook":
72         return "docbook"
73     return "latex"
74
75
76 ##
77 # Class
78 #
79 class LyX_Base:
80     """This class carries all the information of the LyX file."""
81     def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level, try_hard = 0):
82         """Arguments:
83         end_format: final format that the file should be converted. (integer)
84         input: the name of the input source, if empty resort to standard input.
85         output: the name of the output file, if empty use the standard output.
86         error: the name of the error file, if empty use the standard error.
87         debug: debug level, O means no debug, as its value increases be more verbose.
88         """
89         if input and input != '-':
90             self.input = self.open(input)
91         else:
92             self.input = sys.stdin
93         if output:
94             self.output = open(output, "w")
95         else:
96             self.output = sys.stdout
97
98         if error:
99             self.err = open(error, "w")
100         else:
101             self.err = sys.stderr
102
103         self.debug = debug
104         self.try_hard = try_hard
105
106         if end_format:
107             self.end_format = self.lyxformat(end_format)
108         else:
109             self.end_format = get_end_format()
110
111         self.backend = "latex"
112         self.textclass = "article"
113         self.header = []
114         self.body = []
115         self.status = 0
116
117
118     def warning(self, message, debug_level= default_debug_level):
119         " Emits warning to self.error, if the debug_level is less than the self.debug."
120         if debug_level <= self.debug:
121             self.err.write("Warning: " + message + "\n")
122
123
124     def error(self, message):
125         " Emits a warning and exits if not in try_hard mode."
126         self.warning(message)
127         if not self.try_hard:
128             self.warning("Quiting.")
129             sys.exit(1)
130
131         self.status = 2
132
133
134     def read(self):
135         """Reads a file into the self.header and self.body parts, from self.input."""
136         preamble = 0
137
138         while 1:
139             line = self.input.readline()
140             if not line:
141                 self.error("Invalid LyX file.")
142
143             line = line[:-1]
144             # remove '\r' from line's end, if present
145             if line[-1:] == '\r':
146                 line = line[:-1]
147
148             if check_token(line, '\\begin_preamble'):
149                 preamble = 1
150             if check_token(line, '\\end_preamble'):
151                 preamble = 0
152
153             if not preamble:
154                 line = string.strip(line)
155
156             if not preamble:
157                 if not line:
158                     continue
159
160                 if string.split(line)[0] in ("\\layout", "\\begin_layout", "\\begin_body"):
161                     self.body.append(line)
162                     break
163
164             self.header.append(line)
165
166         while 1:
167             line = self.input.readline()
168             if not line:
169                 break
170             # remove '\r' from line's end, if present
171             if line[-2:-1] == '\r':
172                 self.body.append(line[:-2])
173             else:
174                 self.body.append(line[:-1])
175
176         self.textclass = get_value(self.header, "\\textclass", 0)
177         self.backend = get_backend(self.textclass)
178         self.format  = self.read_format()
179         self.language = get_value(self.header, "\\language", 0)
180         if self.language == "":
181             self.language = "english"
182         self.initial_version = self.read_version()
183
184
185     def write(self):
186         " Writes the LyX file to self.output."
187         self.set_version()
188         self.set_format()
189
190         for line in self.header:
191             self.output.write(line+"\n")
192         self.output.write("\n")
193         for line in self.body:
194             self.output.write(line+"\n")
195
196
197     def open(self, file):
198         """Transparently deals with compressed files."""
199
200         self.dir = os.path.dirname(os.path.abspath(file))
201         try:
202             gzip.open(file).readline()
203             self.output = gzip.GzipFile("","wb",6,self.output)
204             return gzip.open(file)
205         except:
206             return open(file)
207
208
209     def lyxformat(self, format):
210         " Returns the file format representation, an integer."
211         result = format_re.match(format)
212         if result:
213             format = int(result.group(1) + result.group(2))
214         else:
215             self.error(str(format) + ": " + "Invalid LyX file.")
216
217         if format in formats_list():
218             return format
219
220         self.error(str(format) + ": " + "Format not supported.")
221         return None
222
223
224     def read_version(self):
225         """ Searchs for clues of the LyX version used to write the file, returns the
226         most likely value, or None otherwise."""
227         for line in self.header:
228             if line[0] != "#":
229                 return None
230
231             result = original_version.match(line)
232             if result:
233                 return result.group(1)
234         return None
235
236
237     def set_version(self):
238         " Set the header with the version used."
239         self.header[0] = "#LyX %s created this file. For more info see http://www.lyx.org/" % version_lyx2lyx
240         if self.header[1][0] == '#':
241             del self.header[1]
242
243
244     def read_format(self):
245         " Read from the header the fileformat of the present LyX file."
246         for line in self.header:
247             result = fileformat.match(line)
248             if result:
249                 return self.lyxformat(result.group(1))
250         else:
251             self.error("Invalid LyX File.")
252         return None
253
254
255     def set_format(self):
256         " Set the file format of the file, in the header."
257         if self.format <= 217:
258             format = str(float(self.format)/100)
259         else:
260             format = str(self.format)
261         i = find_token(self.header, "\\lyxformat", 0)
262         self.header[i] = "\\lyxformat %s" % format
263
264
265     def set_parameter(self, param, value):
266         " Set the value of the header parameter."
267         i = find_token(self.header, '\\' + param, 0)
268         if i == -1:
269             self.warning(3, 'Parameter not found in the header: %s' % param)
270             return
271         self.header[i] = '\\%s %s' % (param, str(value))
272
273
274     def convert(self):
275         "Convert from current (self.format) to self.end_format."
276         mode, convertion_chain = self.chain()
277         self.warning("convertion chain: " + str(convertion_chain), 3)
278
279         for step in convertion_chain:
280             steps = getattr(__import__("lyx_" + step), mode)
281
282             self.warning("Convertion step: %s - %s" % (step, mode), default_debug_level + 1)
283             if not steps:
284                     self.error("The convertion to an older format (%s) is not implemented." % self.format)
285
286             multi_conv = len(steps) != 1
287             for version, table in steps:
288                 if multi_conv and \
289                    (self.format >= version and mode == "convert") or\
290                    (self.format <= version and mode == "revert"):
291                     continue
292
293                 for conv in table:
294                     init_t = time.time()
295                     try:
296                         conv(self)
297                     except:
298                         self.warning("An error ocurred in %s, %s" % (version, str(conv)),
299                                      default_debug_level)
300                         if not self.try_hard:
301                             raise
302                         self.status = 2
303                     else:
304                         self.warning("%lf: Elapsed time on %s"  % (time.time() - init_t, str(conv)),
305                                      default_debug_level + 1)
306
307                 self.format = version
308                 if self.end_format == self.format:
309                     return
310
311
312     def chain(self):
313         """ This is where all the decisions related with the convertion are taken.
314         It returns a list of modules needed to convert the LyX file from
315         self.format to self.end_format"""
316
317         self.start =  self.format
318         format = self.format
319         correct_version = 0
320
321         for rel in format_relation:
322             if self.initial_version in rel[2]:
323                 if format in rel[1]:
324                     initial_step = rel[0]
325                     correct_version = 1
326                     break
327
328         if not correct_version:
329             if format <= 215:
330                 self.warning("Version does not match file format, discarding it.")
331             for rel in format_relation:
332                 if format in rel[1]:
333                     initial_step = rel[0]
334                     break
335             else:
336                 # This should not happen, really.
337                 self.error("Format not supported.")
338
339         # Find the final step
340         for rel in format_relation:
341             if self.end_format in rel[1]:
342                 final_step = rel[0]
343                 break
344         else:
345             self.error("Format not supported.")
346
347         # Convertion mode, back or forth
348         steps = []
349         if (initial_step, self.start) < (final_step, self.end_format):
350             mode = "convert"
351             first_step = 1
352             for step in format_relation:
353                 if  initial_step <= step[0] <= final_step:
354                     if first_step and len(step[1]) == 1:
355                         first_step = 0
356                         continue
357                     steps.append(step[0])
358         else:
359             mode = "revert"
360             relation_format = format_relation
361             relation_format.reverse()
362             last_step = None
363
364             for step in relation_format:
365                 if  final_step <= step[0] <= initial_step:
366                     steps.append(step[0])
367                     last_step = step
368
369             if last_step[1][-1] == self.end_format:
370                 steps.pop()
371
372         return mode, steps
373
374
375     def get_toc(self, depth = 4):
376         " Returns the TOC of this LyX document."
377         paragraphs_filter = {'Title' : 0,'Chapter' : 1, 'Section' : 2, 'Subsection' : 3, 'Subsubsection': 4}
378         allowed_insets = ['Quotes']
379         allowed_parameters = '\\paragraph_spacing', '\\noindent', '\\align', '\\labelwidthstring', "\\start_of_appendix"
380
381         sections = []
382         for section in paragraphs_filter.keys():
383             sections.append('\\begin_layout %s' % section)
384
385         toc_par = []
386         i = 0
387         while 1:
388             i = find_tokens(self.body, sections, i)
389             if i == -1:
390                 break
391
392             j = find_end_of(self.body,  i + 1, '\\begin_layout', '\\end_layout')
393             if j == -1:
394                 self.warning('Incomplete file.', 0)
395                 break
396
397             section = string.split(self.body[i])[1]
398             if section[-1] == '*':
399                 section = section[:-1]
400
401             par = []
402
403             k = i + 1
404             # skip paragraph parameters
405             while not string.strip(self.body[k]) and string.split(self.body[k])[0] in allowed_parameters:
406                 k = k +1
407
408             while k < j:
409                 if check_token(self.body[k], '\\begin_inset'):
410                     inset = string.split(self.body[k])[1]
411                     end = find_end_of_inset(self.body, k)
412                     if end == -1 or end > j:
413                         self.warning('Malformed file.', 0)
414
415                     if inset in allowed_insets:
416                         par.extend(self.body[k: end+1])
417                     k = end + 1
418                 else:
419                     par.append(self.body[k])
420                     k = k + 1
421
422             # trim empty lines in the end.
423             while string.strip(par[-1]) == '' and par:
424                 par.pop()
425
426             toc_par.append(Paragraph(section, par))
427
428             i = j + 1
429
430         return toc_par
431
432
433 class File(LyX_Base):
434     " This class reads existing LyX files."
435     def __init__(self, end_format = 0, input = "", output = "", error = "", debug = default_debug_level, try_hard = 0):
436         LyX_Base.__init__(self, end_format, input, output, error, debug, try_hard)
437         self.read()
438
439
440 class NewFile(LyX_Base):
441     " This class is to create new LyX files."
442     def set_header(self, **params):
443         # set default values
444         self.header.extend([
445             "#LyX xxxx created this file. For more info see http://www.lyx.org/",
446             "\\lyxformat xxx",
447             "\\begin_document",
448             "\\begin_header",
449             "\\textclass article",
450             "\\language english",
451             "\\inputencoding auto",
452             "\\fontscheme default",
453             "\\graphics default",
454             "\\paperfontsize default",
455             "\\papersize default",
456             "\\paperpackage none",
457             "\\use_geometry false",
458             "\\use_amsmath 1",
459             "\\cite_engine basic",
460             "\\use_bibtopic false",
461             "\\paperorientation portrait",
462             "\\secnumdepth 3",
463             "\\tocdepth 3",
464             "\\paragraph_separation indent",
465             "\\defskip medskip",
466             "\\quotes_language english",
467             "\\quotes_times 2",
468             "\\papercolumns 1",
469             "\\papersides 1",
470             "\\paperpagestyle default",
471             "\\tracking_changes false",
472             "\\end_header"])
473
474         self.format = get_end_format()
475         for param in params:
476             self.set_parameter(param, params[param])
477
478
479     def set_body(self, paragraphs):
480         self.body.extend(['\\begin_body',''])
481
482         for par in paragraphs:
483             self.body.extend(par.asLines())
484
485         self.body.extend(['','\\end_body', '\\end_document'])
486
487
488 class Paragraph:
489     # unfinished implementation, it is missing the Text and Insets representation.
490     " This class represents the LyX paragraphs."
491     def __init__(self, name, body=[], settings = [], child = []):
492         """ Parameters:
493         name: paragraph name.
494         body: list of lines of body text.
495         child: list of paragraphs that descend from this paragraph.
496         """
497         self.name = name
498         self.body = body
499         self.settings = settings
500         self.child = child
501
502     def asLines(self):
503         " Converts the paragraph to a list of strings, representing it in the LyX file."
504         result = ['','\\begin_layout %s' % self.name]
505         result.extend(self.settings)
506         result.append('')
507         result.extend(self.body)
508         result.append('\\end_layout')
509
510         if not self.child:
511             return result
512
513         result.append('\\begin_deeper')
514         for node in self.child:
515             result.extend(node.asLines())
516         result.append('\\end_deeper')
517
518         return result
519
520
521 class Inset:
522     " This class represents the LyX insets."
523     pass
524
525
526 class Text:
527     " This class represents simple chuncks of text."
528     pass