/* vim: set encoding=utf8:
 *
 * shiki.c
 *
 * This file is main file of Shiki.
 *
 * Copyright(C)2006 WAKATSUKI toshihiro
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 * $Id: shiki.c,v 1.57 2006/11/27 12:01:50 aloha Exp $
 */

#include"shiki.h"

static gint editor_indent_width = 2;

/* エディタ全体に関する情報と，現在表示されているタブ情報へのキャッシュを管理する構造体 */
ShikiEditorType Shiki_editor;

static gchar *R5RS_keywords[]  = {"and", "begin", "case", "cond-expand", "cond", "define-accessor", "define-class", "defined?", "define-generic", "define", "define-macro", "define-method", "define-module", "define-private", "define-public", "define-reader-ctor", "define-syntax", "define-syntax-macro", "defmacro", "defmacro*-public", "delay", "do", "else", "fluid-let", "if", "lambda", "let", "let*", "letrec", "letrec-syntax", "let-syntax", "or", "quasiquote", "quote", "set!", "syntax-rules", "unquote", NULL};

static gchar *R5RS_functions[] = {"*", "+", "-", "/", "<", ">", "<=", ">=", "?", "`", "=", "abs", "acos", "angle", "append", "apply", "asin", "assoc", "assq", "assv", "atan", "boolean?", "caaar", "caadr", "caar", "cadar", "caddr", "cadr", "call/cc", "call-with-current-continuation", "call-with-input-file", "call-with-output-file", "call-with-values", "car", "catch", "cdaar", "cdadr", "cdar", "cddar", "cdddr", "cddr", "cdr", "ceiling", "char-alphabetic?", "char-ci>=?", "char-ci>?", "char-ci=?", "char-ci<=?", "char-ci<?", "char-downcase", "char->integer", "char>=?", "char>?", "char=?", "char?", "char-lower-case?", "char<=?", "char<?", "char-numeric?", "char-ready?", "char-upcase", "char-upper-case?", "char-whitespace?", "close-input-port", "close-output-port", "complex?", "cons", "cos", "current-input-port", "current-output-port", "delete-file", "display", "dynamic-wind", "eof-object?", "eq?", "equal?", "eqv?", "eval", "even?", "exact->inexact", "exact?", "exit", "exp", "expt", "file-exists?", "file-or-directory-modify-seconds", "floor", "force", "for-each", "gcd", "gensym", "getenv", "get-output-string", "imag-part", "inexact?", "input-port?", "integer->char", "integer?", "lcm", "length", "list->string", "list->vector", "list", "list?", "list-ref", "list-tail", "load", "log", "magnitude", "make-polar", "make-rectangular", "make-string", "make-vector", "map", "max", "member", "memq", "memv", "min", "modulo", "negative?", "newline", "nil", "not", "null?", "number->string", "number?", "odd?", "open-input-file", "open-input-string", "open-output-file", "open-output-string", "output-port?", "pair?", "peek-char", "port?", "positive?", "procedure?", "quotient", "rational?", "read-char", "read", "read-line", "real?", "real-part", "remainder", "reverse", "reverse!", "round", "set-car!", "set-cdr!", "sin", "sqrt", "string-append", "string-ci>=?", "string-ci>?", "string-ci=?", "string-ci<=?", "string-ci<?", "string-copy", "string-fill!", "string>=?", "string>?",  "string->list", "string->number", "string->symbol", "string", "string=?", "string?", "string-length", "string<=?", "string<?", "string-ref", "string-set!", "substring", "symbol->string", "symbol?", "system", "tan", "truncate", "values", "vector-fill!", "vector->list", "vector", "vector?", "vector-length", "vector-ref", "vector-set!", "with-input-from-file", "with-output-to-file", "write-char", "write", "zero", NULL};

static GHashTable *keywords_hash = NULL;

typedef enum {
  R5RS_KEYWORD_COLOR = 1,
  R5RS_FUNCTION_COLOR,
  GAUCHE_KEYWORD_COLOR,
  GAUCHE_FUNCTION_COLOR
} HIGHILIGHT_COLOR; 

GdkColor COLOR_BLACK;
GdkColor COLOR_GREEN;

/* プロトタイプ */

/* タブの生成と削除 : 基本的に，ShikiBuffer の中身に格納する情報を増やしたかったら，この 2 つの関数だけを変更すれば良い (ようにする…) */
extern void Scm_Init_xyzzylisp(ScmModule *module);
static void remove_tabpage();

/* foo_bar_handler() は，イベントハンドラのためのラッパー */
static void append_default_tabpage_handler();

/* ファイル関係 */
static void open_file(const gchar *filename);
static void open_file_handler();
static void save_file();
static void save_file_as();

/* テキストバッファ関係 */
static gchar* get_all_buffer_contents(GtkTextBuffer *buffer);
static gboolean save_text_buffer(const gchar *filename, GtkTextBuffer *buffer);
static void clear_current_buffer_handler();
static void undo();
static void search_current_buffer();
static void insert_text_handler(GtkTextBuffer *buffer, GtkTextIter *p, gchar *str, gint len);
static void delete_range_handler(GtkTextBuffer *buffer, GtkTextIter *start, GtkTextIter *end);

/* モードライン */
static void update_modeline_label();
static void text_buffer_cursor_moved_handler();

/* 確認 */
static gboolean not_yet_save_changes_really_quit(GtkTextBuffer *buffer);
static gboolean delete_event_handler(GtkWidget *widget, GdkEvent *event, GtkTextBuffer *buffer);

/* Gauche と S 式操作やインデント・キーワードハイライティング関連 */
static gchar *eval_cstring_by_gauche(gchar *s);
static gchar *load_cstring_by_gauche(gchar *s);
static void load_buffer_by_gauche();
static void load_region_by_gauche();
static void load_scheme_file_by_gauche();
static gboolean is_kakko_or_kokka(gunichar ch, gpointer); 
static gboolean is_kakko(gunichar ch, gpointer);
static gboolean is_kokka(gunichar ch, gpointer);
static gboolean search_sexp(GtkTextIter *start, GtkTextIter *end);
static gboolean search_sexp_kokka(GtkTextIter *end);
static gboolean search_last_sexp(GtkTextIter *start, GtkTextIter *end);
static gboolean search_last_sexp_kakko(GtkTextIter *start);
static gint get_parent_nest_level_at_cursor(GtkTextBuffer *buffer);
static gboolean is_not_scheme_delimita_p(gunichar ch, gpointer user_data);
static gboolean is_double_quote(gunichar ch, gpointer user_data);
static gboolean is_scheme_delimita_p(gunichar ch, gpointer user_data);
static void scheme_keyword_highlighting_current_buffer();

/* 設定 */
static void select_font();
static void font_selection_ok(GtkWidget *button, GtkWidget *font_dialog);
static void switch_tabpage_handler(GtkNotebook *notebook, GtkNotebookPage *page, guint pagenum) ;
static void tabsborder_on_off(GtkButton *button, GtkNotebook *notebook);
static void rotate_tab_position(GtkButton *button, GtkNotebook *notebook);

/* キーバインド全般 */
static gboolean signal_key_press_handler(GtkWidget *notebook, GdkEventKey *event, gpointer contextid);
static gboolean signal_key_release_handler(GtkWidget *notebook, GdkEventKey *event, gpointer contextid);

/* ヘルプや情報 */
static void open_online_help();
static void about_this_application();

/* エディタの初期化 */
static void Shiki_editor_window_init(int argc, char **argv);

/* バッファの内容を消去 */
static void clear_current_buffer_handler() {
  Shiki_erase_buffer(Shiki_CURRENT_TEXT_BUFFER);
}

static void destroy_handler(GtkWidget *button, GtkWidget *widget) {gtk_widget_destroy(widget);}

static void toggled_handler(GtkToggleButton *togglebutton, gboolean *flag) {
  *flag = !*flag;
}

