From 5cf1896703ece4f825bfcdcdfade7bee67f4279a Mon Sep 17 00:00:00 2001 From: John Whitington Date: Thu, 27 Jun 2024 13:36:05 +0100 Subject: [PATCH] Add Jambon's tree printer --- Makefile | 2 +- cpdfprinttree.ml | 24 ++++++++++++++++++++++++ cpdfprinttree.mli | 5 +++++ 3 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 cpdfprinttree.ml create mode 100644 cpdfprinttree.mli diff --git a/Makefile b/Makefile index 5370b62..202c577 100644 --- a/Makefile +++ b/Makefile @@ -8,7 +8,7 @@ DOC = cpdfunicodedata cpdferror cpdfdebug cpdfjson cpdfstrftime cpdfcoord \ cpdfsqueeze cpdfdraft cpdfspot cpdfpagelabels cpdfcreate cpdfannot \ cpdfxobject cpdfimpose cpdfchop cpdftweak cpdftexttopdf cpdftoc \ cpdfjpeg cpdfjpeg2000 cpdfpng cpdfimage cpdfdraw cpdfcomposition \ - cpdfshape cpdfcolours cpdfdrawcontrol cpdfua cpdfcommand + cpdfshape cpdfcolours cpdfdrawcontrol cpdfprinttree cpdfua cpdfcommand MODS = $(NONDOC) $(DOC) diff --git a/cpdfprinttree.ml b/cpdfprinttree.ml new file mode 100644 index 0000000..ffd199d --- /dev/null +++ b/cpdfprinttree.ml @@ -0,0 +1,24 @@ +(* Courtesy Martin Jambon, in the public domain. *) +let rec titer f = function + | [] -> () + | [x] -> f true x + | x :: tl -> f false x; titer f tl + +let to_buffer ?(line_prefix = "") ~get_name ~get_children buf x = + let rec print_root indent x = + Printf.bprintf buf "%s\n" (get_name x); + let children = get_children x in + titer (print_child indent) children + and print_child indent is_last x = + let line = if is_last then "└── " else "├── " in + Printf.bprintf buf "%s%s" indent line; + let extra_indent = if is_last then " " else "│ " in + print_root (indent ^ extra_indent) x + in + Buffer.add_string buf line_prefix; + print_root line_prefix x + +let to_string ?line_prefix ~get_name ~get_children x = + let buf = Buffer.create 1000 in + to_buffer ?line_prefix ~get_name ~get_children buf x; + Buffer.contents buf diff --git a/cpdfprinttree.mli b/cpdfprinttree.mli new file mode 100644 index 0000000..fad421c --- /dev/null +++ b/cpdfprinttree.mli @@ -0,0 +1,5 @@ +(** Print trees *) + +val to_buffer : ?line_prefix: string -> get_name: ('a -> string) -> get_children: ('a -> 'a list) -> Buffer.t -> 'a -> unit + +val to_string : ?line_prefix: string -> get_name: ('a -> string) -> get_children: ('a -> 'a list) -> 'a -> string