Simplify parsing of CodeBlocks.

This commit is contained in:
Sergio Martínez Portela 2022-05-07 23:33:32 +02:00
parent afd02f55d4
commit 7a9cff57f9
2 changed files with 23 additions and 6 deletions

View File

@ -60,10 +60,10 @@ class BlockNode:
class CodeBlock(BlockNode): class CodeBlock(BlockNode):
def __init__(self, header): def __init__(self, header):
self.header = header self.header = header
self.lines = [] self.lines = None
def append(self, child): def set_lines(self, lines):
self.lines.append(child) self.lines = lines
def __repr__(self): def __repr__(self):
return "<Code: {}>".format(len(self.lines)) return "<Code: {}>".format(len(self.lines))

View File

@ -331,10 +331,22 @@ class Headline:
isinstance(line, DelimiterLine) isinstance(line, DelimiterLine)
and line.delimiter_type == DelimiterLineType.END_SRC and line.delimiter_type == DelimiterLineType.END_SRC
): ):
start = current_node.header.linenum
end = line.linenum
lines = self.get_lines_between(start + 1, end)
contents = "\n".join(lines)
if contents.endswith("\n"):
# This is not ideal, but to avoid having to do this maybe
# the content parsing must be re-thinked
contents = contents[:-1]
current_node.set_lines(contents)
tree.append(current_node) tree.append(current_node)
current_node = None current_node = None
else: else:
current_node.append(line) pass # Ignore
elif isinstance(line, Property): elif isinstance(line, Property):
if type(current_node) in NON_FINISHED_GROUPS: if type(current_node) in NON_FINISHED_GROUPS:
@ -407,7 +419,6 @@ class Headline:
): ):
assert type(current_node) in NON_FINISHED_GROUPS assert type(current_node) in NON_FINISHED_GROUPS
current_node = dom.CodeBlock(line) current_node = dom.CodeBlock(line)
current_node.append(current_node)
elif isinstance(line, Keyword): elif isinstance(line, Keyword):
logging.warning("Keywords not implemented on `as_dom()`") logging.warning("Keywords not implemented on `as_dom()`")
@ -583,7 +594,13 @@ class Headline:
def get_lines_between(self, start, end): def get_lines_between(self, start, end):
for line in self.contents: for line in self.contents:
if start <= line.linenum < end: if start <= line.linenum < end:
yield "".join(line.contents) text = []
for item in line.contents:
if isinstance(item, str):
text.append(item)
elif isinstance(item, MarkerType):
text.append(ModeToMarker[item])
yield "".join(text)
def get_contents(self, format): def get_contents(self, format):
if format == "raw": if format == "raw":