static void replace_current_buffer() {
  GtkWidget *dialog = gtk_dialog_new_with_buttons ("文字列の置換", GTK_WINDOW(Shiki_EDITOR_WINDOW), GTK_DIALOG_DESTROY_WITH_PARENT, NULL);
  GtkWidget *table       = gtk_table_new(7, 3, FALSE);
  GtkWidget *find_label  = gtk_label_new("検索 : ");
  GtkWidget *find        = gtk_entry_new(); 
  GtkWidget *rep_label   = gtk_label_new("置換 : ");
  GtkWidget *replace     = gtk_entry_new();
  GtkWidget *check1      = gtk_check_button_new_with_label("大文字小文字を区別する");
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check1), TRUE);
  GtkWidget *check2 = gtk_check_button_new_with_label("単語単位で検索する");
  GtkWidget *check3 = gtk_check_button_new_with_label("正規表現");
  GtkWidget *check4 = gtk_check_button_new_with_label("エスケープシーケンスを理解する");
  GtkWidget *check5 = gtk_check_button_new_with_label("バッファの先頭から");
  GtkWidget *interactive   = gtk_button_new_with_label ("確認あり");
  GtkWidget *all   = gtk_button_new_with_label ("全て置換");
  GtkWidget *cancel = gtk_button_new_with_label ("キャンセル");
  gboolean f1 = TRUE, f2, f3, f4, f5;
  f2 = f3 = f4 = f5 = FALSE;
  g_signal_connect (check1, "toggled", G_CALLBACK (toggled_handler), &f1);
  g_signal_connect (check2, "toggled", G_CALLBACK (toggled_handler), &f2);
  g_signal_connect (check3, "toggled", G_CALLBACK (toggled_handler), &f3);
  g_signal_connect (check4, "toggled", G_CALLBACK (toggled_handler), &f4);
  g_signal_connect (check5, "toggled", G_CALLBACK (toggled_handler), &f5);

  g_signal_connect (G_OBJECT(dialog), "delete_event", G_CALLBACK(gtk_widget_destroy), NULL);
  g_signal_connect (G_OBJECT(cancel), "clicked", G_CALLBACK(destroy_handler), dialog);
  gtk_table_set_row_spacings(GTK_TABLE(table), 10);
  gtk_table_set_col_spacings(GTK_TABLE(table), 10);
  gtk_container_border_width (GTK_CONTAINER (dialog), 10);

  gtk_table_attach_defaults (GTK_TABLE(table), find_label,  0, 1, 0, 1);
  gtk_table_attach_defaults (GTK_TABLE(table), find,        1, 2, 0, 1);
  gtk_table_attach_defaults (GTK_TABLE(table), interactive, 2, 3, 0, 1);

  gtk_table_attach_defaults (GTK_TABLE(table), rep_label,   0, 1, 1, 2);
  gtk_table_attach_defaults (GTK_TABLE(table), replace,     1, 2, 1, 2);
  gtk_table_attach_defaults (GTK_TABLE(table), all,         2, 3, 1, 2);

  gtk_table_attach_defaults (GTK_TABLE(table), check1, 1, 2, 2, 3);
  gtk_table_attach_defaults (GTK_TABLE(table), cancel, 2, 3, 2, 3);
  
  gtk_table_attach_defaults (GTK_TABLE(table), check2, 1, 2, 3, 4);
  gtk_table_attach_defaults (GTK_TABLE(table), check3, 1, 2, 4, 5);
  gtk_table_attach_defaults (GTK_TABLE(table), check4, 1, 2, 5, 6);
  gtk_table_attach_defaults (GTK_TABLE(table), check5, 1, 2, 6, 7);

  gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), table);
  gtk_widget_show_all(table);
  gtk_dialog_run(GTK_DIALOG(dialog));
}

static void search_current_buffer() {
  GtkWidget *dialog = gtk_dialog_new_with_buttons ("文字列の検索", GTK_WINDOW(Shiki_EDITOR_WINDOW), GTK_DIALOG_DESTROY_WITH_PARENT, NULL);
  GtkWidget *table  = gtk_table_new(6, 3, FALSE);
  GtkWidget *label  = gtk_label_new("検索 : ");
  GtkWidget *input  = gtk_entry_new();
  GtkWidget *check1 = gtk_check_button_new_with_label("大文字小文字を区別する");
  gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check1), TRUE);
  GtkWidget *check2 = gtk_check_button_new_with_label("単語単位で検索する");
  GtkWidget *check3 = gtk_check_button_new_with_label("正規表現");
  GtkWidget *check4 = gtk_check_button_new_with_label("エスケープシーケンスを理解する");
  GtkWidget *check5 = gtk_check_button_new_with_label("見つからなければ戻って");
  GtkWidget *prev   = gtk_button_new_with_label ("上検索");
  GtkWidget *next   = gtk_button_new_with_label ("下検索");
  GtkWidget *cancel = gtk_button_new_with_label ("キャンセル");
  gboolean f1 = TRUE, f2, f3, f4, f5;
  f2 = f3 = f4 = f5 = FALSE;
  g_signal_connect (check1, "toggled", G_CALLBACK (toggled_handler), &f1);
  g_signal_connect (check2, "toggled", G_CALLBACK (toggled_handler), &f2);
  g_signal_connect (check3, "toggled", G_CALLBACK (toggled_handler), &f3);
  g_signal_connect (check4, "toggled", G_CALLBACK (toggled_handler), &f4);
  g_signal_connect (check5, "toggled", G_CALLBACK (toggled_handler), &f5);

  g_signal_connect (G_OBJECT(dialog), "delete_event", G_CALLBACK(gtk_widget_destroy), NULL);
  g_signal_connect (G_OBJECT(cancel), "clicked", G_CALLBACK(destroy_handler), dialog);
  gtk_table_set_row_spacings(GTK_TABLE(table), 10);
  gtk_table_set_col_spacings(GTK_TABLE(table), 10);
  gtk_container_border_width (GTK_CONTAINER (dialog), 10);
  gtk_table_attach_defaults (GTK_TABLE(table), label,  0, 1, 0, 1);
  gtk_table_attach_defaults (GTK_TABLE(table), input,  1, 2, 0, 1);
  gtk_table_attach_defaults (GTK_TABLE(table), prev,   2, 3, 0, 1);
  gtk_table_attach_defaults (GTK_TABLE(table), check1, 1, 2, 1, 2);
  gtk_table_attach_defaults (GTK_TABLE(table), check2, 1, 2, 2, 3);
  gtk_table_attach_defaults (GTK_TABLE(table), check3, 1, 2, 3, 4);
  gtk_table_attach_defaults (GTK_TABLE(table), check4, 1, 2, 4, 5);
  gtk_table_attach_defaults (GTK_TABLE(table), check5, 1, 2, 5, 6);
  gtk_table_attach_defaults (GTK_TABLE(table), next,   2, 3, 1, 2);
  gtk_table_attach_defaults (GTK_TABLE(table), cancel, 2, 3, 2, 3);
  gtk_container_add(GTK_CONTAINER(GTK_DIALOG(dialog)->vbox), table);
  gtk_widget_show_all(table);
  gtk_dialog_run(GTK_DIALOG(dialog));
}

static gboolean is_not_scheme_delimita_p(gunichar ch, gpointer user_data) {
  return ch != '(' && ch != ')' &&  !g_unichar_isspace(ch);
}

static gboolean is_double_quote(gunichar ch, gpointer user_data) {
  return ch == '\"';
}

static gboolean is_scheme_delimita_p(gunichar ch, gpointer user_data) {
  return ch == ' ' || ch == '(' || ch == ')' || ch == '\"' || g_unichar_isspace(ch);
}

/* ソースコードの色分け */
static void scheme_keyword_highlighting_current_buffer() {
  GtkTextIter s, e;
  HIGHILIGHT_COLOR c;
  gchar *word;
  gboolean is_comment, is_string;
  gunichar ch;

  gtk_text_buffer_get_start_iter(Shiki_CURRENT_TEXT_BUFFER, &s);

  /* 簡単な Scheme レキシカルアナライザ */
  while(TRUE) {
    is_comment = FALSE;
    is_string = FALSE;
    if((ch = gtk_text_iter_get_char(&s)) != ';' && ch != '\"')
      gtk_text_iter_forward_find_char(&s, is_not_scheme_delimita_p, NULL, NULL);
    e = s;
    if(gtk_text_iter_get_char(&s) == ';') {
      gtk_text_iter_forward_line(&e);
      gtk_text_iter_backward_char(&e);
      is_comment = TRUE;
    } else if(gtk_text_iter_get_char(&s) == '\"') {
      while(TRUE) {
        gtk_text_iter_forward_find_char(&e, is_double_quote, NULL, NULL);
        gtk_text_iter_backward_char(&e);
        if(gtk_text_iter_get_char(&e) != '\\') {
          is_string = TRUE;
          gtk_text_iter_forward_char(&e);
          gtk_text_iter_forward_char(&e);
          break;
        }
        gtk_text_iter_forward_char(&e);
        gtk_text_iter_forward_char(&e);
      }

    } else
      gtk_text_iter_forward_find_char(&e, is_scheme_delimita_p, NULL, NULL);
    
    word = gtk_text_buffer_get_text(Shiki_CURRENT_TEXT_BUFFER, &s, &e, FALSE);

    /* 対応する色をそれぞれトークン部分につける */
    if(is_comment) /* コメント */
      gtk_text_buffer_apply_tag_by_name(Shiki_CURRENT_TEXT_BUFFER, "comment_highlighting", &s, &e);
    else if(is_string) /* 文字列 */
      gtk_text_buffer_apply_tag_by_name(Shiki_CURRENT_TEXT_BUFFER, "string_highlighting", &s, &e);    
    else if(R5RS_KEYWORD_COLOR == (c = GPOINTER_TO_INT(g_hash_table_lookup(keywords_hash, word)))) /* R5RS キーワード */
      gtk_text_buffer_apply_tag_by_name(Shiki_CURRENT_TEXT_BUFFER, "keyword_highlighting", &s, &e);
    else if(R5RS_FUNCTION_COLOR == c) /* R5RS 関数 */
      gtk_text_buffer_apply_tag_by_name(Shiki_CURRENT_TEXT_BUFFER, "function_highlighting", &s, &e);

    /* XXX : get_text() でいちいち文字列がアロケートされるから，非常に効率が悪いと思うけど… GtkTextBuffer から const gchar * が取れれば良いのに… */
    g_free(word); 

    if(gtk_text_iter_is_end(&e)) break;
    s = e;
  }
}

/* バッファにテキストが挿入された */
static void insert_text_handler(GtkTextBuffer *buffer, GtkTextIter *iter, gchar *str, gint len) {
  /* Undo のための情報を記録 */
  ShikiUndoInfo *undoInfo = g_malloc(sizeof(ShikiUndoInfo));
  g_return_if_fail(undoInfo != NULL);
  undoInfo->action = SHIKI_UNDO_INSERT;
  undoInfo->str    = g_strdup(str);
  undoInfo->strlen = len;
  undoInfo->start  = gtk_text_iter_get_offset(iter);
  undoInfo->end    = undoInfo->start + undoInfo->strlen;
  Shiki_CURRENT_UNDO_INFO_LIST = g_list_prepend(Shiki_CURRENT_UNDO_INFO_LIST, undoInfo);
  /* g_print("insert : %s, len : %d, start : %d, end : %d\n", undoInfo->str, undoInfo->strlen, undoInfo->start, undoInfo->end); */
}

/* バッファからテキストが消去された */
static void delete_range_handler(GtkTextBuffer *buffer, GtkTextIter *start, GtkTextIter *end) {
  /* Undo のための情報を記録 */
  ShikiUndoInfo *undoInfo = g_malloc(sizeof(ShikiUndoInfo));
  g_return_if_fail(undoInfo != NULL);
  undoInfo->action = SHIKI_UNDO_DELETE;
  undoInfo->str    = gtk_text_buffer_get_text(buffer, start, end, FALSE);
  undoInfo->start  = gtk_text_iter_get_offset(start);
  undoInfo->end    = gtk_text_iter_get_offset(end);
  undoInfo->strlen = end - start;
  Shiki_CURRENT_UNDO_INFO_LIST = g_list_prepend(Shiki_CURRENT_UNDO_INFO_LIST, undoInfo);
  /* g_print("delete : %s %d\n", undoInfo->str, undoInfo->strlen); */
}

/* タブが切り替わる時のイベントハンドリング */
static void switch_tabpage_handler(GtkNotebook *notebook, GtkNotebookPage *page, guint pagenum) {
  /* タブに対応する情報が格納された構造体を切替える */
  Shiki_CURRENT_TAB_INFO = (ShikiBuffer *)g_list_nth_data(Shiki_EDITOR_BUFFER_LIST, pagenum);

  /* 現在のタブ番号を切替える */
  Shiki_CURRENT_TAB_NUM = pagenum;

  /* タブのラベルをウィンドウのタイトルに */
  if(!Shiki_CURRENT_TAB_INFO) return;
  gtk_window_set_title (GTK_WINDOW(Shiki_EDITOR_WINDOW), Shiki_CURRENT_FILENAME);

  update_modeline_label();  
}

static void undo() {
  g_print("Undo\n");
  GtkTextIter start, end;
  ShikiUndoInfo *undoInfo = g_list_nth_data(Shiki_CURRENT_UNDO_INFO_LIST, 0);
  if(!undoInfo) {
    g_print("これ以上 Undo できません\n");
    return;
  }
  gtk_text_buffer_get_iter_at_offset(Shiki_CURRENT_TEXT_BUFFER, &start, undoInfo->start);
  gtk_text_buffer_get_iter_at_offset(Shiki_CURRENT_TEXT_BUFFER, &end, undoInfo->end);

  if(undoInfo->action == SHIKI_UNDO_INSERT) {
    Shiki_CURRENT_UNDO_INFO_LIST = g_list_delete_link(Shiki_CURRENT_UNDO_INFO_LIST, g_list_first(Shiki_CURRENT_UNDO_INFO_LIST));
    gtk_text_buffer_delete(Shiki_CURRENT_TEXT_BUFFER, &start, &end);
    g_free(undoInfo->str);
    g_free(undoInfo);
  } else if(undoInfo->action == SHIKI_UNDO_DELETE) {
    Shiki_CURRENT_UNDO_INFO_LIST = g_list_delete_link(Shiki_CURRENT_UNDO_INFO_LIST, g_list_first(Shiki_CURRENT_UNDO_INFO_LIST));
    gtk_text_buffer_insert(Shiki_CURRENT_TEXT_BUFFER, &start, undoInfo->str, -1);
    g_free(undoInfo->str);
    g_free(undoInfo);            
  }

}

/* キーが押された */
static gboolean signal_key_press_handler (GtkWidget *notebook, GdkEventKey *event, gpointer contextid) {
  GtkTextIter start, end;

  /* 括弧の対応の強調を無効に */
  gtk_text_buffer_get_start_iter(Shiki_CURRENT_TEXT_BUFFER, &start);
  gtk_text_buffer_get_end_iter(Shiki_CURRENT_TEXT_BUFFER, &end);
  gtk_text_buffer_remove_tag_by_name(Shiki_CURRENT_TEXT_BUFFER, "parent_emphasis_background", &start, &end);

  if(event->state & GDK_CONTROL_MASK && event->state & GDK_MOD1_MASK) {
    switch(event->keyval) {
      case GDK_at : /* C-M-SPC */
        { GtkTextIter start, end;
          if(!search_sexp(&start, &end)) return FALSE;
          gtk_text_buffer_select_range(Shiki_CURRENT_TEXT_BUFFER, &start, &end);
        }
        break;
      case GDK_space : /* C-M-SPC */
        { GtkTextIter start, end;
          if(!search_last_sexp(&start, &end)) return FALSE;
          gtk_text_buffer_select_range(Shiki_CURRENT_TEXT_BUFFER, &start, &end);
        }
        break;
    }
  } else if(event->state & GDK_CONTROL_MASK) {
    switch(event->keyval) {
      case GDK_f :  /* Ctrl + f : forward */
        Shiki_forward_char();
        break;
      case GDK_b : /* Ctrl + b : backward */
        Shiki_backward_char();
        break;
      case GDK_n : /* Ctrl + n : next line */
        Shiki_forward_line(1);
        break;
      case GDK_p :  /* Ctrl + p : previous line */
        Shiki_forward_line(-1);
        break;
      case GDK_h :
        { GtkTextIter p;
          gtk_text_buffer_get_iter_at_mark(Shiki_CURRENT_TEXT_BUFFER,&p, gtk_text_buffer_get_insert(Shiki_CURRENT_TEXT_BUFFER));
          gtk_text_buffer_backspace(Shiki_CURRENT_TEXT_BUFFER, &p, FALSE, TRUE);
        }
        break;

      case GDK_e :  /* Ctrl + e : eval-expression */
        {
          gchar *code, *result;
          GtkTextIter start, end;

          if(!search_sexp(&start, &end)) return FALSE;

          code = gtk_text_buffer_get_text(Shiki_CURRENT_TEXT_BUFFER, &start, &end, FALSE);
          result = eval_cstring_by_gauche(code);
          g_free(code);
          
          gtk_text_buffer_get_iter_at_mark(Shiki_CURRENT_TEXT_BUFFER, &end, gtk_text_buffer_get_insert(Shiki_CURRENT_TEXT_BUFFER));
          
          gtk_text_buffer_insert(Shiki_CURRENT_TEXT_BUFFER, &end, "\n", -1);
          gtk_text_buffer_insert(Shiki_CURRENT_TEXT_BUFFER, &end, result, -1);
          gtk_text_buffer_insert(Shiki_CURRENT_TEXT_BUFFER, &end, "\n", -1);
        }
        break;

      case GDK_j :  /* Ctrl + j : eval-last-sexp */
        {
          gchar *code, *result;
          GtkTextIter start, end;

          if(!search_last_sexp(&start, &end)) return FALSE;

          code = gtk_text_buffer_get_text(Shiki_CURRENT_TEXT_BUFFER, &start, &end, FALSE);
          result = eval_cstring_by_gauche(code);
          g_free(code);
          
          gtk_text_buffer_get_iter_at_mark(Shiki_CURRENT_TEXT_BUFFER, &end, gtk_text_buffer_get_insert(Shiki_CURRENT_TEXT_BUFFER));
          
          gtk_text_buffer_insert(Shiki_CURRENT_TEXT_BUFFER, &end, "\n", -1);
          gtk_text_buffer_insert(Shiki_CURRENT_TEXT_BUFFER, &end, result, -1);
          gtk_text_buffer_insert(Shiki_CURRENT_TEXT_BUFFER, &end, "\n", -1);
        }
        break;

      case GDK_underscore : /* Ctrl + _ : Undo */
        undo();
        break;

      case GDK_t : /* Ctrl + t : タブを開く */
        append_default_tabpage_handler();
        break;

      case GDK_k : /* Ctrl + k : タブを閉じる */
        remove_tabpage();
        break;

      case GDK_w : /* Ctrl + w : カット */
        gtk_text_buffer_cut_clipboard(Shiki_CURRENT_TEXT_BUFFER, Shiki_EDITOR_CLIPBOARD, TRUE);
        break;

      case GDK_y : /* Ctrl + y : ヤンク */
        {GtkTextIter p;
          gtk_text_buffer_get_iter_at_mark(Shiki_CURRENT_TEXT_BUFFER,&p, gtk_text_buffer_get_insert(Shiki_CURRENT_TEXT_BUFFER));
          gtk_text_buffer_paste_clipboard(Shiki_CURRENT_TEXT_BUFFER, Shiki_EDITOR_CLIPBOARD, &p, TRUE);
        }
        break;        
    }
  }
  return FALSE;
}

ScmClass *ShikiBufferClass;

static gint compBuffer(gconstpointer a, gconstpointer b) {
  return ((ShikiBuffer *)a)->text_buffer == b ? 0 : 1;
}

static void buffer_print(ScmObj obj, ScmPort *out, ScmWriteContext *ctx) {
  GtkTextBuffer *b = SHIKI_BUFFER_UNBOX(obj);
  GList *l  = g_list_find_custom(Shiki_EDITOR_BUFFER_LIST, b, compBuffer);
    if(l)
      Scm_Printf(out, "#<buffer: %s>", ((ShikiBuffer *)(l->data))->name);
    else
      Scm_Printf(out, "#<deleted buffer: %p>", b);
}

static void buffer_cleanup(ScmObj obj)
{
  g_object_unref(SHIKI_BUFFER_UNBOX(obj));
}

