phml.utilities.misc

phml.utilities.misc

Helpful utilities for different tasks that doesn't have a place in the other categories.

 1"""phml.utilities.misc
 2
 3Helpful utilities for different tasks that doesn't have a place in the other categories.
 4"""
 5
 6from phml.core.nodes import Element, Root
 7
 8from .classes import *
 9from .component import *
10from .heading import *
11from .inspect import *
12
13# __all__ = [
14#     "depth",
15#     "size",
16#     "heading_rank",
17#     "classnames",
18#     "ClassList",
19#     "inspect",
20#     "normalize_indent",
21# ]
22
23
24def depth(node) -> int:
25    """Get the depth in the tree for a given node.
26
27    -1 means that you passed in the tree itself and you are at the
28    ast's root.
29    """
30
31    level = -1
32    while node.parent is not None:
33        level += 1
34        node = node.parent
35
36    return level
37
38
39def size(node: Root | Element) -> int:
40    """Get the number of nodes recursively."""
41    from phml import walk  # pylint: disable=import-outside-toplevel
42
43    count = 0
44
45    for _ in walk(node):
46        count += 1
47
48    return count
49
50
51def offset(content: str | list[str]) -> int:
52    """Get the leading offset of the first line of the string."""
53    content = content.split("\n") if isinstance(content, str) else content
54    return len(content[0]) - len(content[0].lstrip())
def depth(node) -> int:
25def depth(node) -> int:
26    """Get the depth in the tree for a given node.
27
28    -1 means that you passed in the tree itself and you are at the
29    ast's root.
30    """
31
32    level = -1
33    while node.parent is not None:
34        level += 1
35        node = node.parent
36
37    return level

Get the depth in the tree for a given node.

-1 means that you passed in the tree itself and you are at the ast's root.

def size(node: phml.core.nodes.nodes.Root | phml.core.nodes.nodes.Element) -> int:
40def size(node: Root | Element) -> int:
41    """Get the number of nodes recursively."""
42    from phml import walk  # pylint: disable=import-outside-toplevel
43
44    count = 0
45
46    for _ in walk(node):
47        count += 1
48
49    return count

Get the number of nodes recursively.

def offset(content: str | list[str]) -> int:
52def offset(content: str | list[str]) -> int:
53    """Get the leading offset of the first line of the string."""
54    content = content.split("\n") if isinstance(content, str) else content
55    return len(content[0]) - len(content[0].lstrip())

Get the leading offset of the first line of the string.