/* -*- 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 <gdk/gdkkeysyms.h>

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

#define ENDTAG_STACK_SIZE    256


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 gint view_keypress_handler(GtkWidget *widget, GdkEventKey *event, gpointer data);


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 < buf+taglen+1)
	{
		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;

	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[ENDTAG_STACK_SIZE];

	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;

		/* ignore processing instructions and empty elements completely */
		if (element[strlen(element)-1] == '/' || element[0] == '?') {
			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 >= ENDTAG_STACK_SIZE)
				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 gint view_keypress_handler(GtkWidget *widget, GdkEventKey *event, gpointer data)
{
	GtkTextMark *search_start, *insert, *select;
	GtkTextIter cursor, prevpos, start, end;
	GtkTextView *view;
	GtkTextBuffer *buffer;
	int keep_search_start, inserted_gt;
	gint key, handled_event;
	char *buf, *element;

	handled_event = FALSE;
	key = event->keyval;

	view = GTK_TEXT_VIEW (widget);
	buffer = gtk_text_view_get_buffer (view);
	search_start = gtk_text_buffer_get_mark (buffer, "search_start");
	keep_search_start = 0;

	if (key == GDK_slash)
	{
		insert = gtk_text_buffer_get_mark (buffer, "insert");
		gtk_text_buffer_get_iter_at_mark (buffer, &cursor, insert);

		prevpos = cursor;
		gtk_text_iter_backward_char (&prevpos);
		buf = gtk_text_iter_get_visible_text (&prevpos, &cursor);

		if (g_utf8_get_char(buf) == '<')
		{
			gtk_text_iter_backward_char (&prevpos);
			element = find_endable_tag (buffer, &prevpos);
			if (element)
			{
				gtk_text_buffer_insert_at_cursor (buffer, "/", -1);
				gtk_text_buffer_begin_user_action (buffer);
				gtk_text_buffer_insert_at_cursor (buffer, element, -1);
				gtk_text_buffer_insert_at_cursor (buffer, ">", -1);
				gtk_text_buffer_end_user_action (buffer);
				g_free (element);
				handled_event = TRUE;
			}
		}
		g_free (buf);
	}
	else if (key == GDK_greater)
	{
		insert = gtk_text_buffer_get_mark (buffer, "insert");
		gtk_text_buffer_get_iter_at_mark (buffer, &cursor, insert);

		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 = cursor;
			gtk_text_iter_backward_char (&prevpos);
			buf = gtk_text_iter_get_visible_text (&prevpos, &cursor);
			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", &cursor, 1);
			g_free (buf);
		}

		if (search_start)
		{

			handled_event = TRUE;
			element = find_previous_end_tag(buffer, &prevpos);
			if (element)
			{
				/* start searching from where we found this element,
				   next time the user hits '>' */
				gtk_text_buffer_move_mark (buffer, search_start, &prevpos);

				select = gtk_text_buffer_get_mark (buffer, "selection_bound");

				gtk_text_buffer_begin_user_action (buffer);
				gtk_text_buffer_delete_selection (buffer, TRUE, TRUE);
				gtk_text_buffer_insert_at_cursor (buffer, element, -1);
				gtk_text_buffer_end_user_action (buffer);

				/* 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);

				/* 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);
				keep_search_start = 1;
			}
			else
			{
				/* no element found... if we're at the end of a cycle, delete
				   the last (selected) element found */
				gtk_text_buffer_delete_selection (buffer, TRUE, TRUE);

			}
		}

	}

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

	return(handled_event);
}


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

	doc = gedit_get_active_document ();
	if (!doc)
		return PLUGIN_OK;

	geditview = gedit_get_active_view ();
	if (!geditview)
		return PLUGIN_OK;

	view = gedit_view_get_gtk_text_view (GEDIT_VIEW (geditview));

	if ((lang = gtk_source_buffer_get_language (GTK_SOURCE_BUFFER (doc))) )
	{
		langname = gtk_source_language_get_name (lang);
		is_xml = !strcmp("XML", langname);
		g_free (langname);
		has_handler = g_signal_handler_find (view, G_SIGNAL_MATCH_FUNC, 0, 0, 0,
						     view_keypress_handler, NULL);

		/* only activate plugin on XML files */
		if (is_xml)
		{
			if (!has_handler)
				g_signal_connect (G_OBJECT (view), "key_press_event",
						  G_CALLBACK(view_keypress_handler), NULL);
		}
		else
		{
			if (has_handler)
				g_signal_handlers_disconnect_by_func(GTK_TEXT_BUFFER(doc),
								     G_CALLBACK(view_keypress_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; }

