0
# Headers and Table of Contents
1
2
Header creation with multiple styles and automated table of contents generation with customizable depth and positioning. MDUtils supports both ATX-style (#) and Setext-style (underlined) headers, along with automatic table of contents generation from header structures.
3
4
## Capabilities
5
6
### Header Creation
7
8
Create headers with configurable levels, styles, and automatic table of contents integration.
9
10
```python { .api }
11
class MdUtils:
12
def new_header(self, level: int, title: str, style: str = "atx", add_table_of_contents: str = "y", header_id: str = "") -> str:
13
"""
14
Add a new header to the markdown document.
15
16
Parameters:
17
- level (int): Header level (1-6 for ATX, 1-2 for Setext)
18
- title (str): Header text content
19
- style (str): Header style ('atx' for #-style, 'setext' for underlined)
20
- add_table_of_contents (str): Include in TOC ('y' or 'n')
21
- header_id (str, optional): HTML ID for the header (extended markdown)
22
23
Returns:
24
str: Formatted header string
25
"""
26
```
27
28
**Usage Example:**
29
30
```python
31
from mdutils import MdUtils
32
33
md = MdUtils(file_name='headers_example')
34
35
# ATX-style headers (default)
36
md.new_header(level=1, title='Main Title') # # Main Title
37
md.new_header(level=2, title='Section Header') # ## Section Header
38
md.new_header(level=3, title='Subsection') # ### Subsection
39
40
# Setext-style headers
41
md.new_header(level=1, title='Main Title', style='setext') # Main Title\n==========
42
md.new_header(level=2, title='Section Header', style='setext') # Section Header\n--------------
43
44
# Headers with IDs (for linking)
45
md.new_header(level=2, title='Advanced Topics', header_id='advanced')
46
47
# Headers excluded from table of contents
48
md.new_header(level=3, title='Internal Note', add_table_of_contents='n')
49
```
50
51
### Header Tool Classes
52
53
Direct access to header creation tools for advanced header manipulation and styling.
54
55
```python { .api }
56
class Header:
57
def __init__(self, level: int, title: str, style: HeaderStyle, header_id: str = None):
58
"""
59
Initialize a header object.
60
61
Parameters:
62
- level (int): Header level (1-6)
63
- title (str): Header text
64
- style (HeaderStyle): ATX or SETEXT style enum
65
- header_id (str, optional): HTML ID for the header
66
"""
67
68
def __str__(self) -> str:
69
"""
70
Get string representation of the header.
71
72
Returns:
73
str: Formatted header string
74
"""
75
76
@staticmethod
77
def atx(level: AtxHeaderLevel, title: str, header_id: str = None) -> str:
78
"""
79
Create ATX-style header (# ## ### etc.).
80
81
Parameters:
82
- level (AtxHeaderLevel): Header level enum (TITLE=1 through LEASTHEADING=6)
83
- title (str): Header text
84
- header_id (str, optional): HTML ID for the header
85
86
Returns:
87
str: ATX-formatted header
88
"""
89
90
@staticmethod
91
def setext(level: SetextHeaderLevel, title: str) -> str:
92
"""
93
Create Setext-style header (underlined).
94
95
Parameters:
96
- level (SetextHeaderLevel): TITLE=1 (===) or HEADING=2 (---)
97
- title (str): Header text
98
99
Returns:
100
str: Setext-formatted header
101
"""
102
103
@staticmethod
104
def header_anchor(text: str, link: str = None) -> str:
105
"""
106
Create internal anchor link to header.
107
108
Parameters:
109
- text (str): Display text for the link
110
- link (str, optional): Header ID to link to (defaults to text)
111
112
Returns:
113
str: Markdown link to header anchor
114
"""
115
```
116
117
**Usage Example:**
118
119
```python
120
from mdutils import MdUtils
121
from mdutils.tools import Header, HeaderStyle, AtxHeaderLevel, SetextHeaderLevel
122
123
md = MdUtils(file_name='header_tools_example')
124
125
# Using Header class directly
126
h1 = Header(level=1, title='Introduction', style=HeaderStyle.ATX)
127
md.write(str(h1))
128
129
h2_setext = Header(level=2, title='Overview', style=HeaderStyle.SETEXT)
130
md.write(str(h2_setext))
131
132
# Using static methods
133
atx_header = Header.atx(AtxHeaderLevel.SUBHEADING, 'Technical Details')
134
setext_header = Header.setext(SetextHeaderLevel.HEADING, 'Summary')
135
136
md.write(atx_header)
137
md.write(setext_header)
138
139
# Creating header anchors
140
anchor_link = Header.header_anchor('Go to Introduction', 'introduction')
141
md.write(f'Reference: {anchor_link}')
142
```
143
144
### Table of Contents Generation
145
146
Automatically generate table of contents from document headers with customizable depth and positioning.
147
148
```python { .api }
149
class MdUtils:
150
def new_table_of_contents(self, table_title: str = "Table of contents", depth: int = 1, marker: str = "") -> str:
151
"""
152
Generate table of contents from document headers.
153
154
Parameters:
155
- table_title (str): Title for the table of contents section
156
- depth (int): Maximum header depth to include (1-6)
157
- marker (str, optional): Marker for positioning TOC at specific location
158
159
Returns:
160
str: Formatted table of contents
161
"""
162
```
163
164
**Usage Example:**
165
166
```python
167
from mdutils import MdUtils
168
169
md = MdUtils(file_name='toc_example')
170
171
# Add some headers first
172
md.new_header(level=1, title='Introduction')
173
md.new_paragraph('Introduction content...')
174
175
md.new_header(level=2, title='Getting Started')
176
md.new_paragraph('Getting started content...')
177
178
md.new_header(level=3, title='Installation')
179
md.new_paragraph('Installation instructions...')
180
181
md.new_header(level=2, title='Advanced Usage')
182
md.new_paragraph('Advanced usage content...')
183
184
md.new_header(level=3, title='Configuration')
185
md.new_paragraph('Configuration details...')
186
187
# Generate table of contents
188
md.new_table_of_contents() # Default: includes all levels, placed after title
189
190
# Generate TOC with custom title and depth
191
md.new_table_of_contents(table_title="Contents", depth=2) # Only H1 and H2
192
193
# Generate TOC at specific location using marker
194
marker = md.create_marker('toc_location')
195
md.new_table_of_contents(table_title="Navigation", depth=3, marker=marker)
196
```
197
198
### Table of Contents Tool Classes
199
200
Direct access to table of contents generation tools for advanced TOC customization.
201
202
```python { .api }
203
class TableOfContents:
204
def create_table_of_contents(self, array_of_title_contents: List[str], depth: int = 1) -> str:
205
"""
206
Create table of contents from a list of header titles.
207
208
Parameters:
209
- array_of_title_contents (List[str]): Nested list structure of headers
210
- depth (int): Maximum depth to include in TOC
211
212
Returns:
213
str: Formatted table of contents markdown
214
"""
215
216
def _loop_through(self, elements, tab: str = "", depth: int = 1) -> str:
217
"""
218
Internal method for processing nested header lists.
219
220
Parameters:
221
- elements: Nested list structure to process
222
- tab (str): Current indentation level
223
- depth (int): Current processing depth
224
225
Returns:
226
str: Processed TOC section
227
"""
228
```
229
230
**Usage Example:**
231
232
```python
233
from mdutils import MdUtils
234
from mdutils.tools import TableOfContents
235
236
md = MdUtils(file_name='toc_tools_example')
237
238
# Create headers and build TOC manually
239
md.new_header(level=1, title='Chapter 1')
240
md.new_header(level=2, title='Section 1.1')
241
md.new_header(level=2, title='Section 1.2')
242
md.new_header(level=1, title='Chapter 2')
243
244
# Access the internal title structure
245
toc_generator = TableOfContents()
246
toc_content = toc_generator.create_table_of_contents(md._table_titles, depth=2)
247
248
md.write(toc_content)
249
```
250
251
### Header Styling Enums
252
253
Enumerations for header levels and styles to ensure type safety and consistency.
254
255
```python { .api }
256
class HeaderStyle(Enum):
257
ATX = "atx" # Hash-style headers (# ## ###)
258
SETEXT = "setext" # Underlined headers (=== ---)
259
260
class AtxHeaderLevel(Enum):
261
TITLE = 1 # H1: #
262
HEADING = 2 # H2: ##
263
SUBHEADING = 3 # H3: ###
264
SUBSUBHEADING = 4 # H4: ####
265
MINORHEADING = 5 # H5: #####
266
LEASTHEADING = 6 # H6: ######
267
268
class SetextHeaderLevel(Enum):
269
TITLE = 1 # H1: underlined with ===
270
HEADING = 2 # H2: underlined with ---
271
```
272
273
**Usage Example:**
274
275
```python
276
from mdutils import MdUtils
277
from mdutils.tools import Header, HeaderStyle, AtxHeaderLevel, SetextHeaderLevel
278
279
md = MdUtils(file_name='enum_example')
280
281
# Using enums for type safety
282
title_header = Header.atx(AtxHeaderLevel.TITLE, 'Document Title')
283
section_header = Header.atx(AtxHeaderLevel.HEADING, 'Main Section')
284
subsection_header = Header.atx(AtxHeaderLevel.SUBHEADING, 'Subsection')
285
286
md.write(title_header)
287
md.write(section_header)
288
md.write(subsection_header)
289
290
# Setext style with enums
291
setext_title = Header.setext(SetextHeaderLevel.TITLE, 'Major Title')
292
setext_heading = Header.setext(SetextHeaderLevel.HEADING, 'Section Heading')
293
294
md.write(setext_title)
295
md.write(setext_heading)
296
```
297
298
### Complete TOC Workflow
299
300
Comprehensive example showing header creation and table of contents generation workflow.
301
302
**Usage Example:**
303
304
```python
305
from mdutils import MdUtils
306
307
# Create document with title
308
md = MdUtils(file_name='complete_doc', title='User Manual', title_header_style='setext')
309
310
# Add structured content with headers
311
md.new_header(level=1, title='Overview')
312
md.new_paragraph('This manual covers all aspects of the software.')
313
314
md.new_header(level=2, title='Key Features')
315
md.new_paragraph('The software includes the following features:')
316
317
md.new_header(level=3, title='User Interface')
318
md.new_paragraph('Clean and intuitive interface design.')
319
320
md.new_header(level=3, title='Performance')
321
md.new_paragraph('Optimized for speed and efficiency.')
322
323
md.new_header(level=2, title='Installation Requirements')
324
md.new_paragraph('System requirements and installation steps.')
325
326
md.new_header(level=1, title='Getting Started')
327
md.new_paragraph('Quick start guide for new users.')
328
329
md.new_header(level=2, title='First Steps')
330
md.new_paragraph('Basic operations to get you up and running.')
331
332
md.new_header(level=2, title='Configuration')
333
md.new_paragraph('How to configure the software for your needs.')
334
335
md.new_header(level=1, title='Advanced Topics')
336
md.new_paragraph('Advanced features and customization options.')
337
338
# Generate comprehensive table of contents
339
md.new_table_of_contents(table_title='Table of Contents', depth=3)
340
341
# Create the final document
342
md.create_md_file()
343
```