/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/*
 * xmlhelp.c
 *
 * Copyright (C) 2005 Bert Vermeulen
 *
 * 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. 
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <string.h> /* strlen() */
#include <stdlib.h> /* malloc() */

#include <glib/gutils.h>
#include <libgnome/gnome-i18n.h>

#include <gedit/gedit-menus.h>
#include <gedit/gedit-plugin.h>
#include <gedit/gedit-debug.h>

G_MODULE_EXPORT GeditPluginState update_ui (GeditPlugin *plugin, BonoboWindow *window);
G_MODULE_EXPORT GeditPluginState destroy (GeditPlugin *pd);
G_MODULE_EXPORT GeditPluginState activate (GeditPlugin *pd);
G_MODULE_EXPORT GeditPluginState deactivate (GeditPlugin *pd);
G_MODULE_EXPORT GeditPluginState init (GeditPlugin *pd);

static void buffer_insert_text_handler(GtkTextBuffer *buffer, GtkTextIter *position,
				       gchar *text, gint text_len, gpointer dummy);



static char *extract_element(char *tag)
{
	gunichar uc;
	int taglen;
	char *buf, *ubuf;

	taglen = strlen(tag);
	buf = g_malloc(taglen + 1);
	memcpy(buf, tag, taglen);
	buf[taglen] = 0;

	ubuf = buf;
	while(ubuf)
	{
		uc = g_utf8_get_char(ubuf);
		/* is this correct? this permits more whitespace chars than XML does... */
		if(g_unichar_isspace(uc) || uc == '>')
		{
			*ubuf = 0;
			break;
		}
		ubuf = g_utf8_next_char(ubuf);
	}

	return(buf);
}


/* find the previous end tag */
static char *find_previous_end_tag(GtkTextBuffer *buffer, GtkTextIter *position)
{
	GtkTextIter match, match_start;
	char *tag, *element;

	gedit_debug (DEBUG_PLUGINS, "");

	if (!gtk_text_iter_backward_search (position, "</", 0, &match, NULL, NULL))
		/* there is no tag anywhere before the cursor; nothing to do */
		return (NULL);

	match_start = match;
	gtk_text_iter_forward_chars (&match, 2);
	tag = gtk_text_iter_get_visible_text (&match, position);
	element = extract_element (tag);
	g_free (tag);

	*position = match_start;

	return (element);
}


/*
  find the innermost open tag
*/
static char *find_endable_tag(GtkTextBuffer *buffer, GtkTextIter *position)
{
	GtkTextIter start, prev_start, match;
	int endtag_stack_index;
	char *tag, *element, *endtag_stack[256];

	gedit_debug (DEBUG_PLUGINS, "");

	prev_start = *position;
	tag = element = NULL;
	endtag_stack_index = -1;
	while (1)
	{
		if (!gtk_text_iter_backward_search (&prev_start, "<", 0, &match, NULL, NULL))
	   		/* there is no tag anywhere before the cursor; nothing to do */
	   		break;

		/* free tag if used in the previous iteration of this loop */
		g_free (tag);

		start = match;
		gtk_text_iter_forward_char (&start);
		tag = gtk_text_iter_get_visible_text (&start, &prev_start);
		element = extract_element (tag);
		prev_start = match;

		if (element[strlen(element)-1] == '/') {
			/* ignore empty elements completely */
			g_free (element);
			element = NULL;
			continue;
		}

		if (element[0] == '/') {
			/* a closing tag... keep this for future reference */
			endtag_stack[++endtag_stack_index] = element;
			if (endtag_stack_index >= 256)
				break;
		}
		else {
			/* a proper open tag... but if we saw the closing tag for this,
			   pop the close and ignore the open */
			if (endtag_stack_index >= 0
			   && !strcmp (endtag_stack[endtag_stack_index]+1, element)) {
				g_free (endtag_stack[endtag_stack_index--]);
				g_free (element);
				element = NULL;
			}
			else {
				/* found an unclosed tag... this is the one */
				break;
			}

		}

	}

	g_free (tag);

	while (endtag_stack_index >= 0)
		g_free (endtag_stack[endtag_stack_index--]);

	return (element);
}


