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