/* ノートブックにタブとページ (バッファ) を追加 */
GtkTextBuffer *Shiki_new_buffer_create(gchar *filename) {
  /*-------------------- 新しいタブを作る ----------------------------------*/
  /* ShikiBuffer には，タブに関連する情報が全て保持されている */
  ShikiBuffer *tabinfo  = g_malloc(sizeof(ShikiBuffer));
  tabinfo->locale        = "Gtk Default (utf8)";
  tabinfo->undoInfoList  = NULL;
  tabinfo->filename      = filename;
  tabinfo->name      = g_path_get_basename(filename);
  tabinfo->tabpage_label = g_strndup(tabinfo->name, 7);
  tabinfo->env           = Scm_MakeModule(NULL, FALSE);
  
  ShikiBufferClass = Scm_MakeForeignPointerClass(SCM_MODULE(tabinfo->env),
                         "<buffer>", buffer_print, buffer_cleanup,
                         SCM_FOREIGN_POINTER_KEEP_IDENTITY
                         |
                         SCM_FOREIGN_POINTER_MAP_NULL);

  /* xyzzy lisp 関数を登録 */
  Scm_Init_xyzzylisp(SCM_MODULE(tabinfo->env));

  /* スクロールウィンドウ (タブの中身の大外) を作る */
  tabinfo->tabpage = GTK_SCROLLED_WINDOW(gtk_scrolled_window_new(NULL, NULL));
  gtk_scrolled_window_set_policy (tabinfo->tabpage, GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);

  /* 枠の中に格納するテキストビューワと，テキストバッファを作る */
  tabinfo->text_view = GTK_TEXT_VIEW(gtk_text_view_new());
  gtk_text_view_set_wrap_mode(tabinfo->text_view, GTK_WRAP_WORD);
  tabinfo->text_buffer = gtk_text_view_get_buffer(tabinfo->text_view);

  gtk_container_add(GTK_CONTAINER(tabinfo->tabpage), GTK_WIDGET(tabinfo->text_view));
  gtk_widget_set_size_request(GTK_WIDGET(tabinfo->text_view), 680, 700);
  g_signal_connect(tabinfo->text_buffer, "mark_set", G_CALLBACK(text_buffer_cursor_moved_handler), tabinfo->text_view);
  g_signal_connect(tabinfo->text_buffer, "insert-text", G_CALLBACK(insert_text_handler), NULL);
  g_signal_connect(tabinfo->text_buffer, "delete-range", G_CALLBACK(delete_range_handler), NULL);

  /* タブを削除する際，デリートハンドラを削除しておかないと警告が出るから */
  tabinfo->delete_handler_id = g_signal_connect(Shiki_EDITOR_WINDOW, "delete_event", G_CALLBACK(delete_event_handler), tabinfo->text_buffer);

  /* 様々な初期化処理 */

  /* 括弧の強調表示のためのタグを作る */
  gtk_text_buffer_create_tag(tabinfo->text_buffer, "parent_emphasis_background", "background", "green", NULL);

  /* キーワードハイライティング */
  gtk_text_buffer_create_tag(tabinfo->text_buffer, "keyword_highlighting", "foreground", "blue", NULL);
  /* 関数 */
  gtk_text_buffer_create_tag(tabinfo->text_buffer, "function_highlighting", "foreground", "red", NULL);
  /* コメント */
  gtk_text_buffer_create_tag (tabinfo->text_buffer, "comment_highlighting", "foreground", "purple", NULL);
  /* 文字列 */
  gtk_text_buffer_create_tag (tabinfo->text_buffer, "string_highlighting", "foreground", "orange", NULL);
  /* タブをノートブックに登録する */
  gtk_notebook_append_page(Shiki_EDITOR_NOTEBOOK, GTK_WIDGET(tabinfo->tabpage), gtk_label_new(tabinfo->tabpage_label));
  /* 対応するタブ情報を大域テーブルに保存しておく */
  Shiki_EDITOR_BUFFER_LIST = g_list_append(Shiki_EDITOR_BUFFER_LIST, tabinfo);

  gtk_widget_show_all(GTK_WIDGET(Shiki_EDITOR_NOTEBOOK));  
  /* 開いたページに移動する */
  gtk_notebook_set_current_page(Shiki_EDITOR_NOTEBOOK, g_list_length(Shiki_EDITOR_BUFFER_LIST) - 1);

  return tabinfo->text_buffer;
}

static void append_default_tabpage_handler() {
  Shiki_new_buffer_create(g_strdup("*scratch*")); 
}

/* ノートブックからタブとページ (バッファ) を削除 */
static void remove_tabpage() {
  /* タブが 1 つしか残っていなかったら消させない */
  if(g_list_length(Shiki_EDITOR_BUFFER_LIST) == 1)
    return;
  if(!not_yet_save_changes_really_quit(Shiki_CURRENT_TEXT_BUFFER)) {
    /* デリートハンドラをエディタトップレベルのウィジットから取り除く */
    g_signal_handler_disconnect(Shiki_EDITOR_WINDOW, (Shiki_CURRENT_TAB_INFO)->delete_handler_id);
    /* タブの中身を削除 */
    gtk_widget_destroy(GTK_WIDGET(Shiki_CURRENT_TEXT_VIEW));
    /* タブに対応するタブ情報を削除 */
    g_free(Shiki_CURRENT_TAB_TITLE);
    g_free(Shiki_CURRENT_BASENAME);
    g_free(Shiki_CURRENT_FILENAME);
    Shiki_EDITOR_BUFFER_LIST = g_list_delete_link(Shiki_EDITOR_BUFFER_LIST, g_list_nth(Shiki_EDITOR_BUFFER_LIST, Shiki_CURRENT_TAB_NUM));
    g_free(Shiki_CURRENT_TAB_INFO);

    /* カレントのタブ情報を更新 */
    Shiki_CURRENT_TAB_INFO = g_list_nth_data(Shiki_EDITOR_BUFFER_LIST, Shiki_CURRENT_TAB_NUM);
    gtk_notebook_remove_page(Shiki_EDITOR_NOTEBOOK, Shiki_CURRENT_TAB_NUM);
    /* ウィジットを強制的に再描画 */
    gtk_widget_queue_draw(GTK_WIDGET(Shiki_EDITOR_NOTEBOOK));
  }
}

/* バッファをまるごとロード */
static void load_buffer_by_gauche() {
  GtkTextIter p;
  gtk_text_buffer_get_end_iter(Shiki_CURRENT_TEXT_BUFFER, &p);
  gtk_text_buffer_insert(Shiki_CURRENT_TEXT_BUFFER, &p, "\n\n", -1);
  gtk_text_buffer_insert(Shiki_CURRENT_TEXT_BUFFER, &p, load_cstring_by_gauche(get_all_buffer_contents(Shiki_CURRENT_TEXT_BUFFER)), -1); 
}

/* ファイルをロード */
static void load_scheme_file_by_gauche() {
  gchar *contents, *text;
  gsize br, bw, len;
  GError *err = NULL;
  const gchar *filename = Shiki_file_name_dialog("File Selection");
  GtkTextIter p;

  if(!filename) return;

  gtk_text_buffer_get_end_iter(Shiki_CURRENT_TEXT_BUFFER, &p);
  gtk_text_buffer_insert(Shiki_CURRENT_TEXT_BUFFER, &p, "\n\n", -1);

  if(g_file_get_contents(filename, &contents, &len, NULL)) {
    if(!(text = g_locale_to_utf8(contents, -1, &br, &bw, &err)))
      gtk_text_buffer_insert(Shiki_CURRENT_TEXT_BUFFER, &p, load_cstring_by_gauche(text), -1); 
    else
      gtk_text_buffer_insert(Shiki_CURRENT_TEXT_BUFFER, &p, load_cstring_by_gauche(contents), -1); 
  }
  g_free(text); g_free(contents);
}

/* gauche を起動して文字列をロード */
static gchar *load_cstring_by_gauche(gchar *s) {
  gchar *msg;

  ScmObj result, error;
  /* 入力文字列ポートを開く */
  ScmObj is = Scm_MakeInputStringPort(SCM_STRING(SCM_MAKE_STR_COPYING(s)), TRUE);
  /* 出力文字列ポート開く */
  ScmObj os = Scm_MakeOutputStringPort(TRUE);

  Scm_Define(SCM_MODULE(Shiki_CURRENT_BUFFER_ENV), SCM_SYMBOL(SCM_INTERN("*input*")), is);
  Scm_Define(SCM_MODULE(Shiki_CURRENT_BUFFER_ENV), SCM_SYMBOL(SCM_INTERN("*error*")), SCM_FALSE);
  /* Scheme のレベルでエラーハンドリングをしつつ，ポートから順番に S 式を読み込み，評価していく．コンパイルエラーなどは *error* に捕捉される */
  result = Scm_EvalCString("(guard (e (else (set! *error* e) #f)) (eval (load-from-port *input*) (current-module)))", SCM_OBJ(Shiki_CURRENT_BUFFER_ENV));

  error = Scm_GlobalVariableRef(SCM_MODULE(Shiki_CURRENT_BUFFER_ENV), SCM_SYMBOL(SCM_INTERN("*error*")), 0);

  /* 文字列を評価した結果をポートに書き込む */
  if (!SCM_FALSEP(error))
    Scm_Write(error, os, SCM_WRITE_DISPLAY);
  else
    Scm_Write(result, os, SCM_WRITE_DISPLAY);

  msg = Scm_GetString(SCM_STRING(Scm_GetOutputString(SCM_PORT(os))));
  /* ポート閉じる */
  Scm_ClosePort(SCM_PORT(is));
  Scm_ClosePort(SCM_PORT(os));

  return msg;
}

