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