-
Notifications
You must be signed in to change notification settings - Fork 1
/
freeplane.py
2856 lines (1989 loc) · 72.4 KB
/
freeplane.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#
# DESCRIPTION
#
# a library holding useful and object-oriented functionalities to interface with
# a (freeplane) mindmap. using this library, information can easily be extracted
# and used in a programmatical way without having to browse through the mindmap
# itself.
#
#
# internally, the following object model is used, where the symbols follow this
# definition:
#
# M Mindmap object - holding general map information
# R root Node object - the first user-accessible Node within a mindmap
# N Node object - any Node attached to a mindmap
# B Branch object - a separate information structure organizing detached elements
# DH Detached Head object - the head of a detached branch
# DN Detached Node object - any branch node below a detached head
# XMLNODE object - an lxml node element representing a real node in Freeplane
#
#
# _path
# _type .---------------------------- . _map .-----------.
# _version | . _node ------------->| XMLNODE |
# _mindmap | . _branch ---| '-----------'
# _root | ^
# _parentmap | | |
# v | |
# | .---. .----. .----. .----. .--------. |
# '----------- | M | | R +-+-+ N +-+ N +-+ N +- ... |
# '---' '----' | '----' '----' '--------' |
# ^ | |
# | | .----. .----. |
# | '-+ N +-+ N +- ... |
# | '----' '----' |--- . _map |
# | . _node ---'
# | .------------------------------------------ . _branch
# _map -------' |
# _parentmap | |
# v |
# | .---. .----. .----. .----. .----. .----. .-------.
# '----------- | B | | DH +-+-+ DN +-+ DN +-+ DN +-+ DN +-+ DN +- ...
# '---' '----' | '----' '----' '----' '----' '-------'
# |
# | .----. .----.
# '-+ DN +-+ DN +- ...
# '----' '----'
#
#
# AUTHOR
#
# - nnako, started in 2016
#
# generals
from __future__ import print_function
import argparse
import datetime
import os
import re
import sys
import io
import logging
# xml format
try:
import lxml.etree as ET
except:
print("at this point, lxml package is not available. shouldn't be a problem, though.")
# html format
try:
import html2text
except:
print("at this point, html2text package is not available. shouldn't be a problem, though.")
# version
__version__ = '0.8.0'
# BUILTIN ICONS
ICON_EXCLAMATION = 'yes'
ICON_LIST = 'list'
ICON_QUESTION = 'help'
ICON_CHECKED = 'button_ok'
ICON_BOOKMARK = 'bookmark'
ICON_PRIO1 = 'full-1'
ICON_PRIO2 = 'full-2'
# logging
logging.basicConfig(
format='%(name)s - %(levelname)-8s - %(message)s',
level=logging.WARNING,
)
# MINDMAP
class Mindmap(object):
"""
representation of Freeplane mindmap file as a container for nodes. access
styles and other general features from here.
"""
# number of available map objects this session
_num_of_maps = 0
# global node id per session and incremented
# each time a node is created will be used to
# increment a session date. this gives 10000
# possible new nodes before the id string is
# added another digit (initially 10 digits).
_global_node_id_incr = 0
_global_node_id_seed = datetime.datetime.now().strftime('%y%m%d')
def __init__(self,
path='',
mtype='freeplane',
version='1.3.0',
id='',
log_level="warning",
):
#
# adjust logging level to user's wishes
#
if log_level.lower() == "debug":
logging.getLogger().setLevel(logging.DEBUG)
elif log_level.lower() == "info":
logging.getLogger().setLevel(logging.INFO)
elif log_level.lower() == "warning":
logging.getLogger().setLevel(logging.WARNING)
elif log_level.lower() == "error":
logging.getLogger().setLevel(logging.ERROR)
else:
logging.getLogger().setLevel(logging.WARNING)
logging.warning("log level mismatch in user arguments. setting to WARNING.")
#
# check for command line arguments
#
# do this only if called from the command line
if id == 'cli':
# define information
parser = argparse.ArgumentParser(
description='Operation on Freeplane mindmap',
usage='''%s <command> [<args>]
Possible commands are:
getText return text portion of a node
test test this library
... ...''' % os.path.basename(sys.argv[0]))
# define command argument
parser.add_argument(
'command',
help='Subcommand to run'
)
#
# read out CLI and execute main command
#
# get main arguments from user
args = parser.parse_args(sys.argv[1:2])
# check if command is provided in script
if not hasattr(self, args.command):
logging.error('Unrecognized command. EXITING.')
parser.print_help()
sys.exit(1)
# use dispatch pattern to invoke method with same name
getattr(self, args.command)()
#
# update class variables
#
Mindmap._num_of_maps += 1
#
# access instance variables
#
# path of instance's mindmap file
self._path = path
# type, version
self._type = mtype
#
# read mindmap in case path is given
#
# when a file name was given as CLI argument, it will be checked if an
# appropriate file is present. if so, the mindmap will be loaded into
# memory.
# check for validity of file
if os.path.isfile(self._path):
#
# determine file's map version
#
# before load of the actual mindmap into memory, the file version
# is to be determined. this is due to the fact that the character
# encoding of older freeplane files was not stable. so, detecting
# the encoding before load prevents some encoding errors.
# open mindmap file and read first row
retry = False
try:
with io.open(self._path, "r", encoding="utf-8") as fpMap:
strFirstLine = fpMap.readline()
except:
logging.warning("format mismatch in mindmap file vs. UTF-8")
retry = True
# in case there are wrong encodings when trying to read as UTF-8,
# it is tried to use Window's native encoding scheme to read the
# file. this will be most likely the case and might be a good
# workaround
if retry:
try:
with io.open(self._path, "r", encoding="windows-1252") as fpMap:
strFirstLine = fpMap.readline()
except:
logging.warning("format mismatch in mindmap file vs. windows-1252")
# now, analyze the characters in the first line of the mindmap file
# and try to find the "freeplane" token which will contain the
# version information.
# detect from '<map version="freeplane 1.3.0">'
idxFpToken = strFirstLine.find("freeplane")
idxSpace = strFirstLine[idxFpToken:].find(" ") + idxFpToken
idxVer = idxSpace+1
idxClQuote = strFirstLine[idxVer:].find('"') + idxVer
self._version = strFirstLine[idxVer:idxClQuote]
#
# set parser encoding due to map version
#
# now use the freeplane file version to determine the encoding.
# check for fitting encoding
encoding = get_version_specific_file_encoding(self._version)
# set encoding to be read
xmlparser = ET.XMLParser(encoding=encoding)
# xmlparser = ET.XMLParser(encoding="latin1")
# xmlparser = ET.XMLParser(encoding="utf-8")
#
# read entire mindmap and evaluate structure
#
# some Freeplane versions produce invalid XML syntax when writing
# the mindmap into file. here, these invalid syntaxes are to be
# removed from the file, before using and parsing the file.
try:
self._mindmap = ET.parse(self._path, parser=xmlparser)
except ET.XMLSyntaxError:
logging.warning("invalid XML syntax. will try to fix it temporarily...")
# write sanitized file into temporary file
_basename = "_" + os.path.basename(self._path)
_dirname = os.path.dirname(self._path)
# ensure temp file is not yet present
while os.path.isfile(os.path.join(_dirname, _basename)):
_basename = "_" + _basename
_temp_file = os.path.join(_dirname, _basename)
# read original XML file
with io.open(self._path, "r", encoding="utf-8") as _file:
_content = _file.read()
# sanitize content
_content = _content.replace(" ", " ")
# create and write temp file
with io.open(_temp_file, "w", encoding="utf-8") as _file:
_file.write(_content)
# repeat open of mindmap
self._mindmap = ET.parse(_temp_file, parser=xmlparser)
# remove temporary file
os.remove(_temp_file)
logging.info("... XML source was successfully sanitized.")
# now that the XML file has been read in in a valid way, the normal
# XML parsing is to take place within the module's functionalities.
# get root of mindmap
self._root = self._mindmap.getroot()
# find and get first node element of etree
self._rootnode = self._root.find('node')
# build parent map (using ElementTree nodes)
self._parentmap = {c:p for p in self._rootnode.iter() for c in p}
return
#
# create mindmap if path is invalid or empty
#
# if there was no path given or the path does not correspond to a valid
# file, a mindmap structure is created within memory. the basis is a
# XML structure containing a lot of standard settings identified within
# the normal freeplane files.
# set version
self._version = version
# init parentmap dictionary in order to facilitate quick identification
# of parent nodes of valid node objects (using ElementTree nodes as
# keys and values)
self._parentmap = {}
# create map element as XML node containing the version information
self._mindmap = ET.Element('map')
self._mindmap.attrib['version'] = 'freeplane ' + self._version
# get root of mindmap (necessary for save operation)
self._root = self._mindmap
# set some attributes for visibility within freeplane editor
_node = ET.Element('attribute_registry')
_node.attrib['SHOW_ATTRIBUTES'] = 'hide'
self._mindmap.append(_node)
# create 1st visible node element containing standard TEXT
self._rootnode = ET.Element('node')
self._rootnode.attrib["TEXT"] = "new_mindmap"
self._rootnode.attrib["FOLDED"] = "false"
self._rootnode.attrib["ID"] = Mindmap.create_node_id()
self._mindmap.append(self._rootnode)
# create some standard edge styles
_node = ET.Element('edge')
_node.attrib['STYLE'] = 'horizontal'
_node.attrib['COLOR'] = '#cccccc'
self._rootnode.append(_node)
#
# hook element and properties
#
_hook = ET.Element('hook')
_hook.attrib["NAME"] = "MapStyle"
_hook.attrib["zoom"] = "1.00"
self._rootnode.append(_hook)
# sub element properties
_node = ET.Element('properties')
_node.attrib["show_icon_for_attributes"] = "false"
_node.attrib["show_note_icons"] = "false"
_hook.append(_node)
#
# map styles
#
# sub element map styles
_mapstyles = ET.Element('map_styles')
_hook.append(_mapstyles)
# sub sub element stylenode
_stylenode = ET.Element('stylenode')
_stylenode.attrib["LOCALIZED_TEXT"] = "styles.root_node"
_mapstyles.append(_stylenode)
#
# predefined styles
#
# sub sub sub element stylenode
_node = ET.Element('stylenode')
_node.attrib["LOCALIZED_TEXT"] = "styles.predefined"
_node.attrib["POSITION"] = "right"
_stylenode.append(_node)
# sub sub sub element stylenode
_node2 = ET.Element('stylenode')
_node2.attrib["LOCALIZED_TEXT"] = "default"
_node2.attrib["MAX_WIDTH"] = "600"
_node2.attrib["COLOR"] = "#000000"
_node2.attrib["STYLE"] = "as_parent"
_node.append(_node2)
# sub sub sub sub element stylenode
_node3 = ET.Element('font')
_node3.attrib["NAME"] = "Segoe UI"
_node3.attrib["SIZE"] = "12"
_node3.attrib["BOLD"] = "false"
_node3.attrib["ITALIC"] = "false"
_node2.append(_node3)
# sub sub sub element stylenode
_node2 = ET.Element('stylenode')
_node2.attrib["LOCALIZED_TEXT"] = "defaultstyle.details"
_node.append(_node2)
# sub sub sub element stylenode
_node2 = ET.Element('stylenode')
_node2.attrib["LOCALIZED_TEXT"] = "defaultstyle.note"
_node.append(_node2)
# sub sub sub element stylenode
_node2 = ET.Element('stylenode')
_node2.attrib["LOCALIZED_TEXT"] = "defaultstyle.floating"
_node.append(_node2)
# sub sub sub sub element stylenode
_node3 = ET.Element('edge')
_node3.attrib["STYLE"] = "hide edge"
_node2.append(_node3)
# sub sub sub sub element stylenode
_node3 = ET.Element('cloud')
_node3.attrib["COLOR"] = "#0f0f0f"
_node3.attrib["SHAPE"] = "ROUND_RECT"
_node2.append(_node3)
#
# user styles
#
# sub sub sub element stylenode
_node = ET.Element('stylenode')
_node.attrib["LOCALIZED_TEXT"] = "styles.user-defined"
_node.attrib["POSITION"] = "right"
_stylenode.append(_node)
# sub sub sub element stylenode
_node2 = ET.Element('stylenode')
_node2.attrib["LOCALIZED_TEXT"] = "styles.topic"
_node2.attrib["COLOR"] = "#18898b"
_node2.attrib["STYLE"] = "fork"
_node.append(_node2)
# sub sub sub sub element stylenode
_node3 = ET.Element('font')
_node3.attrib["NAME"] = "Liberation Sans"
_node3.attrib["SIZE"] = "12"
_node3.attrib["BOLD"] = "true"
_node2.append(_node3)
# sub sub sub element stylenode
_node2 = ET.Element('stylenode')
_node2.attrib["LOCALIZED_TEXT"] = "styles.subtopic"
_node2.attrib["COLOR"] = "#cc3300"
_node2.attrib["STYLE"] = "fork"
_node.append(_node2)
# sub sub sub sub element stylenode
_node3 = ET.Element('font')
_node3.attrib["NAME"] = "Liberation Sans"
_node3.attrib["SIZE"] = "12"
_node3.attrib["BOLD"] = "true"
_node2.append(_node3)
# sub sub sub element stylenode
_node2 = ET.Element('stylenode')
_node2.attrib["LOCALIZED_TEXT"] = "styles.subsubtopic"
_node2.attrib["COLOR"] = "#669900"
_node.append(_node2)
# sub sub sub sub element stylenode
_node3 = ET.Element('font')
_node3.attrib["NAME"] = "Liberation Sans"
_node3.attrib["SIZE"] = "12"
_node3.attrib["BOLD"] = "true"
_node2.append(_node3)
# sub sub sub element stylenode
_node2 = ET.Element('stylenode')
_node2.attrib["LOCALIZED_TEXT"] = "styles.important"
_node.append(_node2)
# sub sub sub sub element stylenode
_node3 = ET.Element('icon')
_node3.attrib["BUILTIN"] = "yes"
_node2.append(_node3)
# MAP
@classmethod
def get_num_of_maps(cls):
"""
return the number of maps already created within the current session
:returns: integer
"""
return cls._num_of_maps
@classmethod
def create_node_id(cls, mindmap=None):
"""
create a valid node id. this node id is incremented automatically,
whenever a new XML node is created. even if it is discarded later.
the node id, here consists of three parts:
1. the id token "ID_" which is used for all nodes directly created
within freeplane editor
2. and kind of session seed which is the current date
3. and a standard 4-digit integer value constantly incremented
"""
# increment future part of node id
cls._global_node_id_incr += 1
# set the node id
_id = 'ID_' + \
cls._global_node_id_seed + \
'{:04}'.format(cls._global_node_id_incr)
#
# resolve overlapping ids
#
# check if the originally intended node id is already present within
# the mindmap. if it is, increment the node id counter, generate the
# node id again and check again. do this until a node id was found
# which does not yet exist within the mindmap.
# only if valid mindmap pointer was given
if mindmap is not None:
bLeave = False
while not bLeave:
# check for calculated id already used
lstOfNodesMatchingId = mindmap._root.xpath("//node[@ID='" + _id + "']")
if len(lstOfNodesMatchingId):
# increment global node id counter
cls._global_node_id_incr += 1
# set the node id string
_id = 'ID_' + \
cls._global_node_id_seed + \
'{:04}'.format(cls._global_node_id_incr)
else:
bLeave = True
# return new node id
return _id
@classmethod
def create_node(cls,
core='',
link='',
id='',
style='',
modified='', # timestamp format, milliseconds since 1.1.1970
created='', # timestamp format, milliseconds since 1.1.1970
):
#
# create and init element
#
# core
_node = ET.Element('node')
node = Node(_node, None)
node.plaintext = core
#
# set current creation and modification dates
#
update_date_attribute_in_node(
node=_node,
key="MODIFIED",
)
update_date_attribute_in_node(
node=_node,
key="CREATED",
)
# create temporary branch with local (empty) parent_map reference
node._branch = Branch()
# check own id choice
if id:
node.id = id
if not node.id == id:
# print("[ WARNING: node id must follow Freplane's format rules. nothing done. ]")
return None
# link
if link:
node.hyperlink = link
# style
if style:
logging.warning("style attribute not implemented, yet")
return node
@property
def rootnode(self):
return Node(self._rootnode, self)
@property
def styles(self):
_style = {}
_stylenode_user = self._mindmap.find('.//stylenode[@LOCALIZED_TEXT="styles.user-defined"]')
_lst = _stylenode_user.findall('./stylenode[@TEXT]')
for _sty in _lst:
_item = {}
# style name
_name = _sty.get('TEXT', '')
# foreground color
_color = _sty.get('COLOR', '')
if _color:
_item['color'] = _color
# background color
_bgcolor = _sty.get('BACKGROUND_COLOR', '')
if _bgcolor:
_item['bgcolor'] = _bgcolor
# font
_sty_sub = _sty.find('./font')
if _sty_sub is not None:
# font name
_fontname = _sty_sub.get('NAME', '')
_item['fontname'] = _fontname
# font size
_fontsize = _sty_sub.get('SIZE', '')
_item['fontsize'] = _fontsize
# ...
# add to dict
_style[_name] = _item
return _style
def add_style(self,
name='',
settings={},
):
"""
This functions adds a style to a mindmap
"""
#
# create new style within mindmap
#
if name:
#
# check validity of requests
#
# look for parent element
_stylenode_user = self._mindmap.find('.//stylenode[@LOCALIZED_TEXT="styles.user-defined"]')
# get list of existing style elements
_lst = _stylenode_user.findall('./stylenode[@TEXT]')
# leave function if style is already existing
for _sty in _lst:
if name.lower() == _sty.get('TEXT').lower():
print('[ WARNING: style "' + name + '" is already existing. ignoring request. ]')
return False
# create element
_sty = ET.Element("stylenode", TEXT=name)
# append element to list of styles
_stylenode_user.append(_sty)
#
# set attributes
#
# foreground color
_check = 'color'
if _check in settings.keys():
_sty.set('COLOR', settings[_check])
# background color
_check = 'bgcolor'
if _check in settings.keys():
_sty.set('BACKGROUND_COLOR', settings[_check])
# font name
_check = 'fontname'
if _check in settings.keys():
_item = ET.Element('font', NAME=settings[_check])
# add item to style
_sty.append(_item)
# font size
_check = 'fontsize'
if _check in settings.keys():
_item = _sty.find('./font')
if _item is None:
# create new font element
_item = ET.Element('font', SIZE=settings[_check])
_sty.append(_item)
else:
# add size attribute to font element
_item.set("SIZE", settings[_check])
return True
return False
def find_nodes(self,
core='',
link='',
id='',
attrib='',
details='',
notes='',
icon='',
exact=False
):
#
# find list of nodes in map
#
# start with ALL nodes within the mindmap and strip down to the number
# of nodes matching all given arguments
# list all nodes regardless of further properties
lstXmlNodes = self._root.findall(".//node")
# do the checks on the base of the list
lstXmlNodes = reduce_node_list(
lstXmlNodes=lstXmlNodes,
id=id,
core=core,
attrib=attrib,
details=details,
notes=notes,
link=link,
icon=icon,
exact=exact,
)
#
# create Node instances
#
lstNodesRet = []
for _node in lstXmlNodes:
# create reference to parent lxml node
#...
# apend to list
lstNodesRet.append(Node(_node, self))
return lstNodesRet
def save(self, strPath, encoding=''):
#
# auto-determine and set encoding
#
# check for fitting encoding
if not encoding:
encoding = get_version_specific_file_encoding(self._version)
#
# create XML formatted output string
#
# create output string
_outputstring = ET.tostring(
self._root,
pretty_print=True,
method='xml',
encoding=encoding,
).decode(encoding)
#
# sanitize string content
#
# prior to v1.8.0 the mindmap file was not a real XML and also not
# consequently encoded in a specific code format. rather the encoding
# is a mixture between "latin1" and "windows-1252". thus, in Germany,
# at least the german special characters must be corrected to be
# properly displayed within freeplane.
_version = self._version.split('.')
if int(_version[0]) == 1 and int(_version[1]) < 8:
# #160 characters representing <SPACE>
_outputstring = _outputstring.replace( chr(160),' ')
# at least substitute encoded german special characters
# with characters fitting to the UTF-8 HTML encoding
_outputstring = _outputstring.replace( 'ä','ä') # ä
_outputstring = _outputstring.replace( 'ö','ö') # ö
_outputstring = _outputstring.replace( 'ü','ü') # ü
_outputstring = _outputstring.replace( 'Ä','Ä')
_outputstring = _outputstring.replace( 'Ö','Ö')
_outputstring = _outputstring.replace( 'Ü','Ü')
_outputstring = _outputstring.replace( 'ß','ß')
# by copy/paste from other applications into the mindmap, there
# might be further character sequences not wanted within this file
# alternative double quotes
# _outputstring = _outputstring.replace( '“','"')
# _outputstring = _outputstring.replace( '„','"')
# three subsequent dots (e.g. from EXCEL's auto chars)
# _outputstring = _outputstring.replace( '…','...')
# _outputstring = _outputstring.replace( chr(0x2026);','...')
# _outputstring = _outputstring.replace( chr(133),'...')
#
# write content into file
#
# remove first line if not starting with "<map"
# as Freeplane doesn't use strict XML
if not _outputstring.startswith("<map"):
_outputstring = _outputstring.split('\n', 1)[1]
# open output file
_file = io.open(strPath, "w", encoding=encoding)
# write output string
_file.write( _outputstring )
# close file
_file.close()
def test(self):
# strExamplePath = "example__code2mm__v1_8_11.mm"
# strExamplePath = "example__code2mm__v1_3_15.mm"
# mm = Mindmap(strExamplePath)
# dicStyles = mm.Styles
# print(dicStyles)
# mm.save(strExamplePath[:strExamplePath.rfind('.')] + '__saved.mm')
# create new mindmap
mm=Mindmap()
# get and print root node
rn=mm.rootnode
print(rn)
# change root node plain text
rn.plaintext = "ROOT NODE"
print(rn)
#
# create some nodes and branches
#
# create detached node
detach=mm.create_node("DETACHED")
print(detach)
# create detached node
detach2=mm.create_node("DETACHED2")
print(detach2)
# add node into 2nd detached branch
nd2=detach2.add_child("ADDED_TO_DETACHED2_AS_CHILD")
print(nd2)
# create detached node
detach3=mm.create_node("DETACHED3")
print(detach3)
# add node into 2nd detached branch
nd3=detach3.add_child("ADDED_TO_DETACHED3_AS_CHILD")
print(nd3)
# check parent node within branch
print(nd2.parent)
#
# create and attach some styles
#
# add style to mindmap
mm.add_style(
"klein und grau",
{
'color': '#999999',
})