-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathfreeplane.py
executable file
·476 lines (390 loc) · 16.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
#!/usr/bin/python2.7
import os
import xml.etree.ElementTree
import itertools
import copy
import shutil
import datetime
import fnmatch
debug = True
################################################################
class mindmap_t(): # {{{
"""
.root = node_t()
"""
def __init__(self, mindmap_fpath):
self.fpath = mindmap_fpath
assert os.path.isfile(self.fpath), 'Error: cannot find mindmap file ' + self.fpath
self.tree = xml.etree.ElementTree.parse(self.fpath)
self.elem = self.tree.getroot()
assert self.elem.tag == 'map', self.elem.tag
n = self.elem.find('node')
assert n is not None
self.root = node_t(n, 0, None) # TODO: probably this will cause floating node cannot be parsed
self.ls_change = list()
def str(self):
s = ''
for n in iter(self.root):
indent = ' ' * n.level
s += indent + n.core.replace('\n', '\\n')
return s.encode('utf-8')
# }}}
class node_t(): # {{{
"""
.core = string
.details = string
.note = string
.attribute = dict
.style_ref = string
.link = string
.ls_icon = list(string)
.ls_sub = list(node_t)
.format = string
.id
.created
.modified
.level = int
.parent = node_t
"""
def __init__(self, elem, level, parent): # {{{
assert elem.tag == 'node', elem.tag
self.elem = elem
self.id = elem.get('ID', default='')
self.created = elem.get('CREATED', default='')
self.modified = elem.get('MODIFIED', default='')
self.level = level
self.parent = parent
self.style_ref = elem.get('STYLE_REF', default='')
self.link = elem.get('LINK', default='')
self.core = elem.get('TEXT', default='')
self.details = ''
self.note = ''
#-------------------------------------------------------
# process richcontent
for sub_elem_richcontent in elem.findall('richcontent'):
# process the html of richcontent, only support plain text style in <p> </p>
# TODO: support ul/ol
# TODO: support table
text = ''
for p in sub_elem_richcontent.iter(tag='p'):
text += p.text.strip() + '\n'
# different types of richcontent
type = sub_elem_richcontent.get('TYPE')
if (type == 'NODE'):
self.core = text
elif (type == 'DETAILS'):
self.details = text
elif (type == 'NOTE'):
self.note = text
else:
raise RuntimeError, 'Error: richcontent type (%s) is not recognized' % type
#-------------------------------------------------------
# process attribute
self.attribute = dict()
for sub_elem_attribute in elem.findall('attribute'):
self.attribute[sub_elem_attribute.get('NAME')] = sub_elem_attribute.get('VALUE')
#-------------------------------------------------------
# process icon
self.ls_icon = list()
for sub_elem_icon in elem.findall('icon'):
self.ls_icon.append(sub_elem_icon.get('BUILTIN'))
#-------------------------------------------------------
# process sub node
self.ls_sub = list()
for sub_elem_node in elem.findall('node'):
self.ls_sub.append(node_t(sub_elem_node, self.level+1, self))
#-------------------------------------------------------
# post-process
self.format = self.style_ref
# }}}
def __iter__(self):
yield self
for n in itertools.chain(*itertools.imap(iter, self.ls_sub)):
yield n
def __eq__(self, other):
return self.id == other.id
# }}}
################################################################
# blog mode
################################################################
blog_mode_footnote = '~~~\nThis Markdown file is generated by freeplane.py blog mode https://github.com/phdbreak/mindmap.py\n~~~'
def mindmap_to_blog(mindmap, do_cleanup=False):
#===========================================================
# cleanup previous markdown files
#===========================================================
# {{{
if do_cleanup:
print '\n## cleanup old markdown files created by freeplane.py blog mode'
dpath = os.path.dirname(mindmap.fpath)
for root, ls_dname, ls_fname in os.walk(dpath):
for fname in ls_fname:
if (fname.endswith('.md')):
# is Markdown file
fpath = os.path.join(root, fname)
with open(fpath, 'r') as f:
f.seek(-2 * len(blog_mode_footnote), os.SEEK_END)
last = f.read().strip()
if last.endswith(blog_mode_footnote):
# is generated, so remove the markdown file
print '### remove file ' + fpath
os.remove(fpath)
# }}}
#===========================================================
# find blog mode settings
#===========================================================
# {{{
print '\n## analyze blog mode settings'
setting_root = next(itertools.ifilter(lambda x: x.core.lower() == 'blog mode settings', mindmap.root.ls_sub), None)
assert (setting_root != None), 'Error: cannot find "blog mode settings" node'
#-------------------------------------------------------
# node type & link type
node_type = dict()
link_type = dict()
for node in itertools.islice(iter(setting_root), 1, None):
type_name = node.core.lower()
if (type_name == 'special nodes'):
continue
if (type_name == 'link file types'):
for (keyword, value) in node.attribute.items():
link_type[keyword] = value.split()
continue
try:
node_type[type_name].append(node)
except KeyError:
node_type[type_name] = [node]
print '### node type'
for (type_name, ls_node) in node_type.items():
s = '%s = ' % type_name
for node in ls_node:
s += node.format + '|'
print s.strip('|')
print '### link type'
for (type_name, ls_pattern) in link_type.items():
s = '%s = ' % type_name
for pattern in ls_pattern:
s += pattern + '|'
print s.strip('|')
#-------------------------------------------------------
# article's default meta-data
article_setting = next(itertools.ifilter(lambda n: n.core.lower() == 'article', setting_root), None)
assert article_setting != None, 'Error: cannot find "article" setting node'
default_metadata = dict()
for (key, value) in article_setting.attribute.items():
default_metadata[key.lower()] = value
print '### default meta-data'
for (key, value) in default_metadata.items():
print '%s = %s' % (key, value)
# }}}
#===========================================================
# set node type according to their format matching with blog mode settings
#===========================================================
# {{{
print '\n## match node format'
# node_type
for node in iter(mindmap.root):
node.type = ''
for (type_name, ls_node_setting) in node_type.items():
for node_setting in ls_node_setting:
if (node.format == node_setting.format):
node.type = type_name
break
if len(node.type) > 0:
break
if (node.type == ''):
if node.core.startswith('- '):
node.type = 'list'
if (node.parent.type != 'list'):
node.list_level = 1
else:
node.list_level = node.parent.list_level + 1
for node in iter(setting_root):
node.type = ''
mindmap.root.type = ''
# link_type
for node in itertools.ifilter(lambda n: len(n.link) > 0, mindmap.root):
node.link_type = ''
for (type_name, ls_link_type_pattern) in link_type.items():
for link_type_pattern in ls_link_type_pattern:
if (fnmatch.fnmatch(node.core, link_type_pattern)):
node.link_type = type_name
break
if len(node.link_type) > 0:
break
# }}}
#===========================================================
# analyze article
#===========================================================
# {{{
print '\n## analyze blog articles'
for node in itertools.ifilter(lambda n: n.type == 'article', mindmap.root):
print '\n### analyze article:\n' + node.core.encode('utf-8')
#-------------------------------------------------------
# article file path
dpath = os.path.dirname(mindmap.fpath)
if node.parent.type == 'directory':
directory = node.parent.core.replace(' ', '-').replace(':', '..')
dpath = os.path.join(dpath, directory)
#-------------------------------------------------------
# article meta-data
metadata = dict()
for (key, value) in node.attribute.items():
metadata[key.lower()] = value
metadata['title'] = node.core
metadata['category'] = directory.replace(' ', '-')
if ('slug' not in metadata.keys()):
metadata['slug'] = metadata['title'].lower().replace(' ', '-')
# set default meta-data
for (keyword, value) in default_metadata.items():
if keyword not in metadata.keys():
metadata[keyword] = value
if ('modified' not in metadata.keys()) or (metadata['modified'] == ''):
if ('created' in metadata.keys()):
metadata['modified'] = metadata['created']
if ('created' in metadata.keys()):
metadata['date'] = metadata['created']
fname = metadata['slug'] + '.md'
fpath = os.path.join(dpath, fname)
#-------------------------------------------------------
# write article
if not os.path.isdir(dpath):
os.mkdir(dpath)
# title
content = 'title: ' + metadata['title'] + '\n'
# meta-data
for (key, value) in metadata.items():
if (key == 'title'):
continue
content += '%s: %s\n' % (key, value)
content += '\n'
#-------------------------------------------------------
# sub node content {{{
for n in itertools.islice(iter(node), 1, None):
if n.type == 'skip':
continue
if n.type == 'comment':
map(lambda m: setattr(m, 'type', 'comment'), n.ls_sub)
continue
# deal with links
if len(n.link) > 0:
# solve relative link
if n.link.startswith('http://'):
# http link
link = n.link
else:
# local files
# copy local files to directory it supposed to be in: "<directory>/<slug>/", and modify the link in original mindmap file
exp_link = directory + '/' + metadata['slug'] + '/' + n.core.replace(' ', '_')
if (n.link != exp_link):
old_fpath = os.path.join(os.path.dirname(mindmap.fpath), n.link).replace(r'%20', r' ')
new_fpath = os.path.join(os.path.dirname(mindmap.fpath), exp_link)
if (os.path.dirname(n.link) == os.path.dirname(exp_link)):
# just filename is different, rename
print 'Info: file (%s) is renamed to (%s)' % (old_fpath, new_fpath)
os.rename(old_fpath, new_fpath)
else:
# copy
print 'Info: file (%s) is copied to (%s)' % (old_fpath, new_fpath)
if not os.path.isdir(os.path.dirname(new_fpath)):
os.mkdir(os.path.dirname(new_fpath))
shutil.copyfile(old_fpath, new_fpath)
# change the link
mindmap.is_changed = True
before = 'LINK="' + n.link + '"'
after = 'LINK="' + exp_link + '"'
mindmap.ls_change.append((before, after))
link = metadata['slug'] + '/' + n.core.replace(' ', '_')
if n.link_type == 'image':
content += '![%s](%s)\n' % (n.core, link)
else:
content += '[%s](%s)\n' % (n.core, link)
continue
# deal with special nodes
prefix = ''
suffix = ''
if n.type == 'section':
prefix = '# '
elif n.type == 'subsection':
prefix = '## '
elif n.type == 'subsubsection':
prefix = '### '
elif n.type == 'paragraph':
prefix = '#### '
elif n.type == 'subparagraph':
prefix = '##### '
elif n.type == 'code':
prefix = '~~~\n'
suffix = '\n~~~'
elif n.type == 'list':
prefix = ' ' * (n.list_level - 1)
suffix = ''
content += prefix + n.core + suffix + '\n'
if len(n.note) > 0:
content += '\n' + n.note + '\n'
# }}}
content += blog_mode_footnote
#-------------------------------------------------------
# write the markdown file {{{
f = open(fpath, 'w')
print >> f, content.encode('utf-8')
f.close()
print '### wrote to ' + fpath
# }}}
# }}}
#===========================================================
# modify original mindmap and backup
#===========================================================
# {{{
if len(mindmap.ls_change) == 0:
pass
else:
print '\n## change mindmap with backup'
# backup
prefix = datetime.datetime.now().strftime('%Y%m%d_%H%M%S.')
bak_fpath = os.path.join(os.path.dirname(mindmap.fpath), 'bak', prefix + os.path.basename(mindmap.fpath))
if not os.path.isdir(os.path.dirname(bak_fpath)):
os.mkdir(os.path.dirname(bak_fpath))
shutil.copyfile(mindmap.fpath, bak_fpath)
print '### mindmap file backup at %s' % bak_fpath
# replace mindmap
with open(mindmap.fpath, 'r') as f:
ls_lines = f.readlines()
for (before, after) in mindmap.ls_change:
print '### (%s) >> (%s)' % (before, after)
for (i, line) in enumerate(ls_lines):
ls_lines[i] = line.replace(before, after)
with open(mindmap.fpath, 'w') as f:
f.writelines(ls_lines)
# }}}
#===========================================================
# cleanup not used attachment dir
#===========================================================
# {{{
if (do_cleanup):
print '\n## cleanup not used attachment dir'
dpath = os.path.dirname(mindmap.fpath)
for root, ls_dname, ls_fname in os.walk(dpath):
# skip the first level
if (root == dpath) or (os.path.basename(root) == 'bak'):
continue
st_dname = set(ls_dname)
st_slug = set(map(lambda x: x[:-3], ls_fname))
st_not_used = st_dname - st_slug
for dname in st_not_used:
dpath = os.path.join(root, dname)
print '### remove dir ' + dpath
shutil.rmtree(dpath)
# }}}
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description='freeplane.py')
parser.add_argument('mindmap_file_path')
parser.add_argument('--blog_mode', action='store_true', default=False)
parser.add_argument('--blog_mode_cleanup', action='store_true', default=False)
args = parser.parse_args()
if (args.blog_mode):
print '# freeplane.py blog mode: START'
print 'input = %s' % args.mindmap_file_path
print ''
mindmap = mindmap_t(args.mindmap_file_path)
mindmap_to_blog(mindmap, do_cleanup=args.blog_mode_cleanup)
print '\n# freeplane.py blog mode: DONE'