/*

    Minimum Profit 5.x
    A Programmer's Text Editor

    Macro recording (learning mode).

    Copyright (C) 1991-2007 Angel Ortega <angel@triptico.com>

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

    http://www.triptico.com

*/

/* editor actions */

mp.actions['record_macro']	= sub (d) { mp.record_macro(); };
mp.actions['play_macro']	= sub (d) { mp.play_macro(); };

/* default key bindings */

mp.keycodes['f10']	= "record_macro";
mp.keycodes['ctrl-f10']	= "record_macro";
mp.keycodes['f7']	= "play_macro";

/* action descriptions */

mp.actdesc['record_macro']	= LL("Record macro");
mp.actdesc['play_macro']	= LL("Play macro");

/* learning/recording data */

mp.macro = {};
mp.macro.process_event = NULL;
mp.macro.keycodes = NULL;

/* code */

sub mp.process_event_and_record(k)
/* patched version of mp.process_event() */
{
	/* records */
	push(mp.macro.keycodes, k);

	/* calls the real mp.process_event() function */
	mp.macro.process_event(k);
}


sub mp.record_macro
/* start recording a macro */
{
	if (mp.macro.process_event == NULL) {
		/* if still not recording, store the real mp.process_event()
		   function and replace it by ours */
		mp.macro.process_event = mp.process_event;
		mp.process_event = mp.process_event_and_record;

		/* reset keycode list */
		mp.macro.keycodes = [];
	}
	else {
		/* unpatch mp.process_event() */
		mp.process_event = mp.macro.process_event;
		mp.macro.process_event = NULL;

		/* drop the last keycode (that triggered mp.record_macro()) */
		if (mp.keycodes[mp.macro.keycodes[-1]] eq 'record_macro')
			pop(mp.macro.keycodes);
	}
}

sub mp.play_macro
/* play a macro */
{
	/* if it's recording, stop now */
	if (mp.macro.process_event != NULL)
		mp.record_macro();

	/* process all stored keycodes */
	foreach (k, mp.macro.keycodes)
		mp.process_event(k);
}
