{"slug": "this-tool-maps-cell-ids-to-their-corresponding-headings-and-content-standalone-c", "title": "This tool maps cell IDs to their corresponding headings and content. Standalone TOC Generator for Google Colab  Copyright (c) 2026 1abcdefggs Licensed under the MIT License  Source: https://github.com/1abcdefggs/cell-id-call GitHub: https://github.com/1abcdefggs", "summary": "This article describes a standalone Python script called `standalone_toc.py` that generates a table of contents for Google Colab notebooks. The tool helps users map cell IDs to their corresponding headings and content, making it easier to understand which cell an AI assistant like Gemini is referencing. Users can customize the output by filtering by cell type, searching by keyword or cell ID, and adjusting preview settings.", "body_md": "standalone_toc.py\n\n      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.\n      \nLearn more about bidirectional Unicode characters\n\n \n    Show hidden characters\n\n# Copyright (c) 2026 1abcdefggs\n\n# Licensed under the MIT License\n\n# See LICENSE file in the project root for full license information\n\n#!/usr/bin/env python3\n\n\"\"\"\n\nStandalone TOC Generator for Google Colab\n\nThis script generates a table of contents for Colab notebooks without requiring external modules.\n\nBackground:\n\nWhen working with AI assistants like Gemini in Colab, they often reference Cell IDs when explaining\n\ncode or content. This tool helps you map Cell IDs to their corresponding headings and content,\n\nmaking it easier to understand which cell the AI is referring to.\n\nUsage:\n\n1. Copy this code to a new cell in your Colab notebook\n\n2. Run the cell to generate a table of contents\n\n3. Customize parameters in generate_standalone_toc() as needed:\n\n   - filter_type: \"All\", \"Code\", or \"Markdown\"\n\n   - keyword: Search keyword (empty string for all cells)\n\n   - match_mode: \"Cell-ID\" or \"Content\"\n\n   - limit: Preview character limit (default: 70)\n\n   - show_jump: Show jump links (True/False)\n\n   - show_stats: Show statistics (True/False)\n\n   - save_log: Save to \"TOC Preview.md\" (True/False)\n\nSource: https://github.com/1abcdefggs/cell-id-call\n\n\"\"\"\n\nimport IPython\n\nimport json\n\nimport os\n\nfrom google.colab import _message\n\nfrom IPython.display import display, HTML\n\ndef _extract_heading_preview_standalone(source, cell_type, limit):\n\n    \"\"\"Extract heading preview from cell source.\"\"\"\n\n    text = \"\".join(source) if isinstance(source, list) else str(source)\n\n    text = text.strip().replace(\"\\n\", \" \")\n\n    if cell_type == \"markdown\" and text.startswith(\"#\"):\n\n        cleaned = text.lstrip(\"#\").strip()\n\n        if not cleaned: return \"(Empty heading)\"\n\n        return f\"**{cleaned[:limit]}**\" if len(cleaned) > limit else f\"**{cleaned}**\"\n\n    return f\"{text[:limit]}...\" if len(text) > limit else text\n\ndef generate_standalone_toc(filter_type, keyword, match_mode, limit, show_jump, show_stats, save_log):\n\n    \"\"\"Generate standalone TOC for Colab notebook.\"\"\"\n\n    resp = _message.blocking_request('get_ipynb')\n\n    if not resp or 'ipynb' not in resp: return\n\n    cells = resp['ipynb'].get('cells', [])\n\n    # Precise ID and Alignment Logic\n\n    processed_ids = []\n\n    for c in cells:\n\n        meta = c.get('metadata', {})\n\n        cid = meta.get('colab', {}).get('id') or c.get('id') or meta.get('id') or \"unknown\"\n\n        processed_ids.append(str(cid))\n\n    max_id_len = max([len(cid) for cid in processed_ids]) if processed_ids else 12\n\n    # Dynamic Column Width Calculation\n\n    jump_link_base = \"[Jump](#scrollTo=)\"\n\n    w_jump = max(len(\"Jump Link\"), max_id_len + len(jump_link_base))\n\n    w_id = max(len(\"Cell ID\"), max_id_len + 2)\n\n    h_jump = f\" {('Jump Link').ljust(w_jump)} |\" if show_jump else \"\"\n\n    s_jump = f\" {(':---').ljust(w_jump, '-')} |\" if show_jump else \"\"\n\n    header = f\"| Type | Index |{h_jump} {('Cell ID').ljust(w_id)} | Heading / Preview |\"\n\n    sep = f\"| :--- | :--- |{s_jump} {(':---').ljust(w_id, '-')} | :--- |\"\n\n    md_table = [\"# 🔍 TOC Preview. Quick Navigation (Standalone)\", f\"Mode: `{match_mode}`, Filter: `{filter_type}`\", header, sep]\n\n    stats = {'markdown': 0, 'code': 0, 'total': len(cells)}\n\n    match_count = 0\n\n    for idx, cell in enumerate(cells):\n\n        c_type = cell.get('cell_type', 'unknown')\n\n        stats[c_type] = stats.get(c_type, 0) + 1\n\n        if filter_type == \"Code\" and c_type != 'code': continue\n\n        if filter_type == \"Markdown\" and c_type != 'markdown': continue\n\n        cell_id = processed_ids[idx]\n\n        source_text = \"\".join(cell.get('source', []))\n\n        if keyword:\n\n            if match_mode == \"Cell-ID\":\n\n                if keyword != cell_id: continue\n\n            else:\n\n                if keyword.lower() not in source_text.lower(): continue\n\n        match_count += 1\n\n        preview = _extract_heading_preview_standalone(source_text, c_type, limit)\n\n        icon = \"📝\" if c_type == 'markdown' else \"💻\"\n\n        row = f\"| {icon} | {idx:03d} |\"\n\n        if show_jump:\n\n            row += f\" {f'[Jump](#scrollTo={cell_id})'.ljust(w_jump)} |\"\n\n        row += f\" {f'`{cell_id}`'.ljust(w_id)} | {preview} |\"\n\n        md_table.append(row)\n\n    full_md = \"\\n\".join(md_table)\n\n    if save_log:\n\n        with open(\"TOC Preview.md\", \"w\", encoding=\"utf-8\") as f: f.write(full_md)\n\n    if show_stats: print(f\"📊 Total: {stats['total']} | Matches: {match_count}\")\n\n    # UI Button with improved JS for copying\n\n    js_content = json.dumps(full_md)\n\n    button_id = \"copy_btn_standalone\"\n\n    html_btn = f'''\n\n    <div style=\"margin: 15px 0;\">\n\n        <button id=\"{button_id}\" style=\"background: #1a73e8; color: white; padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; font-weight: bold;\">\n\n            📋 Copy TOC to Clipboard\n\n        </button>\n\n    </div>\n\n    <script>\n\n    (function() {{\n\n        const btn = document.getElementById(\"{button_id}\");\n\n        if (!btn) return;\n\n        btn.onclick = function() {{\n\n            const text = {js_content};\n\n            if (!navigator.clipboard) {{\n\n               const textArea = document.createElement(\"textarea\");\n\n               textArea.value = text;\n\n               document.body.appendChild(textArea);\n\n               textArea.select();\n\n               try {{ document.execCommand('copy'); }} catch (err) {{ }}\n\n               document.body.removeChild(textArea);\n\n            }} else {{\n\n                navigator.clipboard.writeText(text).then(() {{\n\n                    const original = btn.innerText;\n\n                    btn.innerText = \"✅ Copied!\";\n\n                    btn.style.background = \"#34a853\";\n\n                    setTimeout(() => {{\n\n                        btn.innerText = original;\n\n                        btn.style.background = \"#1a73e8\";\n\n                    }}, 2000);\n\n                }});\n\n            }}\n\n        }};\n\n    }})();\n\n    </script>\n\n    '''\n\n    display(HTML(html_btn))\n\n    print(\"\\n\" + full_md)\n\n# Default configuration for standalone execution\n\nif __name__ == \"__main__\":\n\n    generate_standalone_toc(\n\n        filter_type=\"All\",\n\n        keyword=\"\",\n\n        match_mode=\"Cell-ID\",\n\n        limit=70,\n\n        show_jump=True,\n\n        show_stats=True,\n\n        save_log=True\n\n    )", "url": "https://wpnews.pro/news/this-tool-maps-cell-ids-to-their-corresponding-headings-and-content-standalone-c", "canonical_source": "https://gist.github.com/1abcdefggs/21632dd1f3670e8d1506e4788ab514cc", "published_at": "2026-05-24 03:25:11+00:00", "updated_at": "2026-05-24 03:32:57.469722+00:00", "lang": "en", "topics": ["developer-tools", "open-source"], "entities": ["Google Colab", "Gemini", "MIT License", "1abcdefggs"], "alternates": {"html": "https://wpnews.pro/news/this-tool-maps-cell-ids-to-their-corresponding-headings-and-content-standalone-c", "markdown": "https://wpnews.pro/news/this-tool-maps-cell-ids-to-their-corresponding-headings-and-content-standalone-c.md", "text": "https://wpnews.pro/news/this-tool-maps-cell-ids-to-their-corresponding-headings-and-content-standalone-c.txt", "jsonld": "https://wpnews.pro/news/this-tool-maps-cell-ids-to-their-corresponding-headings-and-content-standalone-c.jsonld"}}