static void font_selection_ok(GtkWidget *button, GtkWidget *font_dialog) {
  gchar *font_name = gtk_font_selection_dialog_get_font_name (GTK_FONT_SELECTION_DIALOG (font_dialog));
  if(font_name) {
    GtkRcStyle *style = gtk_rc_style_new ();
    pango_font_description_free(style->font_desc);
    style->font_desc = pango_font_description_from_string(font_name);
    gtk_widget_modify_style (GTK_WIDGET(Shiki_CURRENT_TEXT_VIEW), style);
    gtk_rc_style_unref (style);
    g_free (font_name);
  }
}

/* フォントを選択させるイベントハンドラ */
static void select_font(){
  GtkWidget *font_dialog = gtk_font_selection_dialog_new("Font Selection Dialog");
  g_signal_connect (GTK_FONT_SELECTION_DIALOG (font_dialog)->ok_button, "clicked", G_CALLBACK(font_selection_ok), font_dialog);
  gtk_dialog_run(GTK_DIALOG(font_dialog));
  gtk_widget_destroy(font_dialog);
}

/* このアプリケーションについて */
static void about_this_application() {
  GtkAboutDialog *about = GTK_ABOUT_DIALOG(gtk_about_dialog_new());
  const gchar *authors[] = {
    "若槻俊宏 (あろは) <alohakun@gmail.com>\n",
    "Contribute : tkng さん",
    "(http://d.hatena.ne.jp/tkng/20061113)", NULL
  };
  gtk_about_dialog_set_authors(about, authors);
  gtk_about_dialog_set_copyright(about, "Copyright(C)2006  WAKATSUKI Toshihiro");
  gtk_about_dialog_set_name(about, "式 (SHIKI)");
  gtk_about_dialog_set_website_label(about, "本当に30日でエディタが出来上がるのかを試してみるBlog");
  gtk_about_dialog_set_website(about, "http://alohakun.blog7.fc2.com/blog-category-29.html");
  gtk_dialog_run(GTK_DIALOG(about));
  gtk_widget_destroy(GTK_WIDGET(about));
}

/* ダミー */
static void dummy_handler() {
  GtkWidget *dummy = gtk_message_dialog_new(GTK_WINDOW(Shiki_EDITOR_WINDOW),
      GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_WARNING, GTK_BUTTONS_CLOSE,
      "Sorry... This Button is Dummy.");
  gtk_dialog_run(GTK_DIALOG(dummy));
  gtk_widget_destroy(dummy);
}

/* バッファの状態に合わせてモードラインを変更 */
static void update_modeline_label() {
  static gchar label[1024];
  GtkTextIter p;
  gtk_text_buffer_get_iter_at_mark(Shiki_CURRENT_TEXT_BUFFER, &p, gtk_text_buffer_get_insert(Shiki_CURRENT_TEXT_BUFFER));

  g_snprintf(label, 1024, "--%s- %-10s (Gauche Interaction) [%s]     L%d:%d    ",
      gtk_text_buffer_get_modified(Shiki_CURRENT_TEXT_BUFFER) ? "**" : "--",
      Shiki_CURRENT_BASENAME,
      Shiki_CURRENT_CES,
      gtk_text_iter_get_line(&p) + 1,
      gtk_text_iter_get_line_offset (&p) + 1);
  gtk_label_set_text(GTK_LABEL(Shiki_EDITOR_MODELINE_LABEL), label);
}

static void text_buffer_cursor_moved_handler(){
  update_modeline_label();
}

/* テキストバッファから全ての文字列を取り出す */
static gchar* get_all_buffer_contents(GtkTextBuffer *buffer) {
  GtkTextIter start, end;
  gtk_text_buffer_get_start_iter(buffer, &start);
  gtk_text_buffer_get_end_iter(buffer, &end);
  return gtk_text_buffer_get_text(buffer, &start, &end, FALSE);
}

/* buffer の内容をファイル filename に保存 */
static gboolean save_text_buffer(const gchar *filename, GtkTextBuffer *buffer) {
  gchar *contents, *text;
  gsize br, bw;
  GError *err = NULL;

  if(!filename) return FALSE;
  contents = get_all_buffer_contents(buffer);
  text = g_locale_from_utf8(contents, -1, &br, &bw, &err);
  /* 文字列をファイルに保存 */
  g_file_set_contents(filename, text, -1, NULL);
  gtk_text_buffer_set_modified(buffer, FALSE);
  update_modeline_label();
  g_free(contents); g_free(text);
  return TRUE;
}

/* 現在表示されているページの内容をファイルに保存 */
static void save_file() {

  /* ヘルプへの変更は保存しない */
  if(g_ascii_strcasecmp("*help*", Shiki_CURRENT_TAB_TITLE) == 0) return;

  /* 変更が無ければ何もしない */
  if(!gtk_text_buffer_get_modified(Shiki_CURRENT_TEXT_BUFFER)) return;

  /* まだファイル名が設定されていなかったら，ダイアログを開いて入力させる */
  if(g_ascii_strcasecmp("*scratch*", Shiki_CURRENT_TAB_TITLE) == 0) {
    const gchar *filename = Shiki_file_name_dialog("Save File As ...");
    if(!filename) return;
    if(!save_text_buffer(filename, Shiki_CURRENT_TEXT_BUFFER)) return;
    gtk_notebook_set_tab_label_text(Shiki_EDITOR_NOTEBOOK, GTK_WIDGET(Shiki_CURRENT_TAB), filename);
    gtk_window_set_title (GTK_WINDOW(Shiki_EDITOR_WINDOW), filename);
  } else
    save_text_buffer(Shiki_CURRENT_TAB_TITLE, Shiki_CURRENT_TEXT_BUFFER);
}

/* 現在表示されているページの内容をファイルに別名保存 */
static void save_file_as() {
  const gchar *filename = Shiki_file_name_dialog("Save File As ...");

  if(!filename) return;
  if(!save_text_buffer(filename, Shiki_CURRENT_TEXT_BUFFER)) return;

  gtk_notebook_set_tab_label_text(Shiki_EDITOR_NOTEBOOK, GTK_WIDGET(Shiki_CURRENT_TAB), filename);
  gtk_window_set_title (GTK_WINDOW (Shiki_EDITOR_WINDOW), filename);
}

/* 本当に終了してもよろしいですか ? */
static gboolean not_yet_save_changes_really_quit(GtkTextBuffer *buffer) {
  /* 変更が無ければそのまま終了 */
  if(!gtk_text_buffer_get_modified(buffer)) return FALSE;

  return !Shiki_yes_or_no_p("バッファが変更されています．\nセーブしないで終了しますか ?");
}
  
/* バッファがまだ保存されていないのに本当に終了するのかを尋ねる */
static gboolean delete_event_handler(GtkWidget *widget, GdkEvent *event, GtkTextBuffer *buffer){
  return not_yet_save_changes_really_quit(buffer);
}

/* ファイルを開く */
static void open_file(const gchar *filename) {
  gchar *text;
  gchar *utf8filename = g_locale_to_utf8(filename, -1, NULL, NULL, NULL);
  GtkTextIter p;
  ScmObj s;

  /* g_file_get_contents(filename, &contents, &len, NULL); */

  /* 新しいバッファを開く */
  Shiki_new_buffer_create(g_strdup(filename));
  gtk_window_set_title (GTK_WINDOW (Shiki_EDITOR_WINDOW), filename); 

  Scm_Define(SCM_MODULE(Shiki_CURRENT_BUFFER_ENV), SCM_SYMBOL(SCM_INTERN("*filename*")), SCM_MAKE_STR_COPYING(utf8filename));
  g_free(utf8filename);

  Scm_EvalCString("(use gauche.charconv)", Shiki_CURRENT_BUFFER_ENV);
  /*
  Scm_EvalCString("(define contents (call-with-input-file *filename* port->string))", Shiki_CURRENT_BUFFER_ENV);
  Scm_EvalCString("(define ces (ces-guess-from-string contents \"*JP\"))", Shiki_CURRENT_BUFFER_ENV);
  ces = Scm_EvalCString("ces", Shiki_CURRENT_BUFFER_ENV);
  Shiki_CURRENT_CES = Scm_GetString(SCM_STRING(ces));
  //s = Scm_EvalCString("(ces-convert contents ces)", Shiki_CURRENT_BUFFER_ENV);
  s = Scm_EvalCString("(ces-convert contents `utf8)", Shiki_CURRENT_BUFFER_ENV);
  */
  
  /* ファイルから文字列を取り出し，変換後にバッファに格納 */
  s = Scm_EvalCString("(port->string (open-input-conversion-port (open-input-file *filename*) \"*jp\" :owner? #t))", Shiki_CURRENT_BUFFER_ENV);
  text = Scm_GetString(SCM_STRING(s));
  gtk_text_buffer_set_text(Shiki_CURRENT_TEXT_BUFFER, text, -1);

  /* バッファ未変更に */
  gtk_text_buffer_set_modified(Shiki_CURRENT_TEXT_BUFFER, FALSE);
  /* カーソル位置を先頭に */
  gtk_text_buffer_get_start_iter(Shiki_CURRENT_TEXT_BUFFER, &p);
  gtk_text_buffer_place_cursor(Shiki_CURRENT_TEXT_BUFFER, &p);
  update_modeline_label();
  /* キーワードを色分けする */
  scheme_keyword_highlighting_current_buffer();
  gtk_widget_show_all(GTK_WIDGET(Shiki_EDITOR_NOTEBOOK));
}

/* ファイルをダイアログで指定して開く */
static void open_file_handler() {
  const gchar *filename = Shiki_file_name_dialog("File Selection");

  if(!filename) return;
  open_file(filename);
}

