]> git.lyx.org Git - features.git/blob - lib/scripts/layout2layout.py
Whoops.
[features.git] / lib / scripts / layout2layout.py
1 #! /usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 # file layout2layout.py
5 # This file is part of LyX, the document processor.
6 # Licence details can be found in the file COPYING.
7
8 # author Georg Baum
9
10 # Full author contact details are available in file CREDITS
11
12 # This script will update a .layout file to 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 tag.
80
81 # Do not forget to document format change in Customization
82 # Manual (section "Declaring a new text class").
83
84 currentFormat = 20
85
86
87 def usage(prog_name):
88     return ("Usage: %s inputfile outputfile\n" % prog_name +
89             "or     %s <inputfile >outputfile" % prog_name)
90
91
92 def error(message):
93     sys.stderr.write(message + '\n')
94     sys.exit(1)
95
96
97 def trim_bom(line):
98     " Remove byte order mark."
99     if line[0:3] == "\357\273\277":
100         return line[3:]
101     else:
102         return line
103
104
105 def read(source):
106     " Read input file and strip lineendings."
107     lines = source.read().splitlines()
108     lines[0] = trim_bom(lines[0])
109     return lines
110
111
112 def write(output, lines):
113     " Write output file with native lineendings."
114     output.write(os.linesep.join(lines) + os.linesep)
115
116
117 # Concatenates old and new in an intelligent way:
118 # If old is wrapped in ", they are stripped. The result is wrapped in ".
119 def concatenate_label(old, new):
120     # Don't use strip as long as we support python 1.5.2
121     if old[0] == '"':
122         return old[0:-1] + new + '"'
123     else:
124         return '"' + old + new + '"'
125
126 # appends a string to a list unless it's already there
127 def addstring(s, l):
128     if l.count(s) > 0:
129         return
130     l.append(s)
131
132
133 def convert(lines):
134     " Convert to new format."
135     re_Comment = re.compile(r'^(\s*)#')
136     re_Counter = re.compile(r'\s*Counter\s*', re.IGNORECASE)
137     re_Name = re.compile(r'\s*Name\s+(\S+)\s*', re.IGNORECASE)
138     re_UseMod = re.compile(r'^\s*UseModule\s+(.*)', re.IGNORECASE)
139     re_Empty = re.compile(r'^(\s*)$')
140     re_Format = re.compile(r'^(\s*)(Format)(\s+)(\S+)', re.IGNORECASE)
141     re_Preamble = re.compile(r'^(\s*)Preamble', re.IGNORECASE)
142     re_EndPreamble = re.compile(r'^(\s*)EndPreamble', re.IGNORECASE)
143     re_LangPreamble = re.compile(r'^(\s*)LangPreamble', re.IGNORECASE)
144     re_EndLangPreamble = re.compile(r'^(\s*)EndLangPreamble', re.IGNORECASE)
145     re_BabelPreamble = re.compile(r'^(\s*)BabelPreamble', re.IGNORECASE)
146     re_EndBabelPreamble = re.compile(r'^(\s*)EndBabelPreamble', re.IGNORECASE)
147     re_MaxCounter = re.compile(r'^(\s*)(MaxCounter)(\s+)(\S+)', re.IGNORECASE)
148     re_LabelType = re.compile(r'^(\s*)(LabelType)(\s+)(\S+)', re.IGNORECASE)
149     re_LabelString = re.compile(r'^(\s*)(LabelString)(\s+)(("[^"]+")|(\S+))', re.IGNORECASE)
150     re_LabelStringAppendix = re.compile(r'^(\s*)(LabelStringAppendix)(\s+)(("[^"]+")|(\S+))', re.IGNORECASE)
151     re_LatexType = re.compile(r'^(\s*)(LatexType)(\s+)(\S+)', re.IGNORECASE)
152     re_Style = re.compile(r'^(\s*)(Style)(\s+)(\S+)', re.IGNORECASE)
153     re_CopyStyle = re.compile(r'^(\s*)(CopyStyle)(\s+)(\S+)', re.IGNORECASE)
154     re_NoStyle = re.compile(r'^(\s*)(NoStyle)(\s+)(\S+)', re.IGNORECASE)
155     re_End = re.compile(r'^(\s*)(End)(\s*)$', re.IGNORECASE)
156     re_Provides = re.compile(r'^(\s*)Provides(\S+)(\s+)(\S+)', re.IGNORECASE)
157     re_CharStyle = re.compile(r'^(\s*)CharStyle(\s+)(\S+)$', re.IGNORECASE)
158     re_AMSMaths = re.compile(r'^\s*Input ams(?:math|def)s.inc\s*')
159     re_AMSMathsPlain = re.compile(r'^\s*Input amsmaths-plain.inc\s*')
160     re_AMSMathsSeq = re.compile(r'^\s*Input amsmaths-seq.inc\s*')
161     re_TocLevel = re.compile(r'^(\s*)(TocLevel)(\s+)(\S+)', re.IGNORECASE)
162     re_I18nPreamble = re.compile(r'^(\s*)I18nPreamble', re.IGNORECASE)
163     re_EndI18nPreamble = re.compile(r'^(\s*)EndI18nPreamble', re.IGNORECASE)
164
165     # counters for sectioning styles (hardcoded in 1.3)
166     counters = {"part"          : "\\Roman{part}",
167                 "chapter"       : "\\arabic{chapter}",
168                 "section"       : "\\arabic{section}",
169                 "subsection"    : "\\arabic{section}.\\arabic{subsection}",
170                 "subsubsection" : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}",
171                 "paragraph"     : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}",
172                 "subparagraph"  : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}.\\arabic{subparagraph}"}
173
174     # counters for sectioning styles in appendix (hardcoded in 1.3)
175     appendixcounters = {"chapter"       : "\\Alph{chapter}",
176                         "section"       : "\\Alph{section}",
177                         "subsection"    : "\\arabic{section}.\\arabic{subsection}",
178                         "subsubsection" : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}",
179                         "paragraph"     : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}",
180                         "subparagraph"  : "\\arabic{section}.\\arabic{subsection}.\\arabic{subsubsection}.\\arabic{paragraph}.\\arabic{subparagraph}"}
181
182     # Value of TocLevel for sectioning styles
183     toclevels = {"part"          : 0,
184                  "chapter"       : 0,
185                  "section"       : 1,
186                  "subsection"    : 2,
187                  "subsubsection" : 3,
188                  "paragraph"     : 4,
189                  "subparagraph"  : 5}
190
191     i = 0
192     only_comment = 1
193     counter = ""
194     toclevel = ""
195     label = ""
196     labelstring = ""
197     labelstringappendix = ""
198     space1 = ""
199     labelstring_line = -1
200     labelstringappendix_line = -1
201     labeltype_line = -1
202     latextype = ""
203     latextype_line = -1
204     style = ""
205     maxcounter = 0
206     format = 1
207     formatline = 0
208     usemodules = []
209
210     while i < len(lines):
211         # Skip comments and empty lines
212         if re_Comment.match(lines[i]) or re_Empty.match(lines[i]):
213             i += 1
214             continue
215
216         # insert file format if not already there
217         if (only_comment):
218             match = re_Format.match(lines[i])
219             if match:
220                 formatline = i
221                 format = int(match.group(4))
222                 if format > 1 and format < currentFormat:
223                     lines[i] = "Format %d" % (format + 1)
224                     only_comment = 0
225                 elif format == currentFormat:
226                     # nothing to do
227                     return format
228                 else:
229                     error('Cannot convert file format %s' % format)
230             else:
231                 lines.insert(i, "Format 2")
232                 only_comment = 0
233                 continue
234
235         # Don't get confused by LaTeX code
236         if re_Preamble.match(lines[i]):
237             i += 1
238             while i < len(lines) and not re_EndPreamble.match(lines[i]):
239                 i += 1
240             continue
241         if re_LangPreamble.match(lines[i]):
242             i += 1
243             while i < len(lines) and not re_EndLangPreamble.match(lines[i]):
244                 i += 1
245             continue
246         if re_BabelPreamble.match(lines[i]):
247             i += 1
248             while i < len(lines) and not re_EndBabelPreamble.match(lines[i]):
249                 i += 1
250             continue
251
252         # This just involved new features, not any changes to old ones
253         if format >= 14 and format <= 20:
254           i += 1
255           continue
256
257         # Rename I18NPreamble to BabelPreamble
258         if format == 13:
259             match = re_I18nPreamble.match(lines[i])
260             if match:
261                 lines[i] = match.group(1) + "BabelPreamble"
262                 i += 1
263                 match = re_EndI18nPreamble.match(lines[i])
264                 while i < len(lines) and not match:
265                     i += 1
266                     match = re_EndI18nPreamble.match(lines[i])
267                 lines[i] = match.group(1) + "EndBabelPreamble"
268                 i += 1
269                 continue
270
271         # These just involved new features, not any changes to old ones
272         if format == 11 or format == 12:
273           i += 1
274           continue
275
276         if format == 10:
277             match = re_UseMod.match(lines[i])
278             if match:
279                 module = match.group(1)
280                 lines[i] = "DefaultModule " + module
281             i += 1
282             continue
283
284         if format == 9:
285             match = re_Counter.match(lines[i])
286             if match:
287                 counterline = i
288                 i += 1
289                 while i < len(lines):
290                     namem = re_Name.match(lines[i])
291                     if namem:
292                         name = namem.group(1)
293                         lines.pop(i)
294                         lines[counterline] = "Counter %s" % name
295                         # we don't need to increment i
296                         continue
297                     endem = re_End.match(lines[i])
298                     if endem:
299                         i += 1
300                         break
301                     i += 1
302             i += 1
303             continue
304
305         if format == 8:
306             # We want to scan for ams-type includes and, if we find them,
307             # add corresponding UseModule tags to the layout.
308             match = re_AMSMaths.match(lines[i])
309             if match:
310                 addstring("theorems-ams", usemodules)
311                 addstring("theorems-ams-extended", usemodules)
312                 addstring("theorems-sec", usemodules)
313                 lines.pop(i)
314                 continue
315             match = re_AMSMathsPlain.match(lines[i])
316             if match:
317                 addstring("theorems-starred", usemodules)
318                 lines.pop(i)
319                 continue
320             match = re_AMSMathsSeq.match(lines[i])
321             if match:
322                 addstring("theorems-ams", usemodules)
323                 addstring("theorems-ams-extended", usemodules)
324                 lines.pop(i)
325                 continue
326             i += 1
327             continue
328
329         # These just involved new features, not any changes to old ones
330         if format >= 5 and format <= 7:
331           i += 1
332           continue
333
334         if format == 4:
335             # Handle conversion to long CharStyle names
336             match = re_CharStyle.match(lines[i])
337             if match:
338                 lines[i] = "InsetLayout CharStyle:%s" % (match.group(3))
339                 i += 1
340                 lines.insert(i, "\tLyXType charstyle")
341                 i += 1
342                 lines.insert(i, "")
343                 lines[i] = "\tLabelString %s" % (match.group(3))
344             i += 1
345             continue
346
347         if format == 3:
348             # convert 'providesamsmath x',  'providesmakeidx x',  'providesnatbib x',  'providesurl x' to
349             #         'provides amsmath x', 'provides makeidx x', 'provides natbib x', 'provides url x'
350             # x is either 0 or 1
351             match = re_Provides.match(lines[i])
352             if match:
353                 lines[i] = "%sProvides %s%s%s" % (match.group(1), match.group(2).lower(),
354                                                   match.group(3), match.group(4))
355             i += 1
356             continue
357
358         if format == 2:
359             caption = []
360
361             # delete caption styles
362             match = re_Style.match(lines[i])
363             if match:
364                 style = string.lower(match.group(4))
365                 if style == "caption":
366                     del lines[i]
367                     while i < len(lines) and not re_End.match(lines[i]):
368                         caption.append(lines[i])
369                         del lines[i]
370                     if i == len(lines):
371                         error('Incomplete caption style.')
372                     else:
373                         del lines[i]
374                         continue
375
376             # delete undefinition of caption styles
377             match = re_NoStyle.match(lines[i])
378             if match:
379                 style = string.lower(match.group(4))
380                 if style == "caption":
381                     del lines[i]
382                     continue
383
384             # replace the CopyStyle statement with the definition of the real
385             # style. This may result in duplicate statements, but that is OK
386             # since the second one will overwrite the first one.
387             match = re_CopyStyle.match(lines[i])
388             if match:
389                 style = string.lower(match.group(4))
390                 if style == "caption":
391                     if len(caption) > 0:
392                         lines[i:i+1] = caption
393                     else:
394                         # FIXME: This style comes from an include file, we
395                         # should replace the real style and not this default.
396                         lines[i:i+1] = ['       Margin                First_Dynamic',
397                                         '       LatexType             Command',
398                                         '       LatexName             caption',
399                                         '       NeedProtect           1',
400                                         '       LabelSep              xx',
401                                         '       ParSkip               0.4',
402                                         '       TopSep                0.5',
403                                         '       Align                 Center',
404                                         '       AlignPossible         Center',
405                                         '       LabelType             Sensitive',
406                                         '       LabelString           "Senseless!"',
407                                         '       OptionalArgs          1',
408                                         '       LabelFont',
409                                         '         Series              Bold',
410                                         '       EndFont']
411
412             i += 1
413             continue
414
415         # Delete MaxCounter and remember the value of it
416         match = re_MaxCounter.match(lines[i])
417         if match:
418             level = match.group(4)
419             if string.lower(level) == "counter_chapter":
420                 maxcounter = 0
421             elif string.lower(level) == "counter_section":
422                 maxcounter = 1
423             elif string.lower(level) == "counter_subsection":
424                 maxcounter = 2
425             elif string.lower(level) == "counter_subsubsection":
426                 maxcounter = 3
427             elif string.lower(level) == "counter_paragraph":
428                 maxcounter = 4
429             elif string.lower(level) == "counter_subparagraph":
430                 maxcounter = 5
431             elif string.lower(level) == "counter_enumi":
432                 maxcounter = 6
433             elif string.lower(level) == "counter_enumii":
434                 maxcounter = 7
435             elif string.lower(level) == "counter_enumiii":
436                 maxcounter = 8
437             del lines[i]
438             continue
439
440         # Replace line
441         #
442         # LabelType Counter_EnumI
443         #
444         # with two lines
445         #
446         # LabelType Counter
447         # LabelCounter EnumI
448         #
449         match = re_LabelType.match(lines[i])
450         if match:
451             label = match.group(4)
452             # Remember indenting space for later reuse in added lines
453             space1 = match.group(1)
454             # Remember the line for adding the LabelCounter later.
455             # We can't do it here because it could shift latextype_line etc.
456             labeltype_line = i
457             if string.lower(label[:8]) == "counter_":
458                 counter = string.lower(label[8:])
459                 lines[i] = re_LabelType.sub(r'\1\2\3Counter', lines[i])
460
461         # Remember the LabelString line
462         match = re_LabelString.match(lines[i])
463         if match:
464             labelstring = match.group(4)
465             labelstring_line = i
466
467         # Remember the LabelStringAppendix line
468         match = re_LabelStringAppendix.match(lines[i])
469         if match:
470             labelstringappendix = match.group(4)
471             labelstringappendix_line = i
472
473         # Remember the LatexType line
474         match = re_LatexType.match(lines[i])
475         if match:
476             latextype = string.lower(match.group(4))
477             latextype_line = i
478
479         # Remember the TocLevel line
480         match = re_TocLevel.match(lines[i])
481         if match:
482             toclevel = string.lower(match.group(4))
483
484         # Reset variables at the beginning of a style definition
485         match = re_Style.match(lines[i])
486         if match:
487             style = string.lower(match.group(4))
488             counter = ""
489             toclevel = ""
490             label = ""
491             space1 = ""
492             labelstring = ""
493             labelstringappendix = ""
494             labelstring_line = -1
495             labelstringappendix_line = -1
496             labeltype_line = -1
497             latextype = ""
498             latextype_line = -1
499
500         if re_End.match(lines[i]):
501
502             # Add a line "LatexType Bib_Environment" if LabelType is Bibliography
503             # (or change the existing LatexType)
504             if string.lower(label) == "bibliography":
505                 if (latextype_line < 0):
506                     lines.insert(i, "%sLatexType Bib_Environment" % space1)
507                     i += 1
508                 else:
509                     lines[latextype_line] = re_LatexType.sub(r'\1\2\3Bib_Environment', lines[latextype_line])
510
511             # Change "LabelType Static" to "LabelType Itemize" for itemize environments
512             if latextype == "item_environment" and string.lower(label) == "static":
513                 lines[labeltype_line] = re_LabelType.sub(r'\1\2\3Itemize', lines[labeltype_line])
514
515             # Change "LabelType Counter_EnumI" to "LabelType Enumerate" for enumerate environments
516             if latextype == "item_environment" and string.lower(label) == "counter_enumi":
517                 lines[labeltype_line] = re_LabelType.sub(r'\1\2\3Enumerate', lines[labeltype_line])
518                 # Don't add the LabelCounter line later
519                 counter = ""
520
521             # Replace
522             #
523             # LabelString "Chapter"
524             #
525             # with
526             #
527             # LabelString "Chapter \arabic{chapter}"
528             #
529             # if this style has a counter. Ditto for LabelStringAppendix.
530             # This emulates the hardcoded article style numbering of 1.3
531             #
532             if counter != "":
533                 if counters.has_key(style):
534                     if labelstring_line < 0:
535                         lines.insert(i, '%sLabelString "%s"' % (space1, counters[style]))
536                         i += 1
537                     else:
538                         new_labelstring = concatenate_label(labelstring, counters[style])
539                         lines[labelstring_line] = re_LabelString.sub(
540                                 r'\1\2\3%s' % new_labelstring.replace("\\", "\\\\"),
541                                 lines[labelstring_line])
542                 if appendixcounters.has_key(style):
543                     if labelstringappendix_line < 0:
544                         lines.insert(i, '%sLabelStringAppendix "%s"' % (space1, appendixcounters[style]))
545                         i += 1
546                     else:
547                         new_labelstring = concatenate_label(labelstring, appendixcounters[style])
548                         lines[labelstringappendix_line] = re_LabelStringAppendix.sub(
549                                 r'\1\2\3%s' % new_labelstring.replace("\\", "\\\\"),
550                                 lines[labelstringappendix_line])
551
552                 # Now we can safely add the LabelCounter line
553                 lines.insert(labeltype_line + 1, "%sLabelCounter %s" % (space1, counter))
554                 i += 1
555
556             # Add the TocLevel setting for sectioning styles
557             if toclevel == "" and toclevels.has_key(style) and maxcounter <= toclevels[style]:
558                 lines.insert(i, '%s\tTocLevel %d' % (space1, toclevels[style]))
559                 i += 1
560
561         i += 1
562
563     if usemodules:
564         i = formatline + 1
565         for mod in usemodules:
566             lines.insert(i, "UseModule " + mod)
567             i += 1
568
569     return format + 1
570
571
572 def main(argv):
573
574     # Open files
575     if len(argv) == 1:
576         source = sys.stdin
577         output = sys.stdout
578     elif len(argv) == 3:
579         source = open(argv[1], 'rb')
580         output = open(argv[2], 'wb')
581     else:
582         error(usage(argv[0]))
583
584     # Do the real work
585     lines = read(source)
586     format = 1
587     while (format < currentFormat):
588         format = convert(lines)
589     write(output, lines)
590
591     # Close files
592     if len(argv) == 3:
593         source.close()
594         output.close()
595
596     return 0
597
598
599 if __name__ == "__main__":
600     main(sys.argv)