]> git.lyx.org Git - lyx.git/blob - lib/scripts/layout2layout.py
f4b89f5563a96852d8b6d0b37eae94b362eef721
[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 current format
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 # Incremented to format 11, 14 October 2008 by rgh
40 # Add ProvidesModule, ExcludesModule tags
41
42 # Incremented to format 12, 10 January 2009 by gb
43 # Add I18NPreamble tag
44
45 # Incremented to format 13, 5 February 2009 by rgh
46 # Add InToc tag for InsetLayout
47
48 # Incremented to format 14, 14 February 2009 by gb
49 # Rename I18NPreamble to BabelPreamble and add LangPreamble
50
51 # Incremented to format 15, 28 May 2009 by lasgouttes
52 # Add new tag OutputFormat; modules can be conditioned on feature 
53 # "from->to".
54
55 # Incremented to format 16, 5 June 2009 by rgh
56 # Add new tags for Text Class:
57 #   HTMLPreamble, HTMLAddToPreamble
58 # For Layout:
59 #   HTMLTag, HTMLAttr, HTMLLabel, HTMLLabelAttr, HTMLItem, HTMLItemAttr
60 #   HTMLStyle, and HTMLPreamble
61 # For InsetLayout:
62 #   HTMLTag, HTMLAttr, HTMLStyle, and HTMLPreamble
63 # For Floats:
64 #   HTMLType, HTMLClass, HTMLStyle
65
66 # Incremented to format 17, 12 August 2009 by rgh
67 # Add IfStyle and IfCounter tags for layout.
68
69 # Incremented to format 18, 27 October 2009 by rgh
70 # Added some new tags for HTML output.
71
72 # Incremented to format 19, 17 November 2009 by rgh
73 # Added InPreamble tag.
74
75 # Incremented to format 20, 17 December 2009 by rgh
76 # Added ContentAsLabel tag.
77
78 # Incremented to format 21, 12 January 2010 by rgh
79 # Added HTMLTocLayout and HTMLTitle tags.
80
81 # Incremented to format 22, 20 January 2010 by rgh
82 # Added HTMLFormat tag to Counters.
83
84 # Incremented to format 23, 13 February 2010 by spitz
85 # Added Spellcheck tag.
86
87 # Incremented to format 24, 5 March 2010 by rgh
88 # Changed LaTeXBuiltin tag to NeedsFloatPkg and
89 # added new tag ListCommand.
90
91 # Incremented to format 25, 12 March 2010 by rgh
92 # Added RefPrefix tag for layouts and floats.
93
94 # Incremented to format 26, 29 March 2010 by rgh
95 # Added CiteFormat.
96
97 # Incremented to format 27, 4 June 2010 by rgh
98 # Added RequiredArgs tag.
99
100 # Incremented to format 28, 6 August 2010 by lasgouttes
101 # Added ParbreakIsNewline tag for Layout and InsetLayout.
102
103 # Incremented to format 29, 10 August 2010 by rgh
104 # Changed Custom:Style, CharStyle:Style, and Element:Style
105 # uniformly to Flex:Style.
106
107 # Incremented to format 30, 13 August 2010 by rgh
108 # Introduced ResetsFont tag for InsetLayout.
109
110 # Incremented to format 31, 12 January 2011 by rgh
111 # Introducted NoCounter tag.
112
113 # Incremented to format 32, 30 January 2011 by forenr
114 # Added Display tag for InsetLayout
115
116 # Do not forget to document format change in Customization
117 # Manual (section "Declaring a new text class").
118
119 # You might also want to consider running the
120 # development/tools/updatelayouts.sh script to update all
121 # layout files to the new format.
122
123 currentFormat = 32
124
125
126 def usage(prog_name):
127     return ("Usage: %s inputfile outputfile\n" % prog_name +
128             "or     %s <inputfile >outputfile" % prog_name)
129
130
131 def error(message):
132     sys.stderr.write(message + '\n')
133     sys.exit(1)
134
135
136 def trim_bom(line):
137     " Remove byte order mark."
138     if line[0:3] == "\357\273\277":
139         return line[3:]
140     else:
141         return line
142
143
144 def read(source):
145     " Read input file and strip lineendings."
146     lines = source.read().splitlines()
147     lines[0] = trim_bom(lines[0])
148     return lines
149
150
151 def write(output, lines):
152     " Write output file with native lineendings."
153     output.write(os.linesep.join(lines) + os.linesep)
154
155
156 # Concatenates old and new in an intelligent way:
157 # If old is wrapped in ", they are stripped. The result is wrapped in ".
158 def concatenate_label(old, new):
159     # Don't use strip as long as we support python 1.5.2
160     if old[0] == '"':
161         return old[0:-1] + new + '"'
162     else:
163         return '"' + old + new + '"'
164
165 # appends a string to a list unless it's already there
166 def addstring(s, l):
167     if l.count(s) > 0:
168         return
169     l.append(s)
170
171
172 def convert(lines):
173     " Convert to new format."
174     re_Comment = re.compile(r'^(\s*)#')
175     re_Counter = re.compile(r'\s*Counter\s*', re.IGNORECASE)
176     re_Name = re.compile(r'\s*Name\s+(\S+)\s*', re.IGNORECASE)
177     re_UseMod = re.compile(r'^\s*UseModule\s+(.*)', re.IGNORECASE)
178     re_Empty = re.compile(r'^(\s*)$')
179     re_Format = re.compile(r'^(\s*)(Format)(\s+)(\S+)', re.IGNORECASE)
180     re_Preamble = re.compile(r'^(\s*)Preamble', re.IGNORECASE)
181     re_EndPreamble = re.compile(r'^(\s*)EndPreamble', re.IGNORECASE)
182     re_LangPreamble = re.compile(r'^(\s*)LangPreamble', re.IGNORECASE)
183     re_EndLangPreamble = re.compile(r'^(\s*)EndLangPreamble', re.IGNORECASE)
184     re_BabelPreamble = re.compile(r'^(\s*)BabelPreamble', re.IGNORECASE)
185     re_EndBabelPreamble = re.compile(r'^(\s*)EndBabelPreamble', re.IGNORECASE)
186     re_MaxCounter = re.compile(r'^(\s*)(MaxCounter)(\s+)(\S+)', re.IGNORECASE)
187     re_LabelType = re.compile(r'^(\s*)(LabelType)(\s+)(\S+)', re.IGNORECASE)
188     re_LabelString = re.compile(r'^(\s*)(LabelString)(\s+)(("[^"]+")|(\S+))', re.IGNORECASE)
189     re_LabelStringAppendix = re.compile(r'^(\s*)(LabelStringAppendix)(\s+)(("[^"]+")|(\S+))', re.IGNORECASE)
190     re_LatexType = re.compile(r'^(\s*)(LatexType)(\s+)(\S+)', re.IGNORECASE)
191     re_Style = re.compile(r'^(\s*)(Style)(\s+)(\S+)', re.IGNORECASE)
192     re_CopyStyle = re.compile(r'^(\s*)(CopyStyle)(\s+)(\S+)', re.IGNORECASE)
193     re_NoStyle = re.compile(r'^(\s*)(NoStyle)(\s+)(\S+)', re.IGNORECASE)
194     re_End = re.compile(r'^(\s*)(End)(\s*)$', re.IGNORECASE)
195     re_Provides = re.compile(r'^(\s*)Provides(\S+)(\s+)(\S+)', re.IGNORECASE)
196     re_CharStyle = re.compile(r'^(\s*)CharStyle(\s+)(\S+)$', re.IGNORECASE)
197     re_AMSMaths = re.compile(r'^\s*Input ams(?:math|def)s.inc\s*')
198     re_AMSMathsPlain = re.compile(r'^\s*Input amsmaths-plain.inc\s*')
199     re_AMSMathsSeq = re.compile(r'^\s*Input amsmaths-seq.inc\s*')
200     re_TocLevel = re.compile(r'^(\s*)(TocLevel)(\s+)(\S+)', re.IGNORECASE)
201     re_I18nPreamble = re.compile(r'^(\s*)I18nPreamble', re.IGNORECASE)
202     re_EndI18nPreamble = re.compile(r'^(\s*)EndI18nPreamble', re.IGNORECASE)
203     re_Float = re.compile(r'^\s*Float\s*$', re.IGNORECASE)
204     re_Type = re.compile(r'\s*Type\s+(\w+)', re.IGNORECASE)
205     re_Builtin = re.compile(r'^(\s*)LaTeXBuiltin\s+(\w*)', re.IGNORECASE)
206     re_True = re.compile(r'^\s*(?:true|1)\s*$', re.IGNORECASE)
207     re_InsetLayout = re.compile(r'^\s*InsetLayout\s+(?:Custom|CharStyle|Element):(\S+)\s*$')
208     # with quotes
209     re_QInsetLayout = re.compile(r'^\s*InsetLayout\s+"(?:Custom|CharStyle|Element):([^"]+)"\s*$')
210
211     # counters for sectioning styles (hardcoded in 1.3)
212     counters = {"part"          : "\\Roman{part}",
213                 "chapter"       : "\\arabic{chapter}",
214                 "section"       : "\\arabic{section}",
215                 "subsection"    : "\\arabic{section}.\\arabic{subsection}",
216                 "subsubsection" : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}",
217                 "paragraph"     : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}",
218                 "subparagraph"  : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}.\\arabic{subparagraph}"}
219
220     # counters for sectioning styles in appendix (hardcoded in 1.3)
221     appendixcounters = {"chapter"       : "\\Alph{chapter}",
222                         "section"       : "\\Alph{section}",
223                         "subsection"    : "\\arabic{section}.\\arabic{subsection}",
224                         "subsubsection" : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}",
225                         "paragraph"     : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}",
226                         "subparagraph"  : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}.\\arabic{subparagraph}"}
227
228     # Value of TocLevel for sectioning styles
229     toclevels = {"part"          : 0,
230                  "chapter"       : 0,
231                  "section"       : 1,
232                  "subsection"    : 2,
233                  "subsubsection" : 3,
234                  "paragraph"     : 4,
235                  "subparagraph"  : 5}
236
237     i = 0
238     only_comment = 1
239     counter = ""
240     toclevel = ""
241     label = ""
242     labelstring = ""
243     labelstringappendix = ""
244     space1 = ""
245     labelstring_line = -1
246     labelstringappendix_line = -1
247     labeltype_line = -1
248     latextype = ""
249     latextype_line = -1
250     style = ""
251     maxcounter = 0
252     format = 1
253     formatline = 0
254     usemodules = []
255
256     while i < len(lines):
257         # Skip comments and empty lines
258         if re_Comment.match(lines[i]) or re_Empty.match(lines[i]):
259             i += 1
260             continue
261
262         # insert file format if not already there
263         if (only_comment):
264             match = re_Format.match(lines[i])
265             if match:
266                 formatline = i
267                 format = int(match.group(4))
268                 if format > 1 and format < currentFormat:
269                     lines[i] = "Format %d" % (format + 1)
270                     only_comment = 0
271                 elif format == currentFormat:
272                     # nothing to do
273                     return format
274                 else:
275                     error('Cannot convert file format %s' % format)
276             else:
277                 lines.insert(i, "Format 2")
278                 only_comment = 0
279                 continue
280
281         # Don't get confused by LaTeX code
282         if re_Preamble.match(lines[i]):
283             i += 1
284             while i < len(lines) and not re_EndPreamble.match(lines[i]):
285                 i += 1
286             continue
287         if re_LangPreamble.match(lines[i]):
288             i += 1
289             while i < len(lines) and not re_EndLangPreamble.match(lines[i]):
290                 i += 1
291             continue
292         if re_BabelPreamble.match(lines[i]):
293             i += 1
294             while i < len(lines) and not re_EndBabelPreamble.match(lines[i]):
295                 i += 1
296             continue
297
298         # Only new features
299         if format >= 29 and format <= 31:
300           i += 1
301           continue
302
303         if format == 28:
304           match = re_InsetLayout.match(lines[i])
305           if match:
306             lines[i] = "InsetLayout Flex:" + match.group(1)
307           else:
308             match = re_QInsetLayout.match(lines[i])
309             if match:
310               lines[i] = "InsetLayout \"Flex:" + match.group(1) + "\""
311           i += 1
312           continue
313         
314         # Only new features
315         if format >= 24 and format <= 27:
316           i += 1
317           continue
318
319         if format == 23:
320           match = re_Float.match(lines[i])
321           i += 1
322           if not match:
323             continue
324           # we need to do two things:
325           # (i)  Convert Builtin to NeedsFloatPkg
326           # (ii) Write ListCommand lines for the builtin floats table and figure
327           builtin = False
328           cmd = ""
329           while True and i < len(lines):
330             m1 = re_End.match(lines[i])
331             if m1:
332               if builtin and cmd:
333                 line = "    ListCommand " + cmd
334                 lines.insert(i, line)
335                 i += 1
336               break
337             m2 = re_Builtin.match(lines[i])
338             if m2:
339               builtin = True
340               ws1 = m2.group(1)
341               arg = m2.group(2)
342               newarg = ""
343               if re_True.match(arg):
344                 newarg = "false"
345               else:
346                 newarg = "true"
347               lines[i] = ws1 + "NeedsFloatPkg " + newarg
348             m3 = re_Type.match(lines[i])
349             if m3:
350               fltype = m3.group(1)
351               fltype = fltype.lower()
352               if fltype == "table":
353                 cmd = "listoftables"
354               elif fltype == "figure":
355                 cmd = "listoffigures"
356               # else unknown, which is why we're doing this
357             i += 1
358           continue              
359           
360         # This just involved new features, not any changes to old ones
361         if format >= 14 and format <= 22:
362           i += 1
363           continue
364
365         # Rename I18NPreamble to BabelPreamble
366         if format == 13:
367             match = re_I18nPreamble.match(lines[i])
368             if match:
369                 lines[i] = match.group(1) + "BabelPreamble"
370                 i += 1
371                 match = re_EndI18nPreamble.match(lines[i])
372                 while i < len(lines) and not match:
373                     i += 1
374                     match = re_EndI18nPreamble.match(lines[i])
375                 lines[i] = match.group(1) + "EndBabelPreamble"
376                 i += 1
377                 continue
378
379         # These just involved new features, not any changes to old ones
380         if format == 11 or format == 12:
381           i += 1
382           continue
383
384         if format == 10:
385             match = re_UseMod.match(lines[i])
386             if match:
387                 module = match.group(1)
388                 lines[i] = "DefaultModule " + module
389             i += 1
390             continue
391
392         if format == 9:
393             match = re_Counter.match(lines[i])
394             if match:
395                 counterline = i
396                 i += 1
397                 while i < len(lines):
398                     namem = re_Name.match(lines[i])
399                     if namem:
400                         name = namem.group(1)
401                         lines.pop(i)
402                         lines[counterline] = "Counter %s" % name
403                         # we don't need to increment i
404                         continue
405                     endem = re_End.match(lines[i])
406                     if endem:
407                         i += 1
408                         break
409                     i += 1
410             i += 1
411             continue
412
413         if format == 8:
414             # We want to scan for ams-type includes and, if we find them,
415             # add corresponding UseModule tags to the layout.
416             match = re_AMSMaths.match(lines[i])
417             if match:
418                 addstring("theorems-ams", usemodules)
419                 addstring("theorems-ams-extended", usemodules)
420                 addstring("theorems-sec", usemodules)
421                 lines.pop(i)
422                 continue
423             match = re_AMSMathsPlain.match(lines[i])
424             if match:
425                 addstring("theorems-starred", usemodules)
426                 lines.pop(i)
427                 continue
428             match = re_AMSMathsSeq.match(lines[i])
429             if match:
430                 addstring("theorems-ams", usemodules)
431                 addstring("theorems-ams-extended", usemodules)
432                 lines.pop(i)
433                 continue
434             i += 1
435             continue
436
437         # These just involved new features, not any changes to old ones
438         if format >= 5 and format <= 7:
439           i += 1
440           continue
441
442         if format == 4:
443             # Handle conversion to long CharStyle names
444             match = re_CharStyle.match(lines[i])
445             if match:
446                 lines[i] = "InsetLayout CharStyle:%s" % (match.group(3))
447                 i += 1
448                 lines.insert(i, "\tLyXType charstyle")
449                 i += 1
450                 lines.insert(i, "")
451                 lines[i] = "\tLabelString %s" % (match.group(3))
452             i += 1
453             continue
454
455         if format == 3:
456             # convert 'providesamsmath x',  'providesmakeidx x',  'providesnatbib x',  'providesurl x' to
457             #         'provides amsmath x', 'provides makeidx x', 'provides natbib x', 'provides url x'
458             # x is either 0 or 1
459             match = re_Provides.match(lines[i])
460             if match:
461                 lines[i] = "%sProvides %s%s%s" % (match.group(1), match.group(2).lower(),
462                                                   match.group(3), match.group(4))
463             i += 1
464             continue
465
466         if format == 2:
467             caption = []
468
469             # delete caption styles
470             match = re_Style.match(lines[i])
471             if match:
472                 style = string.lower(match.group(4))
473                 if style == "caption":
474                     del lines[i]
475                     while i < len(lines) and not re_End.match(lines[i]):
476                         caption.append(lines[i])
477                         del lines[i]
478                     if i == len(lines):
479                         error('Incomplete caption style.')
480                     else:
481                         del lines[i]
482                         continue
483
484             # delete undefinition of caption styles
485             match = re_NoStyle.match(lines[i])
486             if match:
487                 style = string.lower(match.group(4))
488                 if style == "caption":
489                     del lines[i]
490                     continue
491
492             # replace the CopyStyle statement with the definition of the real
493             # style. This may result in duplicate statements, but that is OK
494             # since the second one will overwrite the first one.
495             match = re_CopyStyle.match(lines[i])
496             if match:
497                 style = string.lower(match.group(4))
498                 if style == "caption":
499                     if len(caption) > 0:
500                         lines[i:i+1] = caption
501                     else:
502                         # FIXME: This style comes from an include file, we
503                         # should replace the real style and not this default.
504                         lines[i:i+1] = ['       Margin                First_Dynamic',
505                                         '       LatexType             Command',
506                                         '       LatexName             caption',
507                                         '       NeedProtect           1',
508                                         '       LabelSep              xx',
509                                         '       ParSkip               0.4',
510                                         '       TopSep                0.5',
511                                         '       Align                 Center',
512                                         '       AlignPossible         Center',
513                                         '       LabelType             Sensitive',
514                                         '       LabelString           "Senseless!"',
515                                         '       OptionalArgs          1',
516                                         '       LabelFont',
517                                         '         Series              Bold',
518                                         '       EndFont']
519
520             i += 1
521             continue
522
523         # Delete MaxCounter and remember the value of it
524         match = re_MaxCounter.match(lines[i])
525         if match:
526             level = match.group(4)
527             if string.lower(level) == "counter_chapter":
528                 maxcounter = 0
529             elif string.lower(level) == "counter_section":
530                 maxcounter = 1
531             elif string.lower(level) == "counter_subsection":
532                 maxcounter = 2
533             elif string.lower(level) == "counter_subsubsection":
534                 maxcounter = 3
535             elif string.lower(level) == "counter_paragraph":
536                 maxcounter = 4
537             elif string.lower(level) == "counter_subparagraph":
538                 maxcounter = 5
539             elif string.lower(level) == "counter_enumi":
540                 maxcounter = 6
541             elif string.lower(level) == "counter_enumii":
542                 maxcounter = 7
543             elif string.lower(level) == "counter_enumiii":
544                 maxcounter = 8
545             del lines[i]
546             continue
547
548         # Replace line
549         #
550         # LabelType Counter_EnumI
551         #
552         # with two lines
553         #
554         # LabelType Counter
555         # LabelCounter EnumI
556         #
557         match = re_LabelType.match(lines[i])
558         if match:
559             label = match.group(4)
560             # Remember indenting space for later reuse in added lines
561             space1 = match.group(1)
562             # Remember the line for adding the LabelCounter later.
563             # We can't do it here because it could shift latextype_line etc.
564             labeltype_line = i
565             if string.lower(label[:8]) == "counter_":
566                 counter = string.lower(label[8:])
567                 lines[i] = re_LabelType.sub(r'\1\2\3Counter', lines[i])
568
569         # Remember the LabelString line
570         match = re_LabelString.match(lines[i])
571         if match:
572             labelstring = match.group(4)
573             labelstring_line = i
574
575         # Remember the LabelStringAppendix line
576         match = re_LabelStringAppendix.match(lines[i])
577         if match:
578             labelstringappendix = match.group(4)
579             labelstringappendix_line = i
580
581         # Remember the LatexType line
582         match = re_LatexType.match(lines[i])
583         if match:
584             latextype = string.lower(match.group(4))
585             latextype_line = i
586
587         # Remember the TocLevel line
588         match = re_TocLevel.match(lines[i])
589         if match:
590             toclevel = string.lower(match.group(4))
591
592         # Reset variables at the beginning of a style definition
593         match = re_Style.match(lines[i])
594         if match:
595             style = string.lower(match.group(4))
596             counter = ""
597             toclevel = ""
598             label = ""
599             space1 = ""
600             labelstring = ""
601             labelstringappendix = ""
602             labelstring_line = -1
603             labelstringappendix_line = -1
604             labeltype_line = -1
605             latextype = ""
606             latextype_line = -1
607
608         if re_End.match(lines[i]):
609
610             # Add a line "LatexType Bib_Environment" if LabelType is Bibliography
611             # (or change the existing LatexType)
612             if string.lower(label) == "bibliography":
613                 if (latextype_line < 0):
614                     lines.insert(i, "%sLatexType Bib_Environment" % space1)
615                     i += 1
616                 else:
617                     lines[latextype_line] = re_LatexType.sub(r'\1\2\3Bib_Environment', lines[latextype_line])
618
619             # Change "LabelType Static" to "LabelType Itemize" for itemize environments
620             if latextype == "item_environment" and string.lower(label) == "static":
621                 lines[labeltype_line] = re_LabelType.sub(r'\1\2\3Itemize', lines[labeltype_line])
622
623             # Change "LabelType Counter_EnumI" to "LabelType Enumerate" for enumerate environments
624             if latextype == "item_environment" and string.lower(label) == "counter_enumi":
625                 lines[labeltype_line] = re_LabelType.sub(r'\1\2\3Enumerate', lines[labeltype_line])
626                 # Don't add the LabelCounter line later
627                 counter = ""
628
629             # Replace
630             #
631             # LabelString "Chapter"
632             #
633             # with
634             #
635             # LabelString "Chapter \arabic{chapter}"
636             #
637             # if this style has a counter. Ditto for LabelStringAppendix.
638             # This emulates the hardcoded article style numbering of 1.3
639             #
640             if counter != "":
641                 if counters.has_key(style):
642                     if labelstring_line < 0:
643                         lines.insert(i, '%sLabelString "%s"' % (space1, counters[style]))
644                         i += 1
645                     else:
646                         new_labelstring = concatenate_label(labelstring, counters[style])
647                         lines[labelstring_line] = re_LabelString.sub(
648                                 r'\1\2\3%s' % new_labelstring.replace("\\", "\\\\"),
649                                 lines[labelstring_line])
650                 if appendixcounters.has_key(style):
651                     if labelstringappendix_line < 0:
652                         lines.insert(i, '%sLabelStringAppendix "%s"' % (space1, appendixcounters[style]))
653                         i += 1
654                     else:
655                         new_labelstring = concatenate_label(labelstring, appendixcounters[style])
656                         lines[labelstringappendix_line] = re_LabelStringAppendix.sub(
657                                 r'\1\2\3%s' % new_labelstring.replace("\\", "\\\\"),
658                                 lines[labelstringappendix_line])
659
660                 # Now we can safely add the LabelCounter line
661                 lines.insert(labeltype_line + 1, "%sLabelCounter %s" % (space1, counter))
662                 i += 1
663
664             # Add the TocLevel setting for sectioning styles
665             if toclevel == "" and toclevels.has_key(style) and maxcounter <= toclevels[style]:
666                 lines.insert(i, '%s\tTocLevel %d' % (space1, toclevels[style]))
667                 i += 1
668
669         i += 1
670
671     if usemodules:
672         i = formatline + 1
673         for mod in usemodules:
674             lines.insert(i, "UseModule " + mod)
675             i += 1
676
677     return format + 1
678
679
680 def main(argv):
681
682     # Open files
683     if len(argv) == 1:
684         source = sys.stdin
685         output = sys.stdout
686     elif len(argv) == 3:
687         source = open(argv[1], 'rb')
688         output = open(argv[2], 'wb')
689     else:
690         error(usage(argv[0]))
691
692     # Do the real work
693     lines = read(source)
694     format = 1
695     while (format < currentFormat):
696         format = convert(lines)
697     write(output, lines)
698
699     # Close files
700     if len(argv) == 3:
701         source.close()
702         output.close()
703
704     return 0
705
706
707 if __name__ == "__main__":
708     main(sys.argv)