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