#@+leo
#@+node:0::@file plugins/mod_at_folder.py
#@+body
"""synchronize @folder nodes with folders"""

from leoPlugins import *
from leoGlobals import *


#@<< about this plugin >>
#@+node:1::<< about this plugin >>
#@+body
#@+at
#  If a node is named '@folder path_to_folder', the content (filenames) of the 
# folder and the children of that node will be sync. Whenever a new file is 
# put there, a new node will appear on top of the children list (with mark). 
# So that I can put my description (ie. annotation) as the content
# of that node. In this way, I can find any files much easier from leo.
# 
# Moreover, I add another feature to allow you to group files(in leo) into
# children of another group. This will help when there are many files in that
# folder. You can logically group it in leo (or even clone it to many groups),
# while keep every files in a flat/single directory on your computer.

#@-at
#@-body
#@-node:1::<< about this plugin >>


#@+others
#@+node:2::sync_node_to_folder
#@+body
def sync_node_to_folder(parent,d):

	oldlist = {}
	newlist = []
	#get children info
	v = parent
	after_v = parent.nodeAfterTree()
	while v != after_v:
		if not v.hasChildren():
			oldlist[v.headString()] = v.bodyString()
		v = v.threadNext()
	#compare folder content to children
	for name in os.listdir(d):
		if name in oldlist:
			del oldlist[name]
		else:
			newlist.append(name)
	#insert newlist
	newlist.sort()
	newlist.reverse()
	for name in newlist:
		v = parent.insertAsNthChild(0)
		v.setHeadStringOrHeadline(name)
		v.setMarked()
	#warn for orphan oldlist
	if len(oldlist)>0:
		es('missing: '+','.join(oldlist.keys()))

#@-body
#@-node:2::sync_node_to_folder
#@-others


def onSelect (tag,keywords):
	v = keywords.get("new_v")
	h = v.headString()
	if match_word(h,0,"@folder"):
		sync_node_to_folder(v,h[8:])

if 1: # Register the handlers...
	registerHandler("select1", onSelect)

	import mod_at_folder
	es("...@folder v1.1: " + plugin_date(mod_at_folder))

#@-body
#@-node:0::@file plugins/mod_at_folder.py
#@-leo
