Add xml_indent_tags filetype setting for documents using the
[geany-mirror.git] / src / editor.c
blob68b09f88c7d724e561a16fa03bb7009d3e960534
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 #ifdef HAVE_REGEX_H
48 # include <regex.h>
49 #else
50 # include "gnuregex.h"
51 #endif
53 #include "support.h"
54 #include "editor.h"
55 #include "document.h"
56 #include "documentprivate.h"
57 #include "filetypes.h"
58 #include "filetypesprivate.h"
59 #include "sciwrappers.h"
60 #include "ui_utils.h"
61 #include "utils.h"
62 #include "dialogs.h"
63 #include "symbols.h"
64 #include "callbacks.h"
65 #include "templates.h"
66 #include "keybindings.h"
67 #include "project.h"
68 #include "projectprivate.h"
69 #include "main.h"
72 /* Note: use sciwrappers.h instead where possible.
73 * Do not use SSM in files unrelated to scintilla. */
74 #define SSM(s, m, w, l) scintilla_send_message(s, m, w, l)
77 static GHashTable *snippet_hash = NULL;
78 static GQueue *snippet_offsets = NULL;
79 static gint snippet_cursor_insert_pos;
80 static GtkAccelGroup *snippet_accel_group = NULL;
82 /* holds word under the mouse or keyboard cursor */
83 static gchar current_word[GEANY_MAX_WORD_LENGTH];
85 /* Initialised in keyfile.c. */
86 GeanyEditorPrefs editor_prefs;
88 EditorInfo editor_info = {current_word, -1};
90 static struct
92 gchar *text;
93 gboolean set;
94 gchar *last_word;
95 guint tag_index;
96 gint pos;
97 ScintillaObject *sci;
98 } calltip = {NULL, FALSE, NULL, 0, 0, NULL};
100 static gchar indent[100];
103 static void on_new_line_added(GeanyEditor *editor);
104 static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch);
105 static void insert_indent_after_line(GeanyEditor *editor, gint line);
106 static void auto_multiline(GeanyEditor *editor, gint pos);
107 static gboolean is_code_style(gint lexer, gint style);
108 static gboolean is_string_style(gint lexer, gint style);
109 static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c);
110 static void close_block(GeanyEditor *editor, gint pos);
111 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos);
112 static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, size_t wordlen,
113 const gchar *wc, gboolean stem);
114 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent);
115 static const gchar *snippets_find_completion_by_name(const gchar *type, const gchar *name);
116 static gssize snippets_make_replacements(GeanyEditor *editor, GString *pattern,
117 gsize indent_size);
120 void editor_snippets_free(void)
122 g_hash_table_destroy(snippet_hash);
123 g_queue_free(snippet_offsets);
124 gtk_window_remove_accel_group(GTK_WINDOW(main_widgets.window), snippet_accel_group);
128 static void snippets_load(GKeyFile *sysconfig, GKeyFile *userconfig)
130 gsize i, j, len = 0, len_keys = 0;
131 gchar **groups_user, **groups_sys;
132 gchar **keys_user, **keys_sys;
133 gchar *value;
134 GHashTable *tmp;
136 /* keys are strings, values are GHashTables, so use g_free and g_hash_table_destroy */
137 snippet_hash =
138 g_hash_table_new_full(g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_hash_table_destroy);
140 /* first read all globally defined auto completions */
141 groups_sys = g_key_file_get_groups(sysconfig, &len);
142 for (i = 0; i < len; i++)
144 if (strcmp(groups_sys[i], "Keybindings") == 0)
145 continue;
146 keys_sys = g_key_file_get_keys(sysconfig, groups_sys[i], &len_keys, NULL);
147 /* create new hash table for the read section (=> filetype) */
148 tmp = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
149 g_hash_table_insert(snippet_hash, g_strdup(groups_sys[i]), tmp);
151 for (j = 0; j < len_keys; j++)
153 g_hash_table_insert(tmp, g_strdup(keys_sys[j]),
154 utils_get_setting_string(sysconfig, groups_sys[i], keys_sys[j], ""));
156 g_strfreev(keys_sys);
158 g_strfreev(groups_sys);
160 /* now read defined completions in user's configuration directory and add / replace them */
161 groups_user = g_key_file_get_groups(userconfig, &len);
162 for (i = 0; i < len; i++)
164 if (strcmp(groups_user[i], "Keybindings") == 0)
165 continue;
166 keys_user = g_key_file_get_keys(userconfig, groups_user[i], &len_keys, NULL);
168 tmp = g_hash_table_lookup(snippet_hash, groups_user[i]);
169 if (tmp == NULL)
170 { /* new key found, create hash table */
171 tmp = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
172 g_hash_table_insert(snippet_hash, g_strdup(groups_user[i]), tmp);
174 for (j = 0; j < len_keys; j++)
176 value = g_hash_table_lookup(tmp, keys_user[j]);
177 if (value == NULL)
178 { /* value = NULL means the key doesn't yet exist, so insert */
179 g_hash_table_insert(tmp, g_strdup(keys_user[j]),
180 utils_get_setting_string(userconfig, groups_user[i], keys_user[j], ""));
182 else
183 { /* old key and value will be freed by destroy function (g_free) */
184 g_hash_table_replace(tmp, g_strdup(keys_user[j]),
185 utils_get_setting_string(userconfig, groups_user[i], keys_user[j], ""));
188 g_strfreev(keys_user);
190 g_strfreev(groups_user);
194 static void on_snippet_keybinding_activate(gchar *key)
196 GeanyDocument *doc = document_get_current();
197 const gchar *s;
198 GHashTable *specials;
199 GString *pattern;
200 gint pos, line, indent_width, cursor_pos;
202 if (!doc || !GTK_WIDGET_HAS_FOCUS(doc->editor->sci))
203 return;
205 s = snippets_find_completion_by_name(doc->file_type->name, key);
206 if (!s) /* allow user to specify keybindings for "special" snippets */
208 specials = g_hash_table_lookup(snippet_hash, "Special");
209 if (G_LIKELY(specials != NULL))
210 s = g_hash_table_lookup(specials, key);
212 if (!s)
214 utils_beep();
215 return;
218 pos = sci_get_current_position(doc->editor->sci);
219 line = sci_get_line_from_position(doc->editor->sci, pos);
220 indent_width = sci_get_line_indentation(doc->editor->sci, line);
222 pattern = g_string_new(s);
223 cursor_pos = snippets_make_replacements(doc->editor, pattern, indent_width);
225 editor_insert_text_block(doc->editor, pattern->str, pos, cursor_pos, indent_width, FALSE);
226 sci_scroll_caret(doc->editor->sci);
228 g_string_free(pattern, TRUE);
232 static void add_kb(GKeyFile *keyfile, const gchar *group, gchar **keys)
234 gsize i;
236 if (!keys)
237 return;
238 for (i = 0; i < g_strv_length(keys); i++)
240 guint key;
241 GdkModifierType mods;
242 gchar *accel_string = g_key_file_get_value(keyfile, group, keys[i], NULL);
244 gtk_accelerator_parse(accel_string, &key, &mods);
245 g_free(accel_string);
247 if (key == 0 && mods == 0)
249 g_warning("Can not parse accelerator \"%s\" from user snippets.conf", accel_string);
250 continue;
252 gtk_accel_group_connect(snippet_accel_group, key, mods, 0,
253 g_cclosure_new_swap((GCallback)on_snippet_keybinding_activate,
254 g_strdup(keys[i]), (GClosureNotify)g_free));
259 static void load_kb(GKeyFile *sysconfig, GKeyFile *userconfig)
261 const gchar kb_group[] = "Keybindings";
262 gchar **keys = g_key_file_get_keys(userconfig, kb_group, NULL, NULL);
263 gchar **ptr;
265 /* remove overridden keys from system keyfile */
266 foreach_strv(ptr, keys)
267 g_key_file_remove_key(sysconfig, kb_group, *ptr, NULL);
269 add_kb(userconfig, kb_group, keys);
270 g_strfreev(keys);
272 keys = g_key_file_get_keys(sysconfig, kb_group, NULL, NULL);
273 add_kb(sysconfig, kb_group, keys);
274 g_strfreev(keys);
278 void editor_snippets_init(void)
280 gchar *sysconfigfile, *userconfigfile;
281 GKeyFile *sysconfig = g_key_file_new();
282 GKeyFile *userconfig = g_key_file_new();
284 snippet_offsets = g_queue_new();
286 sysconfigfile = g_strconcat(app->datadir, G_DIR_SEPARATOR_S, "snippets.conf", NULL);
287 userconfigfile = g_strconcat(app->configdir, G_DIR_SEPARATOR_S, "snippets.conf", NULL);
289 /* check for old autocomplete.conf files (backwards compatibility) */
290 if (! g_file_test(userconfigfile, G_FILE_TEST_IS_REGULAR))
291 setptr(userconfigfile,
292 g_strconcat(app->configdir, G_DIR_SEPARATOR_S, "autocomplete.conf", NULL));
294 /* load the actual config files */
295 g_key_file_load_from_file(sysconfig, sysconfigfile, G_KEY_FILE_NONE, NULL);
296 g_key_file_load_from_file(userconfig, userconfigfile, G_KEY_FILE_NONE, NULL);
298 snippets_load(sysconfig, userconfig);
300 /* setup snippet keybindings */
301 snippet_accel_group = gtk_accel_group_new();
302 gtk_window_add_accel_group(GTK_WINDOW(main_widgets.window), snippet_accel_group);
303 load_kb(sysconfig, userconfig);
305 g_free(sysconfigfile);
306 g_free(userconfigfile);
307 g_key_file_free(sysconfig);
308 g_key_file_free(userconfig);
312 static gboolean on_editor_button_press_event(GtkWidget *widget, GdkEventButton *event,
313 gpointer data)
315 GeanyEditor *editor = data;
316 GeanyDocument *doc = editor->document;
318 /* it's very unlikely we got a 'real' click even on 0, 0, so assume it is a
319 * fake event to show the editor menu triggered by a key event where we want to use the
320 * text cursor position. */
321 if (event->x > 0.0 && event->y > 0.0)
322 editor_info.click_pos = sci_get_position_from_xy(editor->sci,
323 (gint)event->x, (gint)event->y, FALSE);
324 else
325 editor_info.click_pos = sci_get_current_position(editor->sci);
327 if (event->button == 1)
329 guint state = event->state & gtk_accelerator_get_default_mod_mask();
331 if (event->type == GDK_BUTTON_PRESS && editor_prefs.disable_dnd)
333 gint ss = sci_get_selection_start(editor->sci);
334 sci_set_selection_end(editor->sci, ss);
336 if (event->type == GDK_BUTTON_PRESS && state == GDK_CONTROL_MASK)
338 sci_set_current_position(editor->sci, editor_info.click_pos, FALSE);
340 editor_find_current_word(editor, editor_info.click_pos,
341 current_word, sizeof current_word, NULL);
342 if (*current_word)
343 return symbols_goto_tag(current_word, TRUE);
344 else
345 keybindings_send_command(GEANY_KEY_GROUP_GOTO, GEANY_KEYS_GOTO_MATCHINGBRACE);
346 return TRUE;
348 return document_check_disk_status(doc, FALSE);
351 /* calls the edit popup menu in the editor */
352 if (event->button == 3)
354 gboolean can_goto;
356 editor_find_current_word(editor, editor_info.click_pos,
357 current_word, sizeof current_word, NULL);
359 can_goto = sci_has_selection(editor->sci) || current_word[0] != '\0';
360 ui_update_popup_goto_items(can_goto);
361 ui_update_popup_copy_items(doc);
362 ui_update_insert_include_item(doc, 0);
364 g_signal_emit_by_name(geany_object, "update-editor-menu",
365 current_word, editor_info.click_pos, doc);
367 gtk_menu_popup(GTK_MENU(main_widgets.editor_menu),
368 NULL, NULL, NULL, NULL, event->button, event->time);
370 return TRUE;
372 return FALSE;
376 static gboolean is_style_php(gint style)
378 if ((style >= SCE_HPHP_DEFAULT && style <= SCE_HPHP_OPERATOR) ||
379 style == SCE_HPHP_COMPLEX_VARIABLE)
381 return TRUE;
384 return FALSE;
388 gint editor_get_long_line_type(void)
390 if (app->project)
391 switch (app->project->long_line_behaviour)
393 case 0: /* marker disabled */
394 return 2;
395 case 1: /* use global settings */
396 break;
397 case 2: /* custom (enabled) */
398 return editor_prefs.long_line_global_type;
401 if (!editor_prefs.long_line_global_enabled)
402 return 2;
403 else
404 return editor_prefs.long_line_global_type;
408 gint editor_get_long_line_column(void)
410 if (app->project && app->project->long_line_behaviour != 1 /* use global settings */)
411 return app->project->long_line_column;
412 else
413 return editor_prefs.long_line_global_column;
417 void editor_toggle_fold(GeanyEditor *editor, gint line, gint modifiers)
419 ScintillaObject *sci;
421 g_return_if_fail(editor != NULL);
423 sci = editor->sci;
425 sci_toggle_fold(sci, line);
427 /* extra toggling of child fold points
428 * use when editor_prefs.unfold_all_children is set and Shift is NOT pressed or when
429 * editor_prefs.unfold_all_children is NOT set but Shift is pressed */
430 if ((editor_prefs.unfold_all_children && ! (modifiers & SCMOD_SHIFT)) ||
431 (! editor_prefs.unfold_all_children && (modifiers & SCMOD_SHIFT)))
433 gint last_line = SSM(sci, SCI_GETLASTCHILD, line, -1);
434 gint i;
436 if (sci_get_line_is_visible(sci, line + 1))
437 { /* unfold all children of the current fold point */
438 for (i = line; i < last_line; i++)
440 if (! sci_get_line_is_visible(sci, i))
442 sci_toggle_fold(sci, sci_get_fold_parent(sci, i));
446 else
447 { /* fold all children of the current fold point */
448 for (i = line; i < last_line; i++)
450 gint level = sci_get_fold_level(sci, i);
451 if (level & SC_FOLDLEVELHEADERFLAG)
453 if (sci_get_fold_expanded(sci, i))
454 sci_toggle_fold(sci, i);
462 static void on_margin_click(GeanyEditor *editor, SCNotification *nt)
464 /* left click to marker margin marks the line */
465 if (nt->margin == 1)
467 gint line = sci_get_line_from_position(editor->sci, nt->position);
469 /*sci_marker_delete_all(editor->sci, 1);*/
470 sci_toggle_marker_at_line(editor->sci, line, 1); /* toggle the marker */
472 /* left click on the folding margin to toggle folding state of current line */
473 else if (nt->margin == 2 && editor_prefs.folding)
475 gint line = sci_get_line_from_position(editor->sci, nt->position);
476 editor_toggle_fold(editor, line, nt->modifiers);
481 static void on_update_ui(GeanyEditor *editor, G_GNUC_UNUSED SCNotification *nt)
483 ScintillaObject *sci = editor->sci;
484 gint pos = sci_get_current_position(sci);
486 /* undo / redo menu update */
487 ui_update_popup_reundo_items(editor->document);
489 /* brace highlighting */
490 editor_highlight_braces(editor, pos);
492 ui_update_statusbar(editor->document, pos);
494 #if 0
495 /** experimental code for inverting selections */
497 gint i;
498 for (i = SSM(sci, SCI_GETSELECTIONSTART, 0, 0); i < SSM(sci, SCI_GETSELECTIONEND, 0, 0); i++)
500 /* need to get colour from getstyleat(), but how? */
501 SSM(sci, SCI_STYLESETFORE, STYLE_DEFAULT, 0);
502 SSM(sci, SCI_STYLESETBACK, STYLE_DEFAULT, 0);
505 sci_get_style_at(sci, pos);
507 #endif
511 static void check_line_breaking(GeanyEditor *editor, gint pos, gchar c)
513 ScintillaObject *sci = editor->sci;
514 gint line, lstart, col;
516 if (!editor->line_breaking)
517 return;
519 col = sci_get_col_from_position(sci, pos);
521 if (c == GDK_space)
522 pos--; /* Look for previous space, not the new one */
524 line = sci_get_current_line(sci);
526 lstart = sci_get_position_from_line(sci, line);
528 /* use column instead of position which might be different with multibyte characters */
529 if (col < editor_prefs.line_break_column)
530 return;
532 /* look for the last space before line_break_column */
533 pos = MIN(pos, lstart + editor_prefs.line_break_column);
535 while (pos > lstart)
537 c = sci_get_char_at(sci, --pos);
538 if (c == GDK_space)
540 gint diff, last_pos, last_col;
542 /* remember the distance between the current column and the last column on the line
543 * (we use column position in case the previous line gets altered, such as removing
544 * trailing spaces or in case it contains multibyte characters) */
545 last_pos = sci_get_line_end_position(sci, line);
546 last_col = sci_get_col_from_position(sci, last_pos);
547 diff = last_col - col;
549 /* break the line after the space */
550 sci_set_current_position(sci, pos + 1, FALSE);
551 sci_cancel(sci); /* don't select from completion list */
552 sci_send_command(sci, SCI_NEWLINE);
553 line++;
555 /* correct cursor position (might not be at line end) */
556 last_pos = sci_get_line_end_position(sci, line);
557 last_col = sci_get_col_from_position(sci, last_pos); /* get last column on line */
558 /* last column - distance is the desired column, then retrieve its document position */
559 pos = SSM(sci, SCI_FINDCOLUMN, line, last_col - diff);
560 sci_set_current_position(sci, pos, FALSE);
562 return;
568 static void show_autocomplete(ScintillaObject *sci, gint rootlen, const gchar *words)
570 /* store whether a calltip is showing, so we can reshow it after autocompletion */
571 calltip.set = SSM(sci, SCI_CALLTIPACTIVE, 0, 0);
572 SSM(sci, SCI_AUTOCSHOW, rootlen, (sptr_t) words);
576 static void show_tags_list(GeanyEditor *editor, const GPtrArray *tags, gsize rootlen)
578 ScintillaObject *sci = editor->sci;
580 g_return_if_fail(tags);
582 if (tags->len > 0)
584 GString *words = g_string_sized_new(150);
585 guint j;
587 for (j = 0; j < tags->len; ++j)
589 TMTag *tag = tags->pdata[j];
591 if (j > 0)
592 g_string_append_c(words, '\n');
594 if (j == editor_prefs.autocompletion_max_entries)
596 g_string_append(words, "...");
597 break;
599 g_string_append(words, tag->name);
601 /* for now, tag types don't all follow C, so just look at arglist */
602 if (NZV(tag->atts.entry.arglist))
603 g_string_append(words, "?2");
604 else
605 g_string_append(words, "?1");
607 show_autocomplete(sci, rootlen, words->str);
608 g_string_free(words, TRUE);
613 /* do not use with long strings */
614 static gboolean match_last_chars(ScintillaObject *sci, gint pos, const gchar *str)
616 gsize len = strlen(str);
617 gchar *buf;
619 g_return_val_if_fail(len < 100, FALSE);
621 buf = g_alloca(len + 1);
622 sci_get_text_range(sci, pos - len, pos, buf);
623 return strcmp(str, buf) == 0;
627 static gboolean reshow_calltip(gpointer data)
629 GeanyDocument *doc;
631 g_return_val_if_fail(calltip.sci != NULL, FALSE);
633 SSM(calltip.sci, SCI_CALLTIPCANCEL, 0, 0);
634 doc = document_get_current();
636 if (doc && doc->editor->sci == calltip.sci)
638 /* we use the position where the calltip was previously started as SCI_GETCURRENTPOS
639 * may be completely wrong in case the user cancelled the auto completion with the mouse */
640 SSM(calltip.sci, SCI_CALLTIPSHOW, calltip.pos, (sptr_t) calltip.text);
642 return FALSE;
646 static void request_reshowing_calltip(SCNotification *nt)
648 if (calltip.set)
650 /* delay the reshow of the calltip window to make sure it is actually displayed,
651 * without it might be not visible on SCN_AUTOCCANCEL */
652 g_idle_add(reshow_calltip, NULL);
657 static void autocomplete_scope(GeanyEditor *editor)
659 ScintillaObject *sci = editor->sci;
660 gint pos = sci_get_current_position(editor->sci);
661 gchar typed = sci_get_char_at(sci, pos - 1);
662 gchar *name;
663 const GPtrArray *tags = NULL;
664 const TMTag *tag;
665 GeanyFiletype *ft = editor->document->file_type;
667 if (ft->id == GEANY_FILETYPES_C || ft->id == GEANY_FILETYPES_CPP)
669 if (match_last_chars(sci, pos, "->") || match_last_chars(sci, pos, "::"))
670 pos--;
671 else if (typed != '.')
672 return;
674 else if (typed != '.')
675 return;
677 /* allow for a space between word and operator */
678 if (isspace(sci_get_char_at(sci, pos - 2)))
679 pos--;
680 name = editor_get_word_at_pos(editor, pos - 1, NULL);
681 if (!name)
682 return;
684 tags = tm_workspace_find(name, tm_tag_max_t, NULL, FALSE, ft->lang);
685 g_free(name);
686 if (!tags || tags->len == 0)
687 return;
689 tag = g_ptr_array_index(tags, 0);
690 name = tag->atts.entry.var_type;
691 if (name)
693 TMWorkObject *obj = editor->document->tm_file;
695 tags = tm_workspace_find_scope_members(obj ? obj->tags_array : NULL,
696 name, TRUE, FALSE);
697 if (tags)
698 show_tags_list(editor, tags, 0);
703 static void on_char_added(GeanyEditor *editor, SCNotification *nt)
705 ScintillaObject *sci = editor->sci;
706 gint pos = sci_get_current_position(sci);
708 switch (nt->ch)
710 case '\r':
711 { /* simple indentation (only for CR format) */
712 if (sci_get_eol_mode(sci) == SC_EOL_CR)
713 on_new_line_added(editor);
714 break;
716 case '\n':
717 { /* simple indentation (for CR/LF and LF format) */
718 on_new_line_added(editor);
719 break;
721 case '>':
722 editor_start_auto_complete(editor, pos, FALSE); /* C/C++ ptr-> scope completion */
723 /* fall through */
724 case '/':
725 { /* close xml-tags */
726 handle_xml(editor, pos, nt->ch);
727 break;
729 case '(':
731 auto_close_chars(sci, pos, nt->ch);
732 /* show calltips */
733 editor_show_calltip(editor, --pos);
734 break;
736 case ')':
737 { /* hide calltips */
738 if (SSM(sci, SCI_CALLTIPACTIVE, 0, 0))
740 SSM(sci, SCI_CALLTIPCANCEL, 0, 0);
742 g_free(calltip.text);
743 calltip.text = NULL;
744 calltip.pos = 0;
745 calltip.sci = NULL;
746 calltip.set = FALSE;
747 break;
749 case '{':
750 case '[':
751 case '"':
752 case '\'':
754 auto_close_chars(sci, pos, nt->ch);
755 break;
757 case '}':
758 { /* closing bracket handling */
759 if (editor->auto_indent)
760 close_block(editor, pos - 1);
761 break;
763 /* scope autocompletion */
764 case '.':
765 case ':': /* C/C++ class:: syntax */
766 /* tag autocompletion */
767 default:
768 #if 0
769 if (! editor_start_auto_complete(editor, pos, FALSE))
770 request_reshowing_calltip(nt);
771 #else
772 editor_start_auto_complete(editor, pos, FALSE);
773 #endif
775 check_line_breaking(editor, pos, nt->ch);
779 /* expand() and fold_changed() are copied from SciTE (thanks) to fix #1923350. */
780 static void expand(ScintillaObject *sci, gint *line, gboolean doExpand,
781 gboolean force, gint visLevels, gint level)
783 gint lineMaxSubord = SSM(sci, SCI_GETLASTCHILD, *line, level & SC_FOLDLEVELNUMBERMASK);
784 gint levelLine = level;
785 (*line)++;
786 while (*line <= lineMaxSubord)
788 if (G_UNLIKELY(force))
790 if (visLevels > 0)
791 SSM(sci, SCI_SHOWLINES, *line, *line);
792 else
793 SSM(sci, SCI_HIDELINES, *line, *line);
795 else
797 if (doExpand)
798 SSM(sci, SCI_SHOWLINES, *line, *line);
800 if (levelLine == -1)
801 levelLine = SSM(sci, SCI_GETFOLDLEVEL, *line, 0);
802 if (levelLine & SC_FOLDLEVELHEADERFLAG)
804 if (G_UNLIKELY(force))
806 if (visLevels > 1)
807 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
808 else
809 SSM(sci, SCI_SETFOLDEXPANDED, *line, 0);
810 expand(sci, line, doExpand, force, visLevels - 1, -1);
812 else
814 if (doExpand)
816 if (!sci_get_fold_expanded(sci, *line))
817 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
818 expand(sci, line, TRUE, force, visLevels - 1, -1);
820 else
822 expand(sci, line, FALSE, force, visLevels - 1, -1);
826 else
828 (*line)++;
834 static void fold_changed(ScintillaObject *sci, gint line, gint levelNow, gint levelPrev)
836 if (levelNow & SC_FOLDLEVELHEADERFLAG)
838 if (! (levelPrev & SC_FOLDLEVELHEADERFLAG))
840 /* Adding a fold point */
841 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
842 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
845 else if (levelPrev & SC_FOLDLEVELHEADERFLAG)
847 if (! sci_get_fold_expanded(sci, line))
848 { /* Removing the fold from one that has been contracted so should expand
849 * otherwise lines are left invisible with no way to make them visible */
850 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
851 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
854 if (! (levelNow & SC_FOLDLEVELWHITEFLAG) &&
855 ((levelPrev & SC_FOLDLEVELNUMBERMASK) > (levelNow & SC_FOLDLEVELNUMBERMASK)))
857 /* See if should still be hidden */
858 gint parentLine = sci_get_fold_parent(sci, line);
859 if (parentLine < 0)
861 SSM(sci, SCI_SHOWLINES, line, line);
863 else if (sci_get_fold_expanded(sci, parentLine) &&
864 sci_get_line_is_visible(sci, parentLine))
866 SSM(sci, SCI_SHOWLINES, line, line);
872 static void ensure_range_visible(ScintillaObject *sci, gint posStart, gint posEnd,
873 gboolean enforcePolicy)
875 gint lineStart = sci_get_line_from_position(sci, MIN(posStart, posEnd));
876 gint lineEnd = sci_get_line_from_position(sci, MAX(posStart, posEnd));
877 gint line;
879 for (line = lineStart; line <= lineEnd; line++)
881 SSM(sci, enforcePolicy ? SCI_ENSUREVISIBLEENFORCEPOLICY : SCI_ENSUREVISIBLE, line, 0);
886 static void auto_update_margin_width(GeanyEditor *editor)
888 gint next_linecount = 1;
889 gint linecount = sci_get_line_count(editor->sci);
890 GeanyDocument *doc = editor->document;
892 while (next_linecount <= linecount)
893 next_linecount *= 10;
895 if (editor->document->priv->line_count != next_linecount)
897 doc->priv->line_count = next_linecount;
898 sci_set_line_numbers(editor->sci, TRUE, 0);
903 static void partial_complete(ScintillaObject *sci, const gchar *text)
905 gint pos = sci_get_current_position(sci);
907 sci_insert_text(sci, pos, text);
908 sci_set_current_position(sci, pos + strlen(text), TRUE);
912 /* Complete the next word part from @a entry */
913 static gboolean check_partial_completion(GeanyEditor *editor, const gchar *entry)
915 gchar *stem, *ptr, *text = utils_strdupa(entry);
917 read_current_word(editor, -1, current_word, sizeof current_word, NULL, TRUE);
918 stem = current_word;
919 if (strstr(text, stem) != text)
920 return FALSE; /* shouldn't happen */
921 if (strlen(text) <= strlen(stem))
922 return FALSE;
924 text += strlen(stem); /* skip stem */
925 ptr = strstr(text + 1, "_");
926 if (ptr)
928 ptr[1] = '\0';
929 partial_complete(editor->sci, text);
930 return TRUE;
932 else
934 /* CamelCase */
935 foreach_str(ptr, text + 1)
937 if (!ptr[0])
938 break;
939 if (g_ascii_isupper(*ptr) && g_ascii_islower(ptr[1]))
941 ptr[0] = '\0';
942 partial_complete(editor->sci, text);
943 return TRUE;
947 return FALSE;
951 /* Callback for the "sci-notify" signal to emit a "editor-notify" signal.
952 * Plugins can connect to the "editor-notify" signal. */
953 void editor_sci_notify_cb(G_GNUC_UNUSED GtkWidget *widget, G_GNUC_UNUSED gint scn,
954 gpointer scnt, gpointer data)
956 GeanyEditor *editor = data;
957 gboolean retval;
959 g_return_if_fail(editor != NULL);
961 g_signal_emit_by_name(geany_object, "editor-notify", editor, scnt, &retval);
965 static gboolean on_editor_notify(G_GNUC_UNUSED GObject *object, GeanyEditor *editor,
966 SCNotification *nt, G_GNUC_UNUSED gpointer data)
968 ScintillaObject *sci = editor->sci;
969 GeanyDocument *doc = editor->document;
971 switch (nt->nmhdr.code)
973 case SCN_SAVEPOINTLEFT:
974 document_set_text_changed(doc, TRUE);
975 break;
977 case SCN_SAVEPOINTREACHED:
978 document_set_text_changed(doc, FALSE);
979 break;
981 case SCN_MODIFYATTEMPTRO:
982 utils_beep();
983 break;
985 case SCN_MARGINCLICK:
986 on_margin_click(editor, nt);
987 break;
989 case SCN_UPDATEUI:
990 on_update_ui(editor, nt);
991 break;
993 case SCN_PAINTED:
994 /* Visible lines are only laid out accurately just before painting,
995 * so we need to only call editor_scroll_to_line here, because the document
996 * may have line wrapping and folding enabled.
997 * http://scintilla.sourceforge.net/ScintillaDoc.html#LineWrapping
998 * This is important e.g. when loading a session and switching pages
999 * and having the cursor scroll in view. */
1000 /* FIXME: Really we want to do this just before painting, not after it
1001 * as it will cause repainting. */
1002 if (editor->scroll_percent > 0.0F)
1004 editor_scroll_to_line(editor, -1, editor->scroll_percent);
1005 /* disable further scrolling */
1006 editor->scroll_percent = -1.0F;
1008 break;
1010 case SCN_MODIFIED:
1011 if (editor_prefs.show_linenumber_margin && (nt->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT)) && nt->linesAdded)
1013 /* automatically adjust Scintilla's line numbers margin width */
1014 auto_update_margin_width(editor);
1016 if (nt->modificationType & SC_STARTACTION && ! ignore_callback)
1018 /* get notified about undo changes */
1019 document_undo_add(doc, UNDO_SCINTILLA, NULL);
1021 if (editor_prefs.folding && (nt->modificationType & SC_MOD_CHANGEFOLD) != 0)
1023 /* handle special fold cases, e.g. #1923350 */
1024 fold_changed(sci, nt->line, nt->foldLevelNow, nt->foldLevelPrev);
1026 break;
1028 case SCN_CHARADDED:
1029 on_char_added(editor, nt);
1030 break;
1032 case SCN_USERLISTSELECTION:
1033 if (nt->listType == 1)
1035 sci_add_text(sci, nt->text);
1037 break;
1039 case SCN_AUTOCSELECTION:
1040 if (g_str_equal(nt->text, "..."))
1042 sci_cancel(sci);
1043 utils_beep();
1044 break;
1046 /* fall through */
1047 case SCN_AUTOCCANCELLED:
1048 /* now that autocomplete is finishing or was cancelled, reshow calltips
1049 * if they were showing */
1050 request_reshowing_calltip(nt);
1051 break;
1053 #ifdef GEANY_DEBUG
1054 case SCN_STYLENEEDED:
1055 geany_debug("style");
1056 break;
1057 #endif
1058 case SCN_NEEDSHOWN:
1059 ensure_range_visible(sci, nt->position, nt->position + nt->length, FALSE);
1060 break;
1062 case SCN_URIDROPPED:
1063 if (nt->text != NULL)
1065 document_open_file_list(nt->text, -1);
1067 break;
1069 case SCN_CALLTIPCLICK:
1070 if (nt->position > 0)
1072 switch (nt->position)
1074 case 1: /* up arrow */
1075 if (calltip.tag_index > 0)
1076 calltip.tag_index--;
1077 break;
1079 case 2: calltip.tag_index++; break; /* down arrow */
1081 editor_show_calltip(editor, -1);
1083 break;
1085 case SCN_ZOOM:
1086 /* recalculate line margin width */
1087 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin, 0);
1088 break;
1090 /* we always return FALSE here to let plugins handle the event too */
1091 return FALSE;
1095 /* Note: this is the same as sci_get_tab_width(), but is still useful when you don't have
1096 * a scintilla pointer. */
1097 static gint get_tab_width(const GeanyIndentPrefs *indent_prefs)
1099 if (indent_prefs->type == GEANY_INDENT_TYPE_BOTH)
1100 return indent_prefs->hard_tab_width;
1102 return indent_prefs->width; /* tab width = indent width */
1106 /* Returns a string containing width chars of whitespace, filled with simple space
1107 * characters or with the right number of tab characters, according to the indent prefs.
1108 * (Result is filled with tabs *and* spaces if width isn't a multiple of
1109 * the tab width). */
1110 static gchar *
1111 get_whitespace(const GeanyIndentPrefs *iprefs, gint width)
1113 g_return_val_if_fail(width >= 0, NULL);
1115 if (width == 0)
1116 return g_strdup("");
1118 if (iprefs->type == GEANY_INDENT_TYPE_SPACES)
1120 return g_strnfill(width, ' ');
1122 else
1123 { /* first fill text with tabs and fill the rest with spaces */
1124 const gint tab_width = get_tab_width(iprefs);
1125 gint tabs = width / tab_width;
1126 gint spaces = width % tab_width;
1127 gint len = tabs + spaces;
1128 gchar *str;
1130 str = g_malloc(len + 1);
1132 memset(str, '\t', tabs);
1133 memset(str + tabs, ' ', spaces);
1134 str[len] = '\0';
1135 return str;
1140 static const GeanyIndentPrefs *
1141 get_default_indent_prefs(void)
1143 static GeanyIndentPrefs iprefs;
1145 iprefs = app->project ? *app->project->priv->indentation : *editor_prefs.indentation;
1146 return &iprefs;
1150 /** Gets the indentation prefs for the editor.
1151 * In future, the prefs might be different according to project or filetype.
1152 * @warning Always get a fresh result instead of keeping a pointer to it if the editor/project
1153 * settings may have changed, or if this function has been called for a different editor.
1154 * @param editor The editor, or @c NULL to get the default indent prefs.
1155 * @return The indent prefs. */
1156 const GeanyIndentPrefs *
1157 editor_get_indent_prefs(GeanyEditor *editor)
1159 static GeanyIndentPrefs iprefs;
1160 const GeanyIndentPrefs *dprefs = get_default_indent_prefs();
1162 /* Return the address of the default prefs to allow returning default and editor
1163 * pref pointers without invalidating the contents of either. */
1164 if (editor == NULL)
1165 return dprefs;
1167 iprefs = *dprefs;
1168 iprefs.type = editor->indent_type;
1169 iprefs.width = editor->indent_width;
1171 /* if per-document auto-indent is enabled, but we don't have a global mode set,
1172 * just use basic auto-indenting */
1173 if (editor->auto_indent && iprefs.auto_indent_mode == GEANY_AUTOINDENT_NONE)
1174 iprefs.auto_indent_mode = GEANY_AUTOINDENT_BASIC;
1176 if (!editor->auto_indent)
1177 iprefs.auto_indent_mode = GEANY_AUTOINDENT_NONE;
1179 return &iprefs;
1183 static void on_new_line_added(GeanyEditor *editor)
1185 ScintillaObject *sci = editor->sci;
1186 gint line = sci_get_current_line(sci);
1188 /* simple indentation */
1189 if (editor->auto_indent)
1191 insert_indent_after_line(editor, line - 1);
1194 if (editor_prefs.auto_continue_multiline)
1195 { /* " * " auto completion in multiline C/C++/D/Java comments */
1196 auto_multiline(editor, line);
1199 if (editor_prefs.newline_strip)
1200 { /* strip the trailing spaces on the previous line */
1201 editor_strip_line_trailing_spaces(editor, line - 1);
1206 static gboolean lexer_has_braces(ScintillaObject *sci)
1208 gint lexer = sci_get_lexer(sci);
1210 switch (lexer)
1212 case SCLEX_CPP:
1213 case SCLEX_D:
1214 case SCLEX_HTML: /* for PHP & JS */
1215 case SCLEX_PASCAL: /* for multiline comments? */
1216 case SCLEX_BASH:
1217 case SCLEX_PERL:
1218 case SCLEX_TCL:
1219 return TRUE;
1220 default:
1221 return FALSE;
1226 /* Read indent chars for the line that pos is on into indent global variable.
1227 * Note: Use sci_get_line_indentation() and get_whitespace()/editor_insert_text_block()
1228 * instead in any new code. */
1229 static void read_indent(GeanyEditor *editor, gint pos)
1231 ScintillaObject *sci = editor->sci;
1232 guint i, len, j = 0;
1233 gint line;
1234 gchar *linebuf;
1236 line = sci_get_line_from_position(sci, pos);
1238 len = sci_get_line_length(sci, line);
1239 linebuf = sci_get_line(sci, line);
1241 for (i = 0; i < len && j <= (sizeof(indent) - 1); i++)
1243 if (linebuf[i] == ' ' || linebuf[i] == '\t') /* simple indentation */
1244 indent[j++] = linebuf[i];
1245 else
1246 break;
1248 indent[j] = '\0';
1249 g_free(linebuf);
1253 static gint get_brace_indent(ScintillaObject *sci, gint line)
1255 guint i, len;
1256 gint ret = 0;
1257 gchar *linebuf;
1259 len = sci_get_line_length(sci, line);
1260 linebuf = sci_get_line(sci, line);
1262 for (i = 0; i < len; i++)
1264 /* i == (len - 1) prevents wrong indentation after lines like
1265 * " { return bless({}, shift); }" (Perl) */
1266 if (linebuf[i] == '{' && i == (len - 1))
1268 ret++;
1269 break;
1271 else
1273 gint k = len - 1;
1275 while (k > 0 && isspace(linebuf[k])) k--;
1277 /* if last non-whitespace character is a { increase indentation by a tab
1278 * e.g. for (...) { */
1279 if (linebuf[k] == '{')
1281 ret++;
1283 break;
1286 g_free(linebuf);
1287 return ret;
1291 static gint get_python_indent(ScintillaObject *sci, gint line)
1293 gint last_char = sci_get_line_end_position(sci, line) - 1;
1295 /* add extra indentation for Python after colon */
1296 if (sci_get_char_at(sci, last_char) == ':' &&
1297 sci_get_style_at(sci, last_char) == SCE_P_OPERATOR)
1299 return 1;
1301 return 0;
1305 static gint get_xml_indent(ScintillaObject *sci, gint line)
1307 gboolean need_close = FALSE;
1308 gint end = sci_get_line_end_position(sci, line) - 1;
1310 if (sci_get_char_at(sci, end) == '>' &&
1311 sci_get_char_at(sci, end - 1) != '/')
1313 gint style = sci_get_style_at(sci, end);
1315 if (style == SCE_H_TAG || style == SCE_H_TAGUNKNOWN)
1317 gint start = sci_get_position_from_line(sci, line);
1318 gchar *line_contents = sci_get_contents_range(sci, start, end + 1);
1319 gchar *opened_tag_name = utils_find_open_xml_tag(line_contents, end + 1 - start);
1321 if (NZV(opened_tag_name))
1323 need_close = TRUE;
1324 if (sci_get_lexer(sci) == SCLEX_HTML && utils_is_short_html_tag(opened_tag_name))
1325 need_close = FALSE;
1327 g_free(line_contents);
1328 g_free(opened_tag_name);
1332 return need_close ? 1 : 0;
1336 static gint get_indent_size_after_line(GeanyEditor *editor, gint line)
1338 ScintillaObject *sci = editor->sci;
1339 gint size;
1340 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1342 g_return_val_if_fail(line >= 0, 0);
1344 size = sci_get_line_indentation(sci, line);
1346 if (iprefs->auto_indent_mode > GEANY_AUTOINDENT_BASIC)
1348 gint additional_indent = 0;
1350 if (lexer_has_braces(sci))
1351 additional_indent = iprefs->width * get_brace_indent(sci, line);
1352 else
1353 if (editor->document->file_type->id == GEANY_FILETYPES_PYTHON)
1354 additional_indent = iprefs->width * get_python_indent(sci, line);
1356 /* HTML lexer "has braces" because of PHP and JavaScript. If get_brace_indent() did not
1357 * recommend us to insert additional indent, we are probably not in PHP/JavaScript chunk and
1358 * should make the XML-related check */
1359 if (additional_indent == 0 && !editor_prefs.auto_close_xml_tags &&
1360 (sci_get_lexer(sci) == SCLEX_HTML ||
1361 sci_get_lexer(sci) == SCLEX_XML) &&
1362 editor->document->file_type->priv->xml_indent_tags)
1364 size += iprefs->width * get_xml_indent(sci, line);
1367 size += additional_indent;
1369 return size;
1373 static void insert_indent_after_line(GeanyEditor *editor, gint line)
1375 ScintillaObject *sci = editor->sci;
1376 gint line_indent = sci_get_line_indentation(sci, line);
1377 gint size = get_indent_size_after_line(editor, line);
1378 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1379 gchar *text;
1381 if (size == 0)
1382 return;
1384 if (iprefs->type == GEANY_INDENT_TYPE_TABS && size == line_indent)
1386 /* support tab indents, space aligns style - copy last line 'indent' exactly */
1387 gint start = sci_get_position_from_line(sci, line);
1388 gint end = sci_get_line_indent_position(sci, line);
1390 text = sci_get_contents_range(sci, start, end);
1392 else
1394 text = get_whitespace(iprefs, size);
1396 sci_add_text(sci, text);
1397 g_free(text);
1401 static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c)
1403 const gchar *closing_char = NULL;
1404 gint end_pos = -1;
1406 if (utils_isbrace(c, 0))
1407 end_pos = sci_find_matching_brace(sci, pos - 1);
1409 switch (c)
1411 case '(':
1412 if ((editor_prefs.autoclose_chars & GEANY_AC_PARENTHESIS) && end_pos == -1)
1413 closing_char = ")";
1414 break;
1415 case '{':
1416 if ((editor_prefs.autoclose_chars & GEANY_AC_CBRACKET) && end_pos == -1)
1417 closing_char = "}";
1418 break;
1419 case '[':
1420 if ((editor_prefs.autoclose_chars & GEANY_AC_SBRACKET) && end_pos == -1)
1421 closing_char = "]";
1422 break;
1423 case '\'':
1424 if (editor_prefs.autoclose_chars & GEANY_AC_SQUOTE)
1425 closing_char = "'";
1426 break;
1427 case '"':
1428 if (editor_prefs.autoclose_chars & GEANY_AC_DQUOTE)
1429 closing_char = "\"";
1430 break;
1433 if (closing_char != NULL)
1435 sci_add_text(sci, closing_char);
1436 sci_set_current_position(sci, pos, TRUE);
1441 /* Finds a corresponding matching brace to the given pos
1442 * (this is taken from Scintilla Editor.cxx,
1443 * fit to work with close_block) */
1444 static gint brace_match(ScintillaObject *sci, gint pos)
1446 gchar chBrace = sci_get_char_at(sci, pos);
1447 gchar chSeek = utils_brace_opposite(chBrace);
1448 gchar chAtPos;
1449 gint direction = -1;
1450 gint styBrace;
1451 gint depth = 1;
1452 gint styAtPos;
1454 styBrace = sci_get_style_at(sci, pos);
1456 if (utils_is_opening_brace(chBrace, editor_prefs.brace_match_ltgt))
1457 direction = 1;
1459 pos = pos + direction;
1460 while ((pos >= 0) && (pos < sci_get_length(sci)))
1462 chAtPos = sci_get_char_at(sci, pos - 1);
1463 styAtPos = sci_get_style_at(sci, pos);
1465 if ((pos > sci_get_end_styled(sci)) || (styAtPos == styBrace))
1467 if (chAtPos == chBrace)
1468 depth++;
1469 if (chAtPos == chSeek)
1470 depth--;
1471 if (depth == 0)
1472 return pos;
1474 pos = pos + direction;
1476 return -1;
1480 /* Called after typing '}'. */
1481 static void close_block(GeanyEditor *editor, gint pos)
1483 GeanyDocument *doc;
1484 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1485 gint x = 0, cnt = 0;
1486 gint line, line_len, eol_char_len;
1487 gchar *text, *line_buf;
1488 ScintillaObject *sci;
1489 gint line_indent, last_indent;
1491 if (iprefs->auto_indent_mode < GEANY_AUTOINDENT_CURRENTCHARS)
1492 return;
1493 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
1495 sci = editor->sci;
1496 doc = editor->document;
1498 if (! lexer_has_braces(sci))
1499 return;
1501 line = sci_get_line_from_position(sci, pos);
1502 line_len = sci_get_line_length(sci, line);
1503 /* set eol_char_len to 0 if on last line, because there is no EOL char */
1504 eol_char_len = (line == (sci_get_line_count(sci) - 1)) ? 0 :
1505 editor_get_eol_char_len(editor);
1507 /* check that the line is empty, to not kill text in the line */
1508 line_buf = sci_get_line(sci, line);
1509 line_buf[line_len - eol_char_len] = '\0';
1510 while (x < (line_len - eol_char_len))
1512 if (isspace(line_buf[x]))
1513 cnt++;
1514 x++;
1516 g_free(line_buf);
1518 if ((line_len - eol_char_len - 1) != cnt)
1519 return;
1521 if (iprefs->auto_indent_mode == GEANY_AUTOINDENT_MATCHBRACES)
1523 gint start_brace = brace_match(sci, pos);
1525 if (start_brace >= 0)
1527 gint line_start;
1528 gint brace_line = sci_get_line_from_position(sci, start_brace);
1529 gint size = sci_get_line_indentation(sci, brace_line);
1530 gchar *ind = get_whitespace(iprefs, size);
1532 text = g_strconcat(ind, "}", NULL);
1533 line_start = sci_get_position_from_line(sci, line);
1534 sci_set_anchor(sci, line_start);
1535 sci_replace_sel(sci, text);
1536 g_free(text);
1537 g_free(ind);
1538 return;
1540 /* fall through - unmatched brace (possibly because of TCL, PHP lexer bugs) */
1543 /* GEANY_AUTOINDENT_CURRENTCHARS */
1544 line_indent = sci_get_line_indentation(sci, line);
1545 last_indent = sci_get_line_indentation(sci, line - 1);
1547 if (line_indent < last_indent)
1548 return;
1549 line_indent -= iprefs->width;
1550 line_indent = MAX(0, line_indent);
1551 sci_set_line_indentation(sci, line, line_indent);
1555 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1556 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1557 * position can be -1, then the current position is used.
1558 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1559 static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, size_t wordlen,
1560 const gchar *wc, gboolean stem)
1562 gint line, line_start, startword, endword;
1563 gchar *chunk;
1564 ScintillaObject *sci;
1566 g_return_if_fail(editor != NULL);
1567 sci = editor->sci;
1569 if (pos == -1)
1570 pos = sci_get_current_position(sci);
1572 line = sci_get_line_from_position(sci, pos);
1573 line_start = sci_get_position_from_line(sci, line);
1574 startword = pos - line_start;
1575 endword = pos - line_start;
1577 word[0] = '\0';
1578 chunk = sci_get_line(sci, line);
1580 if (wc == NULL)
1581 wc = GEANY_WORDCHARS;
1583 /* the checks for "c < 0" are to allow any Unicode character which should make the code
1584 * a little bit more Unicode safe, anyway, this allows also any Unicode punctuation,
1585 * TODO: improve this code */
1586 while (startword > 0 && (strchr(wc, chunk[startword - 1]) || chunk[startword - 1] < 0))
1587 startword--;
1588 if (!stem)
1590 while (chunk[endword] != 0 && (strchr(wc, chunk[endword]) || chunk[endword] < 0))
1591 endword++;
1594 if (startword != endword)
1596 chunk[endword] = '\0';
1598 g_strlcpy(word, chunk + startword, wordlen); /* ensure null terminated */
1600 else
1601 g_strlcpy(word, "", wordlen);
1603 g_free(chunk);
1607 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1608 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1609 * position can be -1, then the current position is used.
1610 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1611 void editor_find_current_word(GeanyEditor *editor, gint pos, gchar *word, size_t wordlen,
1612 const gchar *wc)
1614 read_current_word(editor, pos, word, wordlen, wc, FALSE);
1619 * Finds the word at the position specified by @a pos. If any word is found, it is returned.
1620 * Otherwise NULL is returned.
1621 * Additional wordchars can be specified to define what to consider as a word.
1623 * @param editor The editor to operate on.
1624 * @param pos The position where the word should be read from.
1625 * Maybe @c -1 to use the current position.
1626 * @param wordchars The wordchars to separate words. wordchars mean all characters to count
1627 * as part of a word. Maybe @c NULL to use the default wordchars,
1628 * see @ref GEANY_WORDCHARS.
1630 * @return A newly-allocated string containing the word at the given @a pos or @c NULL.
1631 * Should be freed when no longer needed.
1633 * @since 0.16
1635 gchar *editor_get_word_at_pos(GeanyEditor *editor, gint pos, const gchar *wordchars)
1637 static gchar cword[GEANY_MAX_WORD_LENGTH];
1639 g_return_val_if_fail(editor != NULL, FALSE);
1641 read_current_word(editor, pos, cword, sizeof(cword), wordchars, FALSE);
1643 return (*cword == '\0') ? NULL : g_strdup(cword);
1647 /* Read the word up to position @a pos. */
1648 static const gchar *
1649 editor_read_word_stem(GeanyEditor *editor, gint pos, const gchar *wordchars)
1651 static gchar word[GEANY_MAX_WORD_LENGTH];
1653 read_current_word(editor, pos, word, sizeof word, wordchars, TRUE);
1655 return (*word) ? word : NULL;
1659 static gint find_previous_brace(ScintillaObject *sci, gint pos)
1661 gchar c;
1662 gint orig_pos = pos;
1664 c = sci_get_char_at(sci, pos);
1665 while (pos >= 0 && pos > orig_pos - 300)
1667 c = sci_get_char_at(sci, pos);
1668 pos--;
1669 if (utils_is_opening_brace(c, editor_prefs.brace_match_ltgt))
1670 return pos;
1672 return -1;
1676 static gint find_start_bracket(ScintillaObject *sci, gint pos)
1678 gchar c;
1679 gint brackets = 0;
1680 gint orig_pos = pos;
1682 c = sci_get_char_at(sci, pos);
1683 while (pos > 0 && pos > orig_pos - 300)
1685 c = sci_get_char_at(sci, pos);
1686 if (c == ')') brackets++;
1687 else if (c == '(') brackets--;
1688 pos--;
1689 if (brackets < 0) return pos; /* found start bracket */
1691 return -1;
1695 static gboolean append_calltip(GString *str, const TMTag *tag, filetype_id ft_id)
1697 if (! tag->atts.entry.arglist)
1698 return FALSE;
1700 if (ft_id != GEANY_FILETYPES_PASCAL)
1701 { /* usual calltips: "retval tagname (arglist)" */
1702 if (tag->atts.entry.var_type)
1704 guint i;
1706 g_string_append(str, tag->atts.entry.var_type);
1707 for (i = 0; i < tag->atts.entry.pointerOrder; i++)
1709 g_string_append_c(str, '*');
1711 g_string_append_c(str, ' ');
1713 if (tag->atts.entry.scope)
1715 const gchar *cosep = symbols_get_context_separator(ft_id);
1717 g_string_append(str, tag->atts.entry.scope);
1718 g_string_append(str, cosep);
1720 g_string_append(str, tag->name);
1721 g_string_append_c(str, ' ');
1722 g_string_append(str, tag->atts.entry.arglist);
1724 else
1725 { /* special case Pascal calltips: "tagname (arglist) : retval" */
1726 g_string_append(str, tag->name);
1727 g_string_append_c(str, ' ');
1728 g_string_append(str, tag->atts.entry.arglist);
1730 if (NZV(tag->atts.entry.var_type))
1732 g_string_append(str, " : ");
1733 g_string_append(str, tag->atts.entry.var_type);
1737 return TRUE;
1741 static gchar *find_calltip(const gchar *word, GeanyFiletype *ft)
1743 const GPtrArray *tags;
1744 const gint arg_types = tm_tag_function_t | tm_tag_prototype_t |
1745 tm_tag_method_t | tm_tag_macro_with_arg_t;
1746 TMTagAttrType *attrs = NULL;
1747 TMTag *tag;
1748 GString *str = NULL;
1749 guint i;
1751 g_return_val_if_fail(ft && word && *word, NULL);
1753 /* use all types in case language uses wrong tag type e.g. python "members" instead of "methods" */
1754 tags = tm_workspace_find(word, tm_tag_max_t, attrs, FALSE, ft->lang);
1755 if (tags->len == 0)
1756 return NULL;
1758 tag = TM_TAG(tags->pdata[0]);
1760 if (tag->type == tm_tag_class_t && FILETYPE_ID(ft) == GEANY_FILETYPES_D)
1762 /* user typed e.g. 'new Classname(' so lookup D constructor Classname::this() */
1763 tags = tm_workspace_find_scoped("this", tag->name,
1764 arg_types, attrs, FALSE, ft->lang, TRUE);
1765 if (tags->len == 0)
1766 return NULL;
1769 /* remove tags with no argument list */
1770 for (i = 0; i < tags->len; i++)
1772 tag = TM_TAG(tags->pdata[i]);
1774 if (! tag->atts.entry.arglist)
1775 tags->pdata[i] = NULL;
1777 tm_tags_prune((GPtrArray *) tags);
1778 if (tags->len == 0)
1779 return NULL;
1780 else
1781 { /* remove duplicate calltips */
1782 TMTagAttrType sort_attr[] = {tm_tag_attr_name_t, tm_tag_attr_scope_t,
1783 tm_tag_attr_arglist_t, 0};
1785 tm_tags_sort((GPtrArray *) tags, sort_attr, TRUE);
1788 /* if the current word has changed since last time, start with the first tag match */
1789 if (! utils_str_equal(word, calltip.last_word))
1790 calltip.tag_index = 0;
1791 /* cache the current word for next time */
1792 g_free(calltip.last_word);
1793 calltip.last_word = g_strdup(word);
1794 calltip.tag_index = MIN(calltip.tag_index, tags->len - 1); /* ensure tag_index is in range */
1796 for (i = calltip.tag_index; i < tags->len; i++)
1798 tag = TM_TAG(tags->pdata[i]);
1800 if (str == NULL)
1802 str = g_string_new(NULL);
1803 if (calltip.tag_index > 0)
1804 g_string_prepend(str, "\001 "); /* up arrow */
1805 append_calltip(str, tag, FILETYPE_ID(ft));
1807 else /* add a down arrow */
1809 if (calltip.tag_index > 0) /* already have an up arrow */
1810 g_string_insert_c(str, 1, '\002');
1811 else
1812 g_string_prepend(str, "\002 ");
1813 break;
1816 if (str)
1818 gchar *result = str->str;
1820 g_string_free(str, FALSE);
1821 return result;
1823 return NULL;
1827 /* use pos = -1 to search for the previous unmatched open bracket. */
1828 gboolean editor_show_calltip(GeanyEditor *editor, gint pos)
1830 gint orig_pos = pos; /* the position for the calltip */
1831 gint lexer;
1832 gint style;
1833 gchar word[GEANY_MAX_WORD_LENGTH];
1834 gchar *str;
1835 ScintillaObject *sci;
1837 g_return_val_if_fail(editor != NULL, FALSE);
1838 g_return_val_if_fail(editor->document->file_type != NULL, FALSE);
1840 sci = editor->sci;
1842 lexer = sci_get_lexer(sci);
1844 if (pos == -1)
1846 /* position of '(' is unknown, so go backwards from current position to find it */
1847 pos = sci_get_current_position(sci);
1848 pos--;
1849 orig_pos = pos;
1850 pos = (lexer == SCLEX_LATEX) ? find_previous_brace(sci, pos) :
1851 find_start_bracket(sci, pos);
1852 if (pos == -1)
1853 return FALSE;
1856 /* the style 1 before the brace (which may be highlighted) */
1857 style = sci_get_style_at(sci, pos - 1);
1858 if (! is_code_style(lexer, style))
1859 return FALSE;
1861 word[0] = '\0';
1862 editor_find_current_word(editor, pos - 1, word, sizeof word, NULL);
1863 if (word[0] == '\0')
1864 return FALSE;
1866 str = find_calltip(word, editor->document->file_type);
1867 if (str)
1869 g_free(calltip.text); /* free the old calltip */
1870 calltip.text = str;
1871 calltip.pos = orig_pos;
1872 calltip.sci = sci;
1873 calltip.set = TRUE;
1874 utils_wrap_string(calltip.text, -1);
1875 SSM(sci, SCI_CALLTIPSHOW, orig_pos, (sptr_t) calltip.text);
1876 return TRUE;
1878 return FALSE;
1882 gchar *editor_get_calltip_text(GeanyEditor *editor, const TMTag *tag)
1884 GString *str;
1886 g_return_val_if_fail(editor != NULL, NULL);
1888 str = g_string_new(NULL);
1889 if (append_calltip(str, tag, editor->document->file_type->id))
1890 return g_string_free(str, FALSE);
1891 else
1892 return g_string_free(str, TRUE);
1896 /* HTML entities auto completion from html_entities.tags text file */
1897 static gboolean
1898 autocomplete_html(ScintillaObject *sci, const gchar *root, gsize rootlen)
1900 guint i, j = 0;
1901 gboolean found = FALSE;
1902 GString *words;
1903 const gchar **entities = symbols_get_html_entities();
1905 if (*root != '&' || G_UNLIKELY(entities == NULL))
1906 return FALSE;
1908 words = g_string_sized_new(500);
1909 for (i = 0; ; i++)
1911 if (entities[i] == NULL)
1912 break;
1913 else if (entities[i][0] == '#')
1914 continue;
1916 if (! strncmp(entities[i], root, rootlen))
1918 if (j++ > 0)
1919 g_string_append_c(words, '\n');
1920 g_string_append(words, entities[i]);
1921 found = TRUE;
1924 if (found)
1925 show_autocomplete(sci, rootlen, words->str);
1927 g_string_free(words, TRUE);
1928 return found;
1932 /* Current document & global tags autocompletion */
1933 static gboolean
1934 autocomplete_tags(GeanyEditor *editor, const gchar *root, gsize rootlen)
1936 TMTagAttrType attrs[] = { tm_tag_attr_name_t, 0 };
1937 const GPtrArray *tags;
1938 GeanyDocument *doc;
1940 g_return_val_if_fail(editor, FALSE);
1942 doc = editor->document;
1944 tags = tm_workspace_find(root, tm_tag_max_t, attrs, TRUE, doc->file_type->lang);
1945 if (tags)
1947 show_tags_list(editor, tags, rootlen);
1948 return tags->len > 0;
1950 return FALSE;
1954 /* Check whether to use entity autocompletion:
1955 * - always in a HTML file except when inside embedded JavaScript, Python, ASP, ...
1956 * - in a PHP file only when we are outside of <? ?> */
1957 static gboolean autocomplete_check_for_html(gint ft_id, gint style)
1959 /* use entity completion when style is not JavaScript, ASP, Python, PHP, ...
1960 * (everything after SCE_HJ_START is for embedded scripting languages) */
1961 if (ft_id == GEANY_FILETYPES_HTML && style < SCE_HJ_START)
1962 return TRUE;
1964 if (ft_id == GEANY_FILETYPES_PHP)
1966 /* use entity completion when style is outside of PHP styles */
1967 if (! is_style_php(style))
1968 return TRUE;
1971 return FALSE;
1975 /* Algorithm based on based on Scite's StartAutoCompleteWord() */
1976 static GString *get_doc_words(ScintillaObject *sci, gchar *root, gsize rootlen)
1978 gchar *word;
1979 gint len, current, word_end;
1980 gint pos_find, flags;
1981 guint word_length;
1982 gsize nmatches = 0;
1983 GString *words;
1984 struct Sci_TextToFind ttf;
1986 len = sci_get_length(sci);
1987 current = sci_get_current_position(sci) - rootlen;
1989 ttf.lpstrText = root;
1990 ttf.chrg.cpMin = 0;
1991 ttf.chrg.cpMax = len;
1992 ttf.chrgText.cpMin = 0;
1993 ttf.chrgText.cpMax = 0;
1994 flags = SCFIND_WORDSTART | SCFIND_MATCHCASE;
1996 words = g_string_sized_new(256);
1997 /* put space before first entry to make searching with strstr easy */
1998 g_string_append_c(words, ' ');
2000 /* search the whole document for the word root and collect results */
2001 pos_find = scintilla_send_message(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
2002 while (pos_find >= 0 && pos_find < len)
2004 word_end = pos_find + rootlen;
2005 if (pos_find != current)
2007 while (word_end < len && strchr(GEANY_WORDCHARS, sci_get_char_at(sci, word_end)) != NULL)
2008 word_end++;
2010 word_length = word_end - pos_find;
2011 if (word_length > rootlen)
2013 word = g_malloc0(word_length + 3);
2014 sci_get_text_range(sci, pos_find, word_end, word + 1);
2015 word[0] = ' ';
2016 word[word_length + 1] = ' ';
2017 /* search the words string whether we already have the word in, otherwise add it */
2018 if (strstr(words->str, word) == NULL)
2020 g_string_append(words, word + 1);
2021 nmatches++;
2023 g_free(word);
2025 if (nmatches == editor_prefs.autocompletion_max_entries)
2026 break;
2029 ttf.chrg.cpMin = word_end;
2030 pos_find = scintilla_send_message(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
2033 if (words->len > 1)
2035 g_strdelimit(words->str, " ", '\n');
2036 words->str[words->len - 1] = '\0'; /* remove the trailing '\n' */
2037 return words;
2039 g_string_free(words, TRUE);
2040 return NULL;
2044 static gboolean autocomplete_doc_word(GeanyEditor *editor, gchar *root, gsize rootlen)
2046 ScintillaObject *sci = editor->sci;
2047 GString *words;
2048 GString *str;
2049 gchar *ptr;
2050 GSList *node, *list = NULL;
2052 words = get_doc_words(sci, root, rootlen);
2053 if (!words)
2055 scintilla_send_message(sci, SCI_AUTOCCANCEL, 0, 0);
2056 return FALSE;
2059 /* words are unsorted, make list of words */
2060 foreach_str(ptr, words->str)
2062 if (*ptr == '\n')
2064 list = g_slist_prepend(list, ptr + 1);
2065 /* terminate previous string in list */
2066 ptr[0] = 0x0;
2067 ptr++;
2070 list = g_slist_sort(list, (GCompareFunc)utils_str_casecmp);
2072 str = g_string_sized_new(words->len);
2073 foreach_slist(node, list)
2075 g_string_append(str, node->data);
2076 if (node->next)
2077 g_string_append_c(str, '\n');
2079 if (g_slist_length(list) >= editor_prefs.autocompletion_max_entries)
2080 g_string_append(str, "\n...");
2082 g_slist_free(list);
2083 g_string_free(words, TRUE);
2085 show_autocomplete(sci, rootlen, str->str);
2086 g_string_free(str, TRUE);
2087 return TRUE;
2091 gboolean editor_start_auto_complete(GeanyEditor *editor, gint pos, gboolean force)
2093 gint line, line_start, line_len, line_pos, current, rootlen, startword, lexer, style;
2094 gchar *linebuf, *root;
2095 ScintillaObject *sci;
2096 gboolean ret = FALSE;
2097 const gchar *wordchars;
2098 GeanyFiletype *ft;
2100 if (! editor_prefs.auto_complete_symbols && ! force)
2101 return FALSE;
2103 g_return_val_if_fail(editor != NULL, FALSE);
2105 /* If we are at the beginning of the document, we skip autocompletion as we can't determine the
2106 * necessary styling information */
2107 if (G_UNLIKELY(pos < 2))
2108 return FALSE;
2110 sci = editor->sci;
2111 ft = editor->document->file_type;
2113 line = sci_get_line_from_position(sci, pos);
2114 line_start = sci_get_position_from_line(sci, line);
2115 line_len = sci_get_line_length(sci, line);
2116 line_pos = pos - line_start - 1;
2117 current = pos - line_start;
2118 startword = current;
2119 lexer = sci_get_lexer(sci);
2120 style = sci_get_style_at(sci, pos - 2);
2122 /* don't autocomplete in comments and strings */
2123 if (!force && !is_code_style(lexer, style))
2124 return FALSE;
2126 autocomplete_scope(editor);
2128 linebuf = sci_get_line(sci, line);
2130 if (ft->id == GEANY_FILETYPES_LATEX)
2131 wordchars = GEANY_WORDCHARS"\\"; /* add \ to word chars if we are in a LaTeX file */
2132 else if (ft->id == GEANY_FILETYPES_HTML || ft->id == GEANY_FILETYPES_PHP)
2133 wordchars = GEANY_WORDCHARS"&"; /* add & to word chars if we are in a PHP or HTML file */
2134 else
2135 wordchars = GEANY_WORDCHARS;
2137 /* find the start of the current word */
2138 while ((startword > 0) && (strchr(wordchars, linebuf[startword - 1])))
2139 startword--;
2140 linebuf[current] = '\0';
2141 root = linebuf + startword;
2142 rootlen = current - startword;
2144 if (rootlen > 0)
2146 if (autocomplete_check_for_html(ft->id, style))
2148 /* Allow something like "&quot;some text&quot;". The above startword calculation
2149 * only works on words but for HTML entity completion we also want to have completion
2150 * based on '&' within words. */
2151 gchar *tmp = strchr(root, '&');
2152 if (tmp != NULL)
2154 root = tmp;
2155 rootlen = strlen(tmp);
2157 ret = autocomplete_html(sci, root, rootlen);
2159 else
2161 /* force is set when called by keyboard shortcut, otherwise start at the
2162 * editor_prefs.symbolcompletion_min_chars'th char */
2163 if (force || rootlen >= editor_prefs.symbolcompletion_min_chars)
2165 /* complete tags, except if forcing when completion is already visible */
2166 if (!(force && SSM(sci, SCI_AUTOCACTIVE, 0, 0)))
2167 ret = autocomplete_tags(editor, root, rootlen);
2169 /* If forcing and there's nothing else to show, complete from words in document */
2170 if (!ret && (force || editor_prefs.autocomplete_doc_words))
2171 ret = autocomplete_doc_word(editor, root, rootlen);
2175 if (!ret && force)
2176 utils_beep();
2178 g_free(linebuf);
2179 return ret;
2183 static const gchar *snippets_find_completion_by_name(const gchar *type, const gchar *name)
2185 gchar *result = NULL;
2186 GHashTable *tmp;
2188 g_return_val_if_fail(type != NULL && name != NULL, NULL);
2190 tmp = g_hash_table_lookup(snippet_hash, type);
2191 if (tmp != NULL)
2193 result = g_hash_table_lookup(tmp, name);
2195 /* whether nothing is set for the current filetype(tmp is NULL) or
2196 * the particular completion for this filetype is not set (result is NULL) */
2197 if (tmp == NULL || result == NULL)
2199 tmp = g_hash_table_lookup(snippet_hash, "Default");
2200 if (tmp != NULL)
2202 result = g_hash_table_lookup(tmp, name);
2205 /* if result is still NULL here, no completion could be found */
2207 /* result is owned by the hash table and will be freed when the table will destroyed */
2208 return result;
2212 /* This is very ugly but passing the pattern to ac_replace_specials() doesn't work because it is
2213 * modified when replacing a completion but the foreach function still passes the old pointer
2214 * to ac_replace_specials, so we use a global pointer outside of ac_replace_specials and
2215 * ac_complete_constructs. Any hints to improve this are welcome. */
2216 static GString *snippets_global_pattern = NULL;
2218 static void snippets_replace_specials(gpointer key, gpointer value, gpointer user_data)
2220 gchar *needle;
2222 g_return_if_fail(key != NULL);
2223 g_return_if_fail(value != NULL);
2225 needle = g_strconcat("%", (gchar*) key, "%", NULL);
2227 utils_string_replace_all(snippets_global_pattern, needle, (gchar*) value);
2228 g_free(needle);
2232 /* this only works with spaces only indentation on the lines */
2233 static void fix_line_indents(GeanyEditor *editor, gint line_start, gint line_end)
2235 ScintillaObject *sci = editor->sci;
2236 gint line, cur_line, cur_col, pos;
2238 /* get the line, col position as fixing indentation will move cursor to start of line */
2239 pos = sci_get_current_position(sci);
2240 cur_col = sci_get_col_from_position(sci, pos);
2241 cur_line = sci_get_current_line(sci);
2243 for (line = line_start; line <= line_end; line++)
2245 gint size = sci_get_line_indentation(sci, line);
2247 /* set to 0 first to trigger proper indent creation */
2248 sci_set_line_indentation(sci, line, 0);
2249 sci_set_line_indentation(sci, line, size);
2251 pos = scintilla_send_message(sci, SCI_FINDCOLUMN, cur_line, cur_col);
2252 sci_set_current_position(sci, pos, FALSE);
2256 static void replace_leading_tabs(GString *str, const gchar *whitespace)
2258 regex_t regex;
2259 gssize pos;
2260 regmatch_t matches[2];
2261 gchar *ptr;
2263 if (regcomp(&regex, "^ *(\t)", 0) != 0)
2265 g_return_if_fail(FALSE);
2267 ptr = str->str;
2268 while (ptr)
2270 if (regexec(&regex, ptr,
2271 G_N_ELEMENTS(matches), matches, 0) != 0)
2272 break;
2274 pos = matches[1].rm_so;
2275 g_return_if_fail(pos >= 0);
2276 pos += ptr - str->str;
2277 g_string_erase(str, pos, 1);
2278 g_string_insert(str, pos, whitespace);
2279 ptr = str->str + pos + strlen(whitespace);
2281 regfree(&regex);
2285 /** Inserts text, replacing \\t tab chars (@c 0x9) and \\n newline chars (@c 0xA)
2286 * accordingly for the document.
2287 * - Leading tabs are replaced with the correct indentation.
2288 * - Non-leading tabs are replaced with spaces (except when using 'Tabs' indent type).
2289 * - Newline chars are replaced with the correct line ending string.
2290 * This is very useful for inserting code without having to handle the indent
2291 * type yourself (Tabs & Spaces mode can be tricky).
2292 * @param editor Editor.
2293 * @param text Intended as e.g. @c "if (foo)\n\tbar();".
2294 * @param insert_pos Document position to insert text at.
2295 * @param cursor_index If >= 0, the index into @a text to place the cursor.
2296 * @param newline_indent_size Indentation size (in spaces) to insert for each newline; use
2297 * -1 to read the indent size from the line with @a insert_pos on it.
2298 * @param replace_newlines Whether to replace newlines. If
2299 * newlines have been replaced already, this should be false, to avoid errors e.g. on Windows.
2300 * @warning Make sure all \\t tab chars in @a text are intended as indent widths or alignment,
2301 * not hard tabs, as those won't be preserved.
2302 * @note This doesn't scroll the cursor in view afterwards. **/
2303 void editor_insert_text_block(GeanyEditor *editor, const gchar *text, gint insert_pos,
2304 gint cursor_index, gint newline_indent_size, gboolean replace_newlines)
2306 ScintillaObject *sci = editor->sci;
2307 gint line_start = sci_get_line_from_position(sci, insert_pos);
2308 gint line_end;
2309 gchar *whitespace;
2310 GString *buf;
2311 const gchar cur_marker[] = "__GEANY_CURSOR_MARKER__";
2312 const gchar *eol = editor_get_eol_char(editor);
2313 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
2315 g_return_if_fail(text);
2316 g_return_if_fail(editor != NULL);
2317 g_return_if_fail(insert_pos >= 0);
2319 buf = g_string_new(text);
2321 if (cursor_index >= 0)
2322 g_string_insert(buf, cursor_index, cur_marker); /* remember cursor pos */
2324 if (newline_indent_size == -1)
2326 /* count indent size up to insert_pos instead of asking sci
2327 * because there may be spaces after it */
2328 gchar *tmp = sci_get_line(sci, line_start);
2329 gint idx = insert_pos - sci_get_position_from_line(sci, line_start);
2330 tmp[idx] = '\0';
2331 newline_indent_size = count_indent_size(editor, tmp);
2332 g_free(tmp);
2335 /* Add line indents (in spaces) */
2336 if (newline_indent_size > 0)
2338 whitespace = g_strnfill(newline_indent_size, ' ');
2339 setptr(whitespace, g_strconcat(eol, whitespace, NULL));
2340 utils_string_replace_all(buf, eol, whitespace);
2341 g_free(whitespace);
2344 /* transform line endings */
2345 if (replace_newlines)
2346 utils_string_replace_all(buf, "\n", eol);
2348 /* transform leading tabs into indent widths (in spaces) */
2349 whitespace = g_strnfill(iprefs->width, ' ');
2350 replace_leading_tabs(buf, whitespace);
2351 /* remaining tabs are for alignment */
2352 if (iprefs->type != GEANY_INDENT_TYPE_TABS)
2353 utils_string_replace_all(buf, "\t", whitespace);
2354 g_free(whitespace);
2356 sci_start_undo_action(sci);
2358 if (cursor_index >= 0)
2360 gint idx = utils_strpos(buf->str, cur_marker);
2362 g_string_erase(buf, idx, strlen(cur_marker));
2364 sci_insert_text(sci, insert_pos, buf->str);
2365 sci_set_current_position(sci, insert_pos + idx, FALSE);
2367 else
2368 sci_insert_text(sci, insert_pos, buf->str);
2370 /* fixup indentation (very useful for Tabs & Spaces indent type) */
2371 line_end = sci_get_line_from_position(sci, insert_pos + buf->len);
2372 fix_line_indents(editor, line_start, line_end);
2373 snippet_cursor_insert_pos = sci_get_current_position(sci);
2375 sci_end_undo_action(sci);
2376 g_string_free(buf, TRUE);
2380 /* Move the cursor to the next specified cursor position in an inserted snippet.
2381 * Can, and should, be optimized to give better results */
2382 void editor_goto_next_snippet_cursor(GeanyEditor *editor)
2384 ScintillaObject *sci = editor->sci;
2385 gint current_pos = sci_get_current_position(sci);
2387 if (snippet_offsets && !g_queue_is_empty(snippet_offsets))
2389 gint offset;
2391 offset = GPOINTER_TO_INT(g_queue_pop_head(snippet_offsets));
2392 if (current_pos > snippet_cursor_insert_pos)
2393 snippet_cursor_insert_pos = offset + current_pos;
2394 else
2395 snippet_cursor_insert_pos += offset;
2397 sci_set_current_position(sci, snippet_cursor_insert_pos, FALSE);
2399 else
2401 utils_beep();
2406 static gssize snippets_make_replacements(GeanyEditor *editor, GString *pattern,
2407 gsize indent_size)
2409 gssize cur_index = -1;
2410 gchar *whitespace;
2411 gint i, tmp_pos, whitespace_len, nl_count = 0;
2412 GHashTable *specials;
2413 GList *temp_list = NULL;
2414 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
2415 gint cursor_steps, old_cursor = 0;
2417 /* replace 'special' completions */
2418 specials = g_hash_table_lookup(snippet_hash, "Special");
2419 if (G_LIKELY(specials != NULL))
2421 /* ugly hack using global_pattern */
2422 snippets_global_pattern = pattern;
2423 g_hash_table_foreach(specials, snippets_replace_specials, NULL);
2426 /* replace any template {foo} wildcards */
2427 templates_replace_common(pattern, editor->document->file_name, editor->document->file_type, NULL);
2429 /* transform other wildcards */
2430 /* convert to %newlines%, else we get endless loops */
2431 utils_string_replace_all(pattern, "\n", "%newline%");
2433 /* if spaces are used, replaces all tabs with %ws%, which is later replaced
2434 * by real whitespace characters
2435 * otherwise replace all %ws% by \t, which will be replaced later by tab
2436 * characters,
2437 * this makes seperating between tab and spaces intentation pretty easy */
2438 if (iprefs->type == GEANY_INDENT_TYPE_SPACES)
2439 utils_string_replace_all(pattern, "\t", "%ws%");
2440 else
2441 utils_string_replace_all(pattern, "%ws%", "\t");
2443 whitespace = g_strnfill(iprefs->width, ' '); /* use spaces for indentation, will be fixed up */
2444 whitespace_len = strlen(whitespace);
2445 i = 0;
2446 while ((cursor_steps = utils_strpos(pattern->str, "%cursor%")) >= 0)
2448 /* replace every %newline% (up to next %cursor%) with EOL,
2449 * and update cursor_steps after */
2450 while ((tmp_pos = utils_strpos(pattern->str, "%newline%")) < cursor_steps && tmp_pos != -1)
2452 nl_count++;
2453 utils_string_replace_first(pattern, "%newline%", editor_get_eol_char(editor));
2454 cursor_steps = utils_strpos(pattern->str, "%cursor%");
2456 /* replace every %ws% (up to next %cursor%) with whitespaces,
2457 * and update cursor_steps after */
2458 while ((tmp_pos = utils_strpos(pattern->str, "%ws%")) < cursor_steps && tmp_pos != -1)
2460 utils_string_replace_first(pattern, "%ws%", whitespace);
2461 cursor_steps = utils_strpos(pattern->str, "%cursor%");
2463 /* finally replace the next %cursor% */
2464 utils_string_replace_first(pattern, "%cursor%", "");
2466 /* modify cursor_steps to take indentation count and type into account */
2468 /* We're saving the relative offset to each cursor position in a simple
2469 * linked list, including indentations between them. */
2470 if (i++ > 0)
2472 cursor_steps += (nl_count * indent_size);
2473 temp_list = g_list_append(temp_list, GINT_TO_POINTER(cursor_steps - old_cursor));
2475 else
2477 nl_count = 0;
2478 cur_index = cursor_steps;
2480 old_cursor = cursor_steps;
2482 /* replace remaining %ws% and %newline% which may occur after the last %cursor% */
2483 utils_string_replace_all(pattern, "%newline%", editor_get_eol_char(editor));
2484 utils_string_replace_all(pattern, "%ws%", whitespace);
2485 g_free(whitespace);
2487 /* escape % last */
2488 /* Bug: {ob}pc{cb} will be replaced by % too */
2489 templates_replace_valist(pattern, "{pc}", "%", NULL);
2491 /* We put the cursor positions for the most recent
2492 * parsed snippet first, followed by any remaining positions */
2493 i = 0;
2494 if (temp_list)
2496 GList *node;
2498 foreach_list(node, temp_list)
2499 g_queue_push_nth(snippet_offsets, node->data, i++);
2501 /* limit length of queue */
2502 while (g_queue_get_length(snippet_offsets) > 20)
2503 g_queue_pop_tail(snippet_offsets);
2505 g_list_free(temp_list);
2507 if (cur_index < 0)
2508 cur_index = pattern->len;
2510 return cur_index;
2514 static gboolean snippets_complete_constructs(GeanyEditor *editor, gint pos, const gchar *word)
2516 ScintillaObject *sci = editor->sci;
2517 gchar *str;
2518 GString *pattern;
2519 gssize cur_index = -1;
2520 gint str_len;
2521 gint ft_id = editor->document->file_type->id;
2523 str = g_strdup(word);
2524 g_strstrip(str);
2525 pattern = g_string_new(snippets_find_completion_by_name(filetypes[ft_id]->name, str));
2526 if (pattern == NULL || pattern->len == 0)
2528 g_free(str);
2529 g_string_free(pattern, TRUE);
2530 return FALSE;
2533 read_indent(editor, pos);
2535 /* remove the typed word, it will be added again by the used auto completion
2536 * (not really necessary but this makes the auto completion more flexible,
2537 * e.g. with a completion like hi=hello, so typing "hi<TAB>" will result in "hello") */
2538 str_len = strlen(str);
2539 sci_set_selection_start(sci, pos - str_len);
2540 sci_set_selection_end(sci, pos);
2541 sci_replace_sel(sci, "");
2542 pos -= str_len; /* pos has changed while deleting */
2544 cur_index = snippets_make_replacements(editor, pattern, strlen(indent));
2546 /* finally insert the text and set the cursor */
2547 editor_insert_text_block(editor, pattern->str, pos, cur_index, -1, FALSE);
2548 sci_scroll_caret(sci);
2550 g_free(str);
2551 g_string_free(pattern, TRUE);
2552 return TRUE;
2556 static gboolean at_eol(ScintillaObject *sci, gint pos)
2558 gint line = sci_get_line_from_position(sci, pos);
2559 gchar c;
2561 /* skip any trailing spaces */
2562 while (TRUE)
2564 c = sci_get_char_at(sci, pos);
2565 if (c == ' ' || c == '\t')
2566 pos++;
2567 else
2568 break;
2571 return (pos == sci_get_line_end_position(sci, line));
2575 gboolean editor_complete_snippet(GeanyEditor *editor, gint pos)
2577 gboolean result = FALSE;
2578 const gchar *wc;
2579 const gchar *word;
2580 ScintillaObject *sci;
2582 g_return_val_if_fail(editor != NULL, FALSE);
2584 sci = editor->sci;
2585 if (sci_has_selection(sci))
2586 return FALSE;
2587 /* return if we are editing an existing line (chars on right of cursor) */
2588 if (keybindings_lookup_item(GEANY_KEY_GROUP_EDITOR,
2589 GEANY_KEYS_EDITOR_COMPLETESNIPPET)->key == GDK_space &&
2590 ! editor_prefs.complete_snippets_whilst_editing && ! at_eol(sci, pos))
2591 return FALSE;
2593 wc = snippets_find_completion_by_name("Special", "wordchars");
2594 word = editor_read_word_stem(editor, pos, wc);
2596 /* prevent completion of "for " */
2597 if (NZV(word) &&
2598 ! isspace(sci_get_char_at(sci, pos - 1))) /* pos points to the line end char so use pos -1 */
2600 sci_start_undo_action(sci); /* needed because we insert a space separately from construct */
2601 result = snippets_complete_constructs(editor, pos, word);
2602 sci_end_undo_action(sci);
2603 if (result)
2604 sci_cancel(sci); /* cancel any autocompletion list, etc */
2606 return result;
2610 void editor_show_macro_list(GeanyEditor *editor)
2612 GString *words;
2614 if (editor == NULL || editor->document->file_type == NULL)
2615 return;
2617 words = symbols_get_macro_list(editor->document->file_type->lang);
2618 if (words == NULL)
2619 return;
2621 SSM(editor->sci, SCI_USERLISTSHOW, 1, (sptr_t) words->str);
2622 g_string_free(words, TRUE);
2626 static void insert_closing_tag(GeanyEditor *editor, gint pos, gchar ch, const gchar *tag_name)
2628 ScintillaObject *sci = editor->sci;
2629 gchar *to_insert = NULL;
2631 if (ch == '/')
2633 const gchar *gt = ">";
2634 /* if there is already a '>' behind the cursor, don't add it */
2635 if (sci_get_char_at(sci, pos) == '>')
2636 gt = "";
2638 to_insert = g_strconcat(tag_name, gt, NULL);
2640 else
2641 to_insert = g_strconcat("</", tag_name, ">", NULL);
2643 sci_start_undo_action(sci);
2644 sci_replace_sel(sci, to_insert);
2645 if (ch == '>')
2646 sci_set_selection(sci, pos, pos);
2647 sci_end_undo_action(sci);
2648 g_free(to_insert);
2653 * (stolen from anjuta and heavily modified)
2654 * This routine will auto complete XML or HTML tags that are still open by closing them
2655 * @param ch The character we are dealing with, currently only works with the '>' character
2656 * @return True if handled, false otherwise
2658 static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch)
2660 ScintillaObject *sci = editor->sci;
2661 gint lexer = sci_get_lexer(sci);
2662 gint min, size, style;
2663 gchar *str_found, sel[512];
2664 gboolean result = FALSE;
2666 /* If the user has turned us off, quit now.
2667 * This may make sense only in certain languages */
2668 if (! editor_prefs.auto_close_xml_tags || (lexer != SCLEX_HTML && lexer != SCLEX_XML))
2669 return FALSE;
2671 /* return if we are inside any embedded script */
2672 style = sci_get_style_at(sci, pos);
2673 if (style > SCE_H_XCCOMMENT && ! is_string_style(lexer, style))
2674 return FALSE;
2676 /* if ch is /, check for </, else quit */
2677 if (ch == '/' && sci_get_char_at(sci, pos - 2) != '<')
2678 return FALSE;
2680 /* Grab the last 512 characters or so */
2681 min = pos - (sizeof(sel) - 1);
2682 if (min < 0) min = 0;
2684 if (pos - min < 3)
2685 return FALSE; /* Smallest tag is 3 characters e.g. <p> */
2687 sci_get_text_range(sci, min, pos, sel);
2688 sel[sizeof(sel) - 1] = '\0';
2690 if (ch == '>' && sel[pos - min - 2] == '/')
2691 /* User typed something like "<br/>" */
2692 return FALSE;
2694 size = pos - min;
2695 if (ch == '/')
2696 size -= 2; /* skip </ */
2697 str_found = utils_find_open_xml_tag(sel, size);
2699 if (lexer == SCLEX_HTML && utils_is_short_html_tag(str_found))
2701 /* ignore tag */
2703 else if (NZV(str_found))
2705 insert_closing_tag(editor, pos, ch, str_found);
2706 result = TRUE;
2708 g_free(str_found);
2709 return result;
2713 /* like sci_get_line_indentation(), but for a string. */
2714 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent)
2716 const gchar *ptr;
2717 gsize tab_size = sci_get_tab_width(editor->sci);
2718 gsize count = 0;
2720 g_return_val_if_fail(base_indent, 0);
2722 for (ptr = base_indent; *ptr != 0; ptr++)
2724 switch (*ptr)
2726 case ' ':
2727 count++;
2728 break;
2729 case '\t':
2730 count += tab_size;
2731 break;
2734 return count;
2738 static void real_comment_multiline(GeanyEditor *editor, gint line_start, gint last_line)
2740 const gchar *eol;
2741 gchar *str_begin, *str_end, *co, *cc;
2742 gint line_len;
2744 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2746 eol = editor_get_eol_char(editor);
2747 co = editor->document->file_type->comment_open;
2748 cc = editor->document->file_type->comment_close;
2749 str_begin = g_strdup_printf("%s%s", (co != NULL) ? co : "", eol);
2750 str_end = g_strdup_printf("%s%s", (cc != NULL) ? cc : "", eol);
2752 /* insert the comment strings */
2753 sci_insert_text(editor->sci, line_start, str_begin);
2754 line_len = sci_get_position_from_line(editor->sci, last_line + 2);
2755 sci_insert_text(editor->sci, line_len, str_end);
2757 g_free(str_begin);
2758 g_free(str_end);
2762 static void real_uncomment_multiline(GeanyEditor *editor)
2764 /* find the beginning of the multi line comment */
2765 gint pos, line, len, x;
2766 gchar *linebuf;
2767 GeanyDocument *doc;
2769 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2770 doc = editor->document;
2772 /* remove comment open chars */
2773 pos = document_find_text(doc, doc->file_type->comment_open, 0, TRUE, FALSE, NULL);
2774 SSM(editor->sci, SCI_DELETEBACK, 0, 0);
2776 /* check whether the line is empty and can be deleted */
2777 line = sci_get_line_from_position(editor->sci, pos);
2778 len = sci_get_line_length(editor->sci, line);
2779 linebuf = sci_get_line(editor->sci, line);
2780 x = 0;
2781 while (linebuf[x] != '\0' && isspace(linebuf[x])) x++;
2782 if (x == len) SSM(editor->sci, SCI_LINEDELETE, 0, 0);
2783 g_free(linebuf);
2785 /* remove comment close chars */
2786 pos = document_find_text(doc, doc->file_type->comment_close, 0, FALSE, FALSE, NULL);
2787 SSM(editor->sci, SCI_DELETEBACK, 0, 0);
2789 /* check whether the line is empty and can be deleted */
2790 line = sci_get_line_from_position(editor->sci, pos);
2791 len = sci_get_line_length(editor->sci, line);
2792 linebuf = sci_get_line(editor->sci, line);
2793 x = 0;
2794 while (linebuf[x] != '\0' && isspace(linebuf[x])) x++;
2795 if (x == len) SSM(editor->sci, SCI_LINEDELETE, 0, 0);
2796 g_free(linebuf);
2800 static gint get_multiline_comment_style(GeanyEditor *editor, gint line_start)
2802 gint lexer = sci_get_lexer(editor->sci);
2803 gint style_comment;
2805 /* List only those lexers which support multi line comments */
2806 switch (lexer)
2808 case SCLEX_XML:
2809 case SCLEX_HTML:
2811 if (is_style_php(sci_get_style_at(editor->sci, line_start)))
2812 style_comment = SCE_HPHP_COMMENT;
2813 else
2814 style_comment = SCE_H_COMMENT;
2815 break;
2817 case SCLEX_HASKELL: style_comment = SCE_HA_COMMENTBLOCK; break;
2818 case SCLEX_LUA: style_comment = SCE_LUA_COMMENT; break;
2819 case SCLEX_CSS: style_comment = SCE_CSS_COMMENT; break;
2820 case SCLEX_SQL: style_comment = SCE_SQL_COMMENT; break;
2821 case SCLEX_CAML: style_comment = SCE_CAML_COMMENT; break;
2822 case SCLEX_D: style_comment = SCE_D_COMMENT; break;
2823 case SCLEX_PASCAL: style_comment = SCE_PAS_COMMENT; break;
2824 default: style_comment = SCE_C_COMMENT;
2827 return style_comment;
2831 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise
2832 * returns the amount of uncommented single comment lines, in case of multi line uncomment
2833 * it returns just 1 */
2834 gint editor_do_uncomment(GeanyEditor *editor, gint line, gboolean toggle)
2836 gint first_line, last_line, eol_char_len;
2837 gint x, i, line_start, line_len;
2838 gint sel_start, sel_end;
2839 gint count = 0;
2840 gsize co_len;
2841 gchar sel[256], *co, *cc;
2842 gboolean break_loop = FALSE, single_line = FALSE;
2843 GeanyFiletype *ft;
2845 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, 0);
2847 if (line < 0)
2848 { /* use selection or current line */
2849 sel_start = sci_get_selection_start(editor->sci);
2850 sel_end = sci_get_selection_end(editor->sci);
2852 first_line = sci_get_line_from_position(editor->sci, sel_start);
2853 /* Find the last line with chars selected (not EOL char) */
2854 last_line = sci_get_line_from_position(editor->sci,
2855 sel_end - editor_get_eol_char_len(editor));
2856 last_line = MAX(first_line, last_line);
2858 else
2860 first_line = last_line = line;
2861 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
2864 ft = editor->document->file_type;
2865 eol_char_len = editor_get_eol_char_len(editor);
2867 /* detection of HTML vs PHP code, if non-PHP set filetype to XML */
2868 line_start = sci_get_position_from_line(editor->sci, first_line);
2869 if (ft->id == GEANY_FILETYPES_PHP)
2871 if (! is_style_php(sci_get_style_at(editor->sci, line_start)))
2872 ft = filetypes[GEANY_FILETYPES_XML];
2875 co = ft->comment_open;
2876 cc = ft->comment_close;
2877 if (co == NULL)
2878 return 0;
2880 co_len = strlen(co);
2881 if (co_len == 0)
2882 return 0;
2884 sci_start_undo_action(editor->sci);
2886 for (i = first_line; (i <= last_line) && (! break_loop); i++)
2888 gint buf_len;
2890 line_start = sci_get_position_from_line(editor->sci, i);
2891 line_len = sci_get_line_length(editor->sci, i);
2892 x = 0;
2894 buf_len = MIN((gint)sizeof(sel) - 1, line_len - eol_char_len);
2895 if (buf_len <= 0)
2896 continue;
2897 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
2898 sel[buf_len] = '\0';
2900 while (isspace(sel[x])) x++;
2902 /* to skip blank lines */
2903 if (x < line_len && sel[x] != '\0')
2905 /* use single line comment */
2906 if (cc == NULL || strlen(cc) == 0)
2908 single_line = TRUE;
2910 if (toggle)
2912 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
2913 if (strncmp(sel + x, co, co_len) != 0 ||
2914 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) != 0)
2915 continue;
2917 co_len += tm_len;
2919 else
2921 if (strncmp(sel + x, co, co_len) != 0)
2922 continue;
2925 sci_set_selection(editor->sci, line_start + x, line_start + x + co_len);
2926 sci_replace_sel(editor->sci, "");
2927 count++;
2929 /* use multi line comment */
2930 else
2932 gint style_comment;
2934 /* skip lines which are already comments */
2935 style_comment = get_multiline_comment_style(editor, line_start);
2936 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
2938 real_uncomment_multiline(editor);
2939 count = 1;
2942 /* break because we are already on the last line */
2943 break_loop = TRUE;
2944 break;
2948 sci_end_undo_action(editor->sci);
2950 /* restore selection if there is one
2951 * but don't touch the selection if caller is editor_do_comment_toggle */
2952 if (! toggle && sel_start < sel_end)
2954 if (single_line)
2956 sci_set_selection_start(editor->sci, sel_start - co_len);
2957 sci_set_selection_end(editor->sci, sel_end - (count * co_len));
2959 else
2961 gint eol_len = editor_get_eol_char_len(editor);
2962 sci_set_selection_start(editor->sci, sel_start - co_len - eol_len);
2963 sci_set_selection_end(editor->sci, sel_end - co_len - eol_len);
2967 return count;
2971 void editor_do_comment_toggle(GeanyEditor *editor)
2973 gint first_line, last_line, eol_char_len;
2974 gint x, i, line_start, line_len, first_line_start;
2975 gint sel_start, sel_end;
2976 gint count_commented = 0, count_uncommented = 0;
2977 gchar sel[256], *co, *cc;
2978 gboolean break_loop = FALSE, single_line = FALSE;
2979 gboolean first_line_was_comment = FALSE;
2980 gsize co_len;
2981 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
2982 GeanyFiletype *ft;
2984 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2986 sel_start = sci_get_selection_start(editor->sci);
2987 sel_end = sci_get_selection_end(editor->sci);
2989 ft = editor->document->file_type;
2990 eol_char_len = editor_get_eol_char_len(editor);
2992 first_line = sci_get_line_from_position(editor->sci,
2993 sci_get_selection_start(editor->sci));
2994 /* Find the last line with chars selected (not EOL char) */
2995 last_line = sci_get_line_from_position(editor->sci,
2996 sci_get_selection_end(editor->sci) - editor_get_eol_char_len(editor));
2997 last_line = MAX(first_line, last_line);
2999 /* detection of HTML vs PHP code, if non-PHP set filetype to XML */
3000 first_line_start = sci_get_position_from_line(editor->sci, first_line);
3001 if (ft->id == GEANY_FILETYPES_PHP)
3003 if (! is_style_php(sci_get_style_at(editor->sci, first_line_start)))
3004 ft = filetypes[GEANY_FILETYPES_XML];
3007 co = ft->comment_open;
3008 cc = ft->comment_close;
3009 if (co == NULL)
3010 return;
3012 co_len = strlen(co);
3013 if (co_len == 0)
3014 return;
3016 sci_start_undo_action(editor->sci);
3018 for (i = first_line; (i <= last_line) && (! break_loop); i++)
3020 gint buf_len;
3022 line_start = sci_get_position_from_line(editor->sci, i);
3023 line_len = sci_get_line_length(editor->sci, i);
3024 x = 0;
3026 buf_len = MIN((gint)sizeof(sel) - 1, line_len - eol_char_len);
3027 if (buf_len < 0)
3028 continue;
3029 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3030 sel[buf_len] = '\0';
3032 while (isspace(sel[x])) x++;
3034 /* use single line comment */
3035 if (cc == NULL || strlen(cc) == 0)
3037 gboolean do_continue = FALSE;
3038 single_line = TRUE;
3040 if (strncmp(sel + x, co, co_len) == 0 &&
3041 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) == 0)
3043 do_continue = TRUE;
3046 if (do_continue && i == first_line)
3047 first_line_was_comment = TRUE;
3049 if (do_continue)
3051 count_uncommented += editor_do_uncomment(editor, i, TRUE);
3052 continue;
3055 /* we are still here, so the above lines were not already comments, so comment it */
3056 editor_do_comment(editor, i, TRUE, TRUE);
3057 count_commented++;
3059 /* use multi line comment */
3060 else
3062 gint style_comment;
3064 /* skip lines which are already comments */
3065 style_comment = get_multiline_comment_style(editor, line_start);
3066 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3068 real_uncomment_multiline(editor);
3069 count_uncommented++;
3071 else
3073 real_comment_multiline(editor, line_start, last_line);
3074 count_commented++;
3077 /* break because we are already on the last line */
3078 break_loop = TRUE;
3079 break;
3083 sci_end_undo_action(editor->sci);
3085 co_len += tm_len;
3087 /* restore selection if there is one */
3088 if (sel_start < sel_end)
3090 if (single_line)
3092 gint a = (first_line_was_comment) ? - co_len : co_len;
3094 /* don't modify sel_start when the selection starts within indentation */
3095 read_indent(editor, sel_start);
3096 if ((sel_start - first_line_start) <= (gint) strlen(indent))
3097 a = 0;
3099 sci_set_selection_start(editor->sci, sel_start + a);
3100 sci_set_selection_end(editor->sci, sel_end +
3101 (count_commented * co_len) - (count_uncommented * co_len));
3103 else
3105 gint eol_len = editor_get_eol_char_len(editor);
3106 if (count_uncommented > 0)
3108 sci_set_selection_start(editor->sci, sel_start - co_len + eol_len);
3109 sci_set_selection_end(editor->sci, sel_end - co_len + eol_len);
3111 else if (count_commented > 0)
3113 sci_set_selection_start(editor->sci, sel_start + co_len - eol_len);
3114 sci_set_selection_end(editor->sci, sel_end + co_len - eol_len);
3118 else if (count_uncommented > 0)
3120 gint eol_len = single_line ? 0: editor_get_eol_char_len(editor);
3121 sci_set_current_position(editor->sci, sel_start - co_len + eol_len, TRUE);
3123 else if (count_commented > 0)
3125 gint eol_len = single_line ? 0: editor_get_eol_char_len(editor);
3126 sci_set_current_position(editor->sci, sel_start + co_len - eol_len, TRUE);
3131 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise */
3132 void editor_do_comment(GeanyEditor *editor, gint line, gboolean allow_empty_lines, gboolean toggle)
3134 gint first_line, last_line, eol_char_len;
3135 gint x, i, line_start, line_len;
3136 gint sel_start, sel_end, co_len;
3137 gchar sel[256], *co, *cc;
3138 gboolean break_loop = FALSE, single_line = FALSE;
3139 GeanyFiletype *ft;
3141 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
3143 if (line < 0)
3144 { /* use selection or current line */
3145 sel_start = sci_get_selection_start(editor->sci);
3146 sel_end = sci_get_selection_end(editor->sci);
3148 first_line = sci_get_line_from_position(editor->sci, sel_start);
3149 /* Find the last line with chars selected (not EOL char) */
3150 last_line = sci_get_line_from_position(editor->sci,
3151 sel_end - editor_get_eol_char_len(editor));
3152 last_line = MAX(first_line, last_line);
3154 else
3156 first_line = last_line = line;
3157 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
3160 ft = editor->document->file_type;
3161 eol_char_len = editor_get_eol_char_len(editor);
3163 /* detection of HTML vs PHP code, if non-PHP set filetype to XML */
3164 line_start = sci_get_position_from_line(editor->sci, first_line);
3165 if (ft->id == GEANY_FILETYPES_PHP)
3167 if (! is_style_php(sci_get_style_at(editor->sci, line_start)))
3168 ft = filetypes[GEANY_FILETYPES_XML];
3171 co = ft->comment_open;
3172 cc = ft->comment_close;
3173 if (co == NULL)
3174 return;
3176 co_len = strlen(co);
3177 if (co_len == 0)
3178 return;
3180 sci_start_undo_action(editor->sci);
3182 for (i = first_line; (i <= last_line) && (! break_loop); i++)
3184 gint buf_len;
3186 line_start = sci_get_position_from_line(editor->sci, i);
3187 line_len = sci_get_line_length(editor->sci, i);
3188 x = 0;
3190 buf_len = MIN((gint)sizeof(sel) - 1, line_len - eol_char_len);
3191 if (buf_len < 0)
3192 continue;
3193 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3194 sel[buf_len] = '\0';
3196 while (isspace(sel[x])) x++;
3198 /* to skip blank lines */
3199 if (allow_empty_lines || (x < line_len && sel[x] != '\0'))
3201 /* use single line comment */
3202 if (cc == NULL || strlen(cc) == 0)
3204 gint start = line_start;
3205 single_line = TRUE;
3207 if (ft->comment_use_indent)
3208 start = line_start + x;
3210 if (toggle)
3212 gchar *text = g_strconcat(co, editor_prefs.comment_toggle_mark, NULL);
3213 sci_insert_text(editor->sci, start, text);
3214 g_free(text);
3216 else
3217 sci_insert_text(editor->sci, start, co);
3219 /* use multi line comment */
3220 else
3222 gint style_comment;
3224 /* skip lines which are already comments */
3225 style_comment = get_multiline_comment_style(editor, line_start);
3226 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3227 continue;
3229 real_comment_multiline(editor, line_start, last_line);
3231 /* break because we are already on the last line */
3232 break_loop = TRUE;
3233 break;
3237 sci_end_undo_action(editor->sci);
3239 /* restore selection if there is one
3240 * but don't touch the selection if caller is editor_do_comment_toggle */
3241 if (! toggle && sel_start < sel_end)
3243 if (single_line)
3245 sci_set_selection_start(editor->sci, sel_start + co_len);
3246 sci_set_selection_end(editor->sci, sel_end + ((i - first_line) * co_len));
3248 else
3250 gint eol_len = editor_get_eol_char_len(editor);
3251 sci_set_selection_start(editor->sci, sel_start + co_len + eol_len);
3252 sci_set_selection_end(editor->sci, sel_end + co_len + eol_len);
3258 static gboolean brace_timeout_active = FALSE;
3260 static gboolean delay_match_brace(G_GNUC_UNUSED gpointer user_data)
3262 GeanyDocument *doc = document_get_current();
3263 GeanyEditor *editor;
3264 gint brace_pos = GPOINTER_TO_INT(user_data);
3265 gint end_pos, cur_pos;
3267 brace_timeout_active = FALSE;
3268 if (!doc)
3269 return FALSE;
3271 editor = doc->editor;
3272 cur_pos = sci_get_current_position(editor->sci) - 1;
3274 if (cur_pos != brace_pos)
3276 cur_pos++;
3277 if (cur_pos != brace_pos)
3279 /* we have moved past the original brace_pos, but after the timeout
3280 * we may now be on a new brace, so check again */
3281 editor_highlight_braces(editor, cur_pos);
3282 return FALSE;
3285 if (!utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3287 editor_highlight_braces(editor, cur_pos);
3288 return FALSE;
3290 end_pos = sci_find_matching_brace(editor->sci, brace_pos);
3292 if (end_pos >= 0)
3294 gint col = MIN(sci_get_col_from_position(editor->sci, brace_pos),
3295 sci_get_col_from_position(editor->sci, end_pos));
3296 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, col, 0);
3297 SSM(editor->sci, SCI_BRACEHIGHLIGHT, brace_pos, end_pos);
3299 else
3301 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3302 SSM(editor->sci, SCI_BRACEBADLIGHT, brace_pos, 0);
3304 return FALSE;
3308 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos)
3310 gint brace_pos = cur_pos - 1;
3312 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3313 SSM(editor->sci, SCI_BRACEBADLIGHT, (uptr_t)-1, 0);
3315 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3317 brace_pos++;
3318 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3320 return;
3323 if (!brace_timeout_active)
3325 brace_timeout_active = TRUE;
3326 /* delaying matching makes scrolling faster e.g. holding down arrow keys */
3327 g_timeout_add(100, delay_match_brace, GINT_TO_POINTER(brace_pos));
3332 static gboolean in_block_comment(gint lexer, gint style)
3334 switch (lexer)
3336 case SCLEX_CPP:
3337 return (style == SCE_C_COMMENT ||
3338 style == SCE_C_COMMENTDOC);
3340 case SCLEX_PASCAL:
3341 return (style == SCE_PAS_COMMENT ||
3342 style == SCE_PAS_COMMENT2);
3344 case SCLEX_D:
3345 return (style == SCE_D_COMMENT ||
3346 style == SCE_D_COMMENTDOC ||
3347 style == SCE_D_COMMENTNESTED);
3349 case SCLEX_HTML:
3350 return (style == SCE_HPHP_COMMENT);
3352 case SCLEX_CSS:
3353 return (style == SCE_CSS_COMMENT);
3355 default:
3356 return FALSE;
3361 static gboolean is_comment_char(gchar c, gint lexer)
3363 if ((c == '*' || c == '+') && lexer == SCLEX_D)
3364 return TRUE;
3365 else
3366 if (c == '*')
3367 return TRUE;
3369 return FALSE;
3373 static void auto_multiline(GeanyEditor *editor, gint cur_line)
3375 ScintillaObject *sci = editor->sci;
3376 gint indent_pos, style;
3377 gint lexer = sci_get_lexer(sci);
3379 /* Use the start of the line enter was pressed on, to avoid any doc keyword styles */
3380 indent_pos = sci_get_line_indent_position(sci, cur_line - 1);
3381 style = sci_get_style_at(sci, indent_pos);
3382 if (!in_block_comment(lexer, style))
3383 return;
3385 /* Check whether the comment block continues on this line */
3386 indent_pos = sci_get_line_indent_position(sci, cur_line);
3387 if (sci_get_style_at(sci, indent_pos) == style)
3389 gchar *previous_line = sci_get_line(sci, cur_line - 1);
3390 /* the type of comment, '*' (C/C++/Java), '+' and the others (D) */
3391 gchar *continuation = "*";
3392 gchar *whitespace = ""; /* to hold whitespace if needed */
3393 gchar *result;
3394 gint len = strlen(previous_line);
3395 gint i;
3397 /* find and stop at end of multi line comment */
3398 i = len - 1;
3399 while (i >= 0 && isspace(previous_line[i])) i--;
3400 if (i >= 1 && is_comment_char(previous_line[i - 1], lexer) && previous_line[i] == '/')
3402 gint indent_len, indent_width;
3404 indent_pos = sci_get_line_indent_position(sci, cur_line);
3405 indent_len = sci_get_col_from_position(sci, indent_pos);
3406 indent_width = editor_get_indent_prefs(editor)->width;
3408 /* if there is one too many spaces, delete the last space,
3409 * to return to the indent used before the multiline comment was started. */
3410 if (indent_len % indent_width == 1)
3411 SSM(sci, SCI_DELETEBACKNOTLINE, 0, 0); /* remove whitespace indent */
3412 g_free(previous_line);
3413 return;
3415 /* check whether we are on the second line of multi line comment */
3416 i = 0;
3417 while (i < len && isspace(previous_line[i])) i++; /* get to start of the line */
3419 if (i + 1 < len &&
3420 previous_line[i] == '/' && is_comment_char(previous_line[i + 1], lexer))
3421 { /* we are on the second line of a multi line comment, so we have to insert white space */
3422 whitespace = " ";
3425 if (G_UNLIKELY(style == SCE_D_COMMENTNESTED))
3426 continuation = "+"; /* for nested comments in D */
3428 result = g_strconcat(whitespace, continuation, " ", NULL);
3429 sci_add_text(sci, result);
3430 g_free(result);
3432 g_free(previous_line);
3437 /* Checks whether the given style is a string for the given lexer.
3438 * It doesn't handle LEX_HTML, this should be done by the caller.
3439 * Returns true if the style is a string, FALSE otherwise.
3441 * Don't forget STRINGEOL, to prevent completion whilst typing a string with no closing char.
3443 static gboolean is_string_style(gint lexer, gint style)
3445 switch (lexer)
3447 case SCLEX_CPP:
3448 return (style == SCE_C_CHARACTER ||
3449 style == SCE_C_STRING ||
3450 style == SCE_C_STRINGEOL);
3452 case SCLEX_PASCAL:
3453 return (style == SCE_PAS_CHARACTER ||
3454 style == SCE_PAS_STRING ||
3455 style == SCE_PAS_STRINGEOL);
3457 case SCLEX_D:
3458 return (style == SCE_D_STRING ||
3459 style == SCE_D_STRINGEOL ||
3460 style == SCE_D_CHARACTER ||
3461 style == SCE_D_STRINGB ||
3462 style == SCE_D_STRINGR);
3464 case SCLEX_PYTHON:
3465 return (style == SCE_P_STRING ||
3466 style == SCE_P_TRIPLE ||
3467 style == SCE_P_TRIPLEDOUBLE ||
3468 style == SCE_P_CHARACTER ||
3469 style == SCE_P_STRINGEOL);
3471 case SCLEX_F77:
3472 case SCLEX_FORTRAN:
3473 return (style == SCE_F_STRING1 ||
3474 style == SCE_F_STRING2 ||
3475 style == SCE_F_STRINGEOL);
3477 case SCLEX_PERL:
3478 return (/*style == SCE_PL_STRING ||*/ /* may want variable autocompletion "$(foo)" */
3479 style == SCE_PL_CHARACTER ||
3480 style == SCE_PL_HERE_DELIM ||
3481 style == SCE_PL_HERE_Q ||
3482 style == SCE_PL_HERE_QQ ||
3483 style == SCE_PL_HERE_QX ||
3484 style == SCE_PL_POD ||
3485 style == SCE_PL_STRING_Q ||
3486 style == SCE_PL_STRING_QQ ||
3487 style == SCE_PL_STRING_QX ||
3488 style == SCE_PL_STRING_QR ||
3489 style == SCE_PL_STRING_QW ||
3490 style == SCE_PL_POD_VERB);
3492 case SCLEX_R:
3493 return (style == SCE_R_STRING);
3495 case SCLEX_RUBY:
3496 return (style == SCE_RB_CHARACTER ||
3497 style == SCE_RB_STRING ||
3498 style == SCE_RB_HERE_DELIM ||
3499 style == SCE_RB_HERE_Q ||
3500 style == SCE_RB_HERE_QQ ||
3501 style == SCE_RB_HERE_QX ||
3502 style == SCE_RB_POD);
3504 case SCLEX_BASH:
3505 return (style == SCE_SH_STRING);
3507 case SCLEX_SQL:
3508 return (style == SCE_SQL_STRING);
3510 case SCLEX_TCL:
3511 return (style == SCE_TCL_IN_QUOTE);
3513 case SCLEX_LUA:
3514 return (style == SCE_LUA_LITERALSTRING ||
3515 style == SCE_LUA_CHARACTER ||
3516 style == SCE_LUA_STRINGEOL ||
3517 style == SCE_LUA_STRING);
3519 case SCLEX_HASKELL:
3520 return (style == SCE_HA_CHARACTER ||
3521 style == SCE_HA_STRING);
3523 case SCLEX_FREEBASIC:
3524 return (style == SCE_B_STRING ||
3525 style == SCE_B_STRINGEOL);
3527 case SCLEX_OCTAVE:
3528 return (style == SCE_MATLAB_STRING ||
3529 style == SCE_MATLAB_DOUBLEQUOTESTRING);
3531 case SCLEX_HTML:
3532 return (
3533 style == SCE_HBA_STRING ||
3534 style == SCE_HBA_STRINGEOL ||
3535 style == SCE_HB_STRING ||
3536 style == SCE_HB_STRINGEOL ||
3537 style == SCE_H_CDATA ||
3538 style == SCE_H_DOUBLESTRING ||
3539 style == SCE_HJA_DOUBLESTRING ||
3540 style == SCE_HJA_SINGLESTRING ||
3541 style == SCE_HJA_STRINGEOL ||
3542 style == SCE_HJ_DOUBLESTRING ||
3543 style == SCE_HJ_SINGLESTRING ||
3544 style == SCE_HJ_STRINGEOL ||
3545 style == SCE_HPA_CHARACTER ||
3546 style == SCE_HPA_STRING ||
3547 style == SCE_HPA_TRIPLE ||
3548 style == SCE_HPA_TRIPLEDOUBLE ||
3549 style == SCE_HP_CHARACTER ||
3550 style == SCE_HPHP_HSTRING || /* HSTRING is a heredoc */
3551 style == SCE_HPHP_HSTRING_VARIABLE ||
3552 style == SCE_HPHP_SIMPLESTRING ||
3553 style == SCE_HP_STRING ||
3554 style == SCE_HP_TRIPLE ||
3555 style == SCE_HP_TRIPLEDOUBLE ||
3556 style == SCE_H_SGML_DOUBLESTRING ||
3557 style == SCE_H_SGML_SIMPLESTRING ||
3558 style == SCE_H_SINGLESTRING);
3560 case SCLEX_CMAKE:
3561 return (style == SCE_CMAKE_STRINGDQ ||
3562 style == SCE_CMAKE_STRINGLQ ||
3563 style == SCE_CMAKE_STRINGRQ ||
3564 style == SCE_CMAKE_STRINGVAR);
3566 case SCLEX_NSIS:
3567 return (style == SCE_NSIS_STRINGDQ ||
3568 style == SCE_NSIS_STRINGLQ ||
3569 style == SCE_NSIS_STRINGRQ ||
3570 style == SCE_NSIS_STRINGVAR);
3572 case SCLEX_ADA:
3573 return (style == SCE_ADA_CHARACTER ||
3574 style == SCE_ADA_STRING ||
3575 style == SCE_ADA_CHARACTEREOL ||
3576 style == SCE_ADA_STRINGEOL);
3578 return FALSE;
3582 /* Checks whether the given style is a comment for the given lexer.
3583 * It doesn't handle LEX_HTML, this should be done by the caller.
3584 * Returns true if the style is a comment, FALSE otherwise.
3586 static gboolean is_comment_style(gint lexer, gint style)
3588 switch (lexer)
3590 case SCLEX_CPP:
3591 return (style == SCE_C_COMMENT ||
3592 style == SCE_C_COMMENTLINE ||
3593 style == SCE_C_COMMENTDOC ||
3594 style == SCE_C_COMMENTLINEDOC ||
3595 style == SCE_C_COMMENTDOCKEYWORD ||
3596 style == SCE_C_COMMENTDOCKEYWORDERROR);
3598 case SCLEX_PASCAL:
3599 return (style == SCE_PAS_COMMENT ||
3600 style == SCE_PAS_COMMENT2 ||
3601 style == SCE_PAS_COMMENTLINE);
3603 case SCLEX_D:
3604 return (style == SCE_D_COMMENT ||
3605 style == SCE_D_COMMENTLINE ||
3606 style == SCE_D_COMMENTDOC ||
3607 style == SCE_D_COMMENTNESTED ||
3608 style == SCE_D_COMMENTLINEDOC ||
3609 style == SCE_D_COMMENTDOCKEYWORD ||
3610 style == SCE_D_COMMENTDOCKEYWORDERROR);
3612 case SCLEX_PYTHON:
3613 return (style == SCE_P_COMMENTLINE ||
3614 style == SCE_P_COMMENTBLOCK);
3616 case SCLEX_F77:
3617 case SCLEX_FORTRAN:
3618 return (style == SCE_F_COMMENT);
3620 case SCLEX_PERL:
3621 return (style == SCE_PL_COMMENTLINE);
3623 case SCLEX_PROPERTIES:
3624 return (style == SCE_PROPS_COMMENT);
3626 case SCLEX_PO:
3627 return (style == SCE_PO_COMMENT);
3629 case SCLEX_LATEX:
3630 return (style == SCE_L_COMMENT);
3632 case SCLEX_MAKEFILE:
3633 return (style == SCE_MAKE_COMMENT);
3635 case SCLEX_RUBY:
3636 return (style == SCE_RB_COMMENTLINE);
3638 case SCLEX_BASH:
3639 return (style == SCE_SH_COMMENTLINE);
3641 case SCLEX_R:
3642 return (style == SCE_R_COMMENT);
3644 case SCLEX_SQL:
3645 return (style == SCE_SQL_COMMENT ||
3646 style == SCE_SQL_COMMENTLINE ||
3647 style == SCE_SQL_COMMENTDOC);
3649 case SCLEX_TCL:
3650 return (style == SCE_TCL_COMMENT ||
3651 style == SCE_TCL_COMMENTLINE ||
3652 style == SCE_TCL_COMMENT_BOX ||
3653 style == SCE_TCL_BLOCK_COMMENT);
3655 case SCLEX_OCTAVE:
3656 return (style == SCE_MATLAB_COMMENT);
3658 case SCLEX_LUA:
3659 return (style == SCE_LUA_COMMENT ||
3660 style == SCE_LUA_COMMENTLINE ||
3661 style == SCE_LUA_COMMENTDOC);
3663 case SCLEX_HASKELL:
3664 return (style == SCE_HA_COMMENTLINE ||
3665 style == SCE_HA_COMMENTBLOCK ||
3666 style == SCE_HA_COMMENTBLOCK2 ||
3667 style == SCE_HA_COMMENTBLOCK3);
3669 case SCLEX_FREEBASIC:
3670 return (style == SCE_B_COMMENT);
3672 case SCLEX_YAML:
3673 return (style == SCE_YAML_COMMENT);
3675 case SCLEX_HTML:
3676 return (
3677 style == SCE_HBA_COMMENTLINE ||
3678 style == SCE_HB_COMMENTLINE ||
3679 style == SCE_H_COMMENT ||
3680 style == SCE_HJA_COMMENT ||
3681 style == SCE_HJA_COMMENTDOC ||
3682 style == SCE_HJA_COMMENTLINE ||
3683 style == SCE_HJ_COMMENT ||
3684 style == SCE_HJ_COMMENTDOC ||
3685 style == SCE_HJ_COMMENTLINE ||
3686 style == SCE_HPA_COMMENTLINE ||
3687 style == SCE_HP_COMMENTLINE ||
3688 style == SCE_HPHP_COMMENT ||
3689 style == SCE_HPHP_COMMENTLINE ||
3690 style == SCE_H_SGML_COMMENT);
3692 case SCLEX_CMAKE:
3693 return (style == SCE_CMAKE_COMMENT);
3695 case SCLEX_NSIS:
3696 return (style == SCE_NSIS_COMMENT ||
3697 style == SCE_NSIS_COMMENTBOX);
3699 case SCLEX_ADA:
3700 return (style == SCE_ADA_COMMENTLINE ||
3701 style == SCE_NSIS_COMMENTBOX);
3703 return FALSE;
3707 /* Checks whether the given style is normal code (not string, comment, preprocessor, etc).
3708 * It doesn't handle LEX_HTML, this should be done by the caller.
3710 static gboolean is_code_style(gint lexer, gint style)
3712 switch (lexer)
3714 case SCLEX_CPP:
3715 if (style == SCE_C_PREPROCESSOR)
3716 return FALSE;
3717 break;
3719 return !(is_comment_style(lexer, style) ||
3720 is_string_style(lexer, style));
3724 #if 0
3725 static gboolean editor_lexer_is_c_like(gint lexer)
3727 switch (lexer)
3729 case SCLEX_CPP:
3730 case SCLEX_D:
3731 return TRUE;
3733 default:
3734 return FALSE;
3737 #endif
3740 /* Returns: -1 if lexer doesn't support type keywords */
3741 gint editor_lexer_get_type_keyword_idx(gint lexer)
3743 switch (lexer)
3745 case SCLEX_CPP:
3746 case SCLEX_D:
3747 return 3;
3749 default:
3750 return -1;
3755 /* inserts a three-line comment at one line above current cursor position */
3756 void editor_insert_multiline_comment(GeanyEditor *editor)
3758 gchar *text;
3759 gint text_len;
3760 gint line;
3761 gint pos;
3762 gboolean have_multiline_comment = FALSE;
3763 GeanyDocument *doc;
3765 g_return_if_fail(editor != NULL &&
3766 editor->document->file_type != NULL && editor->document->file_type->comment_open != NULL);
3768 sci_start_undo_action(editor->sci);
3770 doc = editor->document;
3772 if (doc->file_type->comment_close != NULL && strlen(doc->file_type->comment_close) > 0)
3773 have_multiline_comment = TRUE;
3775 /* insert three lines one line above of the current position */
3776 line = sci_get_line_from_position(editor->sci, editor_info.click_pos);
3777 pos = sci_get_position_from_line(editor->sci, line);
3779 /* use the indent on the current line but only when comment indentation is used
3780 * and we don't have multi line comment characters */
3781 if (editor->auto_indent &&
3782 ! have_multiline_comment && doc->file_type->comment_use_indent)
3784 read_indent(editor, editor_info.click_pos);
3785 text = g_strdup_printf("%s\n%s\n%s\n", indent, indent, indent);
3786 text_len = strlen(text);
3788 else
3790 text = g_strdup("\n\n\n");
3791 text_len = 3;
3793 sci_insert_text(editor->sci, pos, text);
3794 g_free(text);
3796 /* select the inserted lines for commenting */
3797 sci_set_selection_start(editor->sci, pos);
3798 sci_set_selection_end(editor->sci, pos + text_len);
3800 editor_do_comment(editor, -1, TRUE, FALSE);
3802 /* set the current position to the start of the first inserted line */
3803 pos += strlen(doc->file_type->comment_open);
3805 /* on multi line comment jump to the next line, otherwise add the length of added indentation */
3806 if (have_multiline_comment)
3807 pos += 1;
3808 else
3809 pos += strlen(indent);
3811 sci_set_current_position(editor->sci, pos, TRUE);
3812 /* reset the selection */
3813 sci_set_anchor(editor->sci, pos);
3815 sci_end_undo_action(editor->sci);
3819 /* Note: If the editor is pending a redraw, set document::scroll_percent instead.
3820 * Scroll the view to make line appear at percent_of_view.
3821 * line can be -1 to use the current position. */
3822 void editor_scroll_to_line(GeanyEditor *editor, gint line, gfloat percent_of_view)
3824 gint los;
3825 GtkWidget *wid;
3827 g_return_if_fail(editor != NULL);
3829 wid = GTK_WIDGET(editor->sci);
3831 if (! wid->window || ! gdk_window_is_viewable(wid->window))
3832 return; /* prevent gdk_window_scroll warning */
3834 if (line == -1)
3835 line = sci_get_current_line(editor->sci);
3837 /* sci 'visible line' != doc line number because of folding and line wrapping */
3838 /* calling SCI_VISIBLEFROMDOCLINE for line is more accurate than calling
3839 * SCI_DOCLINEFROMVISIBLE for vis1. */
3840 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0);
3841 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
3842 line = line - los * percent_of_view;
3843 SSM(editor->sci, SCI_SETFIRSTVISIBLELINE, line, 0);
3844 sci_scroll_caret(editor->sci); /* needed for horizontal scrolling */
3848 /* creates and inserts one tab or whitespace of the amount of the tab width */
3849 void editor_insert_alternative_whitespace(GeanyEditor *editor)
3851 gchar *text;
3852 GeanyIndentPrefs iprefs = *editor_get_indent_prefs(editor);
3854 g_return_if_fail(editor != NULL);
3856 switch (iprefs.type)
3858 case GEANY_INDENT_TYPE_TABS:
3859 iprefs.type = GEANY_INDENT_TYPE_SPACES;
3860 break;
3861 case GEANY_INDENT_TYPE_SPACES:
3862 case GEANY_INDENT_TYPE_BOTH: /* most likely we want a tab */
3863 iprefs.type = GEANY_INDENT_TYPE_TABS;
3864 break;
3866 text = get_whitespace(&iprefs, iprefs.width);
3867 sci_add_text(editor->sci, text);
3868 g_free(text);
3872 void editor_select_word(GeanyEditor *editor)
3874 gint pos;
3875 gint start;
3876 gint end;
3878 g_return_if_fail(editor != NULL);
3880 pos = SSM(editor->sci, SCI_GETCURRENTPOS, 0, 0);
3881 start = SSM(editor->sci, SCI_WORDSTARTPOSITION, pos, TRUE);
3882 end = SSM(editor->sci, SCI_WORDENDPOSITION, pos, TRUE);
3884 if (start == end) /* caret in whitespaces sequence */
3886 /* look forward but reverse the selection direction,
3887 * so the caret end up stay as near as the original position. */
3888 end = SSM(editor->sci, SCI_WORDENDPOSITION, pos, FALSE);
3889 start = SSM(editor->sci, SCI_WORDENDPOSITION, end, TRUE);
3890 if (start == end)
3891 return;
3894 sci_set_selection(editor->sci, start, end);
3898 /* extra_line is for selecting the cursor line (or anchor line) at the bottom of a selection,
3899 * when those lines have no selection (cursor at start of line). */
3900 void editor_select_lines(GeanyEditor *editor, gboolean extra_line)
3902 gint start, end, line;
3904 g_return_if_fail(editor != NULL);
3906 start = sci_get_selection_start(editor->sci);
3907 end = sci_get_selection_end(editor->sci);
3909 /* check if whole lines are already selected */
3910 if (! extra_line && start != end &&
3911 sci_get_col_from_position(editor->sci, start) == 0 &&
3912 sci_get_col_from_position(editor->sci, end) == 0)
3913 return;
3915 line = sci_get_line_from_position(editor->sci, start);
3916 start = sci_get_position_from_line(editor->sci, line);
3918 line = sci_get_line_from_position(editor->sci, end);
3919 end = sci_get_position_from_line(editor->sci, line + 1);
3921 sci_set_selection(editor->sci, start, end);
3925 /* find the start or end of a paragraph by searching all lines in direction (UP or DOWN)
3926 * starting at the given line and return the found line or return -1 if called on an empty line */
3927 static gint find_paragraph_stop(GeanyEditor *editor, gint line, gint direction)
3929 gboolean found_end = FALSE;
3930 gint step;
3931 gchar *line_buf, *x;
3932 ScintillaObject *sci = editor->sci;
3934 /* first check current line and return -1 if it is empty to skip creating of a selection */
3935 line_buf = x = sci_get_line(sci, line);
3936 while (isspace(*x))
3937 x++;
3938 if (*x == '\0')
3940 g_free(line_buf);
3941 return -1;
3944 if (direction == GTK_DIR_UP)
3945 step = -1;
3946 else
3947 step = 1;
3949 while (! found_end)
3951 line += step;
3953 /* sci_get_line checks for sanity of the given line, sci_get_line always return a string
3954 * containing at least '\0' so no need to check for NULL */
3955 line_buf = x = sci_get_line(sci, line);
3957 /* check whether after skipping all whitespace we are at end of line and if so, assume
3958 * this line as end of paragraph */
3959 while (isspace(*x))
3960 x++;
3961 if (*x == '\0')
3963 found_end = TRUE;
3964 if (line == -1)
3965 /* called on the first line but there is no previous line so return line 0 */
3966 line = 0;
3968 g_free(line_buf);
3970 return line;
3974 void editor_select_paragraph(GeanyEditor *editor)
3976 gint pos_start, pos_end, line_start, line_found;
3978 g_return_if_fail(editor != NULL);
3980 line_start = SSM(editor->sci, SCI_LINEFROMPOSITION,
3981 SSM(editor->sci, SCI_GETCURRENTPOS, 0, 0), 0);
3983 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_UP);
3984 if (line_found == -1)
3985 return;
3987 /* find_paragraph_stop returns the emtpy line(previous to the real start of the paragraph),
3988 * so use the next line for selection start */
3989 if (line_found > 0)
3990 line_found++;
3992 pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3994 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_DOWN);
3995 pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3997 sci_set_selection(editor->sci, pos_start, pos_end);
4001 /* simple indentation to indent the current line with the same indent as the previous one */
4002 static void smart_line_indentation(GeanyEditor *editor, gint first_line, gint last_line)
4004 gint i, sel_start = 0, sel_end = 0;
4006 /* get previous line and use it for read_indent to use that line
4007 * (otherwise it would fail on a line only containing "{" in advanced indentation mode) */
4008 read_indent(editor, sci_get_position_from_line(editor->sci, first_line - 1));
4010 for (i = first_line; i <= last_line; i++)
4012 /* skip the first line or if the indentation of the previous and current line are equal */
4013 if (i == 0 ||
4014 SSM(editor->sci, SCI_GETLINEINDENTATION, i - 1, 0) ==
4015 SSM(editor->sci, SCI_GETLINEINDENTATION, i, 0))
4016 continue;
4018 sel_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
4019 sel_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
4020 if (sel_start < sel_end)
4022 sci_set_selection(editor->sci, sel_start, sel_end);
4023 sci_replace_sel(editor->sci, "");
4025 sci_insert_text(editor->sci, sel_start, indent);
4030 /* simple indentation to indent the current line with the same indent as the previous one */
4031 void editor_smart_line_indentation(GeanyEditor *editor, gint pos)
4033 gint first_line, last_line;
4034 gint first_sel_start, first_sel_end;
4035 ScintillaObject *sci;
4037 g_return_if_fail(editor != NULL);
4039 sci = editor->sci;
4041 first_sel_start = sci_get_selection_start(sci);
4042 first_sel_end = sci_get_selection_end(sci);
4044 first_line = sci_get_line_from_position(sci, first_sel_start);
4045 /* Find the last line with chars selected (not EOL char) */
4046 last_line = sci_get_line_from_position(sci, first_sel_end - editor_get_eol_char_len(editor));
4047 last_line = MAX(first_line, last_line);
4049 if (pos == -1)
4050 pos = first_sel_start;
4052 sci_start_undo_action(sci);
4054 smart_line_indentation(editor, first_line, last_line);
4056 /* set cursor position if there was no selection */
4057 if (first_sel_start == first_sel_end)
4059 gint indent_pos = SSM(sci, SCI_GETLINEINDENTPOSITION, first_line, 0);
4061 /* use indent position as user may wish to change indentation afterwards */
4062 sci_set_current_position(sci, indent_pos, FALSE);
4064 else
4066 /* fully select all the lines affected */
4067 sci_set_selection_start(sci, sci_get_position_from_line(sci, first_line));
4068 sci_set_selection_end(sci, sci_get_position_from_line(sci, last_line + 1));
4071 sci_end_undo_action(sci);
4075 /* increase / decrease current line or selection by one space */
4076 void editor_indentation_by_one_space(GeanyEditor *editor, gint pos, gboolean decrease)
4078 gint i, first_line, last_line, line_start, indentation_end, count = 0;
4079 gint sel_start, sel_end, first_line_offset = 0;
4081 g_return_if_fail(editor != NULL);
4083 sel_start = sci_get_selection_start(editor->sci);
4084 sel_end = sci_get_selection_end(editor->sci);
4086 first_line = sci_get_line_from_position(editor->sci, sel_start);
4087 /* Find the last line with chars selected (not EOL char) */
4088 last_line = sci_get_line_from_position(editor->sci, sel_end - editor_get_eol_char_len(editor));
4089 last_line = MAX(first_line, last_line);
4091 if (pos == -1)
4092 pos = sel_start;
4094 sci_start_undo_action(editor->sci);
4096 for (i = first_line; i <= last_line; i++)
4098 indentation_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
4099 if (decrease)
4101 line_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
4102 /* searching backwards for a space to remove */
4103 while (sci_get_char_at(editor->sci, indentation_end) != ' ' && indentation_end > line_start)
4104 indentation_end--;
4106 if (sci_get_char_at(editor->sci, indentation_end) == ' ')
4108 sci_set_selection(editor->sci, indentation_end, indentation_end + 1);
4109 sci_replace_sel(editor->sci, "");
4110 count--;
4111 if (i == first_line)
4112 first_line_offset = -1;
4115 else
4117 sci_insert_text(editor->sci, indentation_end, " ");
4118 count++;
4119 if (i == first_line)
4120 first_line_offset = 1;
4124 /* set cursor position */
4125 if (sel_start < sel_end)
4127 gint start = sel_start + first_line_offset;
4128 if (first_line_offset < 0)
4129 start = MAX(sel_start + first_line_offset,
4130 SSM(editor->sci, SCI_POSITIONFROMLINE, first_line, 0));
4132 sci_set_selection_start(editor->sci, start);
4133 sci_set_selection_end(editor->sci, sel_end + count);
4135 else
4136 sci_set_current_position(editor->sci, pos + count, FALSE);
4138 sci_end_undo_action(editor->sci);
4142 void editor_finalize()
4144 scintilla_release_resources();
4148 /* wordchars: NULL or a string containing characters to match a word.
4149 * Returns: the current selection or the current word. */
4150 gchar *editor_get_default_selection(GeanyEditor *editor, gboolean use_current_word,
4151 const gchar *wordchars)
4153 gchar *s = NULL;
4155 g_return_val_if_fail(editor != NULL, NULL);
4157 if (sci_get_lines_selected(editor->sci) == 1)
4159 gint len = sci_get_selected_text_length(editor->sci);
4161 s = g_malloc(len + 1);
4162 sci_get_selected_text(editor->sci, s);
4164 else if (sci_get_lines_selected(editor->sci) == 0 && use_current_word)
4165 { /* use the word at current cursor position */
4166 gchar word[GEANY_MAX_WORD_LENGTH];
4168 editor_find_current_word(editor, -1, word, sizeof(word), wordchars);
4169 if (word[0] != '\0')
4170 s = g_strdup(word);
4172 return s;
4176 /* Note: Usually the line should be made visible (not folded) before calling this.
4177 * Returns: TRUE if line is/will be displayed to the user, or FALSE if it is
4178 * outside the *vertical* view.
4179 * Warning: You may need horizontal scrolling to make the cursor visible - so always call
4180 * sci_scroll_caret() when this returns TRUE. */
4181 gboolean editor_line_in_view(GeanyEditor *editor, gint line)
4183 gint vis1, los;
4185 g_return_val_if_fail(editor != NULL, FALSE);
4187 /* If line is wrapped the result may occur on another virtual line than the first and may be
4188 * still hidden, so increase the line number to check for the next document line */
4189 if (SSM(editor->sci, SCI_WRAPCOUNT, line, 0) > 1)
4190 line++;
4192 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0); /* convert to visible line number */
4193 vis1 = SSM(editor->sci, SCI_GETFIRSTVISIBLELINE, 0, 0);
4194 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
4196 return (line >= vis1 && line < vis1 + los);
4200 /* If the current line is outside the current view window, scroll the line
4201 * so it appears at percent_of_view. */
4202 void editor_display_current_line(GeanyEditor *editor, gfloat percent_of_view)
4204 gint line;
4206 g_return_if_fail(editor != NULL);
4208 line = sci_get_current_line(editor->sci);
4210 /* unfold maybe folded results */
4211 sci_ensure_line_is_visible(editor->sci, line);
4213 /* scroll the line if it's off screen */
4214 if (! editor_line_in_view(editor, line))
4215 editor->scroll_percent = percent_of_view;
4216 else
4217 sci_scroll_caret(editor->sci); /* may need horizontal scrolling */
4222 * Deletes all currently set indicators in the @a editor window.
4223 * Error indicators (red squiggly underlines) and usual line markers are removed.
4225 * @param editor The editor to operate on.
4227 void editor_indicator_clear_errors(GeanyEditor *editor)
4229 editor_indicator_clear(editor, GEANY_INDICATOR_ERROR);
4230 sci_marker_delete_all(editor->sci, 0); /* remove the yellow error line marker */
4235 * Deletes all currently set indicators matching @a indic in the @a editor window.
4237 * @param editor The editor to operate on.
4238 * @param indic The indicator number to clear, this is a value of @ref GeanyIndicator.
4240 * @since 0.16
4242 void editor_indicator_clear(GeanyEditor *editor, gint indic)
4244 glong last_pos;
4246 g_return_if_fail(editor != NULL);
4248 last_pos = sci_get_length(editor->sci);
4249 if (last_pos > 0)
4251 sci_indicator_set(editor->sci, indic);
4252 sci_indicator_clear(editor->sci, 0, last_pos);
4258 * Sets an indicator @a indic on @a line.
4259 * Whitespace at the start and the end of the line is not marked.
4261 * @param editor The editor to operate on.
4262 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4263 * @param line The line number which should be marked.
4265 * @since 0.16
4267 void editor_indicator_set_on_line(GeanyEditor *editor, gint indic, gint line)
4269 gint start, end;
4270 guint i = 0, len;
4271 gchar *linebuf;
4273 g_return_if_fail(editor != NULL);
4274 g_return_if_fail(line >= 0);
4276 start = sci_get_position_from_line(editor->sci, line);
4277 end = sci_get_position_from_line(editor->sci, line + 1);
4279 /* skip blank lines */
4280 if ((start + 1) == end ||
4281 start > end ||
4282 sci_get_line_length(editor->sci, line) == editor_get_eol_char_len(editor))
4284 return;
4287 len = end - start;
4288 linebuf = sci_get_line(editor->sci, line);
4290 /* don't set the indicator on whitespace */
4291 while (isspace(linebuf[i]))
4292 i++;
4293 while (len > 1 && len > i && isspace(linebuf[len - 1]))
4295 len--;
4296 end--;
4298 g_free(linebuf);
4300 editor_indicator_set_on_range(editor, indic, start + i, end);
4305 * Sets an indicator on the range specified by @a start and @a end.
4306 * No error checking or whitespace removal is performed, this should be done by the calling
4307 * function if necessary.
4309 * @param editor The editor to operate on.
4310 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4311 * @param start The starting position for the marker.
4312 * @param end The ending position for the marker.
4314 * @since 0.16
4316 void editor_indicator_set_on_range(GeanyEditor *editor, gint indic, gint start, gint end)
4318 g_return_if_fail(editor != NULL);
4319 if (start >= end)
4320 return;
4322 sci_indicator_set(editor->sci, indic);
4323 sci_indicator_fill(editor->sci, start, end - start);
4327 /* Inserts the given colour (format should be #...), if there is a selection starting with 0x...
4328 * the replacement will also start with 0x... */
4329 void editor_insert_color(GeanyEditor *editor, const gchar *colour)
4331 g_return_if_fail(editor != NULL);
4333 if (sci_has_selection(editor->sci))
4335 gint start = sci_get_selection_start(editor->sci);
4336 const gchar *replacement = colour;
4338 if (sci_get_char_at(editor->sci, start) == '0' &&
4339 sci_get_char_at(editor->sci, start + 1) == 'x')
4341 sci_set_selection_start(editor->sci, start + 2);
4342 sci_set_selection_end(editor->sci, start + 8);
4343 replacement++; /* skip the leading "0x" */
4345 else if (sci_get_char_at(editor->sci, start - 1) == '#')
4346 { /* double clicking something like #00ffff may only select 00ffff because of wordchars */
4347 replacement++; /* so skip the '#' to only replace the colour value */
4349 sci_replace_sel(editor->sci, replacement);
4351 else
4352 sci_add_text(editor->sci, colour);
4357 * Retrieves the end of line characters mode (LF, CR/LF, CR) in the given editor.
4358 * If @a editor is @c NULL, the default end of line characters are used.
4360 * @param editor The editor to operate on, or @c NULL to query the default value.
4361 * @return The used end of line characters mode.
4363 * @since 0.20
4365 gint editor_get_eol_char_mode(GeanyEditor *editor)
4367 gint mode = file_prefs.default_eol_character;
4369 if (editor != NULL)
4370 mode = sci_get_eol_mode(editor->sci);
4372 return mode;
4377 * Retrieves the localized name (for displaying) of the used end of line characters
4378 * (LF, CR/LF, CR) in the given editor.
4379 * If @a editor is @c NULL, the default end of line characters are used.
4381 * @param editor The editor to operate on, or @c NULL to query the default value.
4382 * @return The name of the end of line characters.
4384 * @since 0.19
4386 const gchar *editor_get_eol_char_name(GeanyEditor *editor)
4388 gint mode = file_prefs.default_eol_character;
4390 if (editor != NULL)
4391 mode = sci_get_eol_mode(editor->sci);
4393 return utils_get_eol_name(mode);
4398 * Retrieves the length of the used end of line characters (LF, CR/LF, CR) in the given editor.
4399 * If @a editor is @c NULL, the default end of line characters are used.
4400 * The returned value is 1 for CR and LF and 2 for CR/LF.
4402 * @param editor The editor to operate on, or @c NULL to query the default value.
4403 * @return The length of the end of line characters.
4405 * @since 0.19
4407 gint editor_get_eol_char_len(GeanyEditor *editor)
4409 gint mode = file_prefs.default_eol_character;
4411 if (editor != NULL)
4412 mode = sci_get_eol_mode(editor->sci);
4414 switch (mode)
4416 case SC_EOL_CRLF: return 2; break;
4417 default: return 1; break;
4423 * Retrieves the used end of line characters (LF, CR/LF, CR) in the given editor.
4424 * If @a editor is @c NULL, the default end of line characters are used.
4425 * The returned value is either "\n", "\r\n" or "\r".
4427 * @param editor The editor to operate on, or @c NULL to query the default value.
4428 * @return The end of line characters.
4430 * @since 0.19
4432 const gchar *editor_get_eol_char(GeanyEditor *editor)
4434 gint mode = file_prefs.default_eol_character;
4436 if (editor != NULL)
4437 mode = sci_get_eol_mode(editor->sci);
4439 return utils_get_eol_char(mode);
4443 static void fold_all(GeanyEditor *editor, gboolean want_fold)
4445 gint lines, first, i;
4447 if (editor == NULL || ! editor_prefs.folding)
4448 return;
4450 lines = sci_get_line_count(editor->sci);
4451 first = sci_get_first_visible_line(editor->sci);
4453 for (i = 0; i < lines; i++)
4455 gint level = sci_get_fold_level(editor->sci, i);
4457 if (level & SC_FOLDLEVELHEADERFLAG)
4459 if (sci_get_fold_expanded(editor->sci, i) == want_fold)
4460 sci_toggle_fold(editor->sci, i);
4463 editor_scroll_to_line(editor, first, 0.0F);
4467 void editor_unfold_all(GeanyEditor *editor)
4469 fold_all(editor, FALSE);
4473 void editor_fold_all(GeanyEditor *editor)
4475 fold_all(editor, TRUE);
4479 void editor_replace_tabs(GeanyEditor *editor)
4481 gint search_pos, pos_in_line, current_tab_true_length;
4482 gint tab_len;
4483 gchar *tab_str;
4484 struct Sci_TextToFind ttf;
4486 g_return_if_fail(editor != NULL);
4488 sci_start_undo_action(editor->sci);
4489 tab_len = sci_get_tab_width(editor->sci);
4490 ttf.chrg.cpMin = 0;
4491 ttf.chrg.cpMax = sci_get_length(editor->sci);
4492 ttf.lpstrText = (gchar*) "\t";
4494 while (TRUE)
4496 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4497 if (search_pos == -1)
4498 break;
4500 pos_in_line = sci_get_col_from_position(editor->sci, search_pos);
4501 current_tab_true_length = tab_len - (pos_in_line % tab_len);
4502 tab_str = g_strnfill(current_tab_true_length, ' ');
4503 sci_set_target_start(editor->sci, search_pos);
4504 sci_set_target_end(editor->sci, search_pos + 1);
4505 sci_replace_target(editor->sci, tab_str, FALSE);
4506 /* next search starts after replacement */
4507 ttf.chrg.cpMin = search_pos + current_tab_true_length - 1;
4508 /* update end of range now text has changed */
4509 ttf.chrg.cpMax += current_tab_true_length - 1;
4510 g_free(tab_str);
4512 sci_end_undo_action(editor->sci);
4516 /* Replaces all occurrences all spaces of the length of a given tab_width. */
4517 void editor_replace_spaces(GeanyEditor *editor)
4519 gint search_pos;
4520 static gdouble tab_len_f = -1.0; /* keep the last used value */
4521 gint tab_len;
4522 struct Sci_TextToFind ttf;
4524 g_return_if_fail(editor != NULL);
4526 if (tab_len_f < 0.0)
4527 tab_len_f = sci_get_tab_width(editor->sci);
4529 if (! dialogs_show_input_numeric(
4530 _("Enter Tab Width"),
4531 _("Enter the amount of spaces which should be replaced by a tab character."),
4532 &tab_len_f, 1, 100, 1))
4534 return;
4536 tab_len = (gint) tab_len_f;
4538 sci_start_undo_action(editor->sci);
4539 ttf.chrg.cpMin = 0;
4540 ttf.chrg.cpMax = sci_get_length(editor->sci);
4541 ttf.lpstrText = g_strnfill(tab_len, ' ');
4543 while (TRUE)
4545 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4546 if (search_pos == -1)
4547 break;
4549 sci_set_target_start(editor->sci, search_pos);
4550 sci_set_target_end(editor->sci, search_pos + tab_len);
4551 sci_replace_target(editor->sci, "\t", FALSE);
4552 ttf.chrg.cpMin = search_pos;
4553 /* update end of range now text has changed */
4554 ttf.chrg.cpMax -= tab_len - 1;
4556 sci_end_undo_action(editor->sci);
4557 g_free(ttf.lpstrText);
4561 void editor_strip_line_trailing_spaces(GeanyEditor *editor, gint line)
4563 gint line_start = sci_get_position_from_line(editor->sci, line);
4564 gint line_end = sci_get_line_end_position(editor->sci, line);
4565 gint i = line_end - 1;
4566 gchar ch = sci_get_char_at(editor->sci, i);
4568 while ((i >= line_start) && ((ch == ' ') || (ch == '\t')))
4570 i--;
4571 ch = sci_get_char_at(editor->sci, i);
4573 if (i < (line_end - 1))
4575 sci_set_target_start(editor->sci, i + 1);
4576 sci_set_target_end(editor->sci, line_end);
4577 sci_replace_target(editor->sci, "", FALSE);
4582 void editor_strip_trailing_spaces(GeanyEditor *editor)
4584 gint max_lines = sci_get_line_count(editor->sci);
4585 gint line;
4587 sci_start_undo_action(editor->sci);
4589 for (line = 0; line < max_lines; line++)
4591 editor_strip_line_trailing_spaces(editor, line);
4593 sci_end_undo_action(editor->sci);
4597 void editor_ensure_final_newline(GeanyEditor *editor)
4599 gint max_lines = sci_get_line_count(editor->sci);
4600 gboolean append_newline = (max_lines == 1);
4601 gint end_document = sci_get_position_from_line(editor->sci, max_lines);
4603 if (max_lines > 1)
4605 append_newline = end_document > sci_get_position_from_line(editor->sci, max_lines - 1);
4607 if (append_newline)
4609 const gchar *eol = editor_get_eol_char(editor);
4611 sci_insert_text(editor->sci, end_document, eol);
4616 void editor_set_font(GeanyEditor *editor, const gchar *font)
4618 gint style, size;
4619 gchar *font_name;
4620 PangoFontDescription *pfd;
4622 g_return_if_fail(editor);
4624 pfd = pango_font_description_from_string(font);
4625 size = pango_font_description_get_size(pfd) / PANGO_SCALE;
4626 font_name = g_strdup_printf("!%s", pango_font_description_get_family(pfd));
4627 pango_font_description_free(pfd);
4629 for (style = 0; style <= 127; style++)
4630 sci_set_font(editor->sci, style, font_name, size);
4632 /* line number and braces */
4633 sci_set_font(editor->sci, STYLE_LINENUMBER, font_name, size);
4634 sci_set_font(editor->sci, STYLE_BRACELIGHT, font_name, size);
4635 sci_set_font(editor->sci, STYLE_BRACEBAD, font_name, size);
4636 g_free(font_name);
4638 /* zoom to 100% to prevent confusion */
4639 sci_zoom_off(editor->sci);
4643 void editor_set_line_wrapping(GeanyEditor *editor, gboolean wrap)
4645 g_return_if_fail(editor != NULL);
4647 editor->line_wrapping = wrap;
4648 sci_set_lines_wrapped(editor->sci, wrap);
4652 /** Sets the indent type for @a editor.
4653 * @param editor Editor.
4654 * @param type Indent type.
4656 * @since 0.16
4658 void editor_set_indent_type(GeanyEditor *editor, GeanyIndentType type)
4660 editor_set_indent(editor, type, editor->indent_width);
4664 void editor_set_indent(GeanyEditor *editor, GeanyIndentType type, gint width)
4666 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
4667 ScintillaObject *sci = editor->sci;
4668 gboolean use_tabs = type != GEANY_INDENT_TYPE_SPACES;
4670 editor->indent_type = type;
4671 editor->indent_width = width;
4672 sci_set_use_tabs(sci, use_tabs);
4674 if (type == GEANY_INDENT_TYPE_BOTH)
4676 sci_set_tab_width(sci, iprefs->hard_tab_width);
4677 if (iprefs->hard_tab_width != 8)
4679 static gboolean warn = TRUE;
4680 if (warn)
4681 ui_set_statusbar(TRUE, _("Warning: non-standard hard tab width: %d != 8!"),
4682 iprefs->hard_tab_width);
4683 warn = FALSE;
4686 else
4687 sci_set_tab_width(sci, width);
4689 SSM(sci, SCI_SETINDENT, width, 0);
4691 /* remove indent spaces on backspace, if using any spaces to indent */
4692 SSM(sci, SCI_SETBACKSPACEUNINDENTS, type != GEANY_INDENT_TYPE_TABS, 0);
4696 /* Convenience function for editor_goto_pos() to pass in a line number. */
4697 gboolean editor_goto_line(GeanyEditor *editor, gint line_no, gint offset)
4699 gint pos;
4701 g_return_val_if_fail(editor, FALSE);
4702 if (line_no < 0 || line_no >= sci_get_line_count(editor->sci))
4703 return FALSE;
4705 if (offset != 0)
4707 gint current_line = sci_get_current_line(editor->sci);
4708 line_no *= offset;
4709 line_no = current_line + line_no;
4712 pos = sci_get_position_from_line(editor->sci, line_no);
4713 return editor_goto_pos(editor, pos, TRUE);
4717 /** Moves to position @a pos, switching to the document if necessary,
4718 * setting a marker if @a mark is set.
4720 * @param editor Editor.
4721 * @param pos The position.
4722 * @param mark Whether to set a mark on the position.
4723 * @return @c TRUE if action has been performed, otherwise @c FALSE.
4725 * @since 0.20
4727 gboolean editor_goto_pos(GeanyEditor *editor, gint pos, gboolean mark)
4729 gint page_num;
4731 g_return_val_if_fail(editor, FALSE);
4732 if (G_UNLIKELY(pos < 0))
4733 return FALSE;
4735 if (mark)
4737 gint line = sci_get_line_from_position(editor->sci, pos);
4739 /* mark the tag with the yellow arrow */
4740 sci_marker_delete_all(editor->sci, 0);
4741 sci_set_marker_at_line(editor->sci, line, 0);
4744 sci_goto_pos(editor->sci, pos, TRUE);
4745 editor->scroll_percent = 0.25F;
4747 /* finally switch to the page */
4748 page_num = gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook), GTK_WIDGET(editor->sci));
4749 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
4751 return TRUE;
4755 static gboolean
4756 on_editor_scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer user_data)
4758 GeanyEditor *editor = user_data;
4760 /* Handle scroll events if Alt is pressed and scroll whole pages instead of a
4761 * few lines only, maybe this could/should be done in Scintilla directly */
4762 if (event->state & GDK_MOD1_MASK)
4764 sci_send_command(editor->sci, (event->direction == GDK_SCROLL_DOWN) ? SCI_PAGEDOWN : SCI_PAGEUP);
4765 return TRUE;
4767 else if (event->state & GDK_SHIFT_MASK)
4769 gint amount = (event->direction == GDK_SCROLL_DOWN) ? 8 : -8;
4771 sci_scroll_columns(editor->sci, amount);
4772 return TRUE;
4775 return FALSE; /* let Scintilla handle all other cases */
4779 static gboolean editor_check_colourise(GeanyEditor *editor)
4781 GeanyDocument *doc = editor->document;
4783 if (!doc->priv->colourise_needed)
4784 return FALSE;
4786 doc->priv->colourise_needed = FALSE;
4787 sci_colourise(editor->sci, 0, -1);
4789 /* now that the current document is colourised, fold points are now accurate,
4790 * so force an update of the current function/tag. */
4791 symbols_get_current_function(NULL, NULL);
4792 ui_update_statusbar(NULL, -1);
4794 return TRUE;
4798 /* We only want to colourise just before drawing, to save startup time and
4799 * prevent unnecessary recolouring other documents after one is saved.
4800 * Really we want a "draw" signal but there doesn't seem to be one (expose is too late,
4801 * and "show" doesn't work). */
4802 static gboolean on_editor_focus_in(GtkWidget *widget, GdkEventFocus *event, gpointer user_data)
4804 GeanyEditor *editor = user_data;
4806 editor_check_colourise(editor);
4807 return FALSE;
4811 static gboolean on_editor_expose_event(GtkWidget *widget, GdkEventExpose *event,
4812 gpointer user_data)
4814 GeanyEditor *editor = user_data;
4816 /* This is just to catch any uncolourised documents being drawn that didn't receive focus
4817 * for some reason, maybe it's not necessary but just in case. */
4818 editor_check_colourise(editor);
4819 return FALSE;
4823 static void setup_sci_keys(ScintillaObject *sci)
4825 /* disable some Scintilla keybindings to be able to redefine them cleanly */
4826 sci_clear_cmdkey(sci, 'A' | (SCMOD_CTRL << 16)); /* select all */
4827 sci_clear_cmdkey(sci, 'D' | (SCMOD_CTRL << 16)); /* duplicate */
4828 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16)); /* line transpose */
4829 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line copy */
4830 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16)); /* line cut */
4831 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line delete */
4832 sci_clear_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line to end delete */
4833 sci_clear_cmdkey(sci, '/' | (SCMOD_CTRL << 16)); /* Previous word part */
4834 sci_clear_cmdkey(sci, '\\' | (SCMOD_CTRL << 16)); /* Next word part */
4835 sci_clear_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16)); /* scroll line up */
4836 sci_clear_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16)); /* scroll line down */
4837 sci_clear_cmdkey(sci, SCK_HOME); /* line start */
4838 sci_clear_cmdkey(sci, SCK_END); /* line end */
4839 sci_clear_cmdkey(sci, SCK_END | (SCMOD_ALT << 16)); /* visual line end */
4841 if (editor_prefs.use_gtk_word_boundaries)
4843 /* use GtkEntry-like word boundaries */
4844 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16), SCI_WORDRIGHTEND);
4845 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_WORDRIGHTENDEXTEND);
4846 sci_assign_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16), SCI_DELWORDRIGHTEND);
4848 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_ALT << 16), SCI_LINESCROLLUP);
4849 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_ALT << 16), SCI_LINESCROLLDOWN);
4850 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16), SCI_PARAUP);
4851 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARAUPEXTEND);
4852 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16), SCI_PARADOWN);
4853 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARADOWNEXTEND);
4855 sci_clear_cmdkey(sci, SCK_BACK | (SCMOD_ALT << 16)); /* clear Alt-Backspace (Undo) */
4859 #include "icons/16x16/classviewer-var.xpm"
4860 #include "icons/16x16/classviewer-method.xpm"
4862 /* Create new editor widget (scintilla).
4863 * @note The @c "sci-notify" signal is connected separately. */
4864 static ScintillaObject *create_new_sci(GeanyEditor *editor)
4866 ScintillaObject *sci;
4868 sci = SCINTILLA(scintilla_new());
4870 gtk_widget_show(GTK_WIDGET(sci));
4872 sci_set_codepage(sci, SC_CP_UTF8);
4873 /*SSM(sci, SCI_SETWRAPSTARTINDENT, 4, 0);*/
4874 /* disable scintilla provided popup menu */
4875 sci_use_popup(sci, FALSE);
4877 setup_sci_keys(sci);
4879 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
4880 sci_set_lines_wrapped(sci, editor_prefs.line_wrapping);
4881 sci_set_scrollbar_mode(sci, editor_prefs.show_scrollbars);
4882 sci_set_caret_policy_x(sci, CARET_JUMPS | CARET_EVEN, 0);
4883 /*sci_set_caret_policy_y(sci, CARET_JUMPS | CARET_EVEN, 0);*/
4884 SSM(sci, SCI_AUTOCSETSEPARATOR, '\n', 0);
4885 SSM(sci, SCI_SETSCROLLWIDTHTRACKING, 1, 0);
4887 /* tag autocompletion images */
4888 SSM(sci, SCI_REGISTERIMAGE, 1, (sptr_t)classviewer_var);
4889 SSM(sci, SCI_REGISTERIMAGE, 2, (sptr_t)classviewer_method);
4891 /* necessary for column mode editing, implemented in Scintilla since 2.0 */
4892 SSM(sci, SCI_SETADDITIONALSELECTIONTYPING, 1, 0);
4894 /* virtual space */
4895 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
4897 /* only connect signals if this is for the document notebook, not split window */
4898 if (editor->sci == NULL)
4900 g_signal_connect(sci, "button-press-event", G_CALLBACK(on_editor_button_press_event), editor);
4901 g_signal_connect(sci, "scroll-event", G_CALLBACK(on_editor_scroll_event), editor);
4902 g_signal_connect(sci, "motion-notify-event", G_CALLBACK(on_motion_event), NULL);
4903 g_signal_connect(sci, "focus-in-event", G_CALLBACK(on_editor_focus_in), editor);
4904 g_signal_connect(sci, "expose-event", G_CALLBACK(on_editor_expose_event), editor);
4906 return sci;
4910 /** Creates a new Scintilla @c GtkWidget based on the settings for @a editor.
4911 * @param editor Editor settings.
4912 * @return The new widget.
4914 * @since 0.15
4916 ScintillaObject *editor_create_widget(GeanyEditor *editor)
4918 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4919 ScintillaObject *old, *sci;
4921 /* temporarily change editor to use the new sci widget */
4922 old = editor->sci;
4923 sci = create_new_sci(editor);
4924 editor->sci = sci;
4926 editor_set_indent(editor, iprefs->type, iprefs->width);
4927 editor_set_font(editor, interface_prefs.editor_font);
4928 editor_apply_update_prefs(editor);
4930 /* if editor already had a widget, restore it */
4931 if (old)
4932 editor->sci = old;
4933 return sci;
4937 GeanyEditor *editor_create(GeanyDocument *doc)
4939 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4940 GeanyEditor *editor = g_new0(GeanyEditor, 1);
4942 editor->document = doc;
4943 doc->editor = editor; /* needed in case some editor functions/callbacks expect it */
4945 editor->auto_indent = (iprefs->auto_indent_mode != GEANY_AUTOINDENT_NONE);
4946 editor->line_wrapping = editor_prefs.line_wrapping;
4947 editor->scroll_percent = -1.0F;
4948 editor->line_breaking = FALSE;
4950 editor->sci = editor_create_widget(editor);
4951 return editor;
4955 /* in case we need to free some fields in future */
4956 void editor_destroy(GeanyEditor *editor)
4958 g_free(editor);
4962 static void on_document_save(GObject *obj, GeanyDocument *doc)
4964 g_return_if_fail(NZV(doc->real_path));
4966 if (utils_str_equal(doc->real_path,
4967 utils_build_path(app->configdir, "snippets.conf", NULL)))
4969 /* reload snippets */
4970 editor_snippets_free();
4971 editor_snippets_init();
4976 gboolean editor_complete_word_part(GeanyEditor *editor)
4978 gchar *entry;
4980 g_return_val_if_fail(editor, FALSE);
4982 if (!SSM(editor->sci, SCI_AUTOCACTIVE, 0, 0))
4983 return FALSE;
4985 entry = sci_get_string(editor->sci, SCI_AUTOCGETCURRENTTEXT, 0);
4987 /* if no word part, complete normally */
4988 if (!check_partial_completion(editor, entry))
4989 SSM(editor->sci, SCI_AUTOCCOMPLETE, 0, 0);
4991 g_free(entry);
4992 return TRUE;
4996 void editor_init(void)
4998 static GeanyIndentPrefs indent_prefs;
5000 memset(&editor_prefs, 0, sizeof(GeanyEditorPrefs));
5001 memset(&indent_prefs, 0, sizeof(GeanyIndentPrefs));
5002 editor_prefs.indentation = &indent_prefs;
5004 /* use g_signal_connect_after() to allow plugins connecting to the signal before the default
5005 * handler (on_editor_notify) is called */
5006 g_signal_connect_after(geany_object, "editor-notify", G_CALLBACK(on_editor_notify), NULL);
5008 ui_add_config_file_menu_item(utils_build_path(app->configdir, "snippets.conf", NULL),
5009 NULL, NULL);
5010 g_signal_connect(geany_object, "document-save", G_CALLBACK(on_document_save), NULL);
5014 /* TODO: Should these be user-defined instead of hard-coded? */
5015 void editor_set_indentation_guides(GeanyEditor *editor)
5017 gint mode;
5018 gint lexer;
5020 g_return_if_fail(editor != NULL);
5022 if (! editor_prefs.show_indent_guide)
5024 sci_set_indentation_guides(editor->sci, SC_IV_NONE);
5025 return;
5028 lexer = sci_get_lexer(editor->sci);
5029 switch (lexer)
5031 /* Lines added/removed are prefixed with +/- characters, so
5032 * those lines will not be shown with any indentation guides.
5033 * It can be distracting that only a few of lines in a diff/patch
5034 * file will show the guides. */
5035 case SCLEX_DIFF:
5036 mode = SC_IV_NONE;
5037 break;
5039 /* These languages use indentation for control blocks; the "look forward" method works
5040 * best here */
5041 case SCLEX_PYTHON:
5042 case SCLEX_HASKELL:
5043 case SCLEX_MAKEFILE:
5044 case SCLEX_ASM:
5045 case SCLEX_SQL:
5046 case SCLEX_PROPERTIES:
5047 case SCLEX_FORTRAN: /* Is this the best option for Fortran? */
5048 case SCLEX_CAML:
5049 mode = SC_IV_LOOKFORWARD;
5050 break;
5052 /* C-like (structured) languages benefit from the "look both" method */
5053 case SCLEX_CPP:
5054 case SCLEX_HTML:
5055 case SCLEX_XML:
5056 case SCLEX_PERL:
5057 case SCLEX_LATEX:
5058 case SCLEX_LUA:
5059 case SCLEX_PASCAL:
5060 case SCLEX_RUBY:
5061 case SCLEX_TCL:
5062 case SCLEX_F77:
5063 case SCLEX_CSS:
5064 case SCLEX_BASH:
5065 case SCLEX_VHDL:
5066 case SCLEX_FREEBASIC:
5067 case SCLEX_D:
5068 case SCLEX_OCTAVE:
5069 mode = SC_IV_LOOKBOTH;
5070 break;
5072 default:
5073 mode = SC_IV_REAL;
5074 break;
5077 sci_set_indentation_guides(editor->sci, mode);
5081 /* Apply just the prefs that can change in the Preferences dialog */
5082 void editor_apply_update_prefs(GeanyEditor *editor)
5084 ScintillaObject *sci;
5086 g_return_if_fail(editor != NULL);
5088 if (main_status.quitting)
5089 return;
5091 sci = editor->sci;
5093 sci_set_mark_long_lines(sci, editor_get_long_line_type(),
5094 editor_get_long_line_column(), editor_prefs.long_line_color);
5096 /* update indent width, tab width */
5097 editor_set_indent(editor, editor->indent_type, editor->indent_width);
5098 sci_set_tab_indents(sci, editor_prefs.use_tab_to_indent);
5100 sci_assign_cmdkey(sci, SCK_HOME | (SCMOD_SHIFT << 16),
5101 editor_prefs.smart_home_key ? SCI_VCHOMEEXTEND : SCI_HOMEEXTEND);
5102 sci_assign_cmdkey(sci, SCK_HOME | ((SCMOD_SHIFT | SCMOD_ALT) << 16),
5103 editor_prefs.smart_home_key ? SCI_VCHOMERECTEXTEND : SCI_HOMERECTEXTEND);
5105 sci_set_autoc_max_height(sci, editor_prefs.symbolcompletion_max_height);
5106 SSM(sci, SCI_AUTOCSETDROPRESTOFWORD, editor_prefs.completion_drops_rest_of_word, 0);
5108 editor_set_indentation_guides(editor);
5110 sci_set_visible_white_spaces(sci, editor_prefs.show_white_space);
5111 sci_set_visible_eols(sci, editor_prefs.show_line_endings);
5112 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
5113 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin, 0);
5115 sci_set_folding_margin_visible(sci, editor_prefs.folding);
5117 /* virtual space */
5118 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
5120 /* (dis)allow scrolling past end of document */
5121 sci_set_scroll_stop_at_last_line(sci, editor_prefs.scroll_stop_at_last_line);
5125 /* This is for tab-indents, space aligns formatted code. Spaces should be preserved. */
5126 static void change_tab_indentation(GeanyEditor *editor, gint line, gboolean increase)
5128 ScintillaObject *sci = editor->sci;
5129 gint pos = sci_get_position_from_line(sci, line);
5131 if (increase)
5133 sci_insert_text(sci, pos, "\t");
5135 else
5137 if (sci_get_char_at(sci, pos) == '\t')
5139 sci_set_selection(sci, pos, pos + 1);
5140 sci_replace_sel(sci, "");
5142 else /* remove spaces only if no tabs */
5144 gint width = sci_get_line_indentation(sci, line);
5146 width -= editor_get_indent_prefs(editor)->width;
5147 sci_set_line_indentation(sci, line, width);
5153 static void editor_change_line_indent(GeanyEditor *editor, gint line, gboolean increase)
5155 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
5156 ScintillaObject *sci = editor->sci;
5158 if (iprefs->type == GEANY_INDENT_TYPE_TABS)
5159 change_tab_indentation(editor, line, increase);
5160 else
5162 gint width = sci_get_line_indentation(sci, line);
5164 width += increase ? iprefs->width : -iprefs->width;
5165 sci_set_line_indentation(sci, line, width);
5170 void editor_indent(GeanyEditor *editor, gboolean increase)
5172 ScintillaObject *sci = editor->sci;
5173 gint start, end;
5174 gint line, lstart, lend;
5176 if (sci_get_lines_selected(sci) <= 1)
5178 line = sci_get_current_line(sci);
5179 editor_change_line_indent(editor, line, increase);
5180 return;
5182 editor_select_lines(editor, FALSE);
5183 start = sci_get_selection_start(sci);
5184 end = sci_get_selection_end(sci);
5185 lstart = sci_get_line_from_position(sci, start);
5186 lend = sci_get_line_from_position(sci, end);
5187 if (end == sci_get_length(sci))
5188 lend++; /* for last line with text on it */
5190 sci_start_undo_action(sci);
5191 for (line = lstart; line < lend; line++)
5193 editor_change_line_indent(editor, line, increase);
5195 sci_end_undo_action(sci);
5197 /* set cursor/selection */
5198 if (lend > lstart)
5200 sci_set_selection_start(sci, start);
5201 end = sci_get_position_from_line(sci, lend);
5202 sci_set_selection_end(sci, end);
5203 editor_select_lines(editor, FALSE);
5205 else
5207 sci_set_current_line(sci, lstart);