/*

    Minimum Profit 5.x
    A Programmer's Text Editor

    Templates.

    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['insert_template']	 = sub(d) {

	local l, t;

	/* no local templates? do nothing */
	if ((l = mp.long_op(mp.read_templates_file)) == NULL)
		return;

	/* select one */
	if ((t = mp.form( [
		{ 'label'	=> L("Template to insert:"),
		  'type'	=> 'list',
		  'list'	=> l }
		])) == NULL)
		return;
	t = t[0];

	mp.store_undo(d);

	/* insert the template content */
	mp.insert(d, mp.templates[l[t]]);
};

/* default key bindings */

/* action descriptions */

mp.actdesc['insert_template']	= LL("Insert template...");

/* data */

mp.templates = {};

/* code */

sub mp.read_templates_file()
/* reads the $HOME/.mp_templates file into mp.templates */
{
	local f, l, k, v, n;

	/* doesn't exist? just return */
	if ((f = open(HOMEDIR ~ "/.mp_templates", "r")) == NULL)
		return NULL;

	k = NULL;
	v = NULL;
	n = [];

	/* reset */
	mp.templates = {};

	while (l = read(f)) {
		if (regex("/^%%/", l)) {
			/* new template: store previous, if any */
			if (k && v) {
				push(n, k);
				mp.templates[k] = v;
			}

			/* strip prefix */
			k = sregex("/^%%/", mp.chomp(l), NULL);
			v = NULL;
		}
		else {
			/* add to v */
			v = v ~ l;
		}
	}

	/* store last value */
	if (k && v) {
		push(n, k);
		mp.templates[k] = v;
	}

	close(f);

	/* returns keys(mp.templates), but in its original order */
	return n;
}
