"""
Write_HyperSearch_Results.py - A Jython macro for jEdit which
writes the results of the most recent HyperSearch to a new buffer
formatted as grep-like output: buffer :line: text.

Copyright (C) 2002 Ollie Rutherfurd <oliver@rutherfurd.net>

$Id: Write_HyperSearch_Results.py 35 2003-04-03 19:13:26Z oliver $
"""

from org.gjt.sp.jedit import Macros

def writeMatches(view):
	hsearch = view.getDockableWindowManager().getDockableWindow('hypersearch-results')

	if hsearch is None:
		Macros.error(view, 'The "HyperSearch Results" window is not open.')
		return

	root = hsearch.getTreeModel().getRoot()
	if root is None:
		view.getStatus().setMessageAndClear('No HyperSearch matches.')
		return

	major,minor,rev = map(int, jEdit.getBuild().split('.'))[:-1]
	handle_multi_match = major >= 4 and (minor > 1 or (minor == 1 and rev >= 6))

	node = root.getFirstChild()
	if handle_multi_match:
		while node.getNextSibling():
			node = node.getNextSibling()
		node = node.getFirstChild()

	results = []

	while node:
		path = str(node.getUserObject())
		match = node.getFirstChild()
		#print dir(match.__class__)
		while match:
			#line = match.getUserObject().line
			text = match.getUserObject().str
			results.append('%s :%s' % (path, text))
			match = match.getNextSibling()
		node = node.getNextSibling()

	if results:
		jEdit.newFile(view)
		view.getTextArea().setText('\n'.join(results))


if __name__ in ('__main__','main'):
	writeMatches(init.view)

# :indentSize=4:lineSeparator=\n:noTabs=false:tabSize=4:

