Add a static global variable to monitor autocompletion mode in order to prevent cance...
[geany-mirror/kugel-geany.git] / src / editor.c
blobb374e3741a3c50a0200887f41e9cde12dc3ffeb5
1 /*
2 * editor.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005-2010 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2010 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com>
6 * Copyright 2009-2010 Frank Lanitz <frank(at)frank(dot)uvena(dot)de>
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 * $Id$
25 /**
26 * @file editor.h
27 * Editor-related functions for @ref GeanyEditor.
28 * Geany uses the Scintilla editing widget, and this file is mostly built around
29 * Scintilla's functionality.
30 * @see sciwrappers.h.
32 /* Callbacks for the Scintilla widget (ScintillaObject).
33 * Most important is the sci-notify callback, handled in on_editor_notification().
34 * This includes auto-indentation, comments, auto-completion, calltips, etc.
35 * Also some general Scintilla-related functions.
39 #include <ctype.h>
40 #include <string.h>
42 #include <gdk/gdkkeysyms.h>
44 #include "SciLexer.h"
45 #include "geany.h"
47 #include "support.h"
48 #include "editor.h"
49 #include "document.h"
50 #include "documentprivate.h"
51 #include "filetypes.h"
52 #include "sciwrappers.h"
53 #include "ui_utils.h"
54 #include "utils.h"
55 #include "dialogs.h"
56 #include "symbols.h"
57 #include "callbacks.h"
58 #include "templates.h"
59 #include "keybindings.h"
60 #include "project.h"
61 #include "projectprivate.h"
64 /* Note: use sciwrappers.h instead where possible.
65 * Do not use SSM in files unrelated to scintilla. */
66 #define SSM(s, m, w, l) scintilla_send_message(s, m, w, l)
69 static GHashTable *snippet_hash = NULL;
70 static GQueue *snippet_offsets = NULL;
71 static gint snippet_cursor_insert_pos;
73 /* holds word under the mouse or keyboard cursor */
74 static gchar current_word[GEANY_MAX_WORD_LENGTH];
76 /* Initialised in keyfile.c. */
77 GeanyEditorPrefs editor_prefs;
79 EditorInfo editor_info = {current_word, -1};
81 static struct
83 gchar *text;
84 gboolean set;
85 gchar *last_word;
86 guint tag_index;
87 gint pos;
88 ScintillaObject *sci;
89 } calltip = {NULL, FALSE, NULL, 0, 0, NULL};
91 static enum {
92 AUTOC_CANCELLED,
93 AUTOC_SCOPE,
94 AUTOC_TAGS,
95 AUTOC_DOC_WORDS,
96 } autocompletion_mode = AUTOC_CANCELLED;
98 static gchar indent[100];
101 static void on_new_line_added(GeanyEditor *editor);
102 static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch);
103 static void insert_indent_after_line(GeanyEditor *editor, gint line);
104 static void auto_multiline(GeanyEditor *editor, gint pos);
105 static gboolean is_code_style(gint lexer, gint style);
106 static gboolean is_string_style(gint lexer, gint style);
107 static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c);
108 static void auto_table(GeanyEditor *editor, gint pos);
109 static void close_block(GeanyEditor *editor, gint pos);
110 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos);
111 static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, size_t wordlen,
112 const gchar *wc, gboolean stem);
113 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent);
116 void editor_snippets_free(void)
118 g_hash_table_destroy(snippet_hash);
119 g_queue_free(snippet_offsets);
123 void editor_snippets_init(void)
125 gsize i, j, len = 0, len_keys = 0;
126 gchar *sysconfigfile, *userconfigfile;
127 gchar **groups_user, **groups_sys;
128 gchar **keys_user, **keys_sys;
129 gchar *value;
130 GKeyFile *sysconfig = g_key_file_new();
131 GKeyFile *userconfig = g_key_file_new();
132 GHashTable *tmp;
134 snippet_offsets = g_queue_new();
136 sysconfigfile = g_strconcat(app->datadir, G_DIR_SEPARATOR_S, "snippets.conf", NULL);
137 userconfigfile = g_strconcat(app->configdir, G_DIR_SEPARATOR_S, "snippets.conf", NULL);
139 /* check for old autocomplete.conf files (backwards compatibility) */
140 if (! g_file_test(userconfigfile, G_FILE_TEST_IS_REGULAR | G_FILE_TEST_IS_SYMLINK))
141 setptr(userconfigfile,
142 g_strconcat(app->configdir, G_DIR_SEPARATOR_S, "autocomplete.conf", NULL));
144 /* load the actual config files */
145 g_key_file_load_from_file(sysconfig, sysconfigfile, G_KEY_FILE_NONE, NULL);
146 g_key_file_load_from_file(userconfig, userconfigfile, G_KEY_FILE_NONE, NULL);
148 /* keys are strings, values are GHashTables, so use g_free and g_hash_table_destroy */
149 snippet_hash =
150 g_hash_table_new_full(g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_hash_table_destroy);
152 /* first read all globally defined auto completions */
153 groups_sys = g_key_file_get_groups(sysconfig, &len);
154 for (i = 0; i < len; i++)
156 keys_sys = g_key_file_get_keys(sysconfig, groups_sys[i], &len_keys, NULL);
157 /* create new hash table for the read section (=> filetype) */
158 tmp = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
159 g_hash_table_insert(snippet_hash, g_strdup(groups_sys[i]), tmp);
161 for (j = 0; j < len_keys; j++)
163 g_hash_table_insert(tmp, g_strdup(keys_sys[j]),
164 utils_get_setting_string(sysconfig, groups_sys[i], keys_sys[j], ""));
166 g_strfreev(keys_sys);
169 /* now read defined completions in user's configuration directory and add / replace them */
170 groups_user = g_key_file_get_groups(userconfig, &len);
171 for (i = 0; i < len; i++)
173 keys_user = g_key_file_get_keys(userconfig, groups_user[i], &len_keys, NULL);
175 tmp = g_hash_table_lookup(snippet_hash, groups_user[i]);
176 if (tmp == NULL)
177 { /* new key found, create hash table */
178 tmp = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
179 g_hash_table_insert(snippet_hash, g_strdup(groups_user[i]), tmp);
181 for (j = 0; j < len_keys; j++)
183 value = g_hash_table_lookup(tmp, keys_user[j]);
184 if (value == NULL)
185 { /* value = NULL means the key doesn't yet exist, so insert */
186 g_hash_table_insert(tmp, g_strdup(keys_user[j]),
187 utils_get_setting_string(userconfig, groups_user[i], keys_user[j], ""));
189 else
190 { /* old key and value will be freed by destroy function (g_free) */
191 g_hash_table_replace(tmp, g_strdup(keys_user[j]),
192 utils_get_setting_string(userconfig, groups_user[i], keys_user[j], ""));
195 g_strfreev(keys_user);
198 g_free(sysconfigfile);
199 g_free(userconfigfile);
200 g_strfreev(groups_sys);
201 g_strfreev(groups_user);
202 g_key_file_free(sysconfig);
203 g_key_file_free(userconfig);
207 static gboolean on_editor_button_press_event(GtkWidget *widget, GdkEventButton *event,
208 gpointer data)
210 GeanyEditor *editor = data;
211 GeanyDocument *doc = editor->document;
213 /* it's very unlikely we got a 'real' click even on 0, 0, so assume it is a
214 * fake event to show the editor menu triggered by a key event where we want to use the
215 * text cursor position. */
216 if (event->x > 0.0 && event->y > 0.0)
217 editor_info.click_pos = sci_get_position_from_xy(editor->sci,
218 (gint)event->x, (gint)event->y, FALSE);
219 else
220 editor_info.click_pos = sci_get_current_position(editor->sci);
222 if (event->button == 1)
224 guint state = event->state & gtk_accelerator_get_default_mod_mask();
226 if (event->type == GDK_BUTTON_PRESS && editor_prefs.disable_dnd)
228 gint ss = sci_get_selection_start(editor->sci);
229 sci_set_selection_end(editor->sci, ss);
231 if (event->type == GDK_BUTTON_PRESS && state == GDK_CONTROL_MASK)
233 sci_set_current_position(editor->sci, editor_info.click_pos, FALSE);
235 editor_find_current_word(editor, editor_info.click_pos,
236 current_word, sizeof current_word, NULL);
237 if (*current_word)
238 return symbols_goto_tag(current_word, TRUE);
239 else
240 keybindings_send_command(GEANY_KEY_GROUP_GOTO, GEANY_KEYS_GOTO_MATCHINGBRACE);
241 return TRUE;
243 return document_check_disk_status(doc, FALSE);
246 /* calls the edit popup menu in the editor */
247 if (event->button == 3)
249 gboolean can_goto;
251 editor_find_current_word(editor, editor_info.click_pos,
252 current_word, sizeof current_word, NULL);
254 can_goto = sci_has_selection(editor->sci) || current_word[0] != '\0';
255 ui_update_popup_goto_items(can_goto);
256 ui_update_popup_copy_items(doc);
257 ui_update_insert_include_item(doc, 0);
259 g_signal_emit_by_name(geany_object, "update-editor-menu",
260 current_word, editor_info.click_pos, doc);
262 gtk_menu_popup(GTK_MENU(main_widgets.editor_menu),
263 NULL, NULL, NULL, NULL, event->button, event->time);
265 return TRUE;
267 return FALSE;
271 static gboolean is_style_php(gint style)
273 if ((style >= SCE_HPHP_DEFAULT && style <= SCE_HPHP_OPERATOR) ||
274 style == SCE_HPHP_COMPLEX_VARIABLE)
276 return TRUE;
279 return FALSE;
283 gint editor_get_long_line_type(void)
285 if (app->project)
286 switch (app->project->long_line_behaviour)
288 case 0: /* marker disabled */
289 return 2;
290 case 1: /* use global settings */
291 break;
292 case 2: /* custom (enabled) */
293 return editor_prefs.long_line_global_type;
296 if (!editor_prefs.long_line_global_enabled)
297 return 2;
298 else
299 return editor_prefs.long_line_global_type;
303 gint editor_get_long_line_column(void)
305 if (app->project && app->project->long_line_behaviour != 1 /* use global settings */)
306 return app->project->long_line_column;
307 else
308 return editor_prefs.long_line_global_column;
312 void editor_toggle_fold(GeanyEditor *editor, gint line, gint modifiers)
314 ScintillaObject *sci;
316 g_return_if_fail(editor != NULL);
318 sci = editor->sci;
320 sci_toggle_fold(sci, line);
322 /* extra toggling of child fold points
323 * use when editor_prefs.unfold_all_children is set and Shift is NOT pressed or when
324 * editor_prefs.unfold_all_children is NOT set but Shift is pressed */
325 if ((editor_prefs.unfold_all_children && ! (modifiers & SCMOD_SHIFT)) ||
326 (! editor_prefs.unfold_all_children && (modifiers & SCMOD_SHIFT)))
328 gint last_line = SSM(sci, SCI_GETLASTCHILD, line, -1);
329 gint i;
331 if (sci_get_line_is_visible(sci, line + 1))
332 { /* unfold all children of the current fold point */
333 for (i = line; i < last_line; i++)
335 if (! sci_get_line_is_visible(sci, i))
337 sci_toggle_fold(sci, sci_get_fold_parent(sci, i));
341 else
342 { /* fold all children of the current fold point */
343 for (i = line; i < last_line; i++)
345 gint level = sci_get_fold_level(sci, i);
346 if (level & SC_FOLDLEVELHEADERFLAG)
348 if (sci_get_fold_expanded(sci, i))
349 sci_toggle_fold(sci, i);
357 static void on_margin_click(GeanyEditor *editor, SCNotification *nt)
359 /* left click to marker margin marks the line */
360 if (nt->margin == 1)
362 gint line = sci_get_line_from_position(editor->sci, nt->position);
364 /*sci_marker_delete_all(editor->sci, 1);*/
365 sci_toggle_marker_at_line(editor->sci, line, 1); /* toggle the marker */
367 /* left click on the folding margin to toggle folding state of current line */
368 else if (nt->margin == 2 && editor_prefs.folding)
370 gint line = sci_get_line_from_position(editor->sci, nt->position);
371 editor_toggle_fold(editor, line, nt->modifiers);
376 static void on_update_ui(GeanyEditor *editor, G_GNUC_UNUSED SCNotification *nt)
378 ScintillaObject *sci = editor->sci;
379 gint pos = sci_get_current_position(sci);
381 /* undo / redo menu update */
382 ui_update_popup_reundo_items(editor->document);
384 /* brace highlighting */
385 editor_highlight_braces(editor, pos);
387 ui_update_statusbar(editor->document, pos);
389 /* Visible lines are only laid out accurately once [SCN_UPDATEUI] is sent,
390 * so we need to only call sci_scroll_to_line here, because the document
391 * may have line wrapping and folding enabled.
392 * http://scintilla.sourceforge.net/ScintillaDoc.html#LineWrapping */
393 if (editor->scroll_percent > 0.0F)
395 editor_scroll_to_line(editor, -1, editor->scroll_percent);
396 editor->scroll_percent = -1.0F; /* disable further scrolling */
398 #if 0
399 /** experimental code for inverting selections */
401 gint i;
402 for (i = SSM(sci, SCI_GETSELECTIONSTART, 0, 0); i < SSM(sci, SCI_GETSELECTIONEND, 0, 0); i++)
404 /* need to get colour from getstyleat(), but how? */
405 SSM(sci, SCI_STYLESETFORE, STYLE_DEFAULT, 0);
406 SSM(sci, SCI_STYLESETBACK, STYLE_DEFAULT, 0);
409 sci_get_style_at(sci, pos);
411 #endif
415 static void check_line_breaking(GeanyEditor *editor, gint pos, gchar c)
417 ScintillaObject *sci = editor->sci;
418 gint line, lstart, col;
420 if (!editor->line_breaking)
421 return;
423 col = sci_get_col_from_position(sci, pos);
425 if (c == GDK_space)
426 pos--; /* Look for previous space, not the new one */
428 line = sci_get_current_line(sci);
430 lstart = sci_get_position_from_line(sci, line);
432 /* use column instead of position which might be different with multibyte characters */
433 if (col < editor_prefs.line_break_column)
434 return;
436 /* look for the last space before line_break_column */
437 pos = MIN(pos, lstart + editor_prefs.line_break_column);
439 while (pos > lstart)
441 c = sci_get_char_at(sci, --pos);
442 if (c == GDK_space)
444 gint diff, last_pos, last_col;
445 const gchar *eol = editor_get_eol_char(editor);
447 /* remember the distance between the current column and the last column on the line
448 * (we use column position in case the previous line gets altered, such as removing
449 * trailing spaces or in case it contains multibyte characters) */
450 last_pos = sci_get_line_end_position(sci, line);
451 last_col = sci_get_col_from_position(sci, last_pos);
452 diff = last_col - col;
454 /* break the line after the space */
455 sci_insert_text(sci, pos + 1, eol);
456 line++;
458 /* set position as if user had pressed return */
459 pos = sci_get_position_from_line(sci, line);
460 sci_set_current_position(sci, pos, FALSE);
461 /* add indentation, comment multilines, etc */
462 on_new_line_added(editor);
464 /* correct cursor position (might not be at line end) */
465 last_pos = sci_get_line_end_position(sci, line);
466 last_col = sci_get_col_from_position(sci, last_pos); /* get last column on line */
467 /* last column - distance is the desired column, then retrieve its document position */
468 pos = SSM(sci, SCI_FINDCOLUMN, line, last_col - diff);
469 sci_set_current_position(sci, pos, FALSE);
471 return;
477 static void show_autocomplete(ScintillaObject *sci, gint rootlen, const gchar *words)
479 /* store whether a calltip is showing, so we can reshow it after autocompletion */
480 calltip.set = SSM(sci, SCI_CALLTIPACTIVE, 0, 0);
481 SSM(sci, SCI_AUTOCSHOW, rootlen, (sptr_t) words);
485 static void show_tags_list(GeanyEditor *editor, const GPtrArray *tags, gsize rootlen)
487 ScintillaObject *sci = editor->sci;
489 g_return_if_fail(tags);
491 if (tags->len > 0)
493 GString *words = g_string_sized_new(150);
494 guint j;
496 for (j = 0; j < tags->len; ++j)
498 TMTag *tag = tags->pdata[j];
500 if (j > 0)
501 g_string_append_c(words, '\n');
503 if (j == editor_prefs.autocompletion_max_entries)
505 g_string_append(words, "...");
506 break;
508 g_string_append(words, tag->name);
510 /* for now, tag types don't all follow C, so just look at arglist */
511 if (NZV(tag->atts.entry.arglist))
512 g_string_append(words, "?2");
513 else
514 g_string_append(words, "?1");
516 show_autocomplete(sci, rootlen, words->str);
517 g_string_free(words, TRUE);
522 /* do not use with long strings */
523 static gboolean match_last_chars(ScintillaObject *sci, gint pos, const gchar *str)
525 gsize len = strlen(str);
526 gchar *buf;
528 g_return_val_if_fail(len < 100, FALSE);
530 buf = g_alloca(len + 1);
531 sci_get_text_range(sci, pos - len, pos, buf);
532 return strcmp(str, buf) == 0;
536 static gboolean reshow_calltip(gpointer data)
538 GeanyDocument *doc;
540 g_return_val_if_fail(calltip.sci != NULL, FALSE);
542 SSM(calltip.sci, SCI_CALLTIPCANCEL, 0, 0);
543 doc = document_get_current();
545 if (doc && doc->editor->sci == calltip.sci)
547 /* we use the position where the calltip was previously started as SCI_GETCURRENTPOS
548 * may be completely wrong in case the user cancelled the auto completion with the mouse */
549 SSM(calltip.sci, SCI_CALLTIPSHOW, calltip.pos, (sptr_t) calltip.text);
551 return FALSE;
555 static void request_reshowing_calltip(SCNotification *nt)
557 if (calltip.set)
559 /* delay the reshow of the calltip window to make sure it is actually displayed,
560 * without it might be not visible on SCN_AUTOCCANCEL */
561 g_idle_add(reshow_calltip, NULL);
566 static void autocomplete_scope(GeanyEditor *editor)
568 ScintillaObject *sci = editor->sci;
569 gint pos = sci_get_current_position(editor->sci);
570 gchar typed = sci_get_char_at(sci, pos - 1);
571 gchar *name;
572 const GPtrArray *tags = NULL;
573 const TMTag *tag;
574 GeanyFiletype *ft = editor->document->file_type;
576 if (ft->id == GEANY_FILETYPES_C || ft->id == GEANY_FILETYPES_CPP)
578 if (match_last_chars(sci, pos, "->") || match_last_chars(sci, pos, "::"))
579 pos--;
580 else if (typed != '.')
581 return;
583 else if (typed != '.')
584 return;
586 /* allow for a space between word and operator */
587 if (isspace(sci_get_char_at(sci, pos - 2)))
588 pos--;
589 name = editor_get_word_at_pos(editor, pos - 1, NULL);
590 if (!name)
591 return;
593 tags = tm_workspace_find(name, tm_tag_max_t, NULL, FALSE, ft->lang);
594 g_free(name);
595 if (!tags || tags->len == 0)
596 return;
598 tag = g_ptr_array_index(tags, 0);
599 name = tag->atts.entry.var_type;
600 if (name)
602 TMWorkObject *obj = editor->document->tm_file;
604 tags = tm_workspace_find_scope_members(obj ? obj->tags_array : NULL,
605 name, TRUE, FALSE);
606 if (tags)
608 autocompletion_mode = AUTOC_SCOPE;
609 show_tags_list(editor, tags, 0);
615 static void on_char_added(GeanyEditor *editor, SCNotification *nt)
617 ScintillaObject *sci = editor->sci;
618 gint pos = sci_get_current_position(sci);
620 switch (nt->ch)
622 case '\r':
623 { /* simple indentation (only for CR format) */
624 if (sci_get_eol_mode(sci) == SC_EOL_CR)
625 on_new_line_added(editor);
626 break;
628 case '\n':
629 { /* simple indentation (for CR/LF and LF format) */
630 on_new_line_added(editor);
631 break;
633 case '>':
634 editor_start_auto_complete(editor, pos, FALSE); /* C/C++ ptr-> scope completion */
635 /* fall through */
636 case '/':
637 { /* close xml-tags */
638 handle_xml(editor, pos, nt->ch);
639 break;
641 case '(':
643 auto_close_chars(sci, pos, nt->ch);
644 /* show calltips */
645 editor_show_calltip(editor, --pos);
646 break;
648 case ')':
649 { /* hide calltips */
650 if (SSM(sci, SCI_CALLTIPACTIVE, 0, 0))
652 SSM(sci, SCI_CALLTIPCANCEL, 0, 0);
654 g_free(calltip.text);
655 calltip.text = NULL;
656 calltip.pos = 0;
657 calltip.sci = NULL;
658 calltip.set = FALSE;
659 break;
661 case '{':
662 case '[':
663 case '"':
664 case '\'':
666 auto_close_chars(sci, pos, nt->ch);
667 break;
669 case '}':
670 { /* closing bracket handling */
671 if (editor->auto_indent)
672 close_block(editor, pos - 1);
673 break;
675 /* scope autocompletion */
676 case '.':
677 case ':': /* C/C++ class:: syntax */
678 /* tag autocompletion */
679 default:
680 #if 0
681 if (! editor_start_auto_complete(editor, pos, FALSE))
682 request_reshowing_calltip(nt);
683 #else
684 editor_start_auto_complete(editor, pos, FALSE);
685 #endif
687 check_line_breaking(editor, pos, nt->ch);
691 /* expand() and fold_changed() are copied from SciTE (thanks) to fix #1923350. */
692 static void expand(ScintillaObject *sci, gint *line, gboolean doExpand,
693 gboolean force, gint visLevels, gint level)
695 gint lineMaxSubord = SSM(sci, SCI_GETLASTCHILD, *line, level & SC_FOLDLEVELNUMBERMASK);
696 gint levelLine = level;
697 (*line)++;
698 while (*line <= lineMaxSubord)
700 if (G_UNLIKELY(force))
702 if (visLevels > 0)
703 SSM(sci, SCI_SHOWLINES, *line, *line);
704 else
705 SSM(sci, SCI_HIDELINES, *line, *line);
707 else
709 if (doExpand)
710 SSM(sci, SCI_SHOWLINES, *line, *line);
712 if (levelLine == -1)
713 levelLine = SSM(sci, SCI_GETFOLDLEVEL, *line, 0);
714 if (levelLine & SC_FOLDLEVELHEADERFLAG)
716 if (G_UNLIKELY(force))
718 if (visLevels > 1)
719 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
720 else
721 SSM(sci, SCI_SETFOLDEXPANDED, *line, 0);
722 expand(sci, line, doExpand, force, visLevels - 1, -1);
724 else
726 if (doExpand)
728 if (!sci_get_fold_expanded(sci, *line))
729 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
730 expand(sci, line, TRUE, force, visLevels - 1, -1);
732 else
734 expand(sci, line, FALSE, force, visLevels - 1, -1);
738 else
740 (*line)++;
746 static void fold_changed(ScintillaObject *sci, gint line, gint levelNow, gint levelPrev)
748 if (levelNow & SC_FOLDLEVELHEADERFLAG)
750 if (! (levelPrev & SC_FOLDLEVELHEADERFLAG))
752 /* Adding a fold point */
753 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
754 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
757 else if (levelPrev & SC_FOLDLEVELHEADERFLAG)
759 if (! sci_get_fold_expanded(sci, line))
760 { /* Removing the fold from one that has been contracted so should expand
761 * otherwise lines are left invisible with no way to make them visible */
762 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
763 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
766 if (! (levelNow & SC_FOLDLEVELWHITEFLAG) &&
767 ((levelPrev & SC_FOLDLEVELNUMBERMASK) > (levelNow & SC_FOLDLEVELNUMBERMASK)))
769 /* See if should still be hidden */
770 gint parentLine = sci_get_fold_parent(sci, line);
771 if (parentLine < 0)
773 SSM(sci, SCI_SHOWLINES, line, line);
775 else if (sci_get_fold_expanded(sci, parentLine) &&
776 sci_get_line_is_visible(sci, parentLine))
778 SSM(sci, SCI_SHOWLINES, line, line);
784 static void ensure_range_visible(ScintillaObject *sci, gint posStart, gint posEnd,
785 gboolean enforcePolicy)
787 gint lineStart = sci_get_line_from_position(sci, MIN(posStart, posEnd));
788 gint lineEnd = sci_get_line_from_position(sci, MAX(posStart, posEnd));
789 gint line;
791 for (line = lineStart; line <= lineEnd; line++)
793 SSM(sci, enforcePolicy ? SCI_ENSUREVISIBLEENFORCEPOLICY : SCI_ENSUREVISIBLE, line, 0);
798 static void auto_update_margin_width(GeanyEditor *editor)
800 gint next_linecount = 1;
801 gint linecount = sci_get_line_count(editor->sci);
802 GeanyDocument *doc = editor->document;
804 while (next_linecount <= linecount)
805 next_linecount *= 10;
807 if (editor->document->priv->line_count != next_linecount)
809 doc->priv->line_count = next_linecount;
810 sci_set_line_numbers(editor->sci, TRUE, 0);
815 static void partial_complete(ScintillaObject *sci, const gchar *text)
817 gint pos = sci_get_current_position(sci);
819 sci_insert_text(sci, pos, text);
820 sci_set_current_position(sci, pos + strlen(text), TRUE);
824 /* Complete the next word part from @a entry */
825 static gboolean check_partial_completion(GeanyEditor *editor, const gchar *entry)
827 gchar *stem, *ptr, *text = utils_strdupa(entry);
829 read_current_word(editor, -1, current_word, sizeof current_word, NULL, TRUE);
830 stem = current_word;
831 if (strstr(text, stem) != text)
832 return FALSE; /* shouldn't happen */
833 if (strlen(text) <= strlen(stem))
834 return FALSE;
836 text += strlen(stem); /* skip stem */
837 ptr = strstr(text + 1, "_");
838 if (ptr)
840 ptr[1] = '\0';
841 partial_complete(editor->sci, text);
842 return TRUE;
844 else
846 /* CamelCase */
847 foreach_str(ptr, text + 1)
849 if (!ptr[0])
850 break;
851 if (g_ascii_isupper(*ptr) && g_ascii_islower(ptr[1]))
853 ptr[0] = '\0';
854 partial_complete(editor->sci, text);
855 return TRUE;
859 return FALSE;
863 /* Callback for the "sci-notify" signal to emit a "editor-notify" signal.
864 * Plugins can connect to the "editor-notify" signal. */
865 void editor_sci_notify_cb(G_GNUC_UNUSED GtkWidget *widget, G_GNUC_UNUSED gint scn,
866 gpointer scnt, gpointer data)
868 GeanyEditor *editor = data;
869 gboolean retval;
871 g_return_if_fail(editor != NULL);
873 g_signal_emit_by_name(geany_object, "editor-notify", editor, scnt, &retval);
877 static gboolean on_editor_notify(G_GNUC_UNUSED GObject *object, GeanyEditor *editor,
878 SCNotification *nt, G_GNUC_UNUSED gpointer data)
880 ScintillaObject *sci = editor->sci;
881 GeanyDocument *doc = editor->document;
883 switch (nt->nmhdr.code)
885 case SCN_SAVEPOINTLEFT:
886 document_set_text_changed(doc, TRUE);
887 break;
889 case SCN_SAVEPOINTREACHED:
890 document_set_text_changed(doc, FALSE);
891 break;
893 case SCN_MODIFYATTEMPTRO:
894 utils_beep();
895 break;
897 case SCN_MARGINCLICK:
898 on_margin_click(editor, nt);
899 break;
901 case SCN_UPDATEUI:
902 on_update_ui(editor, nt);
903 break;
905 case SCN_MODIFIED:
906 if (editor_prefs.show_linenumber_margin && (nt->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT)) && nt->linesAdded)
908 /* automatically adjust Scintilla's line numbers margin width */
909 auto_update_margin_width(editor);
911 if (nt->modificationType & SC_STARTACTION && ! ignore_callback)
913 /* get notified about undo changes */
914 document_undo_add(doc, UNDO_SCINTILLA, NULL);
916 if (editor_prefs.folding && (nt->modificationType & SC_MOD_CHANGEFOLD) != 0)
918 /* handle special fold cases, e.g. #1923350 */
919 fold_changed(sci, nt->line, nt->foldLevelNow, nt->foldLevelPrev);
921 break;
923 case SCN_CHARADDED:
924 on_char_added(editor, nt);
925 break;
927 case SCN_USERLISTSELECTION:
928 if (nt->listType == 1)
930 sci_add_text(sci, nt->text);
932 break;
934 case SCN_AUTOCSELECTION:
935 if (g_str_equal(nt->text, "..."))
937 sci_cancel(sci);
938 utils_beep();
939 break;
941 /* fall through */
942 case SCN_AUTOCCANCELLED:
943 /* now that autocomplete is finishing or was cancelled, reshow calltips
944 * if they were showing */
945 autocompletion_mode = AUTOC_CANCELLED;
946 request_reshowing_calltip(nt);
947 break;
949 #ifdef GEANY_DEBUG
950 case SCN_STYLENEEDED:
951 geany_debug("style");
952 break;
953 #endif
954 case SCN_NEEDSHOWN:
955 ensure_range_visible(sci, nt->position, nt->position + nt->length, FALSE);
956 break;
958 case SCN_URIDROPPED:
959 if (nt->text != NULL)
961 document_open_file_list(nt->text, -1);
963 break;
965 case SCN_CALLTIPCLICK:
966 if (nt->position > 0)
968 switch (nt->position)
970 case 1: /* up arrow */
971 if (calltip.tag_index > 0)
972 calltip.tag_index--;
973 break;
975 case 2: calltip.tag_index++; break; /* down arrow */
977 editor_show_calltip(editor, -1);
979 break;
981 /* we always return FALSE here to let plugins handle the event too */
982 return FALSE;
986 /* Note: this is the same as sci_get_tab_width(), but is still useful when you don't have
987 * a scintilla pointer. */
988 static gint get_tab_width(const GeanyIndentPrefs *indent_prefs)
990 if (indent_prefs->type == GEANY_INDENT_TYPE_BOTH)
991 return indent_prefs->hard_tab_width;
993 return indent_prefs->width; /* tab width = indent width */
997 /* Returns a string containing width chars of whitespace, filled with simple space
998 * characters or with the right number of tab characters, according to the indent prefs.
999 * (Result is filled with tabs *and* spaces if width isn't a multiple of
1000 * the tab width). */
1001 static gchar *
1002 get_whitespace(const GeanyIndentPrefs *iprefs, gint width)
1004 g_return_val_if_fail(width >= 0, NULL);
1006 if (width == 0)
1007 return g_strdup("");
1009 if (iprefs->type == GEANY_INDENT_TYPE_SPACES)
1011 return g_strnfill(width, ' ');
1013 else
1014 { /* first fill text with tabs and fill the rest with spaces */
1015 const gint tab_width = get_tab_width(iprefs);
1016 gint tabs = width / tab_width;
1017 gint spaces = width % tab_width;
1018 gint len = tabs + spaces;
1019 gchar *str;
1021 str = g_malloc(len + 1);
1023 memset(str, '\t', tabs);
1024 memset(str + tabs, ' ', spaces);
1025 str[len] = '\0';
1026 return str;
1031 static const GeanyIndentPrefs *
1032 get_default_indent_prefs(void)
1034 static GeanyIndentPrefs iprefs;
1036 iprefs = app->project ? *app->project->priv->indentation : *editor_prefs.indentation;
1037 return &iprefs;
1041 /** Gets the indentation prefs for the editor.
1042 * In future, the prefs might be different according to project or filetype.
1043 * @warning Always get a fresh result instead of keeping a pointer to it if the editor
1044 * settings may have changed, or if this function has been called for a different @a editor.
1045 * @param editor The editor, or @c NULL to get the default indent prefs.
1046 * @return The indent prefs. */
1047 const GeanyIndentPrefs *
1048 editor_get_indent_prefs(GeanyEditor *editor)
1050 static GeanyIndentPrefs iprefs;
1052 iprefs = *get_default_indent_prefs();
1054 if (editor == NULL)
1055 return &iprefs;
1057 iprefs.type = editor->indent_type;
1059 /* if per-document auto-indent is enabled, but we don't have a global mode set,
1060 * just use basic auto-indenting */
1061 if (editor->auto_indent && iprefs.auto_indent_mode == GEANY_AUTOINDENT_NONE)
1062 iprefs.auto_indent_mode = GEANY_AUTOINDENT_BASIC;
1064 if (!editor->auto_indent)
1065 iprefs.auto_indent_mode = GEANY_AUTOINDENT_NONE;
1067 return &iprefs;
1071 static void on_new_line_added(GeanyEditor *editor)
1073 ScintillaObject *sci = editor->sci;
1074 gint line = sci_get_current_line(sci);
1076 /* simple indentation */
1077 if (editor->auto_indent)
1079 insert_indent_after_line(editor, line - 1);
1082 if (editor_prefs.auto_continue_multiline)
1083 { /* " * " auto completion in multiline C/C++/D/Java comments */
1084 auto_multiline(editor, line);
1087 if (editor_prefs.newline_strip)
1088 { /* strip the trailing spaces on the previous line */
1089 editor_strip_line_trailing_spaces(editor, line - 1);
1094 static gboolean lexer_has_braces(ScintillaObject *sci)
1096 gint lexer = sci_get_lexer(sci);
1098 switch (lexer)
1100 case SCLEX_CPP:
1101 case SCLEX_D:
1102 case SCLEX_HTML: /* for PHP & JS */
1103 case SCLEX_PASCAL: /* for multiline comments? */
1104 case SCLEX_BASH:
1105 case SCLEX_PERL:
1106 case SCLEX_TCL:
1107 return TRUE;
1108 default:
1109 return FALSE;
1114 /* Read indent chars for the line that pos is on into indent global variable.
1115 * Note: Use sci_get_line_indentation() and get_whitespace()/editor_insert_text_block()
1116 * instead in any new code. */
1117 static void read_indent(GeanyEditor *editor, gint pos)
1119 ScintillaObject *sci = editor->sci;
1120 guint i, len, j = 0;
1121 gint line;
1122 gchar *linebuf;
1124 line = sci_get_line_from_position(sci, pos);
1126 len = sci_get_line_length(sci, line);
1127 linebuf = sci_get_line(sci, line);
1129 for (i = 0; i < len && j <= (sizeof(indent) - 1); i++)
1131 if (linebuf[i] == ' ' || linebuf[i] == '\t') /* simple indentation */
1132 indent[j++] = linebuf[i];
1133 else
1134 break;
1136 indent[j] = '\0';
1137 g_free(linebuf);
1141 static gint get_brace_indent(ScintillaObject *sci, gint line)
1143 guint i, len;
1144 gint ret = 0;
1145 gchar *linebuf;
1147 len = sci_get_line_length(sci, line);
1148 linebuf = sci_get_line(sci, line);
1150 for (i = 0; i < len; i++)
1152 /* i == (len - 1) prevents wrong indentation after lines like
1153 * " { return bless({}, shift); }" (Perl) */
1154 if (linebuf[i] == '{' && i == (len - 1))
1156 ret++;
1157 break;
1159 else
1161 gint k = len - 1;
1163 while (k > 0 && isspace(linebuf[k])) k--;
1165 /* if last non-whitespace character is a { increase indentation by a tab
1166 * e.g. for (...) { */
1167 if (linebuf[k] == '{')
1169 ret++;
1171 break;
1174 g_free(linebuf);
1175 return ret;
1179 static gint get_python_indent(ScintillaObject *sci, gint line)
1181 gint last_char = sci_get_line_end_position(sci, line) - 1;
1183 /* add extra indentation for Python after colon */
1184 if (sci_get_char_at(sci, last_char) == ':' &&
1185 sci_get_style_at(sci, last_char) == SCE_P_OPERATOR)
1187 return 1;
1189 return 0;
1193 static gint get_indent_size_after_line(GeanyEditor *editor, gint line)
1195 ScintillaObject *sci = editor->sci;
1196 gint size;
1197 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1199 g_return_val_if_fail(line >= 0, 0);
1201 size = sci_get_line_indentation(sci, line);
1203 if (iprefs->auto_indent_mode > GEANY_AUTOINDENT_BASIC)
1205 if (lexer_has_braces(sci))
1206 size += iprefs->width * get_brace_indent(sci, line);
1207 else
1208 if (FILETYPE_ID(editor->document->file_type) == GEANY_FILETYPES_PYTHON)
1209 size += iprefs->width * get_python_indent(sci, line);
1211 return size;
1215 static void insert_indent_after_line(GeanyEditor *editor, gint line)
1217 ScintillaObject *sci = editor->sci;
1218 gint line_indent = sci_get_line_indentation(sci, line);
1219 gint size = get_indent_size_after_line(editor, line);
1220 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1221 gchar *text;
1223 if (size == 0)
1224 return;
1226 if (iprefs->type == GEANY_INDENT_TYPE_TABS && size == line_indent)
1228 /* support tab indents, space aligns style - copy last line 'indent' exactly */
1229 gint start = sci_get_position_from_line(sci, line);
1230 gint end = sci_get_line_indent_position(sci, line);
1232 text = sci_get_contents_range(sci, start, end);
1234 else
1236 text = get_whitespace(iprefs, size);
1238 sci_add_text(sci, text);
1239 g_free(text);
1243 static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c)
1245 const gchar *closing_char = NULL;
1246 gint end_pos = -1;
1248 if (utils_isbrace(c, 0))
1249 end_pos = sci_find_matching_brace(sci, pos - 1);
1251 switch (c)
1253 case '(':
1254 if ((editor_prefs.autoclose_chars & GEANY_AC_PARENTHESIS) && end_pos == -1)
1255 closing_char = ")";
1256 break;
1257 case '{':
1258 if ((editor_prefs.autoclose_chars & GEANY_AC_CBRACKET) && end_pos == -1)
1259 closing_char = "}";
1260 break;
1261 case '[':
1262 if ((editor_prefs.autoclose_chars & GEANY_AC_SBRACKET) && end_pos == -1)
1263 closing_char = "]";
1264 break;
1265 case '\'':
1266 if (editor_prefs.autoclose_chars & GEANY_AC_SQUOTE)
1267 closing_char = "'";
1268 break;
1269 case '"':
1270 if (editor_prefs.autoclose_chars & GEANY_AC_DQUOTE)
1271 closing_char = "\"";
1272 break;
1275 if (closing_char != NULL)
1277 sci_add_text(sci, closing_char);
1278 sci_set_current_position(sci, pos, TRUE);
1283 /* Finds a corresponding matching brace to the given pos
1284 * (this is taken from Scintilla Editor.cxx,
1285 * fit to work with close_block) */
1286 static gint brace_match(ScintillaObject *sci, gint pos)
1288 gchar chBrace = sci_get_char_at(sci, pos);
1289 gchar chSeek = utils_brace_opposite(chBrace);
1290 gchar chAtPos;
1291 gint direction = -1;
1292 gint styBrace;
1293 gint depth = 1;
1294 gint styAtPos;
1296 styBrace = sci_get_style_at(sci, pos);
1298 if (utils_is_opening_brace(chBrace, editor_prefs.brace_match_ltgt))
1299 direction = 1;
1301 pos = pos + direction;
1302 while ((pos >= 0) && (pos < sci_get_length(sci)))
1304 chAtPos = sci_get_char_at(sci, pos - 1);
1305 styAtPos = sci_get_style_at(sci, pos);
1307 if ((pos > sci_get_end_styled(sci)) || (styAtPos == styBrace))
1309 if (chAtPos == chBrace)
1310 depth++;
1311 if (chAtPos == chSeek)
1312 depth--;
1313 if (depth == 0)
1314 return pos;
1316 pos = pos + direction;
1318 return -1;
1322 /* Called after typing '}'. */
1323 static void close_block(GeanyEditor *editor, gint pos)
1325 GeanyDocument *doc;
1326 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1327 gint x = 0, cnt = 0;
1328 gint line, line_len, eol_char_len;
1329 gchar *text, *line_buf;
1330 ScintillaObject *sci;
1331 gint line_indent, last_indent;
1333 if (iprefs->auto_indent_mode < GEANY_AUTOINDENT_CURRENTCHARS)
1334 return;
1335 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
1337 sci = editor->sci;
1338 doc = editor->document;
1340 if (! lexer_has_braces(sci))
1341 return;
1343 line = sci_get_line_from_position(sci, pos);
1344 line_len = sci_get_line_length(sci, line);
1345 /* set eol_char_len to 0 if on last line, because there is no EOL char */
1346 eol_char_len = (line == (sci_get_line_count(sci) - 1)) ? 0 :
1347 editor_get_eol_char_len(editor);
1349 /* check that the line is empty, to not kill text in the line */
1350 line_buf = sci_get_line(sci, line);
1351 line_buf[line_len - eol_char_len] = '\0';
1352 while (x < (line_len - eol_char_len))
1354 if (isspace(line_buf[x]))
1355 cnt++;
1356 x++;
1358 g_free(line_buf);
1360 if ((line_len - eol_char_len - 1) != cnt)
1361 return;
1363 if (iprefs->auto_indent_mode == GEANY_AUTOINDENT_MATCHBRACES)
1365 gint start_brace = brace_match(sci, pos);
1367 if (start_brace >= 0)
1369 gint line_start;
1370 gint brace_line = sci_get_line_from_position(sci, start_brace);
1371 gint size = sci_get_line_indentation(sci, brace_line);
1372 gchar *ind = get_whitespace(iprefs, size);
1374 text = g_strconcat(ind, "}", NULL);
1375 line_start = sci_get_position_from_line(sci, line);
1376 sci_set_anchor(sci, line_start);
1377 sci_replace_sel(sci, text);
1378 g_free(text);
1379 g_free(ind);
1380 return;
1382 /* fall through - unmatched brace (possibly because of TCL, PHP lexer bugs) */
1385 /* GEANY_AUTOINDENT_CURRENTCHARS */
1386 line_indent = sci_get_line_indentation(sci, line);
1387 last_indent = sci_get_line_indentation(sci, line - 1);
1389 if (line_indent < last_indent)
1390 return;
1391 line_indent -= iprefs->width;
1392 line_indent = MAX(0, line_indent);
1393 sci_set_line_indentation(sci, line, line_indent);
1397 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1398 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1399 * position can be -1, then the current position is used.
1400 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1401 static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, size_t wordlen,
1402 const gchar *wc, gboolean stem)
1404 gint line, line_start, startword, endword;
1405 gchar *chunk;
1406 ScintillaObject *sci;
1408 g_return_if_fail(editor != NULL);
1409 sci = editor->sci;
1411 if (pos == -1)
1412 pos = sci_get_current_position(sci);
1414 line = sci_get_line_from_position(sci, pos);
1415 line_start = sci_get_position_from_line(sci, line);
1416 startword = pos - line_start;
1417 endword = pos - line_start;
1419 word[0] = '\0';
1420 chunk = sci_get_line(sci, line);
1422 if (wc == NULL)
1423 wc = GEANY_WORDCHARS;
1425 /* the checks for "c < 0" are to allow any Unicode character which should make the code
1426 * a little bit more Unicode safe, anyway, this allows also any Unicode punctuation,
1427 * TODO: improve this code */
1428 while (startword > 0 && (strchr(wc, chunk[startword - 1]) || chunk[startword - 1] < 0))
1429 startword--;
1430 if (!stem)
1432 while (chunk[endword] != 0 && (strchr(wc, chunk[endword]) || chunk[endword] < 0))
1433 endword++;
1436 if (startword != endword)
1438 chunk[endword] = '\0';
1440 g_strlcpy(word, chunk + startword, wordlen); /* ensure null terminated */
1442 else
1443 g_strlcpy(word, "", wordlen);
1445 g_free(chunk);
1449 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1450 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1451 * position can be -1, then the current position is used.
1452 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1453 void editor_find_current_word(GeanyEditor *editor, gint pos, gchar *word, size_t wordlen,
1454 const gchar *wc)
1456 read_current_word(editor, pos, word, wordlen, wc, FALSE);
1461 * Finds the word at the position specified by @a pos. If any word is found, it is returned.
1462 * Otherwise NULL is returned.
1463 * Additional wordchars can be specified to define what to consider as a word.
1465 * @param editor The editor to operate on.
1466 * @param pos The position where the word should be read from.
1467 * Maybe @c -1 to use the current position.
1468 * @param wordchars The wordchars to separate words. wordchars mean all characters to count
1469 * as part of a word. Maybe @c NULL to use the default wordchars,
1470 * see @ref GEANY_WORDCHARS.
1472 * @return A newly-allocated string containing the word at the given @a pos or @c NULL.
1473 * Should be freed when no longer needed.
1475 * @since 0.16
1477 gchar *editor_get_word_at_pos(GeanyEditor *editor, gint pos, const gchar *wordchars)
1479 static gchar cword[GEANY_MAX_WORD_LENGTH];
1481 g_return_val_if_fail(editor != NULL, FALSE);
1483 read_current_word(editor, pos, cword, sizeof(cword), wordchars, FALSE);
1485 return (*cword == '\0') ? NULL : g_strdup(cword);
1489 /* Read the word up to position @a pos. */
1490 static const gchar *
1491 editor_read_word_stem(GeanyEditor *editor, gint pos, const gchar *wordchars)
1493 static gchar word[GEANY_MAX_WORD_LENGTH];
1495 read_current_word(editor, pos, word, sizeof word, wordchars, TRUE);
1497 return (*word) ? word : NULL;
1501 static gint find_previous_brace(ScintillaObject *sci, gint pos)
1503 gchar c;
1504 gint orig_pos = pos;
1506 c = sci_get_char_at(sci, pos);
1507 while (pos >= 0 && pos > orig_pos - 300)
1509 c = sci_get_char_at(sci, pos);
1510 pos--;
1511 if (utils_is_opening_brace(c, editor_prefs.brace_match_ltgt))
1512 return pos;
1514 return -1;
1518 static gint find_start_bracket(ScintillaObject *sci, gint pos)
1520 gchar c;
1521 gint brackets = 0;
1522 gint orig_pos = pos;
1524 c = sci_get_char_at(sci, pos);
1525 while (pos > 0 && pos > orig_pos - 300)
1527 c = sci_get_char_at(sci, pos);
1528 if (c == ')') brackets++;
1529 else if (c == '(') brackets--;
1530 pos--;
1531 if (brackets < 0) return pos; /* found start bracket */
1533 return -1;
1537 static gboolean append_calltip(GString *str, const TMTag *tag, filetype_id ft_id)
1539 if (! tag->atts.entry.arglist)
1540 return FALSE;
1542 if (ft_id != GEANY_FILETYPES_PASCAL)
1543 { /* usual calltips: "retval tagname (arglist)" */
1544 if (tag->atts.entry.var_type)
1546 guint i;
1548 g_string_append(str, tag->atts.entry.var_type);
1549 for (i = 0; i < tag->atts.entry.pointerOrder; i++)
1551 g_string_append_c(str, '*');
1553 g_string_append_c(str, ' ');
1555 if (tag->atts.entry.scope)
1557 const gchar *cosep = symbols_get_context_separator(ft_id);
1559 g_string_append(str, tag->atts.entry.scope);
1560 g_string_append(str, cosep);
1562 g_string_append(str, tag->name);
1563 g_string_append_c(str, ' ');
1564 g_string_append(str, tag->atts.entry.arglist);
1566 else
1567 { /* special case Pascal calltips: "tagname (arglist) : retval" */
1568 g_string_append(str, tag->name);
1569 g_string_append_c(str, ' ');
1570 g_string_append(str, tag->atts.entry.arglist);
1572 if (NZV(tag->atts.entry.var_type))
1574 g_string_append(str, " : ");
1575 g_string_append(str, tag->atts.entry.var_type);
1579 return TRUE;
1583 static gchar *find_calltip(const gchar *word, GeanyFiletype *ft)
1585 const GPtrArray *tags;
1586 const gint arg_types = tm_tag_function_t | tm_tag_prototype_t |
1587 tm_tag_method_t | tm_tag_macro_with_arg_t;
1588 TMTagAttrType *attrs = NULL;
1589 TMTag *tag;
1590 GString *str = NULL;
1591 guint i;
1593 g_return_val_if_fail(ft && word && *word, NULL);
1595 /* use all types in case language uses wrong tag type e.g. python "members" instead of "methods" */
1596 tags = tm_workspace_find(word, tm_tag_max_t, attrs, FALSE, ft->lang);
1597 if (tags->len == 0)
1598 return NULL;
1600 tag = TM_TAG(tags->pdata[0]);
1602 if (tag->type == tm_tag_class_t && FILETYPE_ID(ft) == GEANY_FILETYPES_D)
1604 /* user typed e.g. 'new Classname(' so lookup D constructor Classname::this() */
1605 tags = tm_workspace_find_scoped("this", tag->name,
1606 arg_types, attrs, FALSE, ft->lang, TRUE);
1607 if (tags->len == 0)
1608 return NULL;
1611 /* remove tags with no argument list */
1612 for (i = 0; i < tags->len; i++)
1614 tag = TM_TAG(tags->pdata[i]);
1616 if (! tag->atts.entry.arglist)
1617 tags->pdata[i] = NULL;
1619 tm_tags_prune((GPtrArray *) tags);
1620 if (tags->len == 0)
1621 return NULL;
1622 else
1623 { /* remove duplicate calltips */
1624 TMTagAttrType sort_attr[] = {tm_tag_attr_name_t, tm_tag_attr_scope_t,
1625 tm_tag_attr_arglist_t, 0};
1627 tm_tags_sort((GPtrArray *) tags, sort_attr, TRUE);
1630 /* if the current word has changed since last time, start with the first tag match */
1631 if (! utils_str_equal(word, calltip.last_word))
1632 calltip.tag_index = 0;
1633 /* cache the current word for next time */
1634 g_free(calltip.last_word);
1635 calltip.last_word = g_strdup(word);
1636 calltip.tag_index = MIN(calltip.tag_index, tags->len - 1); /* ensure tag_index is in range */
1638 for (i = calltip.tag_index; i < tags->len; i++)
1640 tag = TM_TAG(tags->pdata[i]);
1642 if (str == NULL)
1644 str = g_string_new(NULL);
1645 if (calltip.tag_index > 0)
1646 g_string_prepend(str, "\001 "); /* up arrow */
1647 append_calltip(str, tag, FILETYPE_ID(ft));
1649 else /* add a down arrow */
1651 if (calltip.tag_index > 0) /* already have an up arrow */
1652 g_string_insert_c(str, 1, '\002');
1653 else
1654 g_string_prepend(str, "\002 ");
1655 break;
1658 if (str)
1660 gchar *result = str->str;
1662 g_string_free(str, FALSE);
1663 return result;
1665 return NULL;
1669 /* use pos = -1 to search for the previous unmatched open bracket. */
1670 gboolean editor_show_calltip(GeanyEditor *editor, gint pos)
1672 gint orig_pos = pos; /* the position for the calltip */
1673 gint lexer;
1674 gint style;
1675 gchar word[GEANY_MAX_WORD_LENGTH];
1676 gchar *str;
1677 ScintillaObject *sci;
1679 g_return_val_if_fail(editor != NULL, FALSE);
1680 g_return_val_if_fail(editor->document->file_type != NULL, FALSE);
1682 sci = editor->sci;
1684 lexer = sci_get_lexer(sci);
1686 if (pos == -1)
1688 /* position of '(' is unknown, so go backwards from current position to find it */
1689 pos = sci_get_current_position(sci);
1690 pos--;
1691 orig_pos = pos;
1692 pos = (lexer == SCLEX_LATEX) ? find_previous_brace(sci, pos) :
1693 find_start_bracket(sci, pos);
1694 if (pos == -1)
1695 return FALSE;
1698 /* the style 1 before the brace (which may be highlighted) */
1699 style = sci_get_style_at(sci, pos - 1);
1700 if (! is_code_style(lexer, style))
1701 return FALSE;
1703 word[0] = '\0';
1704 editor_find_current_word(editor, pos - 1, word, sizeof word, NULL);
1705 if (word[0] == '\0')
1706 return FALSE;
1708 str = find_calltip(word, editor->document->file_type);
1709 if (str)
1711 g_free(calltip.text); /* free the old calltip */
1712 calltip.text = str;
1713 calltip.pos = orig_pos;
1714 calltip.sci = sci;
1715 calltip.set = TRUE;
1716 utils_wrap_string(calltip.text, -1);
1717 SSM(sci, SCI_CALLTIPSHOW, orig_pos, (sptr_t) calltip.text);
1718 return TRUE;
1720 return FALSE;
1724 gchar *editor_get_calltip_text(GeanyEditor *editor, const TMTag *tag)
1726 GString *str;
1728 g_return_val_if_fail(editor != NULL, NULL);
1730 str = g_string_new(NULL);
1731 if (append_calltip(str, tag, FILETYPE_ID(editor->document->file_type)))
1732 return g_string_free(str, FALSE);
1733 else
1734 return g_string_free(str, TRUE);
1738 /* HTML entities auto completion from html_entities.tags text file */
1739 static gboolean
1740 autocomplete_html(ScintillaObject *sci, const gchar *root, gsize rootlen)
1742 guint i, j = 0;
1743 gboolean found = FALSE;
1744 GString *words;
1745 const gchar **entities = symbols_get_html_entities();
1747 if (*root != '&' || G_UNLIKELY(entities == NULL))
1748 return FALSE;
1750 words = g_string_sized_new(500);
1751 for (i = 0; ; i++)
1753 if (entities[i] == NULL)
1754 break;
1755 else if (entities[i][0] == '#')
1756 continue;
1758 if (! strncmp(entities[i], root, rootlen))
1760 if (j++ > 0)
1761 g_string_append_c(words, '\n');
1762 g_string_append(words, entities[i]);
1763 found = TRUE;
1766 if (found)
1767 show_autocomplete(sci, rootlen, words->str);
1769 g_string_free(words, TRUE);
1770 return found;
1774 /* Current document & global tags autocompletion */
1775 static gboolean
1776 autocomplete_tags(GeanyEditor *editor, const gchar *root, gsize rootlen)
1778 TMTagAttrType attrs[] = { tm_tag_attr_name_t, 0 };
1779 const GPtrArray *tags;
1780 GeanyDocument *doc;
1782 g_return_val_if_fail(editor, FALSE);
1784 doc = editor->document;
1786 tags = tm_workspace_find(root, tm_tag_max_t, attrs, TRUE, doc->file_type->lang);
1787 if (tags)
1789 autocompletion_mode = AUTOC_TAGS;
1790 show_tags_list(editor, tags, rootlen);
1791 return tags->len > 0;
1793 return FALSE;
1797 /* Check whether to use entity autocompletion:
1798 * - always in a HTML file except when inside embedded JavaScript, Python, ASP, ...
1799 * - in a PHP file only when we are outside of <? ?> */
1800 static gboolean autocomplete_check_for_html(gint ft_id, gint style)
1802 /* use entity completion when style is not JavaScript, ASP, Python, PHP, ...
1803 * (everything after SCE_HJ_START is for embedded scripting languages) */
1804 if (ft_id == GEANY_FILETYPES_HTML && style < SCE_HJ_START)
1805 return TRUE;
1807 if (ft_id == GEANY_FILETYPES_PHP)
1809 /* use entity completion when style is outside of PHP styles */
1810 if (! is_style_php(style))
1811 return TRUE;
1814 return FALSE;
1818 /* Algorithm based on based on Scite's StartAutoCompleteWord() */
1819 static GString *get_doc_words(ScintillaObject *sci, gchar *root, gsize rootlen)
1821 gchar *word;
1822 gint len, current, word_end;
1823 gint pos_find, flags;
1824 guint word_length;
1825 gsize nmatches = 0;
1826 GString *words;
1827 struct Sci_TextToFind ttf;
1829 len = sci_get_length(sci);
1830 current = sci_get_current_position(sci) - rootlen;
1832 ttf.lpstrText = root;
1833 ttf.chrg.cpMin = 0;
1834 ttf.chrg.cpMax = len;
1835 ttf.chrgText.cpMin = 0;
1836 ttf.chrgText.cpMax = 0;
1837 flags = SCFIND_WORDSTART | SCFIND_MATCHCASE;
1839 words = g_string_sized_new(256);
1840 /* put space before first entry to make searching with strstr easy */
1841 g_string_append_c(words, ' ');
1843 /* search the whole document for the word root and collect results */
1844 pos_find = scintilla_send_message(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
1845 while (pos_find >= 0 && pos_find < len)
1847 word_end = pos_find + rootlen;
1848 if (pos_find != current)
1850 while (word_end < len && strchr(GEANY_WORDCHARS, sci_get_char_at(sci, word_end)) != NULL)
1851 word_end++;
1853 word_length = word_end - pos_find;
1854 if (word_length > rootlen)
1856 word = g_malloc0(word_length + 3);
1857 sci_get_text_range(sci, pos_find, word_end, word + 1);
1858 word[0] = ' ';
1859 word[word_length + 1] = ' ';
1860 /* search the words string whether we already have the word in, otherwise add it */
1861 if (strstr(words->str, word) == NULL)
1863 g_string_append(words, word + 1);
1864 nmatches++;
1866 g_free(word);
1868 if (nmatches == editor_prefs.autocompletion_max_entries)
1869 break;
1872 ttf.chrg.cpMin = word_end;
1873 pos_find = scintilla_send_message(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
1876 if (words->len > 1)
1878 g_strdelimit(words->str, " ", '\n');
1879 words->str[words->len - 1] = '\0'; /* remove the trailing '\n' */
1880 return words;
1882 g_string_free(words, TRUE);
1883 return NULL;
1887 static gboolean autocomplete_doc_word(GeanyEditor *editor, gchar *root, gsize rootlen)
1889 ScintillaObject *sci = editor->sci;
1890 GString *words;
1891 GString *str;
1892 gchar *ptr;
1893 GSList *node, *list = NULL;
1895 words = get_doc_words(sci, root, rootlen);
1896 if (!words)
1898 scintilla_send_message(sci, SCI_AUTOCCANCEL, 0, 0);
1899 return FALSE;
1902 /* words are unsorted, make list of words */
1903 foreach_str(ptr, words->str)
1905 if (*ptr == '\n')
1907 list = g_slist_prepend(list, ptr + 1);
1908 /* terminate previous string in list */
1909 ptr[0] = 0x0;
1910 ptr++;
1913 list = g_slist_sort(list, (GCompareFunc)utils_str_casecmp);
1915 str = g_string_sized_new(words->len);
1916 foreach_slist(node, list)
1918 g_string_append(str, node->data);
1919 if (node->next)
1920 g_string_append_c(str, '\n');
1922 if (g_slist_length(list) >= editor_prefs.autocompletion_max_entries)
1923 g_string_append(str, "\n...");
1925 g_slist_free(list);
1926 g_string_free(words, TRUE);
1928 autocompletion_mode = AUTOC_DOC_WORDS;
1929 show_autocomplete(sci, rootlen, str->str);
1930 g_string_free(str, TRUE);
1931 return TRUE;
1935 gboolean editor_start_auto_complete(GeanyEditor *editor, gint pos, gboolean force)
1937 gint line, line_start, line_len, line_pos, current, rootlen, startword, lexer, style;
1938 gchar *linebuf, *root;
1939 ScintillaObject *sci;
1940 gboolean ret = FALSE;
1941 gchar *wordchars;
1942 GeanyFiletype *ft;
1944 if (! editor_prefs.auto_complete_symbols && ! force)
1945 return FALSE;
1947 g_return_val_if_fail(editor != NULL, FALSE);
1949 /* If we are at the beginning of the document, we skip autocompletion as we can't determine the
1950 * necessary styling information */
1951 if (G_UNLIKELY(pos < 2))
1952 return FALSE;
1954 sci = editor->sci;
1955 ft = editor->document->file_type;
1957 line = sci_get_line_from_position(sci, pos);
1958 line_start = sci_get_position_from_line(sci, line);
1959 line_len = sci_get_line_length(sci, line);
1960 line_pos = pos - line_start - 1;
1961 current = pos - line_start;
1962 startword = current;
1963 lexer = sci_get_lexer(sci);
1964 style = sci_get_style_at(sci, pos - 2);
1966 /* don't autocomplete in comments and strings */
1967 if (!force && !is_code_style(lexer, style))
1968 return FALSE;
1970 autocomplete_scope(editor);
1972 linebuf = sci_get_line(sci, line);
1974 if (ft->id == GEANY_FILETYPES_LATEX)
1975 wordchars = GEANY_WORDCHARS"\\"; /* add \ to word chars if we are in a LaTeX file */
1976 else if (ft->id == GEANY_FILETYPES_HTML || ft->id == GEANY_FILETYPES_PHP)
1977 wordchars = GEANY_WORDCHARS"&"; /* add & to word chars if we are in a PHP or HTML file */
1978 else
1979 wordchars = GEANY_WORDCHARS;
1981 /* find the start of the current word */
1982 while ((startword > 0) && (strchr(wordchars, linebuf[startword - 1])))
1983 startword--;
1984 linebuf[current] = '\0';
1985 root = linebuf + startword;
1986 rootlen = current - startword;
1988 if (rootlen > 0 && autocompletion_mode != AUTOC_SCOPE)
1990 if (autocomplete_check_for_html(ft->id, style))
1992 /* Allow something like "&quot;some text&quot;". The above startword calculation
1993 * only works on words but for HTML entity completion we also want to have completion
1994 * based on '&' within words. */
1995 gchar *tmp = strchr(root, '&');
1996 if (tmp != NULL)
1998 root = tmp;
1999 rootlen = strlen(tmp);
2001 ret = autocomplete_html(sci, root, rootlen);
2003 else
2005 /* force is set when called by keyboard shortcut, otherwise start at the
2006 * editor_prefs.symbolcompletion_min_chars'th char */
2007 if (force || rootlen >= editor_prefs.symbolcompletion_min_chars)
2009 /* complete tags, except if forcing when completion is already visible */
2010 if (!(force && SSM(sci, SCI_AUTOCACTIVE, 0, 0)))
2011 ret = autocomplete_tags(editor, root, rootlen);
2013 /* If forcing and there's nothing else to show, complete from words in document */
2014 if (!ret && (force || editor_prefs.autocomplete_doc_words))
2015 ret = autocomplete_doc_word(editor, root, rootlen);
2019 if (!ret && force)
2020 utils_beep();
2022 g_free(linebuf);
2023 return ret;
2027 static const gchar *snippets_find_completion_by_name(const gchar *type, const gchar *name)
2029 gchar *result = NULL;
2030 GHashTable *tmp;
2032 g_return_val_if_fail(type != NULL && name != NULL, NULL);
2034 tmp = g_hash_table_lookup(snippet_hash, type);
2035 if (tmp != NULL)
2037 result = g_hash_table_lookup(tmp, name);
2039 /* whether nothing is set for the current filetype(tmp is NULL) or
2040 * the particular completion for this filetype is not set (result is NULL) */
2041 if (tmp == NULL || result == NULL)
2043 tmp = g_hash_table_lookup(snippet_hash, "Default");
2044 if (tmp != NULL)
2046 result = g_hash_table_lookup(tmp, name);
2049 /* if result is still NULL here, no completion could be found */
2051 /* result is owned by the hash table and will be freed when the table will destroyed */
2052 return result;
2056 /* This is very ugly but passing the pattern to ac_replace_specials() doesn't work because it is
2057 * modified when replacing a completion but the foreach function still passes the old pointer
2058 * to ac_replace_specials, so we use a global pointer outside of ac_replace_specials and
2059 * ac_complete_constructs. Any hints to improve this are welcome. */
2060 static GString *snippets_global_pattern = NULL;
2062 static void snippets_replace_specials(gpointer key, gpointer value, gpointer user_data)
2064 gchar *needle;
2066 g_return_if_fail(key != NULL);
2067 g_return_if_fail(value != NULL);
2069 needle = g_strconcat("%", (gchar*) key, "%", NULL);
2071 utils_string_replace_all(snippets_global_pattern, needle, (gchar*) value);
2072 g_free(needle);
2076 static void snippets_replace_wildcards(GeanyEditor *editor, GString *text)
2078 const gchar *file_name = DOC_FILENAME(editor->document);
2079 gchar *basename = g_path_get_basename(file_name);
2081 templates_replace_default_dates(text);
2082 templates_replace_valist(text, "{filename}", basename, NULL);
2083 templates_replace_command(text, file_name, editor->document->file_type->name, NULL);
2085 g_free(basename);
2089 /* this only works with spaces only indentation on the lines */
2090 static void fix_line_indents(GeanyEditor *editor, gint line_start, gint line_end)
2092 ScintillaObject *sci = editor->sci;
2093 gint line, cur_line, cur_col, pos;
2095 /* get the line, col position as fixing indentation will move cursor to start of line */
2096 pos = sci_get_current_position(sci);
2097 cur_col = sci_get_col_from_position(sci, pos);
2098 cur_line = sci_get_current_line(sci);
2100 for (line = line_start; line <= line_end; line++)
2102 gint size = sci_get_line_indentation(sci, line);
2104 /* set to 0 first to trigger proper indent creation */
2105 sci_set_line_indentation(sci, line, 0);
2106 sci_set_line_indentation(sci, line, size);
2108 pos = scintilla_send_message(sci, SCI_FINDCOLUMN, cur_line, cur_col);
2109 sci_set_current_position(sci, pos, FALSE);
2113 /** Inserts text, replacing \\t tab chars (@c 0x9) with the correct indent
2114 * width, and \\n newline chars (@c 0xA) with the correct line ending string
2115 * for the document.
2116 * This is very useful for inserting code without having to handle the indent
2117 * type yourself (Tabs & Spaces mode can be tricky).
2118 * @param editor Editor.
2119 * @param text Intended as e.g. @c "if (foo)\n\tbar();".
2120 * @param insert_pos Document position to insert text at.
2121 * @param cursor_index If >= 0, the index into @a text to place the cursor.
2122 * @param newline_indent_size Indentation size (in spaces) to insert for each newline; use
2123 * -1 to read the indent size from the line with @a insert_pos on it.
2124 * @param replace_newlines Whether to replace newlines in text or not. If
2125 * newlines have been replaced before, this should be false, to avoid multiple
2126 * replacements of newlines, which is error prone on Windows.
2127 * @warning Make sure all \\t tab chars in @a text are intended as indent widths,
2128 * not hard tabs, as these might not be preserved.
2129 * @note This doesn't scroll the cursor in view afterwards. **/
2130 void editor_insert_text_block(GeanyEditor *editor, const gchar *text, gint insert_pos,
2131 gint cursor_index, gint newline_indent_size, gboolean replace_newlines)
2133 ScintillaObject *sci = editor->sci;
2134 gint line_start = sci_get_line_from_position(sci, insert_pos);
2135 gint line_end;
2136 gchar *whitespace;
2137 GString *buf;
2138 const gchar cur_marker[] = "__GEANY_CURSOR_MARKER__";
2139 const gchar *eol = editor_get_eol_char(editor);
2141 g_return_if_fail(text);
2142 g_return_if_fail(editor != NULL);
2143 g_return_if_fail(insert_pos >= 0);
2145 buf = g_string_new(text);
2147 if (cursor_index >= 0)
2148 g_string_insert(buf, cursor_index, cur_marker); /* remember cursor pos */
2150 if (newline_indent_size == -1)
2152 /* count indent size up to insert_pos instead of asking sci
2153 * because there may be spaces after it */
2154 gchar *tmp = sci_get_line(sci, line_start);
2155 gint idx = insert_pos - sci_get_position_from_line(sci, line_start);
2156 tmp[idx] = '\0';
2157 newline_indent_size = count_indent_size(editor, tmp);
2158 g_free(tmp);
2161 /* Add line indents (in spaces) */
2162 if (newline_indent_size > 0)
2164 whitespace = g_strnfill(newline_indent_size, ' ');
2165 setptr(whitespace, g_strconcat(eol, whitespace, NULL));
2166 utils_string_replace_all(buf, eol, whitespace);
2167 g_free(whitespace);
2170 /* transform line endings */
2171 if (replace_newlines)
2172 utils_string_replace_all(buf, "\n", eol);
2174 /* transform tabs into indent widths (in spaces) */
2175 whitespace = g_strnfill(editor_get_indent_prefs(editor)->width, ' ');
2176 utils_string_replace_all(buf, "\t", whitespace);
2177 g_free(whitespace);
2179 if (cursor_index >= 0)
2181 gint idx = utils_strpos(buf->str, cur_marker);
2183 g_string_erase(buf, idx, strlen(cur_marker));
2185 sci_insert_text(sci, insert_pos, buf->str);
2186 sci_set_current_position(sci, insert_pos + idx, FALSE);
2188 else
2189 sci_insert_text(sci, insert_pos, buf->str);
2191 /* fixup indentation (very useful for Tabs & Spaces indent type) */
2192 line_end = sci_get_line_from_position(sci, insert_pos + buf->len);
2193 fix_line_indents(editor, line_start, line_end);
2194 snippet_cursor_insert_pos = sci_get_current_position(sci);
2196 g_string_free(buf, TRUE);
2200 /* Move the cursor to the next specified cursor position in an inserted snippet.
2201 * Can, and should, be optimized to give better results */
2202 void editor_goto_next_snippet_cursor(GeanyEditor *editor)
2204 ScintillaObject *sci = editor->sci;
2205 gint current_pos = sci_get_current_position(sci);
2207 if (snippet_offsets && !g_queue_is_empty(snippet_offsets))
2209 gint offset;
2211 offset = GPOINTER_TO_INT(g_queue_pop_head(snippet_offsets));
2212 if (current_pos > snippet_cursor_insert_pos)
2213 snippet_cursor_insert_pos = offset + current_pos;
2214 else
2215 snippet_cursor_insert_pos += offset;
2217 sci_set_current_position(sci, snippet_cursor_insert_pos, FALSE);
2219 else
2221 utils_beep();
2226 static gssize snippets_make_replacements(GeanyEditor *editor, GString *pattern,
2227 gsize indent_size)
2229 gssize cur_index = -1;
2230 gchar *whitespace;
2231 gint i, tmp_pos, whitespace_len, nl_count = 0;
2232 GHashTable *specials;
2233 GList *temp_list = NULL;
2234 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
2235 gint cursor_steps, old_cursor = 0;
2237 /* replace 'special' completions */
2238 specials = g_hash_table_lookup(snippet_hash, "Special");
2239 if (G_LIKELY(specials != NULL))
2241 /* ugly hack using global_pattern */
2242 snippets_global_pattern = pattern;
2243 g_hash_table_foreach(specials, snippets_replace_specials, NULL);
2246 /* replace any %template% wildcards */
2247 snippets_replace_wildcards(editor, pattern);
2249 /* transform other wildcards */
2250 /* convert to %newlines%, else we get endless loops */
2251 utils_string_replace_all(pattern, "\n", "%newline%");
2253 /* if spaces are used, replaces all tabs with %ws%, which is later replaced
2254 * by real whitespace characters
2255 * otherwise replace all %ws% by \t, which will be replaced later by tab
2256 * characters,
2257 * this makes seperating between tab and spaces intentation pretty easy */
2258 if (iprefs->type == GEANY_INDENT_TYPE_SPACES)
2259 utils_string_replace_all(pattern, "\t", "%ws%");
2260 else
2261 utils_string_replace_all(pattern, "%ws%", "\t");
2263 whitespace = g_strnfill(iprefs->width, ' '); /* use spaces for indentation, will be fixed up */
2264 whitespace_len = strlen(whitespace);
2265 i = 0;
2266 while ((cursor_steps = utils_strpos(pattern->str, "%cursor%")) >= 0)
2268 /* replace every %newline% (up to next %cursor%) with EOL,
2269 * and update cursor_steps after */
2270 while ((tmp_pos = utils_strpos(pattern->str, "%newline%")) < cursor_steps && tmp_pos != -1)
2272 nl_count++;
2273 utils_string_replace_first(pattern, "%newline%", editor_get_eol_char(editor));
2274 cursor_steps = utils_strpos(pattern->str, "%cursor%");
2276 /* replace every %ws% (up to next %cursor%) with whitespaces,
2277 * and update cursor_steps after */
2278 while ((tmp_pos = utils_strpos(pattern->str, "%ws%")) < cursor_steps && tmp_pos != -1)
2280 utils_string_replace_first(pattern, "%ws%", whitespace);
2281 cursor_steps = utils_strpos(pattern->str, "%cursor%");
2283 /* finally replace the next %cursor% */
2284 utils_string_replace_first(pattern, "%cursor%", "");
2286 /* modify cursor_steps to take indentation count and type into account */
2288 /* We're saving the relative offset to each cursor position in a simple
2289 * linked list, including indentations between them. */
2290 if (i++ > 0)
2292 cursor_steps += (nl_count * indent_size);
2293 temp_list = g_list_append(temp_list, GINT_TO_POINTER(cursor_steps - old_cursor));
2295 else
2297 nl_count = 0;
2298 cur_index = cursor_steps;
2300 old_cursor = cursor_steps;
2302 /* replace remaining %ws% and %newline% which may occur after the last %cursor% */
2303 utils_string_replace_all(pattern, "%newline%", editor_get_eol_char(editor));
2304 utils_string_replace_all(pattern, "%ws%", whitespace);
2305 g_free(whitespace);
2307 /* We put the cursor positions for the most recent
2308 * parsed snippet first, followed by any remaining positions */
2309 i = 0;
2310 if (temp_list)
2312 GList *node;
2314 foreach_list(node, temp_list)
2315 g_queue_push_nth(snippet_offsets, node->data, i++);
2317 /* limit length of queue */
2318 while (g_queue_get_length(snippet_offsets) > 20)
2319 g_queue_pop_tail(snippet_offsets);
2321 g_list_free(temp_list);
2323 if (cur_index < 0)
2324 cur_index = pattern->len;
2326 return cur_index;
2330 static gboolean snippets_complete_constructs(GeanyEditor *editor, gint pos, const gchar *word)
2332 ScintillaObject *sci = editor->sci;
2333 gchar *str;
2334 GString *pattern;
2335 gssize cur_index = -1;
2336 gint str_len;
2337 gint ft_id = FILETYPE_ID(editor->document->file_type);
2339 str = g_strdup(word);
2340 g_strstrip(str);
2341 pattern = g_string_new(snippets_find_completion_by_name(filetypes[ft_id]->name, str));
2342 if (pattern == NULL || pattern->len == 0)
2344 g_free(str);
2345 g_string_free(pattern, TRUE);
2346 return FALSE;
2349 read_indent(editor, pos);
2351 /* remove the typed word, it will be added again by the used auto completion
2352 * (not really necessary but this makes the auto completion more flexible,
2353 * e.g. with a completion like hi=hello, so typing "hi<TAB>" will result in "hello") */
2354 str_len = strlen(str);
2355 sci_set_selection_start(sci, pos - str_len);
2356 sci_set_selection_end(sci, pos);
2357 sci_replace_sel(sci, "");
2358 pos -= str_len; /* pos has changed while deleting */
2360 cur_index = snippets_make_replacements(editor, pattern, strlen(indent));
2362 /* finally insert the text and set the cursor */
2363 editor_insert_text_block(editor, pattern->str, pos, cur_index, -1, FALSE);
2364 sci_scroll_caret(sci);
2366 g_free(str);
2367 g_string_free(pattern, TRUE);
2368 return TRUE;
2372 static gboolean at_eol(ScintillaObject *sci, gint pos)
2374 gint line = sci_get_line_from_position(sci, pos);
2375 gchar c;
2377 /* skip any trailing spaces */
2378 while (TRUE)
2380 c = sci_get_char_at(sci, pos);
2381 if (c == ' ' || c == '\t')
2382 pos++;
2383 else
2384 break;
2387 return (pos == sci_get_line_end_position(sci, line));
2391 gboolean editor_complete_snippet(GeanyEditor *editor, gint pos)
2393 gboolean result = FALSE;
2394 const gchar *wc;
2395 const gchar *word;
2396 ScintillaObject *sci;
2398 g_return_val_if_fail(editor != NULL, FALSE);
2400 sci = editor->sci;
2401 if (sci_has_selection(sci))
2402 return FALSE;
2403 /* return if we are editing an existing line (chars on right of cursor) */
2404 if (keybindings_lookup_item(GEANY_KEY_GROUP_EDITOR,
2405 GEANY_KEYS_EDITOR_COMPLETESNIPPET)->key == GDK_space &&
2406 ! editor_prefs.complete_snippets_whilst_editing && ! at_eol(sci, pos))
2407 return FALSE;
2409 wc = snippets_find_completion_by_name("Special", "wordchars");
2410 word = editor_read_word_stem(editor, pos, wc);
2412 /* prevent completion of "for " */
2413 if (NZV(word) &&
2414 ! isspace(sci_get_char_at(sci, pos - 1))) /* pos points to the line end char so use pos -1 */
2416 sci_start_undo_action(sci); /* needed because we insert a space separately from construct */
2417 result = snippets_complete_constructs(editor, pos, word);
2418 sci_end_undo_action(sci);
2419 if (result)
2420 sci_cancel(sci); /* cancel any autocompletion list, etc */
2422 return result;
2426 void editor_show_macro_list(GeanyEditor *editor)
2428 GString *words;
2430 if (editor == NULL || editor->document->file_type == NULL)
2431 return;
2433 words = symbols_get_macro_list(editor->document->file_type->lang);
2434 if (words == NULL)
2435 return;
2437 SSM(editor->sci, SCI_USERLISTSHOW, 1, (sptr_t) words->str);
2438 g_string_free(words, TRUE);
2442 static void insert_closing_tag(GeanyEditor *editor, gint pos, gchar ch, const gchar *tag_name)
2444 ScintillaObject *sci = editor->sci;
2445 gchar *to_insert = NULL;
2447 if (ch == '/')
2449 const gchar *gt = ">";
2450 /* if there is already a '>' behind the cursor, don't add it */
2451 if (sci_get_char_at(sci, pos) == '>')
2452 gt = "";
2454 to_insert = g_strconcat(tag_name, gt, NULL);
2456 else
2457 to_insert = g_strconcat("</", tag_name, ">", NULL);
2459 sci_start_undo_action(sci);
2460 sci_replace_sel(sci, to_insert);
2461 if (ch == '>')
2463 sci_set_selection(sci, pos, pos);
2464 if (utils_str_equal(tag_name, "table"))
2465 auto_table(editor, pos);
2467 sci_end_undo_action(sci);
2468 g_free(to_insert);
2473 * (stolen from anjuta and heavily modified)
2474 * This routine will auto complete XML or HTML tags that are still open by closing them
2475 * @param ch The character we are dealing with, currently only works with the '>' character
2476 * @return True if handled, false otherwise
2478 static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch)
2480 ScintillaObject *sci = editor->sci;
2481 gint lexer = sci_get_lexer(sci);
2482 gint min, style;
2483 gchar *str_found, sel[512];
2484 gboolean result = FALSE;
2486 /* If the user has turned us off, quit now.
2487 * This may make sense only in certain languages */
2488 if (! editor_prefs.auto_close_xml_tags || (lexer != SCLEX_HTML && lexer != SCLEX_XML))
2489 return FALSE;
2491 /* return if we are inside any embedded script */
2492 style = sci_get_style_at(sci, pos);
2493 if (style > SCE_H_XCCOMMENT && ! is_string_style(lexer, style))
2494 return FALSE;
2496 /* if ch is /, check for </, else quit */
2497 if (ch == '/' && sci_get_char_at(sci, pos - 2) != '<')
2498 return FALSE;
2500 /* Grab the last 512 characters or so */
2501 min = pos - (sizeof(sel) - 1);
2502 if (min < 0) min = 0;
2504 if (pos - min < 3)
2505 return FALSE; /* Smallest tag is 3 characters e.g. <p> */
2507 sci_get_text_range(sci, min, pos, sel);
2508 sel[sizeof(sel) - 1] = '\0';
2510 if (ch == '>' && sel[pos - min - 2] == '/')
2511 /* User typed something like "<br/>" */
2512 return FALSE;
2514 str_found = utils_find_open_xml_tag(sel, pos - min, (ch == '/'));
2516 /* when found string is something like br, img or another short tag, quit */
2517 if (utils_str_equal(str_found, "br")
2518 || utils_str_equal(str_found, "hr")
2519 || utils_str_equal(str_found, "img")
2520 || utils_str_equal(str_found, "base")
2521 || utils_str_equal(str_found, "basefont") /* < or not < */
2522 || utils_str_equal(str_found, "frame")
2523 || utils_str_equal(str_found, "input")
2524 || utils_str_equal(str_found, "link")
2525 || utils_str_equal(str_found, "area")
2526 || utils_str_equal(str_found, "meta"))
2528 /* ignore tag */
2530 else if (NZV(str_found))
2532 insert_closing_tag(editor, pos, ch, str_found);
2533 result = TRUE;
2535 g_free(str_found);
2536 return result;
2540 /* like sci_get_line_indentation(), but for a string. */
2541 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent)
2543 const gchar *ptr;
2544 gsize tab_size = sci_get_tab_width(editor->sci);
2545 gsize count = 0;
2547 g_return_val_if_fail(base_indent, 0);
2549 for (ptr = base_indent; *ptr != 0; ptr++)
2551 switch (*ptr)
2553 case ' ':
2554 count++;
2555 break;
2556 case '\t':
2557 count += tab_size;
2558 break;
2561 return count;
2565 static void auto_table(GeanyEditor *editor, gint pos)
2567 ScintillaObject *sci = editor->sci;
2568 gchar *table;
2569 gint indent_pos;
2570 const gchar *indent_str;
2572 if (sci_get_lexer(sci) != SCLEX_HTML) return;
2574 read_indent(editor, pos);
2575 indent_pos = sci_get_line_indent_position(sci, sci_get_line_from_position(sci, pos));
2576 if ((pos - 7) != indent_pos) /* 7 == strlen("<table>") */
2578 gint i;
2579 guint x;
2581 x = strlen(indent);
2582 /* find the start of the <table tag */
2583 i = 1;
2584 while (i <= pos && sci_get_char_at(sci, pos - i) != '<') i++;
2585 /* add all non whitespace before the tag to the indent string */
2586 while ((pos - i) != indent_pos && x < sizeof(indent) - 1)
2588 indent[x++] = ' ';
2589 i++;
2591 indent[x] = '\0';
2594 if (! editor->auto_indent)
2595 indent_str = "";
2596 else
2597 indent_str = "\t";
2599 table = g_strconcat("\n", indent_str, "<tr>\n",
2600 indent_str, indent_str, "<td> </td>\n",
2601 indent_str, "</tr>\n",
2602 NULL);
2603 editor_insert_text_block(editor, table, pos, -1,
2604 count_indent_size(editor, indent), TRUE);
2605 g_free(table);
2609 static void real_comment_multiline(GeanyEditor *editor, gint line_start, gint last_line)
2611 const gchar *eol;
2612 gchar *str_begin, *str_end, *co, *cc;
2613 gint line_len;
2615 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2617 eol = editor_get_eol_char(editor);
2618 co = editor->document->file_type->comment_open;
2619 cc = editor->document->file_type->comment_close;
2620 str_begin = g_strdup_printf("%s%s", (co != NULL) ? co : "", eol);
2621 str_end = g_strdup_printf("%s%s", (cc != NULL) ? cc : "", eol);
2623 /* insert the comment strings */
2624 sci_insert_text(editor->sci, line_start, str_begin);
2625 line_len = sci_get_position_from_line(editor->sci, last_line + 2);
2626 sci_insert_text(editor->sci, line_len, str_end);
2628 g_free(str_begin);
2629 g_free(str_end);
2633 static void real_uncomment_multiline(GeanyEditor *editor)
2635 /* find the beginning of the multi line comment */
2636 gint pos, line, len, x;
2637 gchar *linebuf;
2638 GeanyDocument *doc;
2640 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2641 doc = editor->document;
2643 /* remove comment open chars */
2644 pos = document_find_text(doc, doc->file_type->comment_open, 0, TRUE, FALSE, NULL);
2645 SSM(editor->sci, SCI_DELETEBACK, 0, 0);
2647 /* check whether the line is empty and can be deleted */
2648 line = sci_get_line_from_position(editor->sci, pos);
2649 len = sci_get_line_length(editor->sci, line);
2650 linebuf = sci_get_line(editor->sci, line);
2651 x = 0;
2652 while (linebuf[x] != '\0' && isspace(linebuf[x])) x++;
2653 if (x == len) SSM(editor->sci, SCI_LINEDELETE, 0, 0);
2654 g_free(linebuf);
2656 /* remove comment close chars */
2657 pos = document_find_text(doc, doc->file_type->comment_close, 0, FALSE, FALSE, NULL);
2658 SSM(editor->sci, SCI_DELETEBACK, 0, 0);
2660 /* check whether the line is empty and can be deleted */
2661 line = sci_get_line_from_position(editor->sci, pos);
2662 len = sci_get_line_length(editor->sci, line);
2663 linebuf = sci_get_line(editor->sci, line);
2664 x = 0;
2665 while (linebuf[x] != '\0' && isspace(linebuf[x])) x++;
2666 if (x == len) SSM(editor->sci, SCI_LINEDELETE, 0, 0);
2667 g_free(linebuf);
2671 static gint get_multiline_comment_style(GeanyEditor *editor, gint line_start)
2673 gint lexer = sci_get_lexer(editor->sci);
2674 gint style_comment;
2676 /* List only those lexers which support multi line comments */
2677 switch (lexer)
2679 case SCLEX_XML:
2680 case SCLEX_HTML:
2682 if (is_style_php(sci_get_style_at(editor->sci, line_start)))
2683 style_comment = SCE_HPHP_COMMENT;
2684 else
2685 style_comment = SCE_H_COMMENT;
2686 break;
2688 case SCLEX_HASKELL: style_comment = SCE_HA_COMMENTBLOCK; break;
2689 case SCLEX_LUA: style_comment = SCE_LUA_COMMENT; break;
2690 case SCLEX_CSS: style_comment = SCE_CSS_COMMENT; break;
2691 case SCLEX_SQL: style_comment = SCE_SQL_COMMENT; break;
2692 case SCLEX_CAML: style_comment = SCE_CAML_COMMENT; break;
2693 case SCLEX_D: style_comment = SCE_D_COMMENT; break;
2694 case SCLEX_PASCAL: style_comment = SCE_PAS_COMMENT; break;
2695 default: style_comment = SCE_C_COMMENT;
2698 return style_comment;
2702 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise
2703 * returns the amount of uncommented single comment lines, in case of multi line uncomment
2704 * it returns just 1 */
2705 gint editor_do_uncomment(GeanyEditor *editor, gint line, gboolean toggle)
2707 gint first_line, last_line;
2708 gint x, i, line_start, line_len;
2709 gint sel_start, sel_end;
2710 gint count = 0;
2711 gsize co_len;
2712 gchar sel[256], *co, *cc;
2713 gboolean break_loop = FALSE, single_line = FALSE;
2714 GeanyFiletype *ft;
2716 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, 0);
2718 if (line < 0)
2719 { /* use selection or current line */
2720 sel_start = sci_get_selection_start(editor->sci);
2721 sel_end = sci_get_selection_end(editor->sci);
2723 first_line = sci_get_line_from_position(editor->sci, sel_start);
2724 /* Find the last line with chars selected (not EOL char) */
2725 last_line = sci_get_line_from_position(editor->sci,
2726 sel_end - editor_get_eol_char_len(editor));
2727 last_line = MAX(first_line, last_line);
2729 else
2731 first_line = last_line = line;
2732 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
2735 ft = editor->document->file_type;
2737 /* detection of HTML vs PHP code, if non-PHP set filetype to XML */
2738 line_start = sci_get_position_from_line(editor->sci, first_line);
2739 if (ft->id == GEANY_FILETYPES_PHP)
2741 if (! is_style_php(sci_get_style_at(editor->sci, line_start)))
2742 ft = filetypes[GEANY_FILETYPES_XML];
2745 co = ft->comment_open;
2746 cc = ft->comment_close;
2747 if (co == NULL)
2748 return 0;
2750 co_len = strlen(co);
2751 if (co_len == 0)
2752 return 0;
2754 sci_start_undo_action(editor->sci);
2756 for (i = first_line; (i <= last_line) && (! break_loop); i++)
2758 gint buf_len;
2760 line_start = sci_get_position_from_line(editor->sci, i);
2761 line_len = sci_get_line_length(editor->sci, i);
2762 x = 0;
2764 buf_len = MIN((gint)sizeof(sel) - 1, line_len - 1);
2765 if (buf_len <= 0)
2766 continue;
2767 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
2768 sel[buf_len] = '\0';
2770 while (isspace(sel[x])) x++;
2772 /* to skip blank lines */
2773 if (x < line_len && sel[x] != '\0')
2775 /* use single line comment */
2776 if (cc == NULL || strlen(cc) == 0)
2778 single_line = TRUE;
2780 if (toggle)
2782 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
2783 if (strncmp(sel + x, co, co_len) != 0 ||
2784 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) != 0)
2785 continue;
2787 co_len += tm_len;
2789 else
2791 if (strncmp(sel + x, co, co_len) != 0)
2792 continue;
2795 sci_set_selection(editor->sci, line_start + x, line_start + x + co_len);
2796 sci_replace_sel(editor->sci, "");
2797 count++;
2799 /* use multi line comment */
2800 else
2802 gint style_comment;
2804 /* skip lines which are already comments */
2805 style_comment = get_multiline_comment_style(editor, line_start);
2806 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
2808 real_uncomment_multiline(editor);
2809 count = 1;
2812 /* break because we are already on the last line */
2813 break_loop = TRUE;
2814 break;
2818 sci_end_undo_action(editor->sci);
2820 /* restore selection if there is one
2821 * but don't touch the selection if caller is editor_do_comment_toggle */
2822 if (! toggle && sel_start < sel_end)
2824 if (single_line)
2826 sci_set_selection_start(editor->sci, sel_start - co_len);
2827 sci_set_selection_end(editor->sci, sel_end - (count * co_len));
2829 else
2831 gint eol_len = editor_get_eol_char_len(editor);
2832 sci_set_selection_start(editor->sci, sel_start - co_len - eol_len);
2833 sci_set_selection_end(editor->sci, sel_end - co_len - eol_len);
2837 return count;
2841 void editor_do_comment_toggle(GeanyEditor *editor)
2843 gint first_line, last_line;
2844 gint x, i, line_start, line_len, first_line_start;
2845 gint sel_start, sel_end;
2846 gint count_commented = 0, count_uncommented = 0;
2847 gchar sel[256], *co, *cc;
2848 gboolean break_loop = FALSE, single_line = FALSE;
2849 gboolean first_line_was_comment = FALSE;
2850 gsize co_len;
2851 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
2852 GeanyFiletype *ft;
2854 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2856 sel_start = sci_get_selection_start(editor->sci);
2857 sel_end = sci_get_selection_end(editor->sci);
2859 ft = editor->document->file_type;
2861 first_line = sci_get_line_from_position(editor->sci,
2862 sci_get_selection_start(editor->sci));
2863 /* Find the last line with chars selected (not EOL char) */
2864 last_line = sci_get_line_from_position(editor->sci,
2865 sci_get_selection_end(editor->sci) - editor_get_eol_char_len(editor));
2866 last_line = MAX(first_line, last_line);
2868 /* detection of HTML vs PHP code, if non-PHP set filetype to XML */
2869 first_line_start = sci_get_position_from_line(editor->sci, first_line);
2870 if (ft->id == GEANY_FILETYPES_PHP)
2872 if (! is_style_php(sci_get_style_at(editor->sci, first_line_start)))
2873 ft = filetypes[GEANY_FILETYPES_XML];
2876 co = ft->comment_open;
2877 cc = ft->comment_close;
2878 if (co == NULL)
2879 return;
2881 co_len = strlen(co);
2882 if (co_len == 0)
2883 return;
2885 sci_start_undo_action(editor->sci);
2887 for (i = first_line; (i <= last_line) && (! break_loop); i++)
2889 gint buf_len;
2891 line_start = sci_get_position_from_line(editor->sci, i);
2892 line_len = sci_get_line_length(editor->sci, i);
2893 x = 0;
2895 buf_len = MIN((gint)sizeof(sel) - 1, line_len - 1);
2896 if (buf_len < 0)
2897 continue;
2898 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
2899 sel[buf_len] = '\0';
2901 while (isspace(sel[x])) x++;
2903 /* use single line comment */
2904 if (cc == NULL || strlen(cc) == 0)
2906 gboolean do_continue = FALSE;
2907 single_line = TRUE;
2909 if (strncmp(sel + x, co, co_len) == 0 &&
2910 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) == 0)
2912 do_continue = TRUE;
2915 if (do_continue && i == first_line)
2916 first_line_was_comment = TRUE;
2918 if (do_continue)
2920 count_uncommented += editor_do_uncomment(editor, i, TRUE);
2921 continue;
2924 /* we are still here, so the above lines were not already comments, so comment it */
2925 editor_do_comment(editor, i, TRUE, TRUE);
2926 count_commented++;
2928 /* use multi line comment */
2929 else
2931 gint style_comment;
2933 /* skip lines which are already comments */
2934 style_comment = get_multiline_comment_style(editor, line_start);
2935 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
2937 real_uncomment_multiline(editor);
2938 count_uncommented++;
2940 else
2942 real_comment_multiline(editor, line_start, last_line);
2943 count_commented++;
2946 /* break because we are already on the last line */
2947 break_loop = TRUE;
2948 break;
2952 sci_end_undo_action(editor->sci);
2954 co_len += tm_len;
2956 /* restore selection if there is one */
2957 if (sel_start < sel_end)
2959 if (single_line)
2961 gint a = (first_line_was_comment) ? - co_len : co_len;
2963 /* don't modify sel_start when the selection starts within indentation */
2964 read_indent(editor, sel_start);
2965 if ((sel_start - first_line_start) <= (gint) strlen(indent))
2966 a = 0;
2968 sci_set_selection_start(editor->sci, sel_start + a);
2969 sci_set_selection_end(editor->sci, sel_end +
2970 (count_commented * co_len) - (count_uncommented * co_len));
2972 else
2974 gint eol_len = editor_get_eol_char_len(editor);
2975 if (count_uncommented > 0)
2977 sci_set_selection_start(editor->sci, sel_start - co_len + eol_len);
2978 sci_set_selection_end(editor->sci, sel_end - co_len + eol_len);
2980 else if (count_commented > 0)
2982 sci_set_selection_start(editor->sci, sel_start + co_len - eol_len);
2983 sci_set_selection_end(editor->sci, sel_end + co_len - eol_len);
2987 else if (count_uncommented > 0)
2989 gint eol_len = single_line ? 0: editor_get_eol_char_len(editor);
2990 sci_set_current_position(editor->sci, sel_start - co_len + eol_len, TRUE);
2992 else if (count_commented > 0)
2994 gint eol_len = single_line ? 0: editor_get_eol_char_len(editor);
2995 sci_set_current_position(editor->sci, sel_start + co_len - eol_len, TRUE);
3000 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise */
3001 void editor_do_comment(GeanyEditor *editor, gint line, gboolean allow_empty_lines, gboolean toggle)
3003 gint first_line, last_line;
3004 gint x, i, line_start, line_len;
3005 gint sel_start, sel_end, co_len;
3006 gchar sel[256], *co, *cc;
3007 gboolean break_loop = FALSE, single_line = FALSE;
3008 GeanyFiletype *ft;
3010 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
3012 if (line < 0)
3013 { /* use selection or current line */
3014 sel_start = sci_get_selection_start(editor->sci);
3015 sel_end = sci_get_selection_end(editor->sci);
3017 first_line = sci_get_line_from_position(editor->sci, sel_start);
3018 /* Find the last line with chars selected (not EOL char) */
3019 last_line = sci_get_line_from_position(editor->sci,
3020 sel_end - editor_get_eol_char_len(editor));
3021 last_line = MAX(first_line, last_line);
3023 else
3025 first_line = last_line = line;
3026 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
3029 ft = editor->document->file_type;
3031 /* detection of HTML vs PHP code, if non-PHP set filetype to XML */
3032 line_start = sci_get_position_from_line(editor->sci, first_line);
3033 if (ft->id == GEANY_FILETYPES_PHP)
3035 if (! is_style_php(sci_get_style_at(editor->sci, line_start)))
3036 ft = filetypes[GEANY_FILETYPES_XML];
3039 co = ft->comment_open;
3040 cc = ft->comment_close;
3041 if (co == NULL)
3042 return;
3044 co_len = strlen(co);
3045 if (co_len == 0)
3046 return;
3048 sci_start_undo_action(editor->sci);
3050 for (i = first_line; (i <= last_line) && (! break_loop); i++)
3052 gint buf_len;
3054 line_start = sci_get_position_from_line(editor->sci, i);
3055 line_len = sci_get_line_length(editor->sci, i);
3056 x = 0;
3058 buf_len = MIN((gint)sizeof(sel) - 1, line_len - 1);
3059 if (buf_len < 0)
3060 continue;
3061 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3062 sel[buf_len] = '\0';
3064 while (isspace(sel[x])) x++;
3066 /* to skip blank lines */
3067 if (allow_empty_lines || (x < line_len && sel[x] != '\0'))
3069 /* use single line comment */
3070 if (cc == NULL || strlen(cc) == 0)
3072 gint start = line_start;
3073 single_line = TRUE;
3075 if (ft->comment_use_indent)
3076 start = line_start + x;
3078 if (toggle)
3080 gchar *text = g_strconcat(co, editor_prefs.comment_toggle_mark, NULL);
3081 sci_insert_text(editor->sci, start, text);
3082 g_free(text);
3084 else
3085 sci_insert_text(editor->sci, start, co);
3087 /* use multi line comment */
3088 else
3090 gint style_comment;
3092 /* skip lines which are already comments */
3093 style_comment = get_multiline_comment_style(editor, line_start);
3094 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3095 continue;
3097 real_comment_multiline(editor, line_start, last_line);
3099 /* break because we are already on the last line */
3100 break_loop = TRUE;
3101 break;
3105 sci_end_undo_action(editor->sci);
3107 /* restore selection if there is one
3108 * but don't touch the selection if caller is editor_do_comment_toggle */
3109 if (! toggle && sel_start < sel_end)
3111 if (single_line)
3113 sci_set_selection_start(editor->sci, sel_start + co_len);
3114 sci_set_selection_end(editor->sci, sel_end + ((i - first_line) * co_len));
3116 else
3118 gint eol_len = editor_get_eol_char_len(editor);
3119 sci_set_selection_start(editor->sci, sel_start + co_len + eol_len);
3120 sci_set_selection_end(editor->sci, sel_end + co_len + eol_len);
3126 static gboolean brace_timeout_active = FALSE;
3128 static gboolean delay_match_brace(G_GNUC_UNUSED gpointer user_data)
3130 GeanyDocument *doc = document_get_current();
3131 GeanyEditor *editor;
3132 gint brace_pos = GPOINTER_TO_INT(user_data);
3133 gint end_pos, cur_pos;
3135 brace_timeout_active = FALSE;
3136 if (!doc)
3137 return FALSE;
3139 editor = doc->editor;
3140 cur_pos = sci_get_current_position(editor->sci) - 1;
3142 if (cur_pos != brace_pos)
3144 cur_pos++;
3145 if (cur_pos != brace_pos)
3147 /* we have moved past the original brace_pos, but after the timeout
3148 * we may now be on a new brace, so check again */
3149 editor_highlight_braces(editor, cur_pos);
3150 return FALSE;
3153 if (!utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3155 editor_highlight_braces(editor, cur_pos);
3156 return FALSE;
3158 end_pos = sci_find_matching_brace(editor->sci, brace_pos);
3160 if (end_pos >= 0)
3162 gint col = MIN(sci_get_col_from_position(editor->sci, brace_pos),
3163 sci_get_col_from_position(editor->sci, end_pos));
3164 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, col, 0);
3165 SSM(editor->sci, SCI_BRACEHIGHLIGHT, brace_pos, end_pos);
3167 else
3169 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3170 SSM(editor->sci, SCI_BRACEBADLIGHT, brace_pos, 0);
3172 return FALSE;
3176 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos)
3178 gint brace_pos = cur_pos - 1;
3180 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3181 SSM(editor->sci, SCI_BRACEBADLIGHT, (uptr_t)-1, 0);
3183 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3185 brace_pos++;
3186 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3188 return;
3191 if (!brace_timeout_active)
3193 brace_timeout_active = TRUE;
3194 /* delaying matching makes scrolling faster e.g. holding down arrow keys */
3195 g_timeout_add(100, delay_match_brace, GINT_TO_POINTER(brace_pos));
3200 static gboolean in_block_comment(gint lexer, gint style)
3202 switch (lexer)
3204 case SCLEX_CPP:
3205 return (style == SCE_C_COMMENT ||
3206 style == SCE_C_COMMENTDOC);
3208 case SCLEX_PASCAL:
3209 return (style == SCE_PAS_COMMENT ||
3210 style == SCE_PAS_COMMENT2);
3212 case SCLEX_D:
3213 return (style == SCE_D_COMMENT ||
3214 style == SCE_D_COMMENTDOC ||
3215 style == SCE_D_COMMENTNESTED);
3217 case SCLEX_HTML:
3218 return (style == SCE_HPHP_COMMENT);
3220 case SCLEX_CSS:
3221 return (style == SCE_CSS_COMMENT);
3223 default:
3224 return FALSE;
3229 static gboolean is_comment_char(gchar c, gint lexer)
3231 if ((c == '*' || c == '+') && lexer == SCLEX_D)
3232 return TRUE;
3233 else
3234 if (c == '*')
3235 return TRUE;
3237 return FALSE;
3241 static void auto_multiline(GeanyEditor *editor, gint cur_line)
3243 ScintillaObject *sci = editor->sci;
3244 gint indent_pos, style;
3245 gint lexer = sci_get_lexer(sci);
3247 /* Use the start of the line enter was pressed on, to avoid any doc keyword styles */
3248 indent_pos = sci_get_line_indent_position(sci, cur_line - 1);
3249 style = sci_get_style_at(sci, indent_pos);
3250 if (!in_block_comment(lexer, style))
3251 return;
3253 /* Check whether the comment block continues on this line */
3254 indent_pos = sci_get_line_indent_position(sci, cur_line);
3255 if (sci_get_style_at(sci, indent_pos) == style)
3257 gchar *previous_line = sci_get_line(sci, cur_line - 1);
3258 /* the type of comment, '*' (C/C++/Java), '+' and the others (D) */
3259 gchar *continuation = "*";
3260 gchar *whitespace = ""; /* to hold whitespace if needed */
3261 gchar *result;
3262 gint len = strlen(previous_line);
3263 gint i;
3265 /* find and stop at end of multi line comment */
3266 i = len - 1;
3267 while (i >= 0 && isspace(previous_line[i])) i--;
3268 if (i >= 1 && is_comment_char(previous_line[i - 1], lexer) && previous_line[i] == '/')
3270 gint indent_len, indent_width;
3272 indent_pos = sci_get_line_indent_position(sci, cur_line);
3273 indent_len = sci_get_col_from_position(sci, indent_pos);
3274 indent_width = editor_get_indent_prefs(editor)->width;
3276 /* if there is one too many spaces, delete the last space,
3277 * to return to the indent used before the multiline comment was started. */
3278 if (indent_len % indent_width == 1)
3279 SSM(sci, SCI_DELETEBACKNOTLINE, 0, 0); /* remove whitespace indent */
3280 g_free(previous_line);
3281 return;
3283 /* check whether we are on the second line of multi line comment */
3284 i = 0;
3285 while (i < len && isspace(previous_line[i])) i++; /* get to start of the line */
3287 if (i + 1 < len &&
3288 previous_line[i] == '/' && is_comment_char(previous_line[i + 1], lexer))
3289 { /* we are on the second line of a multi line comment, so we have to insert white space */
3290 whitespace = " ";
3293 if (G_UNLIKELY(style == SCE_D_COMMENTNESTED))
3294 continuation = "+"; /* for nested comments in D */
3296 result = g_strconcat(whitespace, continuation, " ", NULL);
3297 sci_add_text(sci, result);
3298 g_free(result);
3300 g_free(previous_line);
3305 /* Checks whether the given style is a string for the given lexer.
3306 * It doesn't handle LEX_HTML, this should be done by the caller.
3307 * Returns true if the style is a string, FALSE otherwise.
3309 * Don't forget STRINGEOL, to prevent completion whilst typing a string with no closing char.
3311 static gboolean is_string_style(gint lexer, gint style)
3313 switch (lexer)
3315 case SCLEX_CPP:
3316 return (style == SCE_C_CHARACTER ||
3317 style == SCE_C_STRING ||
3318 style == SCE_C_STRINGEOL);
3320 case SCLEX_PASCAL:
3321 return (style == SCE_PAS_CHARACTER ||
3322 style == SCE_PAS_STRING ||
3323 style == SCE_PAS_STRINGEOL);
3325 case SCLEX_D:
3326 return (style == SCE_D_STRING ||
3327 style == SCE_D_STRINGEOL ||
3328 style == SCE_D_CHARACTER ||
3329 style == SCE_D_STRINGB ||
3330 style == SCE_D_STRINGR);
3332 case SCLEX_PYTHON:
3333 return (style == SCE_P_STRING ||
3334 style == SCE_P_TRIPLE ||
3335 style == SCE_P_TRIPLEDOUBLE ||
3336 style == SCE_P_CHARACTER ||
3337 style == SCE_P_STRINGEOL);
3339 case SCLEX_F77:
3340 case SCLEX_FORTRAN:
3341 return (style == SCE_F_STRING1 ||
3342 style == SCE_F_STRING2 ||
3343 style == SCE_F_STRINGEOL);
3345 case SCLEX_PERL:
3346 return (/*style == SCE_PL_STRING ||*/ /* may want variable autocompletion "$(foo)" */
3347 style == SCE_PL_CHARACTER ||
3348 style == SCE_PL_HERE_DELIM ||
3349 style == SCE_PL_HERE_Q ||
3350 style == SCE_PL_HERE_QQ ||
3351 style == SCE_PL_HERE_QX ||
3352 style == SCE_PL_POD ||
3353 style == SCE_PL_STRING_Q ||
3354 style == SCE_PL_STRING_QQ ||
3355 style == SCE_PL_STRING_QX ||
3356 style == SCE_PL_STRING_QR ||
3357 style == SCE_PL_STRING_QW ||
3358 style == SCE_PL_POD_VERB);
3360 case SCLEX_R:
3361 return (style == SCE_R_STRING);
3363 case SCLEX_RUBY:
3364 return (style == SCE_RB_CHARACTER ||
3365 style == SCE_RB_STRING ||
3366 style == SCE_RB_HERE_DELIM ||
3367 style == SCE_RB_HERE_Q ||
3368 style == SCE_RB_HERE_QQ ||
3369 style == SCE_RB_HERE_QX ||
3370 style == SCE_RB_POD);
3372 case SCLEX_BASH:
3373 return (style == SCE_SH_STRING);
3375 case SCLEX_SQL:
3376 return (style == SCE_SQL_STRING);
3378 case SCLEX_TCL:
3379 return (style == SCE_TCL_IN_QUOTE);
3381 case SCLEX_LUA:
3382 return (style == SCE_LUA_LITERALSTRING ||
3383 style == SCE_LUA_CHARACTER ||
3384 style == SCE_LUA_STRINGEOL ||
3385 style == SCE_LUA_STRING);
3387 case SCLEX_HASKELL:
3388 return (style == SCE_HA_CHARACTER ||
3389 style == SCE_HA_STRING);
3391 case SCLEX_FREEBASIC:
3392 return (style == SCE_B_STRING ||
3393 style == SCE_B_STRINGEOL);
3395 case SCLEX_MATLAB:
3396 return (style == SCE_MATLAB_STRING ||
3397 style == SCE_MATLAB_DOUBLEQUOTESTRING);
3399 case SCLEX_HTML:
3400 return (
3401 style == SCE_HBA_STRING ||
3402 style == SCE_HBA_STRINGEOL ||
3403 style == SCE_HB_STRING ||
3404 style == SCE_HB_STRINGEOL ||
3405 style == SCE_H_CDATA ||
3406 style == SCE_H_DOUBLESTRING ||
3407 style == SCE_HJA_DOUBLESTRING ||
3408 style == SCE_HJA_SINGLESTRING ||
3409 style == SCE_HJA_STRINGEOL ||
3410 style == SCE_HJ_DOUBLESTRING ||
3411 style == SCE_HJ_SINGLESTRING ||
3412 style == SCE_HJ_STRINGEOL ||
3413 style == SCE_HPA_CHARACTER ||
3414 style == SCE_HPA_STRING ||
3415 style == SCE_HPA_TRIPLE ||
3416 style == SCE_HPA_TRIPLEDOUBLE ||
3417 style == SCE_HP_CHARACTER ||
3418 style == SCE_HPHP_HSTRING ||
3419 style == SCE_HPHP_HSTRING || /* HSTRING is a heredoc */
3420 style == SCE_HPHP_HSTRING_VARIABLE ||
3421 style == SCE_HPHP_SIMPLESTRING ||
3422 style == SCE_HPHP_SIMPLESTRING ||
3423 style == SCE_HP_STRING ||
3424 style == SCE_HP_TRIPLE ||
3425 style == SCE_HP_TRIPLEDOUBLE ||
3426 style == SCE_H_SGML_DOUBLESTRING ||
3427 style == SCE_H_SGML_SIMPLESTRING ||
3428 style == SCE_H_SINGLESTRING);
3430 case SCLEX_CMAKE:
3431 return (style == SCE_CMAKE_STRINGDQ ||
3432 style == SCE_CMAKE_STRINGLQ ||
3433 style == SCE_CMAKE_STRINGRQ ||
3434 style == SCE_CMAKE_STRINGVAR);
3436 case SCLEX_NSIS:
3437 return (style == SCE_NSIS_STRINGDQ ||
3438 style == SCE_NSIS_STRINGLQ ||
3439 style == SCE_NSIS_STRINGRQ ||
3440 style == SCE_NSIS_STRINGVAR);
3442 case SCLEX_ADA:
3443 return (style == SCE_ADA_CHARACTER ||
3444 style == SCE_ADA_STRING ||
3445 style == SCE_ADA_CHARACTEREOL ||
3446 style == SCE_ADA_STRINGEOL);
3448 return FALSE;
3452 /* Checks whether the given style is a comment for the given lexer.
3453 * It doesn't handle LEX_HTML, this should be done by the caller.
3454 * Returns true if the style is a comment, FALSE otherwise.
3456 static gboolean is_comment_style(gint lexer, gint style)
3458 switch (lexer)
3460 case SCLEX_CPP:
3461 return (style == SCE_C_COMMENT ||
3462 style == SCE_C_COMMENTLINE ||
3463 style == SCE_C_COMMENTDOC ||
3464 style == SCE_C_COMMENTLINEDOC ||
3465 style == SCE_C_COMMENTDOCKEYWORD ||
3466 style == SCE_C_COMMENTDOCKEYWORDERROR);
3468 case SCLEX_PASCAL:
3469 return (style == SCE_PAS_COMMENT ||
3470 style == SCE_PAS_COMMENT2 ||
3471 style == SCE_PAS_COMMENTLINE);
3473 case SCLEX_D:
3474 return (style == SCE_D_COMMENT ||
3475 style == SCE_D_COMMENTLINE ||
3476 style == SCE_D_COMMENTDOC ||
3477 style == SCE_D_COMMENTNESTED ||
3478 style == SCE_D_COMMENTLINEDOC ||
3479 style == SCE_D_COMMENTDOCKEYWORD ||
3480 style == SCE_D_COMMENTDOCKEYWORDERROR);
3482 case SCLEX_PYTHON:
3483 return (style == SCE_P_COMMENTLINE ||
3484 style == SCE_P_COMMENTBLOCK);
3486 case SCLEX_F77:
3487 case SCLEX_FORTRAN:
3488 return (style == SCE_F_COMMENT);
3490 case SCLEX_PERL:
3491 return (style == SCE_PL_COMMENTLINE);
3493 case SCLEX_PROPERTIES:
3494 return (style == SCE_PROPS_COMMENT);
3496 case SCLEX_PO:
3497 return (style == SCE_PO_COMMENT);
3499 case SCLEX_LATEX:
3500 return (style == SCE_L_COMMENT);
3502 case SCLEX_MAKEFILE:
3503 return (style == SCE_MAKE_COMMENT);
3505 case SCLEX_RUBY:
3506 return (style == SCE_RB_COMMENTLINE);
3508 case SCLEX_BASH:
3509 return (style == SCE_SH_COMMENTLINE);
3511 case SCLEX_R:
3512 return (style == SCE_R_COMMENT);
3514 case SCLEX_SQL:
3515 return (style == SCE_SQL_COMMENT ||
3516 style == SCE_SQL_COMMENTLINE ||
3517 style == SCE_SQL_COMMENTDOC);
3519 case SCLEX_TCL:
3520 return (style == SCE_TCL_COMMENT ||
3521 style == SCE_TCL_COMMENTLINE ||
3522 style == SCE_TCL_COMMENT_BOX ||
3523 style == SCE_TCL_BLOCK_COMMENT);
3525 case SCLEX_MATLAB:
3526 return (style == SCE_MATLAB_COMMENT);
3528 case SCLEX_LUA:
3529 return (style == SCE_LUA_COMMENT ||
3530 style == SCE_LUA_COMMENTLINE ||
3531 style == SCE_LUA_COMMENTDOC);
3533 case SCLEX_HASKELL:
3534 return (style == SCE_HA_COMMENTLINE ||
3535 style == SCE_HA_COMMENTBLOCK ||
3536 style == SCE_HA_COMMENTBLOCK2 ||
3537 style == SCE_HA_COMMENTBLOCK3);
3539 case SCLEX_FREEBASIC:
3540 return (style == SCE_B_COMMENT);
3542 case SCLEX_YAML:
3543 return (style == SCE_YAML_COMMENT);
3545 case SCLEX_HTML:
3546 return (
3547 style == SCE_HBA_COMMENTLINE ||
3548 style == SCE_HB_COMMENTLINE ||
3549 style == SCE_H_COMMENT ||
3550 style == SCE_HJA_COMMENT ||
3551 style == SCE_HJA_COMMENTDOC ||
3552 style == SCE_HJA_COMMENTLINE ||
3553 style == SCE_HJ_COMMENT ||
3554 style == SCE_HJ_COMMENTDOC ||
3555 style == SCE_HJ_COMMENTLINE ||
3556 style == SCE_HPA_COMMENTLINE ||
3557 style == SCE_HP_COMMENTLINE ||
3558 style == SCE_HPHP_COMMENT ||
3559 style == SCE_HPHP_COMMENTLINE ||
3560 style == SCE_H_SGML_COMMENT);
3562 case SCLEX_CMAKE:
3563 return (style == SCE_CMAKE_COMMENT);
3565 case SCLEX_NSIS:
3566 return (style == SCE_NSIS_COMMENT ||
3567 style == SCE_NSIS_COMMENTBOX);
3569 case SCLEX_ADA:
3570 return (style == SCE_ADA_COMMENTLINE ||
3571 style == SCE_NSIS_COMMENTBOX);
3573 return FALSE;
3577 /* Checks whether the given style is normal code (not string, comment, preprocessor, etc).
3578 * It doesn't handle LEX_HTML, this should be done by the caller.
3580 static gboolean is_code_style(gint lexer, gint style)
3582 switch (lexer)
3584 case SCLEX_CPP:
3585 if (style == SCE_C_PREPROCESSOR)
3586 return FALSE;
3587 break;
3589 return !(is_comment_style(lexer, style) ||
3590 is_string_style(lexer, style));
3594 #if 0
3595 static gboolean editor_lexer_is_c_like(gint lexer)
3597 switch (lexer)
3599 case SCLEX_CPP:
3600 case SCLEX_D:
3601 return TRUE;
3603 default:
3604 return FALSE;
3607 #endif
3610 /* Returns: -1 if lexer doesn't support type keywords */
3611 gint editor_lexer_get_type_keyword_idx(gint lexer)
3613 switch (lexer)
3615 case SCLEX_CPP:
3616 case SCLEX_D:
3617 return 3;
3619 default:
3620 return -1;
3625 /* inserts a three-line comment at one line above current cursor position */
3626 void editor_insert_multiline_comment(GeanyEditor *editor)
3628 gchar *text;
3629 gint text_len;
3630 gint line;
3631 gint pos;
3632 gboolean have_multiline_comment = FALSE;
3633 GeanyDocument *doc;
3635 g_return_if_fail(editor != NULL &&
3636 editor->document->file_type != NULL && editor->document->file_type->comment_open != NULL);
3638 doc = editor->document;
3640 if (doc->file_type->comment_close != NULL && strlen(doc->file_type->comment_close) > 0)
3641 have_multiline_comment = TRUE;
3643 /* insert three lines one line above of the current position */
3644 line = sci_get_line_from_position(editor->sci, editor_info.click_pos);
3645 pos = sci_get_position_from_line(editor->sci, line);
3647 /* use the indent on the current line but only when comment indentation is used
3648 * and we don't have multi line comment characters */
3649 if (editor->auto_indent &&
3650 ! have_multiline_comment && doc->file_type->comment_use_indent)
3652 read_indent(editor, editor_info.click_pos);
3653 text = g_strdup_printf("%s\n%s\n%s\n", indent, indent, indent);
3654 text_len = strlen(text);
3656 else
3658 text = g_strdup("\n\n\n");
3659 text_len = 3;
3661 sci_insert_text(editor->sci, pos, text);
3662 g_free(text);
3665 /* select the inserted lines for commenting */
3666 sci_set_selection_start(editor->sci, pos);
3667 sci_set_selection_end(editor->sci, pos + text_len);
3669 editor_do_comment(editor, -1, TRUE, FALSE);
3671 /* set the current position to the start of the first inserted line */
3672 pos += strlen(doc->file_type->comment_open);
3674 /* on multi line comment jump to the next line, otherwise add the length of added indentation */
3675 if (have_multiline_comment)
3676 pos += 1;
3677 else
3678 pos += strlen(indent);
3680 sci_set_current_position(editor->sci, pos, TRUE);
3681 /* reset the selection */
3682 sci_set_anchor(editor->sci, pos);
3686 /* Note: If the editor is pending a redraw, set document::scroll_percent instead.
3687 * Scroll the view to make line appear at percent_of_view.
3688 * line can be -1 to use the current position. */
3689 void editor_scroll_to_line(GeanyEditor *editor, gint line, gfloat percent_of_view)
3691 gint vis1, los, delta;
3692 GtkWidget *wid;
3694 g_return_if_fail(editor != NULL);
3696 wid = GTK_WIDGET(editor->sci);
3698 if (! wid->window || ! gdk_window_is_viewable(wid->window))
3699 return; /* prevent gdk_window_scroll warning */
3701 if (line == -1)
3702 line = sci_get_current_line(editor->sci);
3704 /* sci 'visible line' != doc line number because of folding and line wrapping */
3705 /* calling SCI_VISIBLEFROMDOCLINE for line is more accurate than calling
3706 * SCI_DOCLINEFROMVISIBLE for vis1. */
3707 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0);
3708 vis1 = SSM(editor->sci, SCI_GETFIRSTVISIBLELINE, 0, 0);
3709 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
3710 delta = (line - vis1) - los * percent_of_view;
3711 sci_scroll_lines(editor->sci, delta);
3712 sci_scroll_caret(editor->sci); /* needed for horizontal scrolling */
3716 /* creates and inserts one tab or whitespace of the amount of the tab width */
3717 void editor_insert_alternative_whitespace(GeanyEditor *editor)
3719 gchar *text;
3720 GeanyIndentPrefs iprefs = *editor_get_indent_prefs(editor);
3722 g_return_if_fail(editor != NULL);
3724 switch (iprefs.type)
3726 case GEANY_INDENT_TYPE_TABS:
3727 iprefs.type = GEANY_INDENT_TYPE_SPACES;
3728 break;
3729 case GEANY_INDENT_TYPE_SPACES:
3730 case GEANY_INDENT_TYPE_BOTH: /* most likely we want a tab */
3731 iprefs.type = GEANY_INDENT_TYPE_TABS;
3732 break;
3734 text = get_whitespace(&iprefs, iprefs.width);
3735 sci_add_text(editor->sci, text);
3736 g_free(text);
3740 void editor_select_word(GeanyEditor *editor)
3742 gint pos;
3743 gint start;
3744 gint end;
3746 g_return_if_fail(editor != NULL);
3748 pos = SSM(editor->sci, SCI_GETCURRENTPOS, 0, 0);
3749 start = SSM(editor->sci, SCI_WORDSTARTPOSITION, pos, TRUE);
3750 end = SSM(editor->sci, SCI_WORDENDPOSITION, pos, TRUE);
3752 if (start == end) /* caret in whitespaces sequence */
3754 /* look forward but reverse the selection direction,
3755 * so the caret end up stay as near as the original position. */
3756 end = SSM(editor->sci, SCI_WORDENDPOSITION, pos, FALSE);
3757 start = SSM(editor->sci, SCI_WORDENDPOSITION, end, TRUE);
3758 if (start == end)
3759 return;
3762 sci_set_selection(editor->sci, start, end);
3766 /* extra_line is for selecting the cursor line (or anchor line) at the bottom of a selection,
3767 * when those lines have no selection (cursor at start of line). */
3768 void editor_select_lines(GeanyEditor *editor, gboolean extra_line)
3770 gint start, end, line;
3772 g_return_if_fail(editor != NULL);
3774 start = sci_get_selection_start(editor->sci);
3775 end = sci_get_selection_end(editor->sci);
3777 /* check if whole lines are already selected */
3778 if (! extra_line && start != end &&
3779 sci_get_col_from_position(editor->sci, start) == 0 &&
3780 sci_get_col_from_position(editor->sci, end) == 0)
3781 return;
3783 line = sci_get_line_from_position(editor->sci, start);
3784 start = sci_get_position_from_line(editor->sci, line);
3786 line = sci_get_line_from_position(editor->sci, end);
3787 end = sci_get_position_from_line(editor->sci, line + 1);
3789 sci_set_selection(editor->sci, start, end);
3793 /* find the start or end of a paragraph by searching all lines in direction (UP or DOWN)
3794 * starting at the given line and return the found line or return -1 if called on an empty line */
3795 static gint find_paragraph_stop(GeanyEditor *editor, gint line, gint direction)
3797 gboolean found_end = FALSE;
3798 gint step;
3799 gchar *line_buf, *x;
3800 ScintillaObject *sci = editor->sci;
3802 /* first check current line and return -1 if it is empty to skip creating of a selection */
3803 line_buf = x = sci_get_line(sci, line);
3804 while (isspace(*x))
3805 x++;
3806 if (*x == '\0')
3808 g_free(line_buf);
3809 return -1;
3812 if (direction == GTK_DIR_UP)
3813 step = -1;
3814 else
3815 step = 1;
3817 while (! found_end)
3819 line += step;
3821 /* sci_get_line checks for sanity of the given line, sci_get_line always return a string
3822 * containing at least '\0' so no need to check for NULL */
3823 line_buf = x = sci_get_line(sci, line);
3825 /* check whether after skipping all whitespace we are at end of line and if so, assume
3826 * this line as end of paragraph */
3827 while (isspace(*x))
3828 x++;
3829 if (*x == '\0')
3831 found_end = TRUE;
3832 if (line == -1)
3833 /* called on the first line but there is no previous line so return line 0 */
3834 line = 0;
3836 g_free(line_buf);
3838 return line;
3842 void editor_select_paragraph(GeanyEditor *editor)
3844 gint pos_start, pos_end, line_start, line_found;
3846 g_return_if_fail(editor != NULL);
3848 line_start = SSM(editor->sci, SCI_LINEFROMPOSITION,
3849 SSM(editor->sci, SCI_GETCURRENTPOS, 0, 0), 0);
3851 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_UP);
3852 if (line_found == -1)
3853 return;
3855 /* find_paragraph_stop returns the emtpy line(previous to the real start of the paragraph),
3856 * so use the next line for selection start */
3857 if (line_found > 0)
3858 line_found++;
3860 pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3862 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_DOWN);
3863 pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3865 sci_set_selection(editor->sci, pos_start, pos_end);
3869 /* simple indentation to indent the current line with the same indent as the previous one */
3870 static void smart_line_indentation(GeanyEditor *editor, gint first_line, gint last_line)
3872 gint i, sel_start = 0, sel_end = 0;
3874 /* get previous line and use it for read_indent to use that line
3875 * (otherwise it would fail on a line only containing "{" in advanced indentation mode) */
3876 read_indent(editor, sci_get_position_from_line(editor->sci, first_line - 1));
3878 for (i = first_line; i <= last_line; i++)
3880 /* skip the first line or if the indentation of the previous and current line are equal */
3881 if (i == 0 ||
3882 SSM(editor->sci, SCI_GETLINEINDENTATION, i - 1, 0) ==
3883 SSM(editor->sci, SCI_GETLINEINDENTATION, i, 0))
3884 continue;
3886 sel_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
3887 sel_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
3888 if (sel_start < sel_end)
3890 sci_set_selection(editor->sci, sel_start, sel_end);
3891 sci_replace_sel(editor->sci, "");
3893 sci_insert_text(editor->sci, sel_start, indent);
3898 /* simple indentation to indent the current line with the same indent as the previous one */
3899 void editor_smart_line_indentation(GeanyEditor *editor, gint pos)
3901 gint first_line, last_line;
3902 gint first_sel_start, first_sel_end;
3903 ScintillaObject *sci;
3905 g_return_if_fail(editor != NULL);
3907 sci = editor->sci;
3909 first_sel_start = sci_get_selection_start(sci);
3910 first_sel_end = sci_get_selection_end(sci);
3912 first_line = sci_get_line_from_position(sci, first_sel_start);
3913 /* Find the last line with chars selected (not EOL char) */
3914 last_line = sci_get_line_from_position(sci, first_sel_end - editor_get_eol_char_len(editor));
3915 last_line = MAX(first_line, last_line);
3917 if (pos == -1)
3918 pos = first_sel_start;
3920 sci_start_undo_action(sci);
3922 smart_line_indentation(editor, first_line, last_line);
3924 /* set cursor position if there was no selection */
3925 if (first_sel_start == first_sel_end)
3927 gint indent_pos = SSM(sci, SCI_GETLINEINDENTPOSITION, first_line, 0);
3929 /* use indent position as user may wish to change indentation afterwards */
3930 sci_set_current_position(sci, indent_pos, FALSE);
3932 else
3934 /* fully select all the lines affected */
3935 sci_set_selection_start(sci, sci_get_position_from_line(sci, first_line));
3936 sci_set_selection_end(sci, sci_get_position_from_line(sci, last_line + 1));
3939 sci_end_undo_action(sci);
3943 /* increase / decrease current line or selection by one space */
3944 void editor_indentation_by_one_space(GeanyEditor *editor, gint pos, gboolean decrease)
3946 gint i, first_line, last_line, line_start, indentation_end, count = 0;
3947 gint sel_start, sel_end, first_line_offset = 0;
3949 g_return_if_fail(editor != NULL);
3951 sel_start = sci_get_selection_start(editor->sci);
3952 sel_end = sci_get_selection_end(editor->sci);
3954 first_line = sci_get_line_from_position(editor->sci, sel_start);
3955 /* Find the last line with chars selected (not EOL char) */
3956 last_line = sci_get_line_from_position(editor->sci, sel_end - editor_get_eol_char_len(editor));
3957 last_line = MAX(first_line, last_line);
3959 if (pos == -1)
3960 pos = sel_start;
3962 sci_start_undo_action(editor->sci);
3964 for (i = first_line; i <= last_line; i++)
3966 indentation_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
3967 if (decrease)
3969 line_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
3970 /* searching backwards for a space to remove */
3971 while (sci_get_char_at(editor->sci, indentation_end) != ' ' && indentation_end > line_start)
3972 indentation_end--;
3974 if (sci_get_char_at(editor->sci, indentation_end) == ' ')
3976 sci_set_selection(editor->sci, indentation_end, indentation_end + 1);
3977 sci_replace_sel(editor->sci, "");
3978 count--;
3979 if (i == first_line)
3980 first_line_offset = -1;
3983 else
3985 sci_insert_text(editor->sci, indentation_end, " ");
3986 count++;
3987 if (i == first_line)
3988 first_line_offset = 1;
3992 /* set cursor position */
3993 if (sel_start < sel_end)
3995 gint start = sel_start + first_line_offset;
3996 if (first_line_offset < 0)
3997 start = MAX(sel_start + first_line_offset,
3998 SSM(editor->sci, SCI_POSITIONFROMLINE, first_line, 0));
4000 sci_set_selection_start(editor->sci, start);
4001 sci_set_selection_end(editor->sci, sel_end + count);
4003 else
4004 sci_set_current_position(editor->sci, pos + count, FALSE);
4006 sci_end_undo_action(editor->sci);
4010 void editor_finalize()
4012 scintilla_release_resources();
4016 /* wordchars: NULL or a string containing characters to match a word.
4017 * Returns: the current selection or the current word. */
4018 gchar *editor_get_default_selection(GeanyEditor *editor, gboolean use_current_word,
4019 const gchar *wordchars)
4021 gchar *s = NULL;
4023 g_return_val_if_fail(editor != NULL, NULL);
4025 if (sci_get_lines_selected(editor->sci) == 1)
4027 gint len = sci_get_selected_text_length(editor->sci);
4029 s = g_malloc(len + 1);
4030 sci_get_selected_text(editor->sci, s);
4032 else if (sci_get_lines_selected(editor->sci) == 0 && use_current_word)
4033 { /* use the word at current cursor position */
4034 gchar word[GEANY_MAX_WORD_LENGTH];
4036 editor_find_current_word(editor, -1, word, sizeof(word), wordchars);
4037 if (word[0] != '\0')
4038 s = g_strdup(word);
4040 return s;
4044 /* Note: Usually the line should be made visible (not folded) before calling this.
4045 * Returns: TRUE if line is/will be displayed to the user, or FALSE if it is
4046 * outside the *vertical* view.
4047 * Warning: You may need horizontal scrolling to make the cursor visible - so always call
4048 * sci_scroll_caret() when this returns TRUE. */
4049 gboolean editor_line_in_view(GeanyEditor *editor, gint line)
4051 gint vis1, los;
4053 g_return_val_if_fail(editor != NULL, FALSE);
4055 /* If line is wrapped the result may occur on another virtual line than the first and may be
4056 * still hidden, so increase the line number to check for the next document line */
4057 if (SSM(editor->sci, SCI_WRAPCOUNT, line, 0) > 1)
4058 line++;
4060 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0); /* convert to visible line number */
4061 vis1 = SSM(editor->sci, SCI_GETFIRSTVISIBLELINE, 0, 0);
4062 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
4064 return (line >= vis1 && line < vis1 + los);
4068 /* If the current line is outside the current view window, scroll the line
4069 * so it appears at percent_of_view. */
4070 void editor_display_current_line(GeanyEditor *editor, gfloat percent_of_view)
4072 gint line;
4074 g_return_if_fail(editor != NULL);
4076 line = sci_get_current_line(editor->sci);
4078 /* unfold maybe folded results */
4079 sci_ensure_line_is_visible(editor->sci, line);
4081 /* scroll the line if it's off screen */
4082 if (! editor_line_in_view(editor, line))
4083 editor->scroll_percent = percent_of_view;
4084 else
4085 sci_scroll_caret(editor->sci); /* may need horizontal scrolling */
4090 * Deletes all currently set indicators in the @a editor window.
4091 * Error indicators (red squiggly underlines) and usual line markers are removed.
4093 * @param editor The editor to operate on.
4095 void editor_indicator_clear_errors(GeanyEditor *editor)
4097 editor_indicator_clear(editor, GEANY_INDICATOR_ERROR);
4098 sci_marker_delete_all(editor->sci, 0); /* remove the yellow error line marker */
4103 * Deletes all currently set indicators matching @a indic in the @a editor window.
4105 * @param editor The editor to operate on.
4106 * @param indic The indicator number to clear, this is a value of @ref GeanyIndicator.
4108 * @since 0.16
4110 void editor_indicator_clear(GeanyEditor *editor, gint indic)
4112 glong last_pos;
4114 g_return_if_fail(editor != NULL);
4116 last_pos = sci_get_length(editor->sci);
4117 if (last_pos > 0)
4119 sci_indicator_set(editor->sci, indic);
4120 sci_indicator_clear(editor->sci, 0, last_pos);
4126 * Sets an indicator @a indic on @a line.
4127 * Whitespace at the start and the end of the line is not marked.
4129 * @param editor The editor to operate on.
4130 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4131 * @param line The line number which should be marked.
4133 * @since 0.16
4135 void editor_indicator_set_on_line(GeanyEditor *editor, gint indic, gint line)
4137 gint start, end;
4138 guint i = 0, len;
4139 gchar *linebuf;
4141 g_return_if_fail(editor != NULL);
4142 g_return_if_fail(line >= 0);
4144 start = sci_get_position_from_line(editor->sci, line);
4145 end = sci_get_position_from_line(editor->sci, line + 1);
4147 /* skip blank lines */
4148 if ((start + 1) == end ||
4149 start > end ||
4150 sci_get_line_length(editor->sci, line) == editor_get_eol_char_len(editor))
4152 return;
4155 len = end - start;
4156 linebuf = sci_get_line(editor->sci, line);
4158 /* don't set the indicator on whitespace */
4159 while (isspace(linebuf[i]))
4160 i++;
4161 while (len > 1 && len > i && isspace(linebuf[len - 1]))
4163 len--;
4164 end--;
4166 g_free(linebuf);
4168 editor_indicator_set_on_range(editor, indic, start + i, end);
4173 * Sets an indicator on the range specified by @a start and @a end.
4174 * No error checking or whitespace removal is performed, this should be done by the calling
4175 * function if necessary.
4177 * @param editor The editor to operate on.
4178 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4179 * @param start The starting position for the marker.
4180 * @param end The ending position for the marker.
4182 * @since 0.16
4184 void editor_indicator_set_on_range(GeanyEditor *editor, gint indic, gint start, gint end)
4186 g_return_if_fail(editor != NULL);
4187 if (start >= end)
4188 return;
4190 sci_indicator_set(editor->sci, indic);
4191 sci_indicator_fill(editor->sci, start, end - start);
4195 /* Inserts the given colour (format should be #...), if there is a selection starting with 0x...
4196 * the replacement will also start with 0x... */
4197 void editor_insert_color(GeanyEditor *editor, const gchar *colour)
4199 g_return_if_fail(editor != NULL);
4201 if (sci_has_selection(editor->sci))
4203 gint start = sci_get_selection_start(editor->sci);
4204 const gchar *replacement = colour;
4206 if (sci_get_char_at(editor->sci, start) == '0' &&
4207 sci_get_char_at(editor->sci, start + 1) == 'x')
4209 sci_set_selection_start(editor->sci, start + 2);
4210 sci_set_selection_end(editor->sci, start + 8);
4211 replacement++; /* skip the leading "0x" */
4213 else if (sci_get_char_at(editor->sci, start - 1) == '#')
4214 { /* double clicking something like #00ffff may only select 00ffff because of wordchars */
4215 replacement++; /* so skip the '#' to only replace the colour value */
4217 sci_replace_sel(editor->sci, replacement);
4219 else
4220 sci_add_text(editor->sci, colour);
4225 * Retrieves the localized name (for displaying) of the used end of line characters
4226 * (LF, CR/LF, CR) in the given editor.
4227 * If @a editor is @c NULL, the default end of line characters are used.
4229 * @param editor The editor to operate on, or @c NULL to query the default value.
4230 * @return The name of the end of line characters.
4232 * @since 0.19
4234 const gchar *editor_get_eol_char_name(GeanyEditor *editor)
4236 gint mode = file_prefs.default_eol_character;
4238 if (editor != NULL)
4239 mode = sci_get_eol_mode(editor->sci);
4241 return utils_get_eol_name(mode);
4246 * Retrieves the length of the used end of line characters (LF, CR/LF, CR) in the given editor.
4247 * If @a editor is @c NULL, the default end of line characters are used.
4248 * The returned value is 1 for CR and LF and 2 for CR/LF.
4250 * @param editor The editor to operate on, or @c NULL to query the default value.
4251 * @return The length of the end of line characters.
4253 * @since 0.19
4255 gint editor_get_eol_char_len(GeanyEditor *editor)
4257 gint mode = file_prefs.default_eol_character;
4259 if (editor != NULL)
4260 mode = sci_get_eol_mode(editor->sci);
4262 switch (mode)
4264 case SC_EOL_CRLF: return 2; break;
4265 default: return 1; break;
4271 * Retrieves the used end of line characters (LF, CR/LF, CR) in the given editor.
4272 * If @a editor is @c NULL, the default end of line characters are used.
4273 * The returned value is either "\n", "\r\n" or "\r".
4275 * @param editor The editor to operate on, or @c NULL to query the default value.
4276 * @return The end of line characters.
4278 * @since 0.19
4280 const gchar *editor_get_eol_char(GeanyEditor *editor)
4282 gint mode = file_prefs.default_eol_character;
4284 if (editor != NULL)
4285 mode = sci_get_eol_mode(editor->sci);
4287 switch (mode)
4289 case SC_EOL_CRLF: return "\r\n"; break;
4290 case SC_EOL_CR: return "\r"; break;
4291 default: return "\n"; break;
4296 static void fold_all(GeanyEditor *editor, gboolean want_fold)
4298 gint lines, first, i;
4300 if (editor == NULL || ! editor_prefs.folding)
4301 return;
4303 lines = sci_get_line_count(editor->sci);
4304 first = sci_get_first_visible_line(editor->sci);
4306 for (i = 0; i < lines; i++)
4308 gint level = sci_get_fold_level(editor->sci, i);
4310 if (level & SC_FOLDLEVELHEADERFLAG)
4312 if (sci_get_fold_expanded(editor->sci, i) == want_fold)
4313 sci_toggle_fold(editor->sci, i);
4316 editor_scroll_to_line(editor, first, 0.0F);
4320 void editor_unfold_all(GeanyEditor *editor)
4322 fold_all(editor, FALSE);
4326 void editor_fold_all(GeanyEditor *editor)
4328 fold_all(editor, TRUE);
4332 void editor_replace_tabs(GeanyEditor *editor)
4334 gint search_pos, pos_in_line, current_tab_true_length;
4335 gint tab_len;
4336 gchar *tab_str;
4337 struct Sci_TextToFind ttf;
4339 g_return_if_fail(editor != NULL);
4341 sci_start_undo_action(editor->sci);
4342 tab_len = sci_get_tab_width(editor->sci);
4343 ttf.chrg.cpMin = 0;
4344 ttf.chrg.cpMax = sci_get_length(editor->sci);
4345 ttf.lpstrText = (gchar*) "\t";
4347 while (TRUE)
4349 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4350 if (search_pos == -1)
4351 break;
4353 pos_in_line = sci_get_col_from_position(editor->sci, search_pos);
4354 current_tab_true_length = tab_len - (pos_in_line % tab_len);
4355 tab_str = g_strnfill(current_tab_true_length, ' ');
4356 sci_set_target_start(editor->sci, search_pos);
4357 sci_set_target_end(editor->sci, search_pos + 1);
4358 sci_replace_target(editor->sci, tab_str, FALSE);
4359 /* next search starts after replacement */
4360 ttf.chrg.cpMin = search_pos + current_tab_true_length - 1;
4361 /* update end of range now text has changed */
4362 ttf.chrg.cpMax += current_tab_true_length - 1;
4363 g_free(tab_str);
4365 sci_end_undo_action(editor->sci);
4369 /* Replaces all occurrences all spaces of the length of a given tab_width. */
4370 void editor_replace_spaces(GeanyEditor *editor)
4372 gint search_pos;
4373 static gdouble tab_len_f = -1.0; /* keep the last used value */
4374 gint tab_len;
4375 struct Sci_TextToFind ttf;
4377 g_return_if_fail(editor != NULL);
4379 if (tab_len_f < 0.0)
4380 tab_len_f = sci_get_tab_width(editor->sci);
4382 if (! dialogs_show_input_numeric(
4383 _("Enter Tab Width"),
4384 _("Enter the amount of spaces which should be replaced by a tab character."),
4385 &tab_len_f, 1, 100, 1))
4387 return;
4389 tab_len = (gint) tab_len_f;
4391 sci_start_undo_action(editor->sci);
4392 ttf.chrg.cpMin = 0;
4393 ttf.chrg.cpMax = sci_get_length(editor->sci);
4394 ttf.lpstrText = g_strnfill(tab_len, ' ');
4396 while (TRUE)
4398 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4399 if (search_pos == -1)
4400 break;
4402 sci_set_target_start(editor->sci, search_pos);
4403 sci_set_target_end(editor->sci, search_pos + tab_len);
4404 sci_replace_target(editor->sci, "\t", FALSE);
4405 ttf.chrg.cpMin = search_pos;
4406 /* update end of range now text has changed */
4407 ttf.chrg.cpMax -= tab_len - 1;
4409 sci_end_undo_action(editor->sci);
4410 g_free(ttf.lpstrText);
4414 void editor_strip_line_trailing_spaces(GeanyEditor *editor, gint line)
4416 gint line_start = sci_get_position_from_line(editor->sci, line);
4417 gint line_end = sci_get_line_end_position(editor->sci, line);
4418 gint i = line_end - 1;
4419 gchar ch = sci_get_char_at(editor->sci, i);
4421 while ((i >= line_start) && ((ch == ' ') || (ch == '\t')))
4423 i--;
4424 ch = sci_get_char_at(editor->sci, i);
4426 if (i < (line_end - 1))
4428 sci_set_target_start(editor->sci, i + 1);
4429 sci_set_target_end(editor->sci, line_end);
4430 sci_replace_target(editor->sci, "", FALSE);
4435 void editor_strip_trailing_spaces(GeanyEditor *editor)
4437 gint max_lines = sci_get_line_count(editor->sci);
4438 gint line;
4440 sci_start_undo_action(editor->sci);
4442 for (line = 0; line < max_lines; line++)
4444 editor_strip_line_trailing_spaces(editor, line);
4446 sci_end_undo_action(editor->sci);
4450 void editor_ensure_final_newline(GeanyEditor *editor)
4452 gint max_lines = sci_get_line_count(editor->sci);
4453 gboolean append_newline = (max_lines == 1);
4454 gint end_document = sci_get_position_from_line(editor->sci, max_lines);
4456 if (max_lines > 1)
4458 append_newline = end_document > sci_get_position_from_line(editor->sci, max_lines - 1);
4460 if (append_newline)
4462 const gchar *eol = "\n";
4463 switch (sci_get_eol_mode(editor->sci))
4465 case SC_EOL_CRLF:
4466 eol = "\r\n";
4467 break;
4468 case SC_EOL_CR:
4469 eol = "\r";
4470 break;
4472 sci_insert_text(editor->sci, end_document, eol);
4477 void editor_set_font(GeanyEditor *editor, const gchar *font)
4479 gint style, size;
4480 gchar *font_name;
4481 PangoFontDescription *pfd;
4483 g_return_if_fail(editor);
4485 pfd = pango_font_description_from_string(font);
4486 size = pango_font_description_get_size(pfd) / PANGO_SCALE;
4487 font_name = g_strdup_printf("!%s", pango_font_description_get_family(pfd));
4488 pango_font_description_free(pfd);
4490 for (style = 0; style <= 127; style++)
4491 sci_set_font(editor->sci, style, font_name, size);
4493 /* line number and braces */
4494 sci_set_font(editor->sci, STYLE_LINENUMBER, font_name, size);
4495 sci_set_font(editor->sci, STYLE_BRACELIGHT, font_name, size);
4496 sci_set_font(editor->sci, STYLE_BRACEBAD, font_name, size);
4497 g_free(font_name);
4499 /* zoom to 100% to prevent confusion */
4500 sci_zoom_off(editor->sci);
4504 void editor_set_line_wrapping(GeanyEditor *editor, gboolean wrap)
4506 g_return_if_fail(editor != NULL);
4508 editor->line_wrapping = wrap;
4509 sci_set_lines_wrapped(editor->sci, wrap);
4513 /** Sets the indent type for @a editor.
4514 * @param editor Editor.
4515 * @param type Indent type.
4517 * @since 0.16
4519 void editor_set_indent_type(GeanyEditor *editor, GeanyIndentType type)
4521 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
4522 ScintillaObject *sci = editor->sci;
4523 gboolean use_tabs = type != GEANY_INDENT_TYPE_SPACES;
4525 editor->indent_type = type;
4526 sci_set_use_tabs(sci, use_tabs);
4528 if (type == GEANY_INDENT_TYPE_BOTH)
4529 sci_set_tab_width(sci, iprefs->hard_tab_width);
4530 else
4531 sci_set_tab_width(sci, iprefs->width);
4532 SSM(sci, SCI_SETINDENT, iprefs->width, 0);
4534 /* remove indent spaces on backspace, if using any spaces to indent */
4535 SSM(sci, SCI_SETBACKSPACEUNINDENTS, type != GEANY_INDENT_TYPE_TABS, 0);
4539 /* Convenience function for editor_goto_pos() to pass in a line number. */
4540 gboolean editor_goto_line(GeanyEditor *editor, gint line)
4542 gint pos;
4544 g_return_val_if_fail(editor, FALSE);
4545 if (line < 0 || line >= sci_get_line_count(editor->sci))
4546 return FALSE;
4548 pos = sci_get_position_from_line(editor->sci, line);
4549 return editor_goto_pos(editor, pos, TRUE);
4553 /* Move to position @a pos, switching to the document if necessary,
4554 * setting a marker if @a mark is set. */
4555 gboolean editor_goto_pos(GeanyEditor *editor, gint pos, gboolean mark)
4557 gint page_num;
4559 g_return_val_if_fail(editor, FALSE);
4560 if (G_UNLIKELY(pos < 0))
4561 return FALSE;
4563 if (mark)
4565 gint line = sci_get_line_from_position(editor->sci, pos);
4567 /* mark the tag with the yellow arrow */
4568 sci_marker_delete_all(editor->sci, 0);
4569 sci_set_marker_at_line(editor->sci, line, 0);
4572 sci_goto_pos(editor->sci, pos, TRUE);
4573 editor->scroll_percent = 0.25F;
4575 /* finally switch to the page */
4576 page_num = gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook), GTK_WIDGET(editor->sci));
4577 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
4579 return TRUE;
4583 static gboolean
4584 on_editor_scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer user_data)
4586 GeanyEditor *editor = user_data;
4588 /* Handle scroll events if Alt is pressed and scroll whole pages instead of a
4589 * few lines only, maybe this could/should be done in Scintilla directly */
4590 if (event->state & GDK_MOD1_MASK)
4592 sci_send_command(editor->sci, (event->direction == GDK_SCROLL_DOWN) ? SCI_PAGEDOWN : SCI_PAGEUP);
4593 return TRUE;
4595 else if (event->state & GDK_SHIFT_MASK)
4597 gint amount = (event->direction == GDK_SCROLL_DOWN) ? 8 : -8;
4599 sci_scroll_columns(editor->sci, amount);
4600 return TRUE;
4603 return FALSE; /* let Scintilla handle all other cases */
4607 static gboolean editor_check_colourise(GeanyEditor *editor)
4609 GeanyDocument *doc = editor->document;
4611 if (!doc->priv->colourise_needed)
4612 return FALSE;
4614 doc->priv->colourise_needed = FALSE;
4615 sci_colourise(editor->sci, 0, -1);
4617 /* now that the current document is colourised, fold points are now accurate,
4618 * so force an update of the current function/tag. */
4619 symbols_get_current_function(NULL, NULL);
4620 ui_update_statusbar(NULL, -1);
4622 return TRUE;
4626 /* We only want to colourise just before drawing, to save startup time and
4627 * prevent unnecessary recolouring other documents after one is saved.
4628 * Really we want a "draw" signal but there doesn't seem to be one (expose is too late,
4629 * and "show" doesn't work). */
4630 static gboolean on_editor_focus_in(GtkWidget *widget, GdkEventFocus *event, gpointer user_data)
4632 GeanyEditor *editor = user_data;
4634 editor_check_colourise(editor);
4635 return FALSE;
4639 /* This is just to catch any uncolourised documents being drawn that didn't receive focus
4640 * for some reason, maybe it's not necessary but just in case. */
4641 static gboolean on_editor_expose_event(GtkWidget *widget, GdkEventExpose *event,
4642 gpointer user_data)
4644 GeanyEditor *editor = user_data;
4646 editor_check_colourise(editor);
4647 return FALSE;
4651 static void setup_sci_keys(ScintillaObject *sci)
4653 /* disable some Scintilla keybindings to be able to redefine them cleanly */
4654 sci_clear_cmdkey(sci, 'A' | (SCMOD_CTRL << 16)); /* select all */
4655 sci_clear_cmdkey(sci, 'D' | (SCMOD_CTRL << 16)); /* duplicate */
4656 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16)); /* line transpose */
4657 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line copy */
4658 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16)); /* line cut */
4659 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line delete */
4660 sci_clear_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line to end delete */
4661 sci_clear_cmdkey(sci, '/' | (SCMOD_CTRL << 16)); /* Previous word part */
4662 sci_clear_cmdkey(sci, '\\' | (SCMOD_CTRL << 16)); /* Next word part */
4663 sci_clear_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16)); /* scroll line up */
4664 sci_clear_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16)); /* scroll line down */
4665 sci_clear_cmdkey(sci, SCK_HOME); /* line start */
4666 sci_clear_cmdkey(sci, SCK_END); /* line end */
4667 sci_clear_cmdkey(sci, SCK_END | (SCMOD_ALT << 16)); /* visual line end */
4669 if (editor_prefs.use_gtk_word_boundaries)
4671 /* use GtkEntry-like word boundaries */
4672 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16), SCI_WORDRIGHTEND);
4673 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_WORDRIGHTENDEXTEND);
4674 sci_assign_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16), SCI_DELWORDRIGHTEND);
4676 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_ALT << 16), SCI_LINESCROLLUP);
4677 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_ALT << 16), SCI_LINESCROLLDOWN);
4678 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16), SCI_PARAUP);
4679 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARAUPEXTEND);
4680 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16), SCI_PARADOWN);
4681 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARADOWNEXTEND);
4683 sci_clear_cmdkey(sci, SCK_BACK | (SCMOD_ALT << 16)); /* clear Alt-Backspace (Undo) */
4687 #include "icons/16x16/classviewer-var.xpm"
4688 #include "icons/16x16/classviewer-method.xpm"
4690 /* Create new editor widget (scintilla).
4691 * @note The @c "sci-notify" signal is connected separately. */
4692 static ScintillaObject *create_new_sci(GeanyEditor *editor)
4694 ScintillaObject *sci;
4696 sci = SCINTILLA(scintilla_new());
4698 gtk_widget_show(GTK_WIDGET(sci));
4700 sci_set_codepage(sci, SC_CP_UTF8);
4701 /*SSM(sci, SCI_SETWRAPSTARTINDENT, 4, 0);*/
4702 /* disable scintilla provided popup menu */
4703 sci_use_popup(sci, FALSE);
4705 setup_sci_keys(sci);
4707 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
4708 sci_set_lines_wrapped(sci, editor_prefs.line_wrapping);
4709 sci_set_scrollbar_mode(sci, editor_prefs.show_scrollbars);
4710 sci_set_caret_policy_x(sci, CARET_JUMPS | CARET_EVEN, 0);
4711 /*sci_set_caret_policy_y(sci, CARET_JUMPS | CARET_EVEN, 0);*/
4712 SSM(sci, SCI_AUTOCSETSEPARATOR, '\n', 0);
4713 SSM(sci, SCI_SETSCROLLWIDTHTRACKING, 1, 0);
4715 /* tag autocompletion images */
4716 SSM(sci, SCI_REGISTERIMAGE, 1, (sptr_t)classviewer_var);
4717 SSM(sci, SCI_REGISTERIMAGE, 2, (sptr_t)classviewer_method);
4719 /* necessary for column mode editing, implemented in Scintilla since 2.0 */
4720 SSM(sci, SCI_SETADDITIONALSELECTIONTYPING, 1, 0);
4722 /* virtual space */
4723 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
4725 /* only connect signals if this is for the document notebook, not split window */
4726 if (editor->sci == NULL)
4728 g_signal_connect(sci, "button-press-event", G_CALLBACK(on_editor_button_press_event), editor);
4729 g_signal_connect(sci, "scroll-event", G_CALLBACK(on_editor_scroll_event), editor);
4730 g_signal_connect(sci, "motion-notify-event", G_CALLBACK(on_motion_event), NULL);
4731 g_signal_connect(sci, "focus-in-event", G_CALLBACK(on_editor_focus_in), editor);
4732 g_signal_connect(sci, "expose-event", G_CALLBACK(on_editor_expose_event), editor);
4734 return sci;
4738 /** Creates a new Scintilla @c GtkWidget based on the settings for @a editor.
4739 * @param editor Editor settings.
4740 * @return The new widget.
4742 * @since 0.15
4744 ScintillaObject *editor_create_widget(GeanyEditor *editor)
4746 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4747 ScintillaObject *old, *sci;
4749 /* temporarily change editor to use the new sci widget */
4750 old = editor->sci;
4751 sci = create_new_sci(editor);
4752 editor->sci = sci;
4754 editor_set_indent_type(editor, iprefs->type);
4755 editor_set_font(editor, interface_prefs.editor_font);
4756 editor_apply_update_prefs(editor);
4758 /* if editor already had a widget, restore it */
4759 if (old)
4760 editor->sci = old;
4761 return sci;
4765 GeanyEditor *editor_create(GeanyDocument *doc)
4767 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4768 GeanyEditor *editor = g_new0(GeanyEditor, 1);
4770 editor->document = doc;
4771 doc->editor = editor; /* needed in case some editor functions/callbacks expect it */
4773 editor->auto_indent = (iprefs->auto_indent_mode != GEANY_AUTOINDENT_NONE);
4774 editor->line_wrapping = editor_prefs.line_wrapping;
4775 editor->scroll_percent = -1.0F;
4776 editor->line_breaking = FALSE;
4778 editor->sci = editor_create_widget(editor);
4779 return editor;
4783 /* in case we need to free some fields in future */
4784 void editor_destroy(GeanyEditor *editor)
4786 g_free(editor);
4790 static void on_document_save(GObject *obj, GeanyDocument *doc)
4792 g_return_if_fail(NZV(doc->real_path));
4794 if (utils_str_equal(doc->real_path,
4795 utils_build_path(app->configdir, "snippets.conf", NULL)))
4797 /* reload snippets */
4798 editor_snippets_free();
4799 editor_snippets_init();
4804 gboolean editor_complete_word_part(GeanyEditor *editor)
4806 gchar *entry;
4808 g_return_val_if_fail(editor, FALSE);
4810 if (!SSM(editor->sci, SCI_AUTOCACTIVE, 0, 0))
4811 return FALSE;
4813 entry = sci_get_string(editor->sci, SCI_AUTOCGETCURRENTTEXT, 0);
4815 /* if no word part, complete normally */
4816 if (!check_partial_completion(editor, entry))
4817 SSM(editor->sci, SCI_AUTOCCOMPLETE, 0, 0);
4819 g_free(entry);
4820 return TRUE;
4824 void editor_init(void)
4826 static GeanyIndentPrefs indent_prefs;
4828 memset(&editor_prefs, 0, sizeof(GeanyEditorPrefs));
4829 memset(&indent_prefs, 0, sizeof(GeanyIndentPrefs));
4830 editor_prefs.indentation = &indent_prefs;
4832 /* use g_signal_connect_after() to allow plugins connecting to the signal before the default
4833 * handler (on_editor_notify) is called */
4834 g_signal_connect_after(geany_object, "editor-notify", G_CALLBACK(on_editor_notify), NULL);
4836 ui_add_config_file_menu_item(utils_build_path(app->configdir, "snippets.conf", NULL),
4837 NULL, NULL);
4838 g_signal_connect(geany_object, "document-save", G_CALLBACK(on_document_save), NULL);
4842 /* TODO: Should these be user-defined instead of hard-coded? */
4843 void editor_set_indentation_guides(GeanyEditor *editor)
4845 gint mode;
4846 gint lexer;
4848 g_return_if_fail(editor != NULL);
4850 if (! editor_prefs.show_indent_guide)
4852 sci_set_indentation_guides(editor->sci, SC_IV_NONE);
4853 return;
4856 lexer = sci_get_lexer(editor->sci);
4857 switch (lexer)
4859 /* Lines added/removed are prefixed with +/- characters, so
4860 * those lines will not be shown with any indentation guides.
4861 * It can be distracting that only a few of lines in a diff/patch
4862 * file will show the guides. */
4863 case SCLEX_DIFF:
4864 mode = SC_IV_NONE;
4865 break;
4867 /* These languages use indentation for control blocks; the "look forward" method works
4868 * best here */
4869 case SCLEX_PYTHON:
4870 case SCLEX_HASKELL:
4871 case SCLEX_MAKEFILE:
4872 case SCLEX_ASM:
4873 case SCLEX_SQL:
4874 case SCLEX_PROPERTIES:
4875 case SCLEX_FORTRAN: /* Is this the best option for Fortran? */
4876 case SCLEX_CAML:
4877 mode = SC_IV_LOOKFORWARD;
4878 break;
4880 /* C-like (structured) languages benefit from the "look both" method */
4881 case SCLEX_CPP:
4882 case SCLEX_HTML:
4883 case SCLEX_XML:
4884 case SCLEX_PERL:
4885 case SCLEX_LATEX:
4886 case SCLEX_LUA:
4887 case SCLEX_PASCAL:
4888 case SCLEX_RUBY:
4889 case SCLEX_TCL:
4890 case SCLEX_F77:
4891 case SCLEX_CSS:
4892 case SCLEX_BASH:
4893 case SCLEX_VHDL:
4894 case SCLEX_FREEBASIC:
4895 case SCLEX_D:
4896 case SCLEX_MATLAB:
4897 mode = SC_IV_LOOKBOTH;
4898 break;
4900 default:
4901 mode = SC_IV_REAL;
4902 break;
4905 sci_set_indentation_guides(editor->sci, mode);
4909 /* Apply just the prefs that can change in the Preferences dialog */
4910 void editor_apply_update_prefs(GeanyEditor *editor)
4912 ScintillaObject *sci;
4914 g_return_if_fail(editor != NULL);
4916 sci = editor->sci;
4918 sci_set_mark_long_lines(sci, editor_get_long_line_type(),
4919 editor_get_long_line_column(), editor_prefs.long_line_color);
4921 /* update indent width, tab width */
4922 editor_set_indent_type(editor, editor->indent_type);
4923 sci_set_tab_indents(sci, editor_prefs.use_tab_to_indent);
4925 sci_set_autoc_max_height(sci, editor_prefs.symbolcompletion_max_height);
4926 SSM(sci, SCI_AUTOCSETDROPRESTOFWORD, editor_prefs.completion_drops_rest_of_word, 0);
4928 editor_set_indentation_guides(editor);
4930 sci_set_visible_white_spaces(sci, editor_prefs.show_white_space);
4931 sci_set_visible_eols(sci, editor_prefs.show_line_endings);
4932 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
4933 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin, 0);
4935 sci_set_folding_margin_visible(sci, editor_prefs.folding);
4937 /* virtual space */
4938 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
4940 /* (dis)allow scrolling past end of document */
4941 sci_set_scroll_stop_at_last_line(sci, editor_prefs.scroll_stop_at_last_line);
4945 /* This is for tab-indents, space aligns formatted code. Spaces should be preserved. */
4946 static void change_tab_indentation(GeanyEditor *editor, gint line, gboolean increase)
4948 ScintillaObject *sci = editor->sci;
4949 gint pos = sci_get_position_from_line(sci, line);
4951 if (increase)
4953 sci_insert_text(sci, pos, "\t");
4955 else
4957 if (sci_get_char_at(sci, pos) == '\t')
4959 sci_set_selection(sci, pos, pos + 1);
4960 sci_replace_sel(sci, "");
4962 else /* remove spaces only if no tabs */
4964 gint width = sci_get_line_indentation(sci, line);
4966 width -= editor_get_indent_prefs(editor)->width;
4967 sci_set_line_indentation(sci, line, width);
4973 static void editor_change_line_indent(GeanyEditor *editor, gint line, gboolean increase)
4975 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
4976 ScintillaObject *sci = editor->sci;
4978 if (iprefs->type == GEANY_INDENT_TYPE_TABS)
4979 change_tab_indentation(editor, line, increase);
4980 else
4982 gint width = sci_get_line_indentation(sci, line);
4984 width += increase ? iprefs->width : -iprefs->width;
4985 sci_set_line_indentation(sci, line, width);
4990 void editor_indent(GeanyEditor *editor, gboolean increase)
4992 ScintillaObject *sci = editor->sci;
4993 gint start, end;
4994 gint line, lstart, lend;
4996 if (sci_get_lines_selected(sci) <= 1)
4998 line = sci_get_current_line(sci);
4999 editor_change_line_indent(editor, line, increase);
5000 return;
5002 editor_select_lines(editor, FALSE);
5003 start = sci_get_selection_start(sci);
5004 end = sci_get_selection_end(sci);
5005 lstart = sci_get_line_from_position(sci, start);
5006 lend = sci_get_line_from_position(sci, end);
5007 if (end == sci_get_length(sci))
5008 lend++; /* for last line with text on it */
5010 sci_start_undo_action(sci);
5011 for (line = lstart; line < lend; line++)
5013 editor_change_line_indent(editor, line, increase);
5015 sci_end_undo_action(sci);
5017 /* set cursor/selection */
5018 if (lend > lstart)
5020 sci_set_selection_start(sci, start);
5021 end = sci_get_position_from_line(sci, lend);
5022 sci_set_selection_end(sci, end);
5023 editor_select_lines(editor, FALSE);
5025 else
5027 sci_set_current_line(sci, lstart);