"""
Make_Shortcuts_Reference.py - A Jython macro for jEdit that prints
a mapping of action names to shortcut bindings.

Ollie Rutherfurd <oliver@rutherfurd.net>

$Id: Make_Shortcuts_Reference.py 57 2003-11-03 21:35:03Z oliver $
"""

from org.gjt.sp.jedit import GUIUtilities
import math

def getShortcuts():

	actions = []

	# get labels and shortcuts for actions that have shortcuts
	for a in jEdit.getActions():
		name,label = a.getName(),a.getLabel()
		if not label: 
			label = name
		else:
			label = GUIUtilities.prettifyMenuLabel(label)
		shortcuts = filter(None,[jEdit.getProperty(name + '.shortcut' + x) for x in ('', '2')])
		if shortcuts:
			actions.append((label, ' or '.join(shortcuts),))

	# sort by label (case insensitive)
	actions.sort(lambda a,b: cmp(a[0].upper(), b[0].upper()))

	return actions

def shortcuts2text(actions):

	lines = []
	name_max = max([len(a[0]) for a in actions])
	shortcut_max = max([len(a[1]) for a in actions])
	half = int(math.ceil(len(actions) / 2.0))
	
	for i in range(half):
		# use '.' instead of space every other line, for readability
		space_char = ['.', '.'][i % 2]
		name,shortcuts = actions[i]
		line = name + ': ' + (name_max - len(name)) * space_char
		line += shortcuts + (shortcut_max - len(shortcuts)) * ' '
		try:
			name,shortcuts = actions[half+i]
			line += '   '
			line += name + ': ' + (name_max - len(name)) * space_char
			line += shortcuts + (shortcut_max - len(shortcuts)) * ' '
		except IndexError,e:
			pass
		lines.append(line)

	return '\n'.join(lines)

def makeShortcutsReference(v):
	actions = getShortcuts()
	ref = shortcuts2text(actions)

	title = 'jEdit Shortcuts Reference'
	pad = (len(ref.split('\n')[0]) - len(title))/2 * ' '
	title = pad + title
	ref = title + '\n\n' + ref

	jEdit.newFile(v)
	v.getTextArea().setSelectedText(ref)


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


