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