static void buffer_insert_text_handler(GtkTextBuffer *buffer, GtkTextIter *position,
				       gchar *text, gint text_len, gpointer dummy)
{
	GtkTextMark *search_start, *insert, *select;
	GtkTextIter prevpos, start, end;
	int keep_search_start, inserted_gt;
	char *buf, *element;

	if (text_len != 1)
		return;

	search_start = gtk_text_buffer_get_mark (buffer, "search_start");
	keep_search_start = 0;

	/* automatically fill in end tag when </ is entered */
	if (text[0] == '/')
	{
		prevpos = *position;
		gtk_text_iter_backward_char (&prevpos);
		buf = gtk_text_iter_get_visible_text (&prevpos, position);
		if (g_utf8_get_char(buf) == '<')
		{
			gtk_text_iter_backward_char(&prevpos);
			element = find_endable_tag(buffer, &prevpos);
			if (element)
			{
				g_signal_handlers_block_by_func(buffer, buffer_insert_text_handler, NULL);
				gtk_text_buffer_insert_at_cursor (buffer, "/", -1);
				gtk_text_buffer_insert_at_cursor (buffer, element, -1);
				gtk_text_buffer_insert_at_cursor (buffer, ">", -1);
				g_signal_handlers_unblock_by_func(buffer, buffer_insert_text_handler, NULL);
				g_free (element);
				g_signal_stop_emission_by_name (buffer, "insert-text");
			}
		}
		g_free (buf);
	}
	/* fill in new open tag when <> is entered */
	else if (text[0] == '>')
	{
		if(search_start)
		{
			/* last thing that happened in this buffer was this command...
			   so we're being asked to cycle through tags */
			gtk_text_buffer_get_iter_at_mark (buffer, &prevpos, search_start);
		}
		else
		{
			prevpos = *position;
			gtk_text_iter_backward_char (&prevpos);
			buf = gtk_text_iter_get_visible_text (&prevpos, position);
			if (g_utf8_get_char (buf) == '<')
				/* save this position, to start a new tag cycle with */
				search_start = gtk_text_buffer_create_mark(buffer, "search_start", position, 1);
			g_free (buf);
		}

		if (search_start)
		{
			g_signal_stop_emission_by_name (buffer, "insert-text");
			element = find_previous_end_tag(buffer, &prevpos);
			if (element)
			{
				/* start searching from here, next time the user hits '>' */
				gtk_text_buffer_move_mark (buffer, search_start, &prevpos);

				insert = gtk_text_buffer_get_mark (buffer, "insert");
				select = gtk_text_buffer_get_mark (buffer, "selection_bound");

				g_signal_handlers_block_by_func(buffer, buffer_insert_text_handler, NULL);
				gtk_text_buffer_insert_at_cursor (buffer, element, -1);

				/* only insert the > if there isn't one already there */
				gtk_text_buffer_get_iter_at_mark (buffer, &start, insert);
				end = start;
				gtk_text_iter_forward_char (&end);
				buf = gtk_text_iter_get_visible_text (&start, &end);
				if (g_utf8_get_char (buf) != '>') {
					gtk_text_buffer_insert_at_cursor (buffer, ">", -1);
					inserted_gt = 1;
				}
				else
					inserted_gt = 0;
				g_free (buf);

				g_signal_handlers_unblock_by_func(buffer, buffer_insert_text_handler, NULL);

				/* find cursor */
				gtk_text_buffer_get_iter_at_mark (buffer, &start, insert);
				end = start;

				/* go back over element, and select from there to cursor */
				gtk_text_iter_backward_chars (&start, strlen(element) + inserted_gt);
				gtk_text_buffer_move_mark (buffer, select, &start);

				if(inserted_gt)
				{
					/* skip the cursor back one place, so right arrow in the
					   selection ends up right after the > */
					start = end;
					gtk_text_iter_backward_char (&start);
					gtk_text_buffer_move_mark (buffer, insert, &start);
				}

				g_free (element);
				*position = end;
				keep_search_start = 1;
			}
		}

	}

	if (search_start && !keep_search_start)
		gtk_text_buffer_delete_mark (buffer, search_start);

}


G_MODULE_EXPORT GeditPluginState
update_ui (GeditPlugin *plugin, BonoboWindow *window)
{
	GeditDocument *doc;
	GtkSourceLanguage *lang;
	int is_xml, has_handler;
	
	g_return_val_if_fail (window != NULL, PLUGIN_ERROR);

	doc = gedit_get_active_document ();

	if (doc && (lang = gtk_source_buffer_get_language (GTK_SOURCE_BUFFER (doc))) )
	{
		is_xml = !strcmp("XML", gtk_source_language_get_name (lang));
		has_handler = g_signal_handler_find(doc,  G_SIGNAL_MATCH_FUNC, 0, 0, 0,
						    buffer_insert_text_handler, NULL);

		/* only activate plugin on XML files */
		if (is_xml)
		{
			if (!has_handler)
				g_signal_connect(GTK_TEXT_BUFFER(doc), "insert-text",
						 G_CALLBACK(buffer_insert_text_handler), NULL);
		}
		else
		{
			if (has_handler)
				g_signal_handlers_disconnect_by_func(GTK_TEXT_BUFFER(doc),
								     G_CALLBACK(buffer_insert_text_handler),
								     NULL);
		}
	}

	return PLUGIN_OK;
}


G_MODULE_EXPORT GeditPluginState    destroy (GeditPlugin *plugin) { return PLUGIN_OK; }
G_MODULE_EXPORT GeditPluginState   activate (GeditPlugin *plugin) { return PLUGIN_OK; }
G_MODULE_EXPORT GeditPluginState deactivate (GeditPlugin *plugin) { return PLUGIN_OK; }
G_MODULE_EXPORT GeditPluginState       init (GeditPlugin *plugin) { return PLUGIN_OK; }

