]> git.lyx.org Git - lyx.git/blob - lib/scripts/layout2layout.py
* lib/scripts/TeXFiles.py:
[lyx.git] / lib / scripts / layout2layout.py
1 #! /usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # file layout2layout.py
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
7
8 # author Georg Baum
9
10 # Full author contact details are available in file CREDITS
11
12 # This script will update a .layout file to format 6
13
14
15 import os, re, string, sys
16
17 # Incremented to format 4, 6 April 2007, lasgouttes
18 # Introduction of generic "Provides" declaration
19
20 # Incremented to format 5, 22 August 2007 by vermeer
21 # InsetLayout material
22
23 # Incremented to format 6, 7 January 2008 by spitz
24 # Requires tag added to layout files
25
26 # Incremented to format 7, 24 March 2008 by rgh
27 # AddToPreamble tag added to layout files
28 currentFormat = 7
29
30
31 def usage(prog_name):
32     return ("Usage: %s inputfile outputfile\n" % prog_name +
33             "or     %s <inputfile >outputfile" % prog_name)
34
35
36 def error(message):
37     sys.stderr.write(message + '\n')
38     sys.exit(1)
39
40
41 def trim_eol(line):
42     " Remove end of line char(s)."
43     if line[-2:-1] == '\r':
44         return line[:-2]
45     elif line[-1:] == '\r' or line[-1:] == '\n':
46         return line[:-1]
47     else:
48         # file with no EOL in last line
49         return line
50
51
52 def read(input):
53     " Read input file and strip lineendings."
54     lines = list()
55     while 1:
56         line = input.readline()
57         if not line:
58             break
59         lines.append(trim_eol(line))
60     return lines
61
62
63 def write(output, lines):
64     " Write output file with native lineendings."
65     for line in lines:
66         output.write(line + os.linesep)
67
68
69 # Concatenates old and new in an intelligent way:
70 # If old is wrapped in ", they are stripped. The result is wrapped in ".
71 def concatenate_label(old, new):
72     # Don't use strip as long as we support python 1.5.2
73     if old[0] == '"':
74         return old[0:-1] + new + '"'
75     else:
76         return '"' + old + new + '"'
77
78
79 def convert(lines):
80     " Convert to new format."
81     re_Comment = re.compile(r'^(\s*)#')
82     re_Empty = re.compile(r'^(\s*)$')
83     re_Format = re.compile(r'^(\s*)(Format)(\s+)(\S+)', re.IGNORECASE)
84     re_Preamble = re.compile(r'^(\s*)Preamble', re.IGNORECASE)
85     re_EndPreamble = re.compile(r'^(\s*)EndPreamble', re.IGNORECASE)
86     re_MaxCounter = re.compile(r'^(\s*)(MaxCounter)(\s+)(\S+)', re.IGNORECASE)
87     re_LabelType = re.compile(r'^(\s*)(LabelType)(\s+)(\S+)', re.IGNORECASE)
88     re_LabelString = re.compile(r'^(\s*)(LabelString)(\s+)(("[^"]+")|(\S+))', re.IGNORECASE)
89     re_LabelStringAppendix = re.compile(r'^(\s*)(LabelStringAppendix)(\s+)(("[^"]+")|(\S+))', re.IGNORECASE)
90     re_LatexType = re.compile(r'^(\s*)(LatexType)(\s+)(\S+)', re.IGNORECASE)
91     re_Style = re.compile(r'^(\s*)(Style)(\s+)(\S+)', re.IGNORECASE)
92     re_CopyStyle = re.compile(r'^(\s*)(CopyStyle)(\s+)(\S+)', re.IGNORECASE)
93     re_NoStyle = re.compile(r'^(\s*)(NoStyle)(\s+)(\S+)', re.IGNORECASE)
94     re_End = re.compile(r'^(\s*)(End)(\s*)$', re.IGNORECASE)
95     re_Provides = re.compile(r'^(\s*)Provides(\S+)(\s+)(\S+)', re.IGNORECASE)
96     re_CharStyle = re.compile(r'^(\s*)CharStyle(\s+)(\S+)$', re.IGNORECASE)
97
98     # counters for sectioning styles (hardcoded in 1.3)
99     counters = {"part"          : "\\Roman{part}",
100                 "chapter"       : "\\arabic{chapter}",
101                 "section"       : "\\arabic{section}",
102                 "subsection"    : "\\arabic{section}.\\arabic{subsection}",
103                 "subsubsection" : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}",
104                 "paragraph"     : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}",
105                 "subparagraph"  : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}.\\arabic{subparagraph}"}
106
107     # counters for sectioning styles in appendix (hardcoded in 1.3)
108     appendixcounters = {"chapter"       : "\\Alph{chapter}",
109                         "section"       : "\\Alph{section}",
110                         "subsection"    : "\\arabic{section}.\\arabic{subsection}",
111                         "subsubsection" : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}",
112                         "paragraph"     : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}",
113                         "subparagraph"  : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}.\\arabic{subparagraph}"}
114
115     # Value of TocLevel for sectioning styles
116     toclevels = {"part"          : 0,
117                  "chapter"       : 0,
118                  "section"       : 1,
119                  "subsection"    : 2,
120                  "subsubsection" : 3,
121                  "paragraph"     : 4,
122                  "subparagraph"  : 5}
123
124     i = 0
125     only_comment = 1
126     counter = ""
127     label = ""
128     labelstring = ""
129     labelstringappendix = ""
130     space1 = ""
131     labelstring_line = -1
132     labelstringappendix_line = -1
133     labeltype_line = -1
134     latextype = ""
135     latextype_line = -1
136     style = ""
137     maxcounter = 0
138     format = 1
139     while i < len(lines):
140
141         # Skip comments and empty lines
142         if re_Comment.match(lines[i]) or re_Empty.match(lines[i]):
143             i += 1
144             continue
145
146         # insert file format if not already there
147         if (only_comment):
148                 match = re_Format.match(lines[i])
149                 if match:
150                         format = int(match.group(4))
151                         if format > 1 and format < currentFormat:
152                             lines[i] = "Format %d" % (format + 1)
153                             only_comment = 0
154                         elif format == currentFormat:
155                                 # nothing to do
156                                 return format
157                         else:
158                             error('Cannot convert file format %s' % format)
159                 else:
160                         lines.insert(i, "Format 2")
161                         only_comment = 0
162                         continue
163
164         # Don't get confused by LaTeX code
165         if re_Preamble.match(lines[i]):
166             i += 1
167             while i < len(lines) and not re_EndPreamble.match(lines[i]):
168                 i += 1
169             continue
170
171         if format == 6:
172           i += 1
173           continue
174
175         if format == 5:
176           i += 1
177           continue
178
179         if format == 4:
180             # Handle conversion to long CharStyle names
181             match = re_CharStyle.match(lines[i])
182             if match:
183                 lines[i] = "InsetLayout CharStyle:%s" % (match.group(3))
184                 i += 1
185                 lines.insert(i, "\tLyXType charstyle")
186                 i += 1
187                 lines.insert(i, "")
188                 lines[i] = "\tLabelString %s" % (match.group(3))
189             i += 1
190             continue
191
192         if format == 3:
193             # convert 'providesamsmath x',  'providesmakeidx x',  'providesnatbib x',  'providesurl x' to
194             #         'provides amsmath x', 'provides makeidx x', 'provides natbib x', 'provides url x'
195             # x is either 0 or 1
196             match = re_Provides.match(lines[i])
197             if match:
198                 lines[i] = "%sProvides %s%s%s" % (match.group(1), match.group(2).lower(),
199                                                   match.group(3), match.group(4))
200             i += 1
201             continue
202
203         if format == 2:
204             caption = []
205
206             # delete caption styles
207             match = re_Style.match(lines[i])
208             if match:
209                 style = string.lower(match.group(4))
210                 if style == "caption":
211                     del lines[i]
212                     while i < len(lines) and not re_End.match(lines[i]):
213                         caption.append(lines[i])
214                         del lines[i]
215                     if i == len(lines):
216                         error('Incomplete caption style.')
217                     else:
218                         del lines[i]
219                         continue
220
221             # delete undefinition of caption styles
222             match = re_NoStyle.match(lines[i])
223             if match:
224                 style = string.lower(match.group(4))
225                 if style == "caption":
226                     del lines[i]
227                     continue
228
229             # replace the CopyStyle statement with the definition of the real
230             # style. This may result in duplicate statements, but that is OK
231             # since the second one will overwrite the first one.
232             match = re_CopyStyle.match(lines[i])
233             if match:
234                 style = string.lower(match.group(4))
235                 if style == "caption":
236                     if len(caption) > 0:
237                         lines[i:i+1] = caption
238                     else:
239                         # FIXME: This style comes from an include file, we
240                         # should replace the real style and not this default.
241                         lines[i:i+1] = ['       Margin                First_Dynamic',
242                                         '       LatexType             Command',
243                                         '       LatexName             caption',
244                                         '       NeedProtect           1',
245                                         '       LabelSep              xx',
246                                         '       ParSkip               0.4',
247                                         '       TopSep                0.5',
248                                         '       Align                 Center',
249                                         '       AlignPossible         Center',
250                                         '       LabelType             Sensitive',
251                                         '       LabelString           "Senseless!"',
252                                         '       OptionalArgs          1',
253                                         '       LabelFont',
254                                         '         Series              Bold',
255                                         '       EndFont']
256
257             i += 1
258             continue
259
260         # Delete MaxCounter and remember the value of it
261         match = re_MaxCounter.match(lines[i])
262         if match:
263             level = match.group(4)
264             if string.lower(level) == "counter_chapter":
265                 maxcounter = 0
266             elif string.lower(level) == "counter_section":
267                 maxcounter = 1
268             elif string.lower(level) == "counter_subsection":
269                 maxcounter = 2
270             elif string.lower(level) == "counter_subsubsection":
271                 maxcounter = 3
272             elif string.lower(level) == "counter_paragraph":
273                 maxcounter = 4
274             elif string.lower(level) == "counter_subparagraph":
275                 maxcounter = 5
276             elif string.lower(level) == "counter_enumi":
277                 maxcounter = 6
278             elif string.lower(level) == "counter_enumii":
279                 maxcounter = 7
280             elif string.lower(level) == "counter_enumiii":
281                 maxcounter = 8
282             del lines[i]
283             continue
284
285         # Replace line
286         #
287         # LabelType Counter_EnumI
288         #
289         # with two lines
290         #
291         # LabelType Counter
292         # LabelCounter EnumI
293         #
294         match = re_LabelType.match(lines[i])
295         if match:
296             label = match.group(4)
297             # Remember indenting space for later reuse in added lines
298             space1 = match.group(1)
299             # Remember the line for adding the LabelCounter later.
300             # We can't do it here because it could shift latextype_line etc.
301             labeltype_line = i
302             if string.lower(label[:8]) == "counter_":
303                 counter = string.lower(label[8:])
304                 lines[i] = re_LabelType.sub(r'\1\2\3Counter', lines[i])
305
306         # Remember the LabelString line
307         match = re_LabelString.match(lines[i])
308         if match:
309             labelstring = match.group(4)
310             labelstring_line = i
311
312         # Remember the LabelStringAppendix line
313         match = re_LabelStringAppendix.match(lines[i])
314         if match:
315             labelstringappendix = match.group(4)
316             labelstringappendix_line = i
317
318         # Remember the LatexType line
319         match = re_LatexType.match(lines[i])
320         if match:
321             latextype = string.lower(match.group(4))
322             latextype_line = i
323
324         # Reset variables at the beginning of a style definition
325         match = re_Style.match(lines[i])
326         if match:
327             style = string.lower(match.group(4))
328             counter = ""
329             label = ""
330             space1 = ""
331             labelstring = ""
332             labelstringappendix = ""
333             labelstring_line = -1
334             labelstringappendix_line = -1
335             labeltype_line = -1
336             latextype = ""
337             latextype_line = -1
338
339         if re_End.match(lines[i]):
340
341             # Add a line "LatexType Bib_Environment" if LabelType is Bibliography
342             # (or change the existing LatexType)
343             if string.lower(label) == "bibliography":
344                 if (latextype_line < 0):
345                     lines.insert(i, "%sLatexType Bib_Environment" % space1)
346                     i += 1
347                 else:
348                     lines[latextype_line] = re_LatexType.sub(r'\1\2\3Bib_Environment', lines[latextype_line])
349
350             # Change "LabelType Static" to "LabelType Itemize" for itemize environments
351             if latextype == "item_environment" and string.lower(label) == "static":
352                 lines[labeltype_line] = re_LabelType.sub(r'\1\2\3Itemize', lines[labeltype_line])
353
354             # Change "LabelType Counter_EnumI" to "LabelType Enumerate" for enumerate environments
355             if latextype == "item_environment" and string.lower(label) == "counter_enumi":
356                 lines[labeltype_line] = re_LabelType.sub(r'\1\2\3Enumerate', lines[labeltype_line])
357                 # Don't add the LabelCounter line later
358                 counter = ""
359
360             # Replace
361             #
362             # LabelString "Chapter"
363             #
364             # with
365             #
366             # LabelString "Chapter \arabic{chapter}"
367             #
368             # if this style has a counter. Ditto for LabelStringAppendix.
369             # This emulates the hardcoded article style numbering of 1.3
370             #
371             if counter != "":
372                 if counters.has_key(style):
373                     if labelstring_line < 0:
374                         lines.insert(i, '%sLabelString "%s"' % (space1, counters[style]))
375                         i += 1
376                     else:
377                         new_labelstring = concatenate_label(labelstring, counters[style])
378                         lines[labelstring_line] = re_LabelString.sub(
379                                 r'\1\2\3%s' % new_labelstring.replace("\\", "\\\\"),
380                                 lines[labelstring_line])
381                 if appendixcounters.has_key(style):
382                     if labelstringappendix_line < 0:
383                         lines.insert(i, '%sLabelStringAppendix "%s"' % (space1, appendixcounters[style]))
384                         i += 1
385                     else:
386                         new_labelstring = concatenate_label(labelstring, appendixcounters[style])
387                         lines[labelstringappendix_line] = re_LabelStringAppendix.sub(
388                                 r'\1\2\3%s' % new_labelstring.replace("\\", "\\\\"),
389                                 lines[labelstringappendix_line])
390
391                 # Now we can safely add the LabelCounter line
392                 lines.insert(labeltype_line + 1, "%sLabelCounter %s" % (space1, counter))
393                 i += 1
394
395             # Add the TocLevel setting for sectioning styles
396             if toclevels.has_key(style) and maxcounter <= toclevels[style]:
397                 lines.insert(i, '%sTocLevel %d' % (space1, toclevels[style]))
398                 i += 1
399
400         i += 1
401
402     return format + 1
403
404
405 def main(argv):
406
407     # Open files
408     if len(argv) == 1:
409         input = sys.stdin
410         output = sys.stdout
411     elif len(argv) == 3:
412         input = open(argv[1], 'rb')
413         output = open(argv[2], 'wb')
414     else:
415         error(usage(argv[0]))
416
417     # Do the real work
418     lines = read(input)
419     format = 1
420     while (format < currentFormat):
421         format = convert(lines)
422     write(output, lines)
423
424     # Close files
425     if len(argv) == 3:
426         input.close()
427         output.close()
428
429     return 0
430
431
432 if __name__ == "__main__":
433     main(sys.argv)