blob: a62257cbc013956111e23d5acf380fb5778f9ff1 [file] [log] [blame]
Guido van Rossuma7925f11994-01-26 10:20:16 +00001#! /usr/local/bin/python
2
3# Renumber the Python FAQ
4
5import string
6import regex
7import sys
8import os
9
10FAQ = 'FAQ'
11
12chapterprog = regex.compile('^\([1-9][0-9]*\)\. ')
13questionprog = regex.compile('^\([1-9][0-9]*\)\.\([1-9][0-9]*\)\. ')
14newquestionprog = regex.compile('^Q\. ')
15blankprog = regex.compile('^[ \t]*$')
16indentedorblankprog = regex.compile('^\([ \t]+\|[ \t]*$\)')
17
18def main():
19 print 'Reading lines...'
20 lines = open(FAQ, 'r').readlines()
21 print 'Renumbering in memory...'
22 oldlines = lines[:]
23 after_blank = 1
24 chapter = 0
25 question = 0
26 chapters = ['\n']
27 questions = []
28 for i in range(len(lines)):
29 line = lines[i]
30 if after_blank:
31 n = chapterprog.match(line)
32 if n >= 0:
33 chapter = chapter + 1
34 question = 0
35 line = `chapter` + '. ' + line[n:]
36 lines[i] = line
37 chapters.append(' ' + line)
38 questions.append('\n')
39 questions.append(' ' + line)
40 afterblank = 0
41 continue
42 n = questionprog.match(line)
43 if n < 0: n = newquestionprog.match(line) - 3
44 if n >= 0:
45 question = question + 1
46 line = '%d.%d. '%(chapter, question) + line[n:]
47 lines[i] = line
48 questions.append(' ' + line)
49 # Add up to 4 continuations of the question
50 for j in range(i+1, i+5):
51 if blankprog.match(lines[j]) >= 0:
52 break
53 questions.append(' '*(n+2) + lines[j])
54 afterblank = 0
55 continue
56 afterblank = (blankprog.match(line) >= 0)
57 print 'Inserting list of chapters...'
58 chapters.append('\n')
59 for i in range(len(lines)):
60 line = lines[i]
61 if regex.match(
62 '^This FAQ is divided in the following chapters',
63 line) >= 0:
64 i = i+1
65 while 1:
66 line = lines[i]
67 if indentedorblankprog.match(line) < 0:
68 break
69 del lines[i]
70 lines[i:i] = chapters
71 break
72 else:
73 print '*** Can\'t find header for list of chapters'
74 print '*** Chapters found:'
75 for line in chapters: print line,
76 print 'Inserting list of questions...'
77 questions.append('\n')
78 for i in range(len(lines)):
79 line = lines[i]
80 if regex.match('^Here.s an overview of the questions',
81 line) >= 0:
82 i = i+1
83 while 1:
84 line = lines[i]
85 if indentedorblankprog.match(line) < 0:
86 break
87 del lines[i]
88 lines[i:i] = questions
89 break
90 else:
91 print '*** Can\'t find header for list of questions'
92 print '*** Questions found:'
93 for line in questions: print line,
94 if lines == oldlines:
95 print 'No changes.'
96 return
97 print 'Writing new file...'
98 f = open(FAQ + '.new', 'w')
99 for line in lines:
100 f.write(line)
101 f.close()
102 print 'Making backup...'
103 os.rename(FAQ, FAQ + '~')
104 print 'Moving new file...'
105 os.rename(FAQ + '.new', FAQ)
106 print 'Done.'
107
108main()