def _MakeTocAndAnchors(headings, toc_pos):
  """
  Given a list of extract headings and TOC position, render HTML to insert.
  """
  # Example:
  # <div class="toclevel2"><a href="#_toc_0">Introduction</a></div>
  #
  # Yeah it's just a flat list, and then indentation is done with CSS.  Hm
  # that's easy.

  toc_lines = ['<div id="toctitle">Table of Contents</div>']
  insertions = []

  i = 0
  for line_num, tag, css_id, html_parts in headings:
    css_class = {'h3': 'toclevel2', 'h4': 'toclevel3'}[tag]

    # Add BOTH anchors, for stability.
    numeric_anchor = 'toc_%d' % i
    href = css_id or numeric_anchor

    line = '<div class="%s"><a href="#%s">%s</a></div>\n' % (
        css_class, href, ''.join(html_parts))
    toc_lines.append(line)

    target = '<a name="%s"></a>\n' % numeric_anchor
    if css_id:
      target += '<a name="%s"></a>\n' % css_id
    insertions.append((line_num, target))

    i += 1

  # +1 to insert AFTER the <div>
  toc_insert = (toc_pos+1, ''.join(toc_lines))
  insertions.insert(0, toc_insert)  # The first insertion is TOC

  return insertions