Is there a way to get the parent of an element, i.e. the element in which an element is in?
Use cases: when printing the traversal of the elements (show_level
) or when checking whether a Str
is in a ListItem
(str_in_listitem
). See my python example below.
If there is no parent
in Lua, how are those use cases implemented in a Lua filter?
from panflute import *
from panflute.utils import debug
def get_level(elem: Element, level=0):
if elem.parent is None:
return level
else:
return get_level(elem.parent, level=level + 1)
def is_ancestor_of(elem: Element, clazz: Element):
if elem.parent is not None:
if type(elem.parent) == clazz:
return True
else:
return is_ancestor_of(elem.parent, clazz)
else:
return False
def show_level(elem: Element, doc: Doc):
debug(" " * get_level(elem) + elem.tag)
def str_in_listitem(elem: Element, doc: Doc):
if type(elem) == Str:
if is_ancestor_of(elem, ListItem):
debug(stringify(elem))
if __name__ == "__main__":
run_filters([show_level, str_in_listitem])
Appying this filter to the following input:
[ Para [ Str "some" , Space , Str "text" ]
, BulletList
[ [ Plain [ Str "item1" ] ]
, [ Plain [ Str "item2" ]
, BulletList
[ [ Plain [ Str "subitemA" ] ]
, [ Plain [ Str "subitemB" ] ]
]
]
]
]
shows the following output for show_level
:
MetaMap
Str
Space
Str
Para
Str
Plain
ListItem
Str
Plain
Str
Plain
ListItem
Str
Plain
ListItem
BulletList
ListItem
BulletList
Doc
and the following for str_in_listitem
:
item1
item2
subitemA
subitemB