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