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