Skip to content

Commit

Permalink
add .body property for root node
Browse files Browse the repository at this point in the history
  • Loading branch information
karlicoss committed Nov 6, 2020
1 parent b64dd8f commit 3067189
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 32 deletions.
1 change: 1 addition & 0 deletions orgparse/__init__.py
Expand Up @@ -127,6 +127,7 @@ def load(path, env=None):
:rtype: :class:`orgparse.node.OrgRootNode`
"""
path = str(path) # in case of pathlib.Path
if isinstance(path, basestring):
orgfile = codecs.open(path, encoding='utf8')
filename = path
Expand Down
66 changes: 34 additions & 32 deletions orgparse/node.py
Expand Up @@ -353,6 +353,8 @@ class OrgBaseNode(Sequence):
5
"""

_body_lines: List[str] # set by the child classes

def __init__(self, env, index=None) -> None:
"""
Create an :class:`OrgBaseNode` object.
Expand Down Expand Up @@ -703,6 +705,30 @@ def shallow_tags(self) -> Set[str]:
"""
return self._get_tags(inher=False)

@staticmethod
def _get_text(text, format='plain'):
if format == 'plain':
return to_plain_text(text)
elif format == 'raw':
return text
else:
raise ValueError('format={0} is not supported.'.format(format))

def get_body(self, format='plain') -> str:
"""
Return a string of body text.
See also: :meth:`get_heading`.
"""
return self._get_text(
'\n'.join(self._body_lines), format) if self._lines else ''

@property
def body(self) -> str:
"""Alias of ``.get_body(format='plain')``."""
return self.get_body()

def is_root(self):
"""
Return ``True`` when it is a root node.
Expand Down Expand Up @@ -757,7 +783,11 @@ class OrgRootNode(OrgBaseNode):
"""

# getter
@property
def _body_lines(self) -> List[str]: # type: ignore[override]
# todo hacky..
# for root node, the body is whatever is before the first node
return self._lines

@property
def level(self):
Expand All @@ -766,8 +796,6 @@ def level(self):
def get_parent(self, max_level=None):
return None

# misc

def is_root(self):
return True

Expand Down Expand Up @@ -909,17 +937,6 @@ def _iparse_repeated_tasks(self, ilines: Iterator[str]) -> Iterator[str]:
\[ (?P<date> [^\]]+) \]''',
re.VERBOSE)

# getter

@staticmethod
def _get_text(text, format='plain'):
if format == 'plain':
return to_plain_text(text)
elif format == 'raw':
return text
else:
raise ValueError('format={0} is not supported.'.format(format))

def get_heading(self, format='plain'):
"""
Return a string of head text without tags and TODO keywords.
Expand All @@ -942,26 +959,11 @@ def get_heading(self, format='plain'):
"""
return self._get_text(self._heading, format)

def get_body(self, format='plain'):
"""
Return a string of body text.
See also: :meth:`get_heading`.
"""
return self._get_text(
'\n'.join(self._body_lines), format) if self._lines else ''

@property
def heading(self):
def heading(self) -> str:
"""Alias of ``.get_heading(format='plain')``."""
return self.get_heading()

@property
def body(self):
"""Alias of ``.get_body(format='plain')``."""
return self.get_body()

@property
def level(self):
return self._level
Expand Down Expand Up @@ -1022,7 +1024,7 @@ def todo(self) -> Optional[str]:
"""
return self._todo

def get_property(self, key, val=None):
def get_property(self, key, val=None) -> Optional[PropertyValue]:
"""
Return property named ``key`` if exists or ``val`` otherwise.
Expand All @@ -1036,7 +1038,7 @@ def get_property(self, key, val=None):
return self._properties.get(key, val)

@property
def properties(self):
def properties(self) -> Dict[str, PropertyValue]:
"""
Node properties as a dictionary.
Expand Down
12 changes: 12 additions & 0 deletions orgparse/tests/test_misc.py
Expand Up @@ -14,6 +14,18 @@ def test_empty_heading() -> None:
assert h.tags == {'sometag'}


def test_root() -> None:
root = loads('''
#+STARTUP: hidestars
Whatever
# comment
* heading 1
'''.strip())
assert len(root.children) == 1
# todo not sure if should strip special comments??
assert root.body.endswith('Whatever\n# comment')


def test_stars():
# https://github.com/karlicoss/orgparse/issues/7#issuecomment-533732660
root = loads("""
Expand Down

0 comments on commit 3067189

Please sign in to comment.