1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/moinformat/parsers/pretty.py Fri Jun 30 00:40:39 2023 +0200
1.3 @@ -0,0 +1,78 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +Prettyprinted document tree parser.
1.8 +
1.9 +Copyright (C) 2017, 2018, 2019, 2023 Paul Boddie <paul@boddie.org.uk>
1.10 +
1.11 +This program is free software; you can redistribute it and/or modify it under
1.12 +the terms of the GNU General Public License as published by the Free Software
1.13 +Foundation; either version 3 of the License, or (at your option) any later
1.14 +version.
1.15 +
1.16 +This program is distributed in the hope that it will be useful, but WITHOUT
1.17 +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
1.18 +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
1.19 +details.
1.20 +
1.21 +You should have received a copy of the GNU General Public License along with
1.22 +this program. If not, see <http://www.gnu.org/licenses/>.
1.23 +"""
1.24 +
1.25 +from moinformat.tree.pretty import Node
1.26 +
1.27 +class PrettyParser:
1.28 +
1.29 + "A prettyprinted document tree parser."
1.30 +
1.31 + formats = ["pretty"]
1.32 +
1.33 + def __init__(self, metadata):
1.34 + self.metadata = metadata
1.35 +
1.36 + def parse(self, s):
1.37 +
1.38 + "Parse the tree structure representation in 's'."
1.39 +
1.40 + indent = 0
1.41 + branches = []
1.42 +
1.43 + for line in s.split("\n"):
1.44 + line = line.rstrip()
1.45 + if not line:
1.46 + continue
1.47 +
1.48 + new_indent = line.rfind(" ") + 1
1.49 + node = Node(line[new_indent:])
1.50 +
1.51 + # Establish a branch to add nodes to.
1.52 +
1.53 + if not branches:
1.54 + branches.append(node)
1.55 + else:
1.56 + # Note the current node as outermost branch.
1.57 +
1.58 + if new_indent > indent:
1.59 + branches.append(node)
1.60 + else:
1.61 + # Reduced indent involves obtaining an inner branch again.
1.62 +
1.63 + while indent > new_indent:
1.64 + del branches[-1]
1.65 + indent -= 2
1.66 +
1.67 + # Note the current node as outermost branch.
1.68 +
1.69 + branches[-1] = node
1.70 +
1.71 + # Append the current node to the parent branch.
1.72 +
1.73 + branches[-2].append(node)
1.74 +
1.75 + indent = new_indent
1.76 +
1.77 + return branches[0]
1.78 +
1.79 +parser = PrettyParser
1.80 +
1.81 +# vim: tabstop=4 expandtab shiftwidth=4