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