1 #!/usr/bin/env python 2 3 """ 4 Prettyprinted document tree parser. 5 6 Copyright (C) 2017, 2018, 2019, 2023 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from moinformat.tree.pretty import Node 23 24 class PrettyParser: 25 26 "A prettyprinted document tree parser." 27 28 formats = ["pretty"] 29 30 def __init__(self, metadata): 31 self.metadata = metadata 32 33 def parse(self, s): 34 35 "Parse the tree structure representation in 's'." 36 37 indent = 0 38 branches = [] 39 40 for line in s.split("\n"): 41 line = line.rstrip() 42 if not line: 43 continue 44 45 new_indent = line.rfind(" ") + 1 46 node = Node(line[new_indent:]) 47 48 # Establish a branch to add nodes to. 49 50 if not branches: 51 branches.append(node) 52 else: 53 # Note the current node as outermost branch. 54 55 if new_indent > indent: 56 branches.append(node) 57 else: 58 # Reduced indent involves obtaining an inner branch again. 59 60 while indent > new_indent: 61 del branches[-1] 62 indent -= 2 63 64 # Note the current node as outermost branch. 65 66 branches[-1] = node 67 68 # Append the current node to the parent branch. 69 70 branches[-2].append(node) 71 72 indent = new_indent 73 74 return branches[0] 75 76 parser = PrettyParser 77 78 # vim: tabstop=4 expandtab shiftwidth=4