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