view make/indexsections.py @ 60:db0a5f758831

Make the index output have more distinct major sections.
author Rob Landley <rob@landley.net>
date Tue, 02 Oct 2007 14:01:29 -0500
parents 0df6348fc276
children 503142fc4d43
line wrap: on
line source

#!/usr/bin/python

import os,sys

# Print appropriate number of <ul> or </ul> tags, with indentation.
def adjust_depth(newdepth, depth):
  while newdepth > depth:
    sys.stdout.write("%s<ul>\n" % ("  "*depth))
    depth += 1
  while newdepth < depth:
    sys.stdout.write("%s</ul>\n" % ("  "*depth))
    depth -= 1
  return depth

def process(data, idx):
  line = data[0].count("\n")
  depth = 0
  spans = []
  secnum = [0]

  if not idx: sys.stdout.write(data[0])
  for i in data[1:]:
    i = i.split(">",1)
    tag = i[0].split(None,1)
    if tag[0] == "put_index_here":
      if not idx: process(data, 1)
      continue
    if tag[0] == "span":
      if len(tag) == 0 or not tag[1].startswith("id="):
        sys.stderr.write("Bad span at line %s: %s" % (line,i[0]))
        sys.exit(1)
      tag = tag[1][3:]
      if tag[0]=='"' and tag[-1]=='"': tag=tag[1:-1]
      spans.append("_".join(tag.split()))
      secnum[-1] += 1
      secstr = ".".join(map(lambda a: str(a), secnum))
      if idx:
        depth = adjust_depth(len(spans)-1, depth)
        if depth: style="li"
        else: style="h2"
        sys.stdout.write('%s<%s><a href="#%s">%s %s</a></%s>\n' % ("  "*len(spans),style,spans[-1],secstr,tag,style))
      else:
        sys.stdout.write('<h2><a name="%s">%s %s</a></h2>\n' % (spans[-1],secstr,tag))
        sys.stdout.write('<%s>%s' % (i[0], i[1]))
      secnum.append(0)
    elif tag[0] == "/span":
      spans.pop()
      secnum.pop()
    else:
      if not idx: sys.stdout.write('<%s>%s' % (i[0], i[1]));
    line += i[1].count("\n")
  if idx: adjust_depth(0, depth)

if len(sys.argv) != 2:
  sys.stderr.write("Usage: indexsections.py filename\n");
  sys.exit(1)

process(open(sys.argv[1]).read().split("<"), 0)