Skip to content

manipulator

ContentSection

ContentSection(title: str, level: int)

Represents a specific section within a note, containing a title, hierarchy level, and text content.

Attributes:

  • title (str) –

    The title of the section (e.g., "Introduction").

  • level (int) –

    The heading level of the section (e.g., 1 for #, 2 for ##).

  • content (List[str]) –

    A list of strings representing the lines of content in this section.

Initializes a ContentSection with a title and a heading level.

Parameters:

  • title (str) –

    The title of the section.

  • level (int) –

    The Markdown heading level (e.g., 1, 2, 3).

Source code in ures/markdown/manipulator.py
19
20
21
22
23
24
25
26
27
28
def __init__(self, title: str, level: int):
    """Initializes a ContentSection with a title and a heading level.

    Args:
        title (str): The title of the section.
        level (int): The Markdown heading level (e.g., 1, 2, 3).
    """
    self.title = title
    self.level = level
    self.content: List[str] = []

add_content

add_content(content: Union[str, List[str]])

Appends text content to this section.

Parameters:

  • content (Union[str, List[str]]) –

    A single string line or a list of string lines to add.

Source code in ures/markdown/manipulator.py
30
31
32
33
34
35
36
37
38
39
def add_content(self, content: Union[str, List[str]]):
    """Appends text content to this section.

    Args:
        content (Union[str, List[str]]): A single string line or a list of string lines to add.
    """
    if isinstance(content, list):
        self.content.extend(content)
    else:
        self.content.append(content)

Content

Content()

Represents the body of a note, organized into titled sections.

Attributes:

  • sections (Dict[str, ContentSection]) –

    A dictionary mapping section titles to ContentSection objects.

Initializes an empty Content container.

Source code in ures/markdown/manipulator.py
49
50
51
def __init__(self):
    """Initializes an empty Content container."""
    self.sections: OrderedDict[str, ContentSection] = OrderedDict()

new_section

new_section(title: str, level: int)

Creates a new empty section if it does not already exist.

Parameters:

  • title (str) –

    The unique title of the section.

  • level (int) –

    The Markdown heading level for the section.

Source code in ures/markdown/manipulator.py
53
54
55
56
57
58
59
60
61
def new_section(self, title: str, level: int):
    """Creates a new empty section if it does not already exist.

    Args:
        title (str): The unique title of the section.
        level (int): The Markdown heading level for the section.
    """
    if title not in self.sections:
        self.sections[title] = ContentSection(title, level)

add_section

add_section(section: ContentSection)

Adds an existing ContentSection object to the content.

If a section with the same title already exists, this operation is ignored.

Parameters:

Source code in ures/markdown/manipulator.py
63
64
65
66
67
68
69
70
71
72
def add_section(self, section: ContentSection):
    """Adds an existing ContentSection object to the content.

    If a section with the same title already exists, this operation is ignored.

    Args:
        section (ContentSection): The section object to add.
    """
    if section.title not in self.sections.keys():
        self.sections[section.title] = section

add_content

add_content(content: Union[str, list], section_title: str = 'default', section_level: int = 1)

Adds content to a specific section, creating the section if it does not exist.

Parameters:

  • content ((str, list)) –

    The text content to add.

  • section_title (str, default: 'default' ) –

    The title of the target section. Defaults to "default".

  • section_level (int, default: 1 ) –

    The heading level if a new section needs to be created. Defaults to 1.

Source code in ures/markdown/manipulator.py
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def add_content(
    self,
    content: Union[str, list],
    section_title: str = "default",
    section_level: int = 1,
):
    """Adds content to a specific section, creating the section if it does not exist.

    Args:
        content (str, list): The text content to add.
        section_title (str, optional): The title of the target section. Defaults to "default".
        section_level (int, optional): The heading level if a new section needs to be created. Defaults to 1.
    """
    if section_title not in self.sections:
        self.new_section(section_title, section_level)
    self.sections[section_title].add_content(content)

to_string

to_string() -> str

Serializes the entire content into a Markdown-formatted string.

Returns:

  • str ( str ) –

    The complete Markdown content with section headers.

Source code in ures/markdown/manipulator.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def to_string(self) -> str:
    """Serializes the entire content into a Markdown-formatted string.

    Returns:
        str: The complete Markdown content with section headers.
    """
    markdown_lines: List[str] = []
    for section in self.sections.values():
        if section.title != "default":
            markdown_lines.append(f"{'#' * section.level} {section.title}")
        markdown_lines.extend(section.content)
        markdown_lines.append("")  # Add a blank line after each section
    return "\n".join(markdown_lines).strip()

MarkdownDocument

MarkdownDocument(content: str = '', metadata: Optional[Dict[str, Any]] = None)

A low-level class for manipulating Markdown files with front matter.

This class provides methods to add and modify Markdown content and front matter, supporting nested structures in front matter (e.g., dictionaries within YAML front matter).

Examples:

>>> doc = MarkdownDocument(content="Hello", metadata={"title": "Note"})
>>> doc.metadata["title"]
'Note'

Initializes a new MarkdownDocument instance.

Parameters:

  • content (str, default: '' ) –

    The Markdown content. Defaults to an empty string.

  • metadata (Optional[Dict[str, Any]], default: None ) –

    The front matter metadata as a dictionary. Defaults to None.

Examples:

>>> doc = MarkdownDocument(
...     content="# Hello World",
...     metadata={"title": "Greeting", "tags": ["intro", "welcome"]}
... )
Source code in ures/markdown/manipulator.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def __init__(self, content: str = "", metadata: Optional[Dict[str, Any]] = None):
    """
    Initializes a new MarkdownDocument instance.

    Args:
        content (str): The Markdown content. Defaults to an empty string.
        metadata (Optional[Dict[str, Any]]): The front matter metadata as a dictionary. Defaults to None.

    Examples:
        >>> doc = MarkdownDocument(
        ...     content="# Hello World",
        ...     metadata={"title": "Greeting", "tags": ["intro", "welcome"]}
        ... )
    """
    if metadata is None:
        metadata = {}
    self.post = frontmatter.Post(content, **metadata)

content property writable

content: str

Retrieves the Markdown content.

Returns:

  • str ( str ) –

    The Markdown content.

Examples:

>>> doc = MarkdownDocument(content="# Hello World")
>>> doc.content
"# Hello World"

metadata property writable

metadata: Dict[str, Any]

Retrieves the front matter metadata.

Returns:

  • Dict[str, Any] –

    Dict[str, Any]: The metadata dictionary.

Examples:

>>> doc = MarkdownDocument(metadata={"title": "Greeting", "tags": ["intro", "welcome"]})
>>> doc.metadata
{"title": "Greeting", "tags": ["intro", "welcome"]}

from_file classmethod

from_file(file_path: Union[Path, str]) -> MarkdownDocument

Creates a MarkdownDocument instance by loading a Markdown file.

Parameters:

  • file_path (str) –

    The path to the Markdown file.

Returns:

  • MarkdownDocument ( MarkdownDocument ) –

    An instance representing the loaded Markdown file.

Raises:

  • FileNotFoundError –

    If the specified file does not exist.

  • InvalidFrontMatterError –

    If the front matter is malformed.

Source code in ures/markdown/manipulator.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
@classmethod
def from_file(cls, file_path: Union[Path, str]) -> "MarkdownDocument":
    """
    Creates a MarkdownDocument instance by loading a Markdown file.

    Args:
        file_path (str): The path to the Markdown file.

    Returns:
        MarkdownDocument: An instance representing the loaded Markdown file.

    Raises:
        FileNotFoundError: If the specified file does not exist.
        frontmatter.InvalidFrontMatterError: If the front matter is malformed.
    """
    file_path = cls.path_preprocess(file_path)
    if not file_path.is_file():
        raise FileNotFoundError(f"The file '{file_path}' does not exist.")

    with open(file_path, "r", encoding="utf-8") as f:
        post = frontmatter.load(f)
    return cls(content=post.content, metadata=deepcopy(post.metadata))

add_content

add_content(content: str, append: bool = True) -> None

Adds content to the Markdown document.

Parameters:

  • content (str) –

    The Markdown content to add.

  • append (bool, default: True ) –

    If True, appends to existing content; otherwise, prepends. Defaults to True.

Examples:

>>> doc = MarkdownDocument()
>>> doc.add_content("# Introduction")
>>> doc.add_content("Some introductory text.", append=True)
Source code in ures/markdown/manipulator.py
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
def add_content(self, content: str, append: bool = True) -> None:
    """
    Adds content to the Markdown document.

    Args:
        content (str): The Markdown content to add.
        append (bool): If True, appends to existing content; otherwise, prepends.
                       Defaults to True.

    Examples:
        >>> doc = MarkdownDocument()
        >>> doc.add_content("# Introduction")
        >>> doc.add_content("Some introductory text.", append=True)
    """
    if append:
        if self.post.content:
            self.post.content += "\n" + content
        else:
            self.post.content = content
    else:
        if self.post.content:
            self.post.content = content + "\n" + self.post.content
        else:
            self.post.content = content

set_frontmatter

set_frontmatter(key_path: str, value: Any, overwrite: bool = True) -> None

Sets a front matter key to a specified value. Supports nested keys using dot notation, including mixed types such as dictionaries within lists.

Parameters:

  • key_path (str) –

    The front matter key path. Use dot notation for nested keys (e.g., "author.name" or "sections.0.title").

  • value (Any) –

    The value to set for the key.

  • overwrite (bool, default: True ) –

    If True, overwrites the existing value; otherwise, appends to lists or creates new entries in lists. Defaults to True.

Examples:

>>> doc = MarkdownDocument()
>>> doc.set_frontmatter("author.name", "John Doe")
>>> doc.set_frontmatter("author.contact.email", "john@example.com")
>>> doc.set_frontmatter("sections.0.title", "Introduction")
>>> doc.set_frontmatter("sections.0.content", "Welcome to the introduction.")
>>> doc.set_frontmatter("sections.1.title", "Conclusion")
>>> doc.set_frontmatter("sections.1.content", "Wrapping up.")
Source code in ures/markdown/manipulator.py
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
def set_frontmatter(
    self, key_path: str, value: Any, overwrite: bool = True
) -> None:
    """
    Sets a front matter key to a specified value. Supports nested keys using dot notation,
    including mixed types such as dictionaries within lists.

    Args:
        key_path (str): The front matter key path. Use dot notation for nested keys
                        (e.g., "author.name" or "sections.0.title").
        value (Any): The value to set for the key.
        overwrite (bool): If True, overwrites the existing value; otherwise, appends to lists
                          or creates new entries in lists. Defaults to True.

    Examples:
        >>> doc = MarkdownDocument()
        >>> doc.set_frontmatter("author.name", "John Doe")
        >>> doc.set_frontmatter("author.contact.email", "john@example.com")
        >>> doc.set_frontmatter("sections.0.title", "Introduction")
        >>> doc.set_frontmatter("sections.0.content", "Welcome to the introduction.")
        >>> doc.set_frontmatter("sections.1.title", "Conclusion")
        >>> doc.set_frontmatter("sections.1.content", "Wrapping up.")
    """
    keys = key_path.split(".")
    current = self.post.metadata

    for i, key in enumerate(keys):
        is_last = i == len(keys) - 1
        # Determine if the current key is meant to be a list index
        if key.isdigit():
            index = int(key)
            if not isinstance(current, list):
                if overwrite:
                    # Initialize as list
                    parent = self.post.metadata
                    for k in keys[:i]:
                        if k.isdigit():
                            parent = parent[int(k)]
                        else:
                            parent = parent[k]
                    parent[int(keys[i - 1])] = []
                    current = parent[int(keys[i - 1])]
                else:
                    raise TypeError(
                        f"Expected list at {'.'.join(keys[:i])}, found {type(current).__name__}"
                    )
            # Extend the list if necessary
            while len(current) <= index:
                current.append({})
            if is_last:
                if isinstance(current[index], list) and not overwrite:
                    current[index].append(value)
                elif isinstance(current[index], dict):
                    if isinstance(value, dict):
                        current[index].update(value)
                    else:
                        current[index]["value"] = value
                elif not overwrite:
                    current[index] = [current[index], value]
                else:
                    current[index] = value
            else:
                if not isinstance(current[index], (dict, list)):
                    # Initialize as dict or list based on next key
                    next_key = keys[i + 1]
                    if next_key.isdigit():
                        current[index] = []
                    else:
                        current[index] = {}
                current = current[index]
        else:
            if not isinstance(current, dict):
                if overwrite:
                    # Initialize as dict
                    parent = self.post.metadata
                    for k in keys[:i]:
                        if k.isdigit():
                            parent = parent[int(k)]
                        else:
                            parent = parent[k]
                    parent[keys[i - 1]] = {}
                    current = parent[keys[i - 1]]
                else:
                    raise TypeError(
                        f"Expected dict at {'.'.join(keys[:i])}, found {type(current).__name__}"
                    )
            if is_last:
                if key in current:
                    if isinstance(current[key], list) and not overwrite:
                        current[key].append(value)
                    elif isinstance(current[key], dict):
                        if isinstance(value, dict):
                            current[key].update(value)
                        else:
                            current[key]["value"] = value
                    elif not overwrite:
                        current[key] = [current[key], value]
                    else:
                        current[key] = value
                else:
                    current[key] = value
            else:
                if key not in current or not isinstance(current[key], (dict, list)):
                    # Initialize as dict or list based on next key
                    next_key = keys[i + 1]
                    if next_key.isdigit():
                        current[key] = []
                    else:
                        current[key] = {}
                current = current[key]

get_frontmatter

get_frontmatter(key_path: str) -> Any

Retrieves the value of a front matter key. Supports nested keys using dot notation, including list indices.

Parameters:

  • key_path (str) –

    The front matter key path. Use dot notation for nested keys (e.g., "author.name" or "sections.0.title").

Returns:

  • Any ( Any ) –

    The value associated with the key, or None if the key does not exist.

Examples:

>>> doc = MarkdownDocument(
...     metadata={
...         "author": {"name": "John Doe", "contact": {"email": "john@example.com"}},
...         "sections": [
...             {"title": "Introduction", "content": "Welcome."},
...             {"title": "Conclusion", "content": "Goodbye."}
...         ]
...     }
... )
>>> doc.get_frontmatter("author.name")
"John Doe"
>>> doc.get_frontmatter("sections.0.title")
"Introduction"
>>> doc.get_frontmatter("sections.1.content")
"Goodbye."
Source code in ures/markdown/manipulator.py
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
def get_frontmatter(self, key_path: str) -> Any:
    """
    Retrieves the value of a front matter key. Supports nested keys using dot notation,
    including list indices.

    Args:
        key_path (str): The front matter key path. Use dot notation for nested keys
                        (e.g., "author.name" or "sections.0.title").

    Returns:
        Any: The value associated with the key, or None if the key does not exist.

    Examples:
        >>> doc = MarkdownDocument(
        ...     metadata={
        ...         "author": {"name": "John Doe", "contact": {"email": "john@example.com"}},
        ...         "sections": [
        ...             {"title": "Introduction", "content": "Welcome."},
        ...             {"title": "Conclusion", "content": "Goodbye."}
        ...         ]
        ...     }
        ... )
        >>> doc.get_frontmatter("author.name")
        "John Doe"
        >>> doc.get_frontmatter("sections.0.title")
        "Introduction"
        >>> doc.get_frontmatter("sections.1.content")
        "Goodbye."
    """
    keys = key_path.split(".")
    metadata = self.post.metadata

    for key in keys:
        if isinstance(metadata, dict):
            metadata = metadata.get(key, None)
        elif isinstance(metadata, list):
            if key.isdigit():
                index = int(key)
                if 0 <= index < len(metadata):
                    metadata = metadata[index]
                else:
                    return None
            else:
                return None
        else:
            return None

        if metadata is None:
            return None

    return metadata

remove_frontmatter

remove_frontmatter(key_path: str) -> None

Removes a front matter key. Supports nested keys using dot notation, including list indices.

Parameters:

  • key_path (str) –

    The front matter key path to remove. Use dot notation for nested keys (e.g., "author.contact.email" or "sections.0.title").

Examples:

>>> doc = MarkdownDocument(
...     metadata={
...         "author": {"name": "John Doe", "contact": {"email": "john@example.com"}},
...         "sections": [
...             {"title": "Introduction", "content": "Welcome."},
...             {"title": "Conclusion", "content": "Goodbye."}
...         ]
...     }
... )
>>> doc.remove_frontmatter("author.contact.email")
>>> doc.get_frontmatter("author.contact.email") is None
True
>>> doc.remove_frontmatter("sections.1.title")
>>> doc.get_frontmatter("sections.1.title") is None
True
Source code in ures/markdown/manipulator.py
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
def remove_frontmatter(self, key_path: str) -> None:
    """
    Removes a front matter key. Supports nested keys using dot notation,
    including list indices.

    Args:
        key_path (str): The front matter key path to remove. Use dot notation for nested keys
                        (e.g., "author.contact.email" or "sections.0.title").

    Examples:
        >>> doc = MarkdownDocument(
        ...     metadata={
        ...         "author": {"name": "John Doe", "contact": {"email": "john@example.com"}},
        ...         "sections": [
        ...             {"title": "Introduction", "content": "Welcome."},
        ...             {"title": "Conclusion", "content": "Goodbye."}
        ...         ]
        ...     }
        ... )
        >>> doc.remove_frontmatter("author.contact.email")
        >>> doc.get_frontmatter("author.contact.email") is None
        True
        >>> doc.remove_frontmatter("sections.1.title")
        >>> doc.get_frontmatter("sections.1.title") is None
        True
    """
    keys = key_path.split(".")
    metadata = self.post.metadata

    for i, key in enumerate(keys):
        is_last = i == len(keys) - 1
        if isinstance(metadata, dict):
            if key not in metadata:
                return  # Key path does not exist; nothing to remove
            if is_last:
                del metadata[key]
                return
            metadata = metadata[key]
        elif isinstance(metadata, list):
            if key.isdigit():
                index = int(key)
                if 0 <= index < len(metadata):
                    if is_last:
                        del metadata[index]
                        return
                    metadata = metadata[index]
                else:
                    return  # Index out of range; nothing to remove
            else:
                return  # Invalid key for list; nothing to remove
        else:
            return  # Neither dict nor list; nothing to remove

to_markdown

to_markdown() -> str

Serializes the MarkdownDocument to a Markdown-formatted string, including front matter.

Returns:

  • str ( str ) –

    The complete Markdown content with front matter.

ERROR

ValueError: If the front matter is missing mandatory fields.

Examples:

>>> doc = MarkdownDocument(
...     content="# Hello World",
...     metadata={"title": "Greeting", "tags": ["intro", "welcome"]}
... )
>>> print(doc.to_markdown())
---
title: Greeting
tags:
  - intro
  - welcome
---

Hello World

Source code in ures/markdown/manipulator.py
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
def to_markdown(self) -> str:
    """
    Serializes the MarkdownDocument to a Markdown-formatted string, including front matter.

    Returns:
        str: The complete Markdown content with front matter.

    ERROR:
        ValueError: If the front matter is missing mandatory fields.

    Examples:
        >>> doc = MarkdownDocument(
        ...     content="# Hello World",
        ...     metadata={"title": "Greeting", "tags": ["intro", "welcome"]}
        ... )
        >>> print(doc.to_markdown())
        ---
        title: Greeting
        tags:
          - intro
          - welcome
        ---

        # Hello World
    """
    self.validation_frontmatter()
    return frontmatter.dumps(self.post)

save

save(file_path: Union[Path, str]) -> None

Saves the MarkdownDocument to a specified file.

Parameters:

  • file_path (str) –

    The path where the Markdown file will be saved.

Examples:

>>> doc = MarkdownDocument(
...     content="# Hello World",
...     metadata={"title": "Greeting", "tags": ["intro", "welcome"]}
... )
>>> doc.save_to_file("greeting.md")
Source code in ures/markdown/manipulator.py
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
def save(self, file_path: Union[Path, str]) -> None:
    """
    Saves the MarkdownDocument to a specified file.

    Args:
        file_path (str): The path where the Markdown file will be saved.

    Examples:
        >>> doc = MarkdownDocument(
        ...     content="# Hello World",
        ...     metadata={"title": "Greeting", "tags": ["intro", "welcome"]}
        ... )
        >>> doc.save_to_file("greeting.md")
    """
    file_path = self.path_preprocess(file_path)
    markdown_str = self.to_markdown()
    with open(file_path, "w", encoding="utf-8") as f:
        f.write(markdown_str)

load_from_file

load_from_file(file_path: Union[Path, str]) -> None

Loads Markdown content and front matter from a specified file into the current instance.

Parameters:

  • file_path (str) –

    The path to the Markdown file to load.

Raises:

  • FileNotFoundError –

    If the specified file does not exist.

  • InvalidFrontMatterError –

    If the front matter is malformed.

Examples:

>>> doc = MarkdownDocument()
>>> doc.load_from_file("existing.md")
Source code in ures/markdown/manipulator.py
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
def load_from_file(self, file_path: Union[Path, str]) -> None:
    """
    Loads Markdown content and front matter from a specified file into the current instance.

    Args:
        file_path (str): The path to the Markdown file to load.

    Raises:
        FileNotFoundError: If the specified file does not exist.
        frontmatter.InvalidFrontMatterError: If the front matter is malformed.

    Examples:
        >>> doc = MarkdownDocument()
        >>> doc.load_from_file("existing.md")
    """
    file_path = self.path_preprocess(file_path)
    if not os.path.isfile(file_path):
        raise FileNotFoundError(f"The file '{file_path}' does not exist.")

    with open(file_path, "r", encoding="utf-8") as f:
        post = frontmatter.load(f)

    self.post.content = post.content
    self.post.metadata = deepcopy(post.metadata)

parse_content

parse_content() -> Content

Parses the raw note content into a structured Content object.

Iterates through the raw text line by line, identifying Markdown headers (e.g., '# Title') to delimit sections. Text found before the first header is assigned to a 'default' section.

Returns:

  • Content ( Content ) –

    An object containing the parsed sections, their hierarchy levels,

  • Content –

    and associated text content.

Source code in ures/markdown/manipulator.py
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
def parse_content(self) -> Content:
    """Parses the raw note content into a structured Content object.

    Iterates through the raw text line by line, identifying Markdown headers
    (e.g., '# Title') to delimit sections. Text found before the first header
    is assigned to a 'default' section.

    Returns:
        Content: An object containing the parsed sections, their hierarchy levels,
        and associated text content.
    """
    lines = self.content.split("\n")
    current_section = "default"
    current_head_level = 1
    content_buffer: List[str] = []
    new_content = Content()

    for line in lines:
        header_match = re.match(r"^(#+)\s+(.+)$", line)

        if header_match:
            if len(content_buffer) > 0:
                new_content.add_content(
                    content="\n".join(content_buffer).strip(),
                    section_title=current_section,
                    section_level=current_head_level,
                )
                content_buffer = []

            current_head_level = len(header_match.group(1))
            current_section = header_match.group(2).strip()

            new_content.new_section(title=current_section, level=current_head_level)
        else:
            if line.strip() or len(content_buffer) > 0:
                content_buffer.append(line)

    if len(content_buffer) > 0:
        new_content.add_content(
            content="\n".join(content_buffer).strip(),
            section_title=current_section,
            section_level=current_head_level,
        )

    return new_content

clear_content

clear_content() -> None

Clears all Markdown content, leaving only the front matter.

Examples:

>>> doc = MarkdownDocument(content="# Hello World")
>>> doc.clear_content()
>>> print(doc.content)
""
Source code in ures/markdown/manipulator.py
587
588
589
590
591
592
593
594
595
596
597
def clear_content(self) -> None:
    """
    Clears all Markdown content, leaving only the front matter.

    Examples:
        >>> doc = MarkdownDocument(content="# Hello World")
        >>> doc.clear_content()
        >>> print(doc.content)
        ""
    """
    self.post.content = ""

clear_frontmatter

clear_frontmatter() -> None

Clears all front matter metadata, leaving only the Markdown content.

Examples:

>>> doc = MarkdownDocument(
...     content="# Hello World",
...     metadata={"title": "Greeting", "tags": ["intro", "welcome"]}
... )
>>> doc.clear_frontmatter()
>>> print(doc.metadata)
{}
Source code in ures/markdown/manipulator.py
599
600
601
602
603
604
605
606
607
608
609
610
611
612
def clear_frontmatter(self) -> None:
    """
    Clears all front matter metadata, leaving only the Markdown content.

    Examples:
        >>> doc = MarkdownDocument(
        ...     content="# Hello World",
        ...     metadata={"title": "Greeting", "tags": ["intro", "welcome"]}
        ... )
        >>> doc.clear_frontmatter()
        >>> print(doc.metadata)
        {}
    """
    self.post.metadata = {}

validation_frontmatter

validation_frontmatter()

Validate the frontmatter metadata against the mandatory fields.

Source code in ures/markdown/manipulator.py
614
615
616
617
618
619
620
621
622
623
624
625
def validation_frontmatter(self):
    """
    Validate the frontmatter metadata against the mandatory fields.
    """
    missing_fields = []
    for field in self.MANDATORY_FIELDS:
        if self.get_frontmatter(field) is None:
            missing_fields.append(field)

    if missing_fields:
        missing = ", ".join(missing_fields)
        raise ValueError(f"Missing mandatory front matter fields: {missing}")