/* gauche を起動して文字列を評価 */
static gchar *eval_cstring_by_gauche(gchar *s) {
  gchar *msg;

  ScmObj result, error; 
  /* 出力文字列ポート開く */
  ScmObj os = Scm_MakeOutputStringPort(TRUE);

  /* Scheme レベルでエラーハンドリング */
  /* http://alohakun.blog7.fc2.com/blog-entry-517.html */
  Scm_Define(SCM_MODULE(Shiki_CURRENT_BUFFER_ENV), SCM_SYMBOL(SCM_INTERN("*input*")), SCM_MAKE_STR_COPYING(s));
  Scm_Define(SCM_MODULE(Shiki_CURRENT_BUFFER_ENV), SCM_SYMBOL(SCM_INTERN("*error*")), SCM_FALSE);

  result = Scm_EvalCString("(guard (e (else (set! *error* e) #f)) (eval (read-from-string *input*) (current-module)))", SCM_OBJ(Shiki_CURRENT_BUFFER_ENV));

  error = Scm_GlobalVariableRef(SCM_MODULE(Shiki_CURRENT_BUFFER_ENV), SCM_SYMBOL(SCM_INTERN("*error*")), 0);

  /* 文字列を評価した結果をポートに書き込む */
  if (!SCM_FALSEP(error))
    Scm_Write(error, os, SCM_WRITE_DISPLAY);
  else
    Scm_Write(result, os, SCM_WRITE_DISPLAY);

  msg = Scm_GetString(SCM_STRING(Scm_GetOutputString(SCM_PORT(os))));
  /* ポート閉じる */
  Scm_ClosePort(SCM_PORT(os));

  return msg;
}

/* 緑ボタンのハンドリング．バッファの選択範囲の S 式をロード (逐次評価) */
static void load_region_by_gauche() {

  GtkTextIter start, end, p;
  gchar *code;
  gtk_text_buffer_get_end_iter(Shiki_CURRENT_TEXT_BUFFER, &p);
  gtk_text_buffer_insert(Shiki_CURRENT_TEXT_BUFFER, &p, "\n\n", -1);

  /* マウスで選択されている範囲の文字列を取得 */
  if(gtk_text_buffer_get_selection_bounds(Shiki_CURRENT_TEXT_BUFFER, &start, &end)) {
    code = gtk_text_buffer_get_text(Shiki_CURRENT_TEXT_BUFFER, &start, &end, FALSE);
    gtk_text_buffer_insert(Shiki_CURRENT_TEXT_BUFFER, &p, load_cstring_by_gauche(code), -1);
    g_free(code);
  }
}

// GtkTextCharPredicate
static gboolean is_kakko_or_kokka(gunichar ch, gpointer p) {
  return ch == '(' || ch == ')';
}
static gboolean is_kakko(gunichar ch, gpointer p) {return ch == '(';}
static gboolean is_kokka(gunichar ch, gpointer p) {return ch == ')';}

/* カーソル以降の '(' に対応する ')' までの文字列 (S 式) を切り出す */
static gboolean search_sexp(GtkTextIter *start, GtkTextIter *end) {

  /* カーソルの位置を取得 */
  gtk_text_buffer_get_iter_at_mark(Shiki_CURRENT_TEXT_BUFFER, start, gtk_text_buffer_get_insert(Shiki_CURRENT_TEXT_BUFFER));

  if(gtk_text_iter_get_char(start) != '(')
    gtk_text_iter_forward_find_char(start, is_kakko, NULL, NULL);

  *end = *start;

  /* カーソル位置の前にある S 式を切り出す */
  if(!search_sexp_kokka(end)) return FALSE;
  gtk_text_iter_forward_char(end);
  return TRUE;
}

static gboolean search_sexp_kokka(GtkTextIter *end) {
  gint nest_level = 0;

  /* 対応する ')' を探す */
  while(1) {
    if(!gtk_text_iter_forward_find_char(end, is_kakko_or_kokka, NULL, NULL))
      return FALSE;

    if(gtk_text_iter_get_char(end) == '(')
      nest_level++;
    else {
      if(!nest_level)
        break;
      else
        nest_level--;
    }
  }
  return TRUE;
}

/* カーソル以前の ')' に対応する '(' までの文字列 (S 式) を切り出す */
static gboolean search_last_sexp(GtkTextIter *start, GtkTextIter *end) {

  /* カーソルの位置を取得 */
  gtk_text_buffer_get_iter_at_mark(Shiki_CURRENT_TEXT_BUFFER, end, gtk_text_buffer_get_insert(Shiki_CURRENT_TEXT_BUFFER));

  gtk_text_iter_backward_char(end);

  if(gtk_text_iter_get_char(end) != ')')
    gtk_text_iter_backward_find_char(end, is_kokka, NULL, NULL);
  *start = *end;
  gtk_text_iter_forward_char(end);

  /* カーソル位置の前にある S 式を切り出す */
  if(!search_last_sexp_kakko(start)) return FALSE;

  return TRUE;
}

/* ')' に対応する '(' までの文字列 (S 式) を切り出す */
static gboolean search_last_sexp_kakko(GtkTextIter *start) {
  gint nest_level = 0;
  /* ネストレベルを計算しながら ')' を探す */
  while(1) {
    if(!gtk_text_iter_backward_find_char(start, is_kakko_or_kokka, NULL, NULL))
      return FALSE;

    if(gtk_text_iter_get_char(start) == ')')
      nest_level++;
    else {
      if(!nest_level)
        break;
      else
        nest_level--;
    }
  }
  return TRUE;
}

/* カーソル位置のネストレベルを返す */
static gint get_parent_nest_level_at_cursor(GtkTextBuffer *buffer) {
  gint nest_level = 0;
  GtkTextIter start, end;
  gtk_text_buffer_get_start_iter(buffer, &start);
  if(gtk_text_iter_get_char(&start) == '(') nest_level++;

  /* カーソルの位置 (= end) を取得 */
  gtk_text_buffer_get_iter_at_mark(buffer,&end, gtk_text_buffer_get_insert(buffer));

  while(1) {
    /* end まで '(' か ')' を探して見つからなかったら終了 */
    if(!gtk_text_iter_forward_find_char(&start, is_kakko_or_kokka, NULL, &end))
      return nest_level;

    if(gtk_text_iter_get_char(&start) == '(')
      nest_level++;
    else 
      nest_level--;
  }
}

/* ページのタブと境界線を on/off */
static void tabsborder_on_off(GtkButton *button, GtkNotebook *notebook) {
  gint tval = FALSE;
  gint bval = FALSE;
  if(notebook->show_tabs == FALSE)
    tval = TRUE; 
  if(notebook->show_border == FALSE)
    bval = TRUE;

  gtk_notebook_set_show_tabs(notebook, tval);
  gtk_notebook_set_show_border(notebook, bval);
}

/* タブの位置を調整 */
static void rotate_tab_position(GtkButton *button, GtkNotebook *notebook ) {
  gtk_notebook_set_tab_pos(notebook, (notebook->tab_pos + 1) % 4);
}

/* キーが離された */
static gboolean signal_key_release_handler (GtkWidget *notebook, GdkEventKey *event, gpointer contextid) {
  static gint metakey_pressed = 0;
  static gint controlx_pressed = 0;

  if(event->keyval == GDK_parenright && event->state & GDK_SHIFT_MASK) {
    GtkTextIter start, end;

    /* カーソルの位置を取得 */
    gtk_text_buffer_get_iter_at_mark(Shiki_CURRENT_TEXT_BUFFER, &end, gtk_text_buffer_get_insert(Shiki_CURRENT_TEXT_BUFFER));

    start = end;
    gtk_text_iter_backward_char(&start);

    /* カーソル位置の前にある S 式を切り出す */
    if(!search_last_sexp_kakko(&start)) return FALSE;

    gtk_text_buffer_apply_tag_by_name(Shiki_CURRENT_TEXT_BUFFER, "parent_emphasis_background", &start, &end);
  }

  /* 改行されるたびに，自動的に括弧のネストの深さに応じた数のスペース (インデント) が行頭に入る */
  if(event->keyval == GDK_Return) {
    gint indentWidth = get_parent_nest_level_at_cursor(Shiki_CURRENT_TEXT_BUFFER) * editor_indent_width;
    gchar *indent = g_strnfill(indentWidth, ' ');
    gtk_text_buffer_insert_at_cursor(Shiki_CURRENT_TEXT_BUFFER, indent, -1);
    g_free(indent);
  }

  /* C-x */
  if(event->keyval == GDK_x && event->state & GDK_CONTROL_MASK) {
    controlx_pressed++;
    gtk_statusbar_push(GTK_STATUSBAR(Shiki_EDITOR_STATUSBAR), GPOINTER_TO_INT(contextid), "C-x -");
  } else if(event->state & GDK_CONTROL_MASK) {

    if(controlx_pressed > 0) {
      switch(event->keyval) {
        case GDK_c :/* C-x C-c : 終了 */
          gtk_statusbar_push(GTK_STATUSBAR(Shiki_EDITOR_STATUSBAR), GPOINTER_TO_INT(contextid), "C-c");
          {/* "delete-event" を発生させる．ウィンドウの × ボタンが押されたのと同じ */
            GdkEvent ev;

            ev.any.type = GDK_DELETE;
            ev.any.window = Shiki_EDITOR_WINDOW->window;
            ev.any.send_event = FALSE;
            gdk_event_put (&ev);
          }
          break;

        case GDK_f : /* C-x C-f : ファイル開く */
          gtk_statusbar_push(GTK_STATUSBAR(Shiki_EDITOR_STATUSBAR), GPOINTER_TO_INT(contextid), "C-f");
          open_file_handler();
          break;

        case GDK_s : /* C-x C-s : ファイル保存 */
          gtk_statusbar_push(GTK_STATUSBAR(Shiki_EDITOR_STATUSBAR), GPOINTER_TO_INT(contextid), "C-s");
          save_file();    
          break;

        case GDK_w : /* C-x C-w : ファイル別名保存 */
          gtk_statusbar_push(GTK_STATUSBAR(Shiki_EDITOR_STATUSBAR), GPOINTER_TO_INT(contextid), "C-w");
          save_file_as();    
          break;
      }
      controlx_pressed = 0;
    }

    switch(event->keyval) {
      case GDK_g :/* C-g : キャンセル */
        metakey_pressed = 0;
        controlx_pressed = 0;

        gtk_statusbar_push(GTK_STATUSBAR(Shiki_EDITOR_STATUSBAR), GPOINTER_TO_INT(contextid), "Quit");
        break;
    }

  }
  return FALSE;
}
static void open_online_help() {
  GtkTextIter p;
  Shiki_new_buffer_create(g_strdup("*help*"));
  gtk_text_buffer_set_text(Shiki_CURRENT_TEXT_BUFFER,
      "コマンドラインからの起動方法\n"
      "$ ./shiki [file1 file2 ....]\n\n"
      "[フォルダのアイコン]             ファイルを開く (C-x C-f)\n"
      "[フロッピーディスクのアイコン]   バッファを保存 (C-x C-s)\n"
      "[フロッピーとえんぴつのアイコン] バッファを別名保存 (C-x C-w)\n"
      "[ギアのアイコン]                 選択領域を gauche にロード\n"
      "[マーキング (ちょん) のアイコン] タブの on/off\n"
      "[工具 (スパナ) のアイコン]       タブの位置の調整\n"
      "[新規アイコン]                   新規バッファを開く (C-t)\n"
      "[左向き矢印アイコン]             やり直し (C-_)\n"
      "[ゴミ箱アイコン]                 バッファをクリア\n"
      "\n"
      "(注 : 通常，バッファの内容が失われる恐れがあるときには警告しますが，クリアだけは警告をしません．もし間違って消してしまった場合には慌てずに Undo してください)\n"
      "\n"
      "[× アイコン]                     バッファを閉じる (C-k)\n"
      "[A アイコン]                     フォントの選択\n"
      "[顔みたいなアイコン]             Scheme ファイルのロード\n"
      "[緑っぽい，変換アイコン]         バッファの内容を全てロード\n"
      "[ヘルプ (?) アイコン]            このヘルプ画面を表示します\n"
      "[info アイコン]                  このアプリケーションについての情報\n"
      "\n"
      "C-f : → に移動 (forward)\n"
      "C-b : ← に移動 (backward)\n"
      "C-n : ↓ に移動 (next line)\n"
      "C-p : ↑ に移動 (previous line)\n"
      "\n"
      "C-h : バックスペース\n"
      "C-w : カット\n"
      "C-y : ヤンク (ペースト)\n"
      "\n"
      "C-e : カーソル後ろの S 式を評価 (eval-expression)\n"
      "C-j : カーソル手前の S 式を評価 (eval-last-sexp)\n"
      "(emacs/xyzzy の *scratch* バッファと同じ)\n"
      "\n"
      "C-M-@ : カーソル以降の S 式を選択 (mark-sexp)\n"
      "C-M-SPC : カーソル手前の S 式を選択 (mark-last-sexp)\n"
      "C-x C-c : 終了．ウィンドウの × ボタンを押したのと同じ\n"
      "\n"
      "エディタ API\n"
      "(clear-current-buffer) : バッファをクリアします (警告無し)\n"
      , -1);
  gtk_text_buffer_set_modified(Shiki_CURRENT_TEXT_BUFFER, FALSE);
  /* カーソル位置を先頭に */
  gtk_text_buffer_get_start_iter(Shiki_CURRENT_TEXT_BUFFER, &p);
  gtk_text_buffer_place_cursor(Shiki_CURRENT_TEXT_BUFFER, &p);    
}

/* エディタの編集画面の初期化 */
static void Shiki_editor_window_init(int argc, char **argv) {
  GtkWidget *vbox, *toolbar, *modeline_bg = gtk_event_box_new();
  GtkToolItem *icon;
  GtkIconSize iconsize;
  GtkTooltips *toolbar_tips = gtk_tooltips_new();
  /* 「開く」「保存」「別名保存」「選択領域を実行」アイコン */
  GtkToolItem *oicon, *sicon, *saicon, *eicon;

  gint contextid, i;

  /* ハイライティングキーワードのハッシュテーブルを初期化 */
  keywords_hash = g_hash_table_new(g_str_hash, g_str_equal);
  i = 0;
  while(R5RS_keywords[i] != NULL)
    g_hash_table_insert(keywords_hash, R5RS_keywords[i++], GINT_TO_POINTER(R5RS_KEYWORD_COLOR));
  i = 0;
  while(R5RS_functions[i] != NULL)
    g_hash_table_insert(keywords_hash, R5RS_functions[i++], GINT_TO_POINTER(R5RS_FUNCTION_COLOR));

  /* 窓を作る */
  Shiki_EDITOR_WINDOW = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  g_signal_connect(G_OBJECT(Shiki_EDITOR_WINDOW), "destroy", G_CALLBACK(gtk_main_quit), NULL);

  /* システムのデフォルトクリップボードを取得 */
  Shiki_EDITOR_CLIPBOARD = gtk_clipboard_get(GDK_SELECTION_PRIMARY);

  /* パッキングボックスを作る */
  vbox = gtk_vbox_new(FALSE, 0);
  /* ツールバー作る */
  toolbar = gtk_toolbar_new();
  gtk_box_pack_start(GTK_BOX(vbox), toolbar, FALSE, FALSE, 0);

  Shiki_EDITOR_NOTEBOOK = GTK_NOTEBOOK(gtk_notebook_new());
  g_signal_connect(G_OBJECT(Shiki_EDITOR_NOTEBOOK), "switch-page", GTK_SIGNAL_FUNC(switch_tabpage_handler), NULL);

  /* ツールバーに付けるアイコンの設定 */
  gtk_toolbar_set_style(GTK_TOOLBAR (toolbar), GTK_TOOLBAR_ICONS);
  iconsize = gtk_toolbar_get_icon_size (GTK_TOOLBAR (toolbar));

  /* アイコン作る */

  /* ファイル開く */
  oicon = gtk_tool_button_new(gtk_image_new_from_stock (GTK_STOCK_OPEN, iconsize), "");
  /* 「開く」ボタンにファイルを読み込むアクションを関連付ける */
  g_signal_connect(G_OBJECT(oicon), "clicked", G_CALLBACK(open_file_handler), NULL);
  gtk_container_add(GTK_CONTAINER (toolbar), GTK_WIDGET(oicon));
  gtk_tool_item_set_tooltip(oicon, toolbar_tips, "ファイルを開きます",
      "新しいバッファを開いて，そこにファイルの内容を展開します．");

  /* バッファ保存 */
  sicon = gtk_tool_button_new(gtk_image_new_from_stock (GTK_STOCK_SAVE, iconsize), "");
  /* 「保存」ボタンにファイルを書き出すアクションを関連付ける */
  g_signal_connect(G_OBJECT(sicon), "clicked", G_CALLBACK(save_file), NULL);
  gtk_container_add (GTK_CONTAINER (toolbar), GTK_WIDGET(sicon));      
  gtk_tool_item_set_tooltip(sicon, toolbar_tips, "バッファを保存します",
      "バッファにファイル名が設定されていない場合には，ダイアログを開いてファイル名を取得します");

  /* バッファを別名保存 */
  saicon = gtk_tool_button_new(gtk_image_new_from_stock (GTK_STOCK_SAVE_AS, iconsize), "");
  /* 「別名保存」ボタンに別名のファイル開いて内容を書き出すアクションを関連付ける */
  g_signal_connect(G_OBJECT(saicon), "clicked", G_CALLBACK(save_file_as), NULL);
  gtk_container_add (GTK_CONTAINER (toolbar), GTK_WIDGET(saicon));
  gtk_tool_item_set_tooltip(saicon, toolbar_tips, "バッファを別名保存します",
      "");

  /* バッファ実行 */
  eicon = gtk_tool_button_new(gtk_image_new_from_stock (GTK_STOCK_EXECUTE, iconsize), "");
  /* 「選択範囲をロード」ボタンに libgauche を関連付ける */
  g_signal_connect(G_OBJECT(eicon), "clicked", G_CALLBACK(load_region_by_gauche), NULL);
  gtk_container_add (GTK_CONTAINER (toolbar), GTK_WIDGET(eicon));
  gtk_tool_item_set_tooltip(eicon, toolbar_tips, "選択範囲の S 式をロードします (load-region-lisp)",
      "Scheme (gauche) で評価できる S 式を評価します．");

  gtk_container_add(GTK_CONTAINER(Shiki_EDITOR_WINDOW), vbox);
  gtk_container_add(GTK_CONTAINER(vbox), GTK_WIDGET(Shiki_EDITOR_NOTEBOOK));

  icon = gtk_tool_button_new(gtk_image_new_from_stock (GTK_STOCK_NEW, iconsize), "");
  g_signal_connect(G_OBJECT(icon), "clicked", G_CALLBACK(append_default_tabpage_handler), NULL);
  gtk_container_add(GTK_CONTAINER (toolbar), GTK_WIDGET(icon));
  gtk_tool_item_set_tooltip(icon, toolbar_tips, "新規バッファを開きます", "");

  icon = gtk_tool_button_new(gtk_image_new_from_stock (GTK_STOCK_UNDO, iconsize), "");
  g_signal_connect(G_OBJECT(icon), "clicked", G_CALLBACK(undo), G_OBJECT(Shiki_EDITOR_NOTEBOOK));
  gtk_container_add(GTK_CONTAINER (toolbar), GTK_WIDGET(icon));
  gtk_tool_item_set_tooltip(icon, toolbar_tips, "Undo","");

  /* XXX : TODO */
  icon = gtk_tool_button_new(gtk_image_new_from_stock (GTK_STOCK_REDO, iconsize), "");
  g_signal_connect(G_OBJECT(icon), "clicked", G_CALLBACK(dummy_handler), NULL);
  gtk_container_add(GTK_CONTAINER (toolbar), GTK_WIDGET(icon));
  gtk_tool_item_set_tooltip(icon, toolbar_tips, "Redo", "");

  icon = gtk_tool_button_new(gtk_image_new_from_stock (GTK_STOCK_FIND, iconsize), "");
  g_signal_connect(G_OBJECT(icon), "clicked", G_CALLBACK(search_current_buffer), NULL);
  gtk_container_add(GTK_CONTAINER (toolbar), GTK_WIDGET(icon));
  gtk_tool_item_set_tooltip(icon, toolbar_tips, "検索", "");


  icon = gtk_tool_button_new(gtk_image_new_from_stock (GTK_STOCK_FIND_AND_REPLACE, iconsize), "");
  g_signal_connect(G_OBJECT(icon), "clicked", G_CALLBACK(replace_current_buffer), NULL);
  gtk_container_add(GTK_CONTAINER (toolbar), GTK_WIDGET(icon));
  gtk_tool_item_set_tooltip(icon, toolbar_tips, "置換", "");

  icon = gtk_tool_button_new(gtk_image_new_from_stock (GTK_STOCK_REFRESH, iconsize), "");
  g_signal_connect(G_OBJECT(icon), "clicked", G_CALLBACK(dummy_handler), NULL);
  gtk_container_add(GTK_CONTAINER (toolbar), GTK_WIDGET(icon));
  gtk_tool_item_set_tooltip(icon, toolbar_tips, "リロード", "");

  /* TODO ここまで */

  icon = gtk_tool_button_new(gtk_image_new_from_stock (GTK_STOCK_DELETE, iconsize), "");
  g_signal_connect(G_OBJECT(icon), "clicked", G_CALLBACK(clear_current_buffer_handler), NULL);
  gtk_container_add(GTK_CONTAINER (toolbar), GTK_WIDGET(icon));
  gtk_tool_item_set_tooltip(icon, toolbar_tips, "バッファの内容を全消去",
      "まだ内容が保存されていない場合でも警告しません");

  icon = gtk_tool_button_new(gtk_image_new_from_stock (GTK_STOCK_CLOSE, iconsize), "");
  g_signal_connect(G_OBJECT(icon), "clicked", G_CALLBACK(remove_tabpage), NULL);
  gtk_container_add(GTK_CONTAINER (toolbar), GTK_WIDGET(icon));
  gtk_tool_item_set_tooltip(icon, toolbar_tips, "バッファを閉じます",
      "まだ内容が保存されていない場合は警告します");

  icon = gtk_tool_button_new(gtk_image_new_from_stock (GTK_STOCK_CONNECT, iconsize), "");
  g_signal_connect(G_OBJECT(icon), "clicked", G_CALLBACK(load_scheme_file_by_gauche), NULL);
  gtk_container_add(GTK_CONTAINER (toolbar), GTK_WIDGET(icon));
  gtk_tool_item_set_tooltip(icon, toolbar_tips, "Scheme ファイルをロード", "");

  icon = gtk_tool_button_new(gtk_image_new_from_stock (GTK_STOCK_CONVERT, iconsize), "");
  g_signal_connect(G_OBJECT(icon), "clicked", G_CALLBACK(load_buffer_by_gauche), G_OBJECT(Shiki_EDITOR_NOTEBOOK));
  gtk_container_add(GTK_CONTAINER (toolbar), GTK_WIDGET(icon));
  gtk_tool_item_set_tooltip(icon, toolbar_tips, "バッファをロード", "");

  icon = gtk_tool_button_new(gtk_image_new_from_stock (GTK_STOCK_SPELL_CHECK, iconsize), "");
  g_signal_connect(G_OBJECT(icon), "clicked", G_CALLBACK(scheme_keyword_highlighting_current_buffer), NULL);
  gtk_container_add(GTK_CONTAINER (toolbar), GTK_WIDGET(icon));
  gtk_tool_item_set_tooltip(icon, toolbar_tips, "シンタックスハイライティング", "");


  icon = gtk_tool_button_new(gtk_image_new_from_stock (GTK_STOCK_DIALOG_QUESTION, iconsize), "");
  g_signal_connect(G_OBJECT(icon), "clicked", G_CALLBACK(open_online_help), NULL);
  gtk_container_add(GTK_CONTAINER (toolbar), GTK_WIDGET(icon));
  gtk_tool_item_set_tooltip(icon, toolbar_tips, "ヘルプ", "");

  icon = gtk_tool_button_new(gtk_image_new_from_stock (GTK_STOCK_BOLD, iconsize), "");
  g_signal_connect(G_OBJECT(icon), "clicked", G_CALLBACK(select_font), NULL);
  gtk_container_add(GTK_CONTAINER (toolbar), GTK_WIDGET(icon));
  gtk_tool_item_set_tooltip(icon, toolbar_tips, "フォントの変更", "");

  icon = gtk_tool_button_new(gtk_image_new_from_stock (GTK_STOCK_APPLY, iconsize), "");
  g_signal_connect(G_OBJECT(icon), "clicked", G_CALLBACK(tabsborder_on_off), G_OBJECT(Shiki_EDITOR_NOTEBOOK));
  gtk_container_add(GTK_CONTAINER (toolbar), GTK_WIDGET(icon));
  gtk_tool_item_set_tooltip(icon, toolbar_tips, "タブの on/off", "");

  icon = gtk_tool_button_new(gtk_image_new_from_stock (GTK_STOCK_PREFERENCES, iconsize), "");
  g_signal_connect(G_OBJECT(icon), "clicked", G_CALLBACK(rotate_tab_position), G_OBJECT(Shiki_EDITOR_NOTEBOOK));
  gtk_container_add(GTK_CONTAINER (toolbar), GTK_WIDGET(icon));
  gtk_tool_item_set_tooltip(icon, toolbar_tips, "タブ位置の設定", "");

  icon = gtk_tool_button_new(gtk_image_new_from_stock (GTK_STOCK_DIALOG_INFO, iconsize), "");
  g_signal_connect(G_OBJECT(icon), "clicked", G_CALLBACK(about_this_application), NULL);
  gtk_container_add(GTK_CONTAINER (toolbar), GTK_WIDGET(icon));
  gtk_tool_item_set_tooltip(icon, toolbar_tips, "このアプリケーションについて", "");

  /* モードライン作る */
  Shiki_EDITOR_MODELINE_LABEL = gtk_label_new(NULL);
  gtk_container_add(GTK_CONTAINER (modeline_bg), Shiki_EDITOR_MODELINE_LABEL);

  gdk_color_parse("black", &COLOR_BLACK);
  gdk_color_parse("green", &COLOR_GREEN);

  gtk_widget_modify_fg(Shiki_EDITOR_MODELINE_LABEL, GTK_STATE_NORMAL, &COLOR_GREEN);
  gtk_widget_modify_bg(modeline_bg, GTK_STATE_NORMAL, &COLOR_BLACK);

  gtk_box_pack_start(GTK_BOX(vbox), modeline_bg, TRUE, TRUE, 0);

  /* C-x C-s などの状態を表示するステータスバーをウィンドウボトムに追加 */
  Shiki_EDITOR_STATUSBAR = gtk_statusbar_new();
  gtk_box_pack_start(GTK_BOX(vbox), Shiki_EDITOR_STATUSBAR, TRUE, TRUE, 0);
  contextid = gtk_statusbar_get_context_id(GTK_STATUSBAR(Shiki_EDITOR_STATUSBAR), "");

  /* キーバインドのハンドリングを登録 */
  g_signal_connect(G_OBJECT(Shiki_EDITOR_NOTEBOOK), "key-press-event", G_CALLBACK (signal_key_press_handler), GINT_TO_POINTER(contextid));
  g_signal_connect(G_OBJECT(Shiki_EDITOR_NOTEBOOK), "key-release-event", G_CALLBACK (signal_key_release_handler), GINT_TO_POINTER(contextid));

  /* 引数に指定されたファイルを開く */
  if(argc >= 2) {
    int i;
    for(i = 1; i < argc; i++)
      open_file(g_strdup(argv[i]));
  } else /* 指定されてなければ，デフォルトのページを追加 */
    open_online_help(Shiki_EDITOR_NOTEBOOK);

  gtk_widget_grab_focus(GTK_WIDGET(Shiki_EDITOR_NOTEBOOK));
  gtk_widget_show_all(Shiki_EDITOR_WINDOW);
}

int main(int argc, char *argv[]) {
  /* 初期化してメインループへ */
  Shiki_EDITOR_DEFAULT_LOCALE = g_locale_to_utf8(gtk_set_locale(), -1, NULL, NULL, NULL);
  gtk_init(&argc, &argv);
  GC_INIT(); Scm_Init(GAUCHE_SIGNATURE);
  Scm_Load("gauche-init.scm", 0);
  Shiki_editor_window_init(argc, argv);
  gtk_main();
  Scm_Exit(0);
  return 0;
}
