Generate TOC entry for a file
(file_name, title, lang, depth, content_dir)
| 76 | |
| 77 | |
| 78 | def generate_toc_entry(file_name, title, lang, depth, content_dir): |
| 79 | """Generate TOC entry for a file""" |
| 80 | entries = [] |
| 81 | |
| 82 | # Determine URL path |
| 83 | base_name = file_name.replace('.md', '') |
| 84 | if lang == 'zh': |
| 85 | url = f"/{base_name}" |
| 86 | else: |
| 87 | url = f"/{lang}/{base_name}" |
| 88 | |
| 89 | # Add main entry (level 1) |
| 90 | entries.append({ |
| 91 | 'level': 1, |
| 92 | 'text': f"[{title}]({url})", |
| 93 | 'raw_text': title |
| 94 | }) |
| 95 | |
| 96 | # Special case: glossary.md only shows main title (no sub-headings) |
| 97 | if file_name == 'glossary.md': |
| 98 | effective_depth = 0 # Don't extract any sub-headings |
| 99 | else: |
| 100 | effective_depth = depth - 1 # Adjust depth: user depth 1 = no extraction, 2 = extract H2, etc. |
| 101 | |
| 102 | # If effective_depth >= 1, extract headings from file |
| 103 | if effective_depth >= 1: |
| 104 | file_path = content_dir / file_name |
| 105 | if file_path.exists(): |
| 106 | with open(file_path, 'r', encoding='utf-8') as f: |
| 107 | content = f.read() |
| 108 | |
| 109 | headings = extract_headings(content, effective_depth) |
| 110 | for heading in headings: |
| 111 | # Create link with anchor |
| 112 | if heading['id']: |
| 113 | anchor_url = f"{url}#{heading['id']}" |
| 114 | else: |
| 115 | # Generate anchor from heading text (simplified) |
| 116 | anchor = heading['text'].lower() |
| 117 | anchor = re.sub(r'[^\w\s-]', '', anchor) |
| 118 | anchor = re.sub(r'\s+', '-', anchor) |
| 119 | anchor_url = f"{url}#{anchor}" |
| 120 | |
| 121 | # Adjust level: H2 becomes level 2, H3 becomes level 3, etc. |
| 122 | # This ensures proper indentation under the main entry |
| 123 | entries.append({ |
| 124 | 'level': heading['level'], |
| 125 | 'text': f"[{heading['text']}]({anchor_url})", |
| 126 | 'raw_text': heading['text'] |
| 127 | }) |
| 128 | |
| 129 | return entries |
| 130 | |
| 131 | |
| 132 | def format_toc_entries(entries): |
no test coverage detected