From 93f59493610cec80705e994ec5a17fdae5120163 Mon Sep 17 00:00:00 2001 From: Greenscreener Date: Tue, 20 Feb 2024 12:13:06 +0100 Subject: [PATCH] =?UTF-8?q?P=C5=99id=C3=A1na=20data=20na=20kontextu=20nez?= =?UTF-8?q?=C3=A1visl=C3=A1=20na=20docu.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/formatitko/context.py | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/src/formatitko/context.py b/src/formatitko/context.py index 11f0b94..0b885a3 100644 --- a/src/formatitko/context.py +++ b/src/formatitko/context.py @@ -23,6 +23,7 @@ CommandCallable = Callable[[Command, 'Context', 'NOPProcessor'], list[Element]] class Context: parent: Union["Context", None] _commands: dict[str, Union[CommandCallable, None]] + _data: dict[str, object] doc: Doc trusted: bool path: str @@ -34,6 +35,7 @@ class Context: def __init__(self, doc: Doc, path: str, parent: Union['Context', None]=None, trusted: bool=True): self.parent = parent self._commands = {} + self._data = {} self.doc = doc self.trusted = trusted self.path = path @@ -113,6 +115,40 @@ class Context: else: self.set_metadata(key, data) + def get_data(self, key: str, immediate: bool=False): + data = self._data + keys = key.split(".") + try: + for k in keys: + data = data[k] + return data + except KeyError: + if self.parent and not immediate: + return self.parent.get_data(key) + else: + return None + + def set_data(self, key: str, value: object): + data = self._data + keys = key.split(".") + for k in keys[:-1]: + try: + data = data[k] + except KeyError: + data[k] = {} + data = data[k] + data[keys[-1]] = value + + def unset_data(self, key: str): + if key == "": + self._doc = {} + data = self._doc + keys = key.split(".") + for k in keys[:-1]: + data = data[k] + del data[keys[-1]] + + # This is a custom element which creates \begingroup \endgroup groups in TeX