Fix snippets keybindings not blocking handled events
[geany-mirror.git] / src / editor.c
blobe80696c8f9ab8c938922ad7f4b5c4b0264a1d3cf
1 /*
2 * editor.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005-2012 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2012 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com>
6 * Copyright 2009-2012 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 along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 /**
24 * @file editor.h
25 * Editor-related functions for @ref GeanyEditor.
26 * Geany uses the Scintilla editing widget, and this file is mostly built around
27 * Scintilla's functionality.
28 * @see sciwrappers.h.
30 /* Callbacks for the Scintilla widget (ScintillaObject).
31 * Most important is the sci-notify callback, handled in on_editor_notification().
32 * This includes auto-indentation, comments, auto-completion, calltips, etc.
33 * Also some general Scintilla-related functions.
36 #ifdef HAVE_CONFIG_H
37 # include "config.h"
38 #endif
40 #include "editor.h"
42 #include "app.h"
43 #include "callbacks.h"
44 #include "dialogs.h"
45 #include "documentprivate.h"
46 #include "filetypesprivate.h"
47 #include "geanyobject.h"
48 #include "highlighting.h"
49 #include "keybindings.h"
50 #include "main.h"
51 #include "prefs.h"
52 #include "projectprivate.h"
53 #include "sciwrappers.h"
54 #include "support.h"
55 #include "symbols.h"
56 #include "templates.h"
57 #include "ui_utils.h"
58 #include "utils.h"
60 #include "SciLexer.h"
62 #include "gtkcompat.h"
64 #include <ctype.h>
65 #include <string.h>
67 #include <gdk/gdkkeysyms.h>
70 /* Note: use sciwrappers.h instead where possible.
71 * Do not use SSM in files unrelated to scintilla. */
72 #define SSM(s, m, w, l) scintilla_send_message(s, m, w, l)
74 static GHashTable *snippet_hash = NULL;
75 static GQueue *snippet_offsets = NULL;
76 static gint snippet_cursor_insert_pos;
77 static GtkAccelGroup *snippet_accel_group = NULL;
78 static gboolean autocomplete_scope_shown = FALSE;
80 static const gchar geany_cursor_marker[] = "__GEANY_CURSOR_MARKER__";
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 void auto_close_chars(ScintillaObject *sci, gint pos, gchar c);
108 static void close_block(GeanyEditor *editor, gint pos);
109 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos);
110 static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen,
111 const gchar *wc, gboolean stem);
112 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent);
113 static const gchar *snippets_find_completion_by_name(const gchar *type, const gchar *name);
114 static void snippets_make_replacements(GeanyEditor *editor, GString *pattern);
115 static gssize replace_cursor_markers(GeanyEditor *editor, GString *pattern);
116 static GeanyFiletype *editor_get_filetype_at_line(GeanyEditor *editor, gint line);
117 static gboolean sci_is_blank_line(ScintillaObject *sci, gint line);
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 gboolean on_snippet_keybinding_activate(gchar *key)
196 GeanyDocument *doc = document_get_current();
197 const gchar *s;
199 if (!doc || !gtk_widget_has_focus(GTK_WIDGET(doc->editor->sci)))
200 return FALSE;
202 s = snippets_find_completion_by_name(doc->file_type->name, key);
203 if (!s) /* allow user to specify keybindings for "special" snippets */
205 GHashTable *specials = g_hash_table_lookup(snippet_hash, "Special");
207 if (G_LIKELY(specials != NULL))
208 s = g_hash_table_lookup(specials, key);
210 if (!s)
212 utils_beep();
213 return FALSE;
216 editor_insert_snippet(doc->editor, sci_get_current_position(doc->editor->sci), s);
217 sci_scroll_caret(doc->editor->sci);
219 return TRUE;
223 static void add_kb(GKeyFile *keyfile, const gchar *group, gchar **keys)
225 gsize i;
227 if (!keys)
228 return;
229 for (i = 0; i < g_strv_length(keys); i++)
231 guint key;
232 GdkModifierType mods;
233 gchar *accel_string = g_key_file_get_value(keyfile, group, keys[i], NULL);
235 gtk_accelerator_parse(accel_string, &key, &mods);
236 g_free(accel_string);
238 if (key == 0 && mods == 0)
240 g_warning("Can not parse accelerator \"%s\" from user snippets.conf", accel_string);
241 continue;
243 gtk_accel_group_connect(snippet_accel_group, key, mods, 0,
244 g_cclosure_new_swap((GCallback)on_snippet_keybinding_activate,
245 g_strdup(keys[i]), (GClosureNotify)g_free));
250 static void load_kb(GKeyFile *sysconfig, GKeyFile *userconfig)
252 const gchar kb_group[] = "Keybindings";
253 gchar **keys = g_key_file_get_keys(userconfig, kb_group, NULL, NULL);
254 gchar **ptr;
256 /* remove overridden keys from system keyfile */
257 foreach_strv(ptr, keys)
258 g_key_file_remove_key(sysconfig, kb_group, *ptr, NULL);
260 add_kb(userconfig, kb_group, keys);
261 g_strfreev(keys);
263 keys = g_key_file_get_keys(sysconfig, kb_group, NULL, NULL);
264 add_kb(sysconfig, kb_group, keys);
265 g_strfreev(keys);
269 void editor_snippets_init(void)
271 gchar *sysconfigfile, *userconfigfile;
272 GKeyFile *sysconfig = g_key_file_new();
273 GKeyFile *userconfig = g_key_file_new();
275 snippet_offsets = g_queue_new();
277 sysconfigfile = g_build_filename(app->datadir, "snippets.conf", NULL);
278 userconfigfile = g_build_filename(app->configdir, "snippets.conf", NULL);
280 /* check for old autocomplete.conf files (backwards compatibility) */
281 if (! g_file_test(userconfigfile, G_FILE_TEST_IS_REGULAR))
282 SETPTR(userconfigfile, g_build_filename(app->configdir, "autocomplete.conf", NULL));
284 /* load the actual config files */
285 g_key_file_load_from_file(sysconfig, sysconfigfile, G_KEY_FILE_NONE, NULL);
286 g_key_file_load_from_file(userconfig, userconfigfile, G_KEY_FILE_NONE, NULL);
288 snippets_load(sysconfig, userconfig);
290 /* setup snippet keybindings */
291 snippet_accel_group = gtk_accel_group_new();
292 gtk_window_add_accel_group(GTK_WINDOW(main_widgets.window), snippet_accel_group);
293 load_kb(sysconfig, userconfig);
295 g_free(sysconfigfile);
296 g_free(userconfigfile);
297 g_key_file_free(sysconfig);
298 g_key_file_free(userconfig);
302 static gboolean on_editor_button_press_event(GtkWidget *widget, GdkEventButton *event,
303 gpointer data)
305 GeanyEditor *editor = data;
306 GeanyDocument *doc = editor->document;
308 /* it's very unlikely we got a 'real' click even on 0, 0, so assume it is a
309 * fake event to show the editor menu triggered by a key event where we want to use the
310 * text cursor position. */
311 if (event->x > 0.0 && event->y > 0.0)
312 editor_info.click_pos = sci_get_position_from_xy(editor->sci,
313 (gint)event->x, (gint)event->y, FALSE);
314 else
315 editor_info.click_pos = sci_get_current_position(editor->sci);
317 if (event->button == 1)
319 guint state = keybindings_get_modifiers(event->state);
321 if (event->type == GDK_BUTTON_PRESS && editor_prefs.disable_dnd)
323 gint ss = sci_get_selection_start(editor->sci);
324 sci_set_selection_end(editor->sci, ss);
326 if (event->type == GDK_BUTTON_PRESS && state == GEANY_PRIMARY_MOD_MASK)
328 sci_set_current_position(editor->sci, editor_info.click_pos, FALSE);
330 editor_find_current_word(editor, editor_info.click_pos,
331 current_word, sizeof current_word, NULL);
332 if (*current_word)
333 return symbols_goto_tag(current_word, TRUE);
334 else
335 keybindings_send_command(GEANY_KEY_GROUP_GOTO, GEANY_KEYS_GOTO_MATCHINGBRACE);
336 return TRUE;
338 return document_check_disk_status(doc, FALSE);
341 /* calls the edit popup menu in the editor */
342 if (event->button == 3)
344 gboolean can_goto;
346 /* ensure the editor widget has the focus after this operation */
347 gtk_widget_grab_focus(widget);
349 editor_find_current_word(editor, editor_info.click_pos,
350 current_word, sizeof current_word, NULL);
352 can_goto = sci_has_selection(editor->sci) || current_word[0] != '\0';
353 ui_update_popup_goto_items(can_goto);
354 ui_update_popup_copy_items(doc);
355 ui_update_insert_include_item(doc, 0);
357 g_signal_emit_by_name(geany_object, "update-editor-menu",
358 current_word, editor_info.click_pos, doc);
360 gtk_menu_popup(GTK_MENU(main_widgets.editor_menu),
361 NULL, NULL, NULL, NULL, event->button, event->time);
363 return TRUE;
365 return FALSE;
369 static gboolean is_style_php(gint style)
371 if ((style >= SCE_HPHP_DEFAULT && style <= SCE_HPHP_OPERATOR) ||
372 style == SCE_HPHP_COMPLEX_VARIABLE)
374 return TRUE;
377 return FALSE;
381 static gint editor_get_long_line_type(void)
383 if (app->project)
384 switch (app->project->priv->long_line_behaviour)
386 case 0: /* marker disabled */
387 return 2;
388 case 1: /* use global settings */
389 break;
390 case 2: /* custom (enabled) */
391 return editor_prefs.long_line_type;
394 if (!editor_prefs.long_line_enabled)
395 return 2;
396 else
397 return editor_prefs.long_line_type;
401 static gint editor_get_long_line_column(void)
403 if (app->project && app->project->priv->long_line_behaviour != 1 /* use global settings */)
404 return app->project->priv->long_line_column;
405 else
406 return editor_prefs.long_line_column;
410 #define get_project_pref(id)\
411 (app->project ? app->project->priv->id : editor_prefs.id)
413 static const GeanyEditorPrefs *
414 get_default_prefs(void)
416 static GeanyEditorPrefs eprefs;
418 eprefs = editor_prefs;
420 /* project overrides */
421 eprefs.indentation = (GeanyIndentPrefs*)editor_get_indent_prefs(NULL);
422 eprefs.long_line_type = editor_get_long_line_type();
423 eprefs.long_line_column = editor_get_long_line_column();
424 eprefs.line_wrapping = get_project_pref(line_wrapping);
425 eprefs.line_break_column = get_project_pref(line_break_column);
426 eprefs.auto_continue_multiline = get_project_pref(auto_continue_multiline);
427 return &eprefs;
431 /* Gets the prefs for the editor.
432 * Prefs can be different according to project or document.
433 * @warning Always get a fresh result instead of keeping a pointer to it if the editor/project
434 * settings may have changed, or if this function has been called for a different editor.
435 * @param editor The editor, or @c NULL to get the default prefs.
436 * @return The prefs. */
437 const GeanyEditorPrefs *editor_get_prefs(GeanyEditor *editor)
439 static GeanyEditorPrefs eprefs;
440 const GeanyEditorPrefs *dprefs = get_default_prefs();
442 /* Return the address of the default prefs to allow returning default and editor
443 * pref pointers without invalidating the contents of either. */
444 if (editor == NULL)
445 return dprefs;
447 eprefs = *dprefs;
448 eprefs.indentation = (GeanyIndentPrefs*)editor_get_indent_prefs(editor);
449 /* add other editor & document overrides as needed */
450 return &eprefs;
454 void editor_toggle_fold(GeanyEditor *editor, gint line, gint modifiers)
456 ScintillaObject *sci;
457 gint header;
459 g_return_if_fail(editor != NULL);
461 sci = editor->sci;
462 /* When collapsing a fold range whose starting line is offscreen,
463 * scroll the starting line to display at the top of the view.
464 * Otherwise it can be confusing when the document scrolls down to hide
465 * the folded lines. */
466 if ((sci_get_fold_level(sci, line) & SC_FOLDLEVELNUMBERMASK) > SC_FOLDLEVELBASE &&
467 !(sci_get_fold_level(sci, line) & SC_FOLDLEVELHEADERFLAG))
469 gint parent = sci_get_fold_parent(sci, line);
470 gint first = sci_get_first_visible_line(sci);
472 parent = SSM(sci, SCI_VISIBLEFROMDOCLINE, parent, 0);
473 if (first > parent)
474 SSM(sci, SCI_SETFIRSTVISIBLELINE, parent, 0);
477 /* find the fold header of the given line in case the one clicked isn't a fold point */
478 if (sci_get_fold_level(sci, line) & SC_FOLDLEVELHEADERFLAG)
479 header = line;
480 else
481 header = sci_get_fold_parent(sci, line);
483 if ((editor_prefs.unfold_all_children && ! (modifiers & SCMOD_SHIFT)) ||
484 (! editor_prefs.unfold_all_children && (modifiers & SCMOD_SHIFT)))
486 SSM(sci, SCI_FOLDCHILDREN, header, SC_FOLDACTION_TOGGLE);
488 else
490 SSM(sci, SCI_FOLDLINE, header, SC_FOLDACTION_TOGGLE);
495 static void on_margin_click(GeanyEditor *editor, SCNotification *nt)
497 /* left click to marker margin marks the line */
498 if (nt->margin == 1)
500 gint line = sci_get_line_from_position(editor->sci, nt->position);
502 /*sci_marker_delete_all(editor->sci, 1);*/
503 sci_toggle_marker_at_line(editor->sci, line, 1); /* toggle the marker */
505 /* left click on the folding margin to toggle folding state of current line */
506 else if (nt->margin == 2 && editor_prefs.folding)
508 gint line = sci_get_line_from_position(editor->sci, nt->position);
509 editor_toggle_fold(editor, line, nt->modifiers);
514 static void on_update_ui(GeanyEditor *editor, G_GNUC_UNUSED SCNotification *nt)
516 ScintillaObject *sci = editor->sci;
517 gint pos = sci_get_current_position(sci);
519 /* since Scintilla 2.24, SCN_UPDATEUI is also sent on scrolling though we don't need to handle
520 * this and so ignore every SCN_UPDATEUI events except for content and selection changes */
521 if (! (nt->updated & SC_UPDATE_CONTENT) && ! (nt->updated & SC_UPDATE_SELECTION))
522 return;
524 /* undo / redo menu update */
525 ui_update_popup_reundo_items(editor->document);
527 /* brace highlighting */
528 editor_highlight_braces(editor, pos);
530 ui_update_statusbar(editor->document, pos);
532 #if 0
533 /** experimental code for inverting selections */
535 gint i;
536 for (i = SSM(sci, SCI_GETSELECTIONSTART, 0, 0); i < SSM(sci, SCI_GETSELECTIONEND, 0, 0); i++)
538 /* need to get colour from getstyleat(), but how? */
539 SSM(sci, SCI_STYLESETFORE, STYLE_DEFAULT, 0);
540 SSM(sci, SCI_STYLESETBACK, STYLE_DEFAULT, 0);
543 sci_get_style_at(sci, pos);
545 #endif
549 static void check_line_breaking(GeanyEditor *editor, gint pos)
551 ScintillaObject *sci = editor->sci;
552 gint line, lstart, col;
553 gchar c;
555 if (!editor->line_breaking)
556 return;
558 col = sci_get_col_from_position(sci, pos);
560 line = sci_get_current_line(sci);
562 lstart = sci_get_position_from_line(sci, line);
564 /* use column instead of position which might be different with multibyte characters */
565 if (col < get_project_pref(line_break_column))
566 return;
568 /* look for the last space before line_break_column */
569 pos = MIN(pos, lstart + get_project_pref(line_break_column));
571 while (pos > lstart)
573 c = sci_get_char_at(sci, --pos);
574 if (c == GDK_space)
576 gint diff, last_pos, last_col;
578 /* remember the distance between the current column and the last column on the line
579 * (we use column position in case the previous line gets altered, such as removing
580 * trailing spaces or in case it contains multibyte characters) */
581 last_pos = sci_get_line_end_position(sci, line);
582 last_col = sci_get_col_from_position(sci, last_pos);
583 diff = last_col - col;
585 /* break the line after the space */
586 sci_set_current_position(sci, pos + 1, FALSE);
587 sci_cancel(sci); /* don't select from completion list */
588 sci_send_command(sci, SCI_NEWLINE);
589 line++;
591 /* correct cursor position (might not be at line end) */
592 last_pos = sci_get_line_end_position(sci, line);
593 last_col = sci_get_col_from_position(sci, last_pos); /* get last column on line */
594 /* last column - distance is the desired column, then retrieve its document position */
595 pos = sci_get_position_from_col(sci, line, last_col - diff);
596 sci_set_current_position(sci, pos, FALSE);
597 sci_scroll_caret(sci);
598 return;
604 static void show_autocomplete(ScintillaObject *sci, gsize rootlen, GString *words)
606 /* hide autocompletion if only option is already typed */
607 if (rootlen >= words->len ||
608 (words->str[rootlen] == '?' && rootlen >= words->len - 2))
610 sci_send_command(sci, SCI_AUTOCCANCEL);
611 return;
613 /* store whether a calltip is showing, so we can reshow it after autocompletion */
614 calltip.set = (gboolean) SSM(sci, SCI_CALLTIPACTIVE, 0, 0);
615 SSM(sci, SCI_AUTOCSHOW, rootlen, (sptr_t) words->str);
619 static void show_tags_list(GeanyEditor *editor, const GPtrArray *tags, gsize rootlen)
621 ScintillaObject *sci = editor->sci;
623 g_return_if_fail(tags);
625 if (tags->len > 0)
627 GString *words = g_string_sized_new(150);
628 guint j;
630 for (j = 0; j < tags->len; ++j)
632 TMTag *tag = tags->pdata[j];
634 if (j > 0)
635 g_string_append_c(words, '\n');
637 if (j == editor_prefs.autocompletion_max_entries)
639 g_string_append(words, "...");
640 break;
642 g_string_append(words, tag->name);
644 /* for now, tag types don't all follow C, so just look at arglist */
645 if (!EMPTY(tag->arglist))
646 g_string_append(words, "?2");
647 else
648 g_string_append(words, "?1");
650 show_autocomplete(sci, rootlen, words);
651 g_string_free(words, TRUE);
656 /* do not use with long strings */
657 static gboolean match_last_chars(ScintillaObject *sci, gint pos, const gchar *str)
659 gsize len = strlen(str);
660 gchar *buf;
662 g_return_val_if_fail(len < 100, FALSE);
664 if ((gint)len > pos)
665 return FALSE;
667 buf = g_alloca(len + 1);
668 sci_get_text_range(sci, pos - len, pos, buf);
669 return strcmp(str, buf) == 0;
673 static gboolean reshow_calltip(gpointer data)
675 GeanyDocument *doc;
677 g_return_val_if_fail(calltip.sci != NULL, FALSE);
679 SSM(calltip.sci, SCI_CALLTIPCANCEL, 0, 0);
680 doc = document_get_current();
682 if (doc && doc->editor->sci == calltip.sci)
684 /* we use the position where the calltip was previously started as SCI_GETCURRENTPOS
685 * may be completely wrong in case the user cancelled the auto completion with the mouse */
686 SSM(calltip.sci, SCI_CALLTIPSHOW, calltip.pos, (sptr_t) calltip.text);
688 return FALSE;
692 static void request_reshowing_calltip(SCNotification *nt)
694 if (calltip.set)
696 /* delay the reshow of the calltip window to make sure it is actually displayed,
697 * without it might be not visible on SCN_AUTOCCANCEL. the priority is set to
698 * low to hopefully make Scintilla's events happen before reshowing since they
699 * seem to re-cancel the calltip on autoc menu hiding too */
700 g_idle_add_full(G_PRIORITY_LOW, reshow_calltip, NULL, NULL);
705 static gboolean autocomplete_scope(GeanyEditor *editor, const gchar *root, gsize rootlen)
707 ScintillaObject *sci = editor->sci;
708 gint pos = sci_get_current_position(editor->sci);
709 gchar typed = sci_get_char_at(sci, pos - 1);
710 gchar brace_char;
711 gchar *name;
712 GeanyFiletype *ft = editor->document->file_type;
713 GPtrArray *tags;
714 gboolean function = FALSE;
715 gboolean member;
716 gboolean scope_sep_typed = FALSE;
717 gboolean ret = FALSE;
718 const gchar *current_scope;
719 const gchar *context_sep = tm_tag_context_separator(ft->lang);
721 if (autocomplete_scope_shown)
723 /* move at the operator position */
724 pos -= rootlen;
726 /* allow for a space between word and operator */
727 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
728 pos--;
730 if (pos > 0)
731 typed = sci_get_char_at(sci, pos - 1);
734 /* make sure to keep in sync with similar checks below */
735 if (match_last_chars(sci, pos, context_sep))
737 pos -= strlen(context_sep);
738 scope_sep_typed = TRUE;
740 else if (typed == '.')
741 pos -= 1;
742 else if ((ft->id == GEANY_FILETYPES_C || ft->id == GEANY_FILETYPES_CPP) &&
743 match_last_chars(sci, pos, "->"))
744 pos -= 2;
745 else if (ft->id == GEANY_FILETYPES_CPP && match_last_chars(sci, pos, "->*"))
746 pos -= 3;
747 else
748 return FALSE;
750 /* allow for a space between word and operator */
751 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
752 pos--;
754 /* if function or array index, skip to matching brace */
755 brace_char = sci_get_char_at(sci, pos - 1);
756 if (pos > 0 && (brace_char == ')' || brace_char == ']'))
758 gint brace_pos = sci_find_matching_brace(sci, pos - 1);
760 if (brace_pos != -1)
762 pos = brace_pos;
763 function = brace_char == ')';
766 /* allow for a space between opening brace and name */
767 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
768 pos--;
771 name = editor_get_word_at_pos(editor, pos, NULL);
772 if (!name)
773 return FALSE;
775 /* check if invoked on member */
776 pos -= strlen(name);
777 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
778 pos--;
779 /* make sure to keep in sync with similar checks above */
780 member = match_last_chars(sci, pos, ".") || match_last_chars(sci, pos, context_sep) ||
781 match_last_chars(sci, pos, "->") || match_last_chars(sci, pos, "->*");
783 if (symbols_get_current_scope(editor->document, &current_scope) == -1)
784 current_scope = "";
785 tags = tm_workspace_find_scope_members(editor->document->tm_file, name, function,
786 member, current_scope, scope_sep_typed);
787 if (tags)
789 GPtrArray *filtered = g_ptr_array_new();
790 TMTag *tag;
791 guint i;
793 foreach_ptr_array(tag, i, tags)
795 if (g_str_has_prefix(tag->name, root))
796 g_ptr_array_add(filtered, tag);
799 if (filtered->len > 0)
801 show_tags_list(editor, filtered, rootlen);
802 ret = TRUE;
805 g_ptr_array_free(tags, TRUE);
806 g_ptr_array_free(filtered, TRUE);
809 g_free(name);
810 return ret;
814 static void on_char_added(GeanyEditor *editor, SCNotification *nt)
816 ScintillaObject *sci = editor->sci;
817 gint pos = sci_get_current_position(sci);
819 switch (nt->ch)
821 case '\r':
822 { /* simple indentation (only for CR format) */
823 if (sci_get_eol_mode(sci) == SC_EOL_CR)
824 on_new_line_added(editor);
825 break;
827 case '\n':
828 { /* simple indentation (for CR/LF and LF format) */
829 on_new_line_added(editor);
830 break;
832 case '>':
833 editor_start_auto_complete(editor, pos, FALSE); /* C/C++ ptr-> scope completion */
834 /* fall through */
835 case '/':
836 { /* close xml-tags */
837 handle_xml(editor, pos, nt->ch);
838 break;
840 case '(':
842 auto_close_chars(sci, pos, nt->ch);
843 /* show calltips */
844 editor_show_calltip(editor, --pos);
845 break;
847 case ')':
848 { /* hide calltips */
849 if (SSM(sci, SCI_CALLTIPACTIVE, 0, 0))
851 SSM(sci, SCI_CALLTIPCANCEL, 0, 0);
853 g_free(calltip.text);
854 calltip.text = NULL;
855 calltip.pos = 0;
856 calltip.sci = NULL;
857 calltip.set = FALSE;
858 break;
860 case '{':
861 case '[':
862 case '"':
863 case '\'':
865 auto_close_chars(sci, pos, nt->ch);
866 break;
868 case '}':
869 { /* closing bracket handling */
870 if (editor->auto_indent)
871 close_block(editor, pos - 1);
872 break;
874 /* scope autocompletion */
875 case '.':
876 case ':': /* C/C++ class:: syntax */
877 /* tag autocompletion */
878 default:
879 #if 0
880 if (! editor_start_auto_complete(editor, pos, FALSE))
881 request_reshowing_calltip(nt);
882 #else
883 editor_start_auto_complete(editor, pos, FALSE);
884 #endif
886 check_line_breaking(editor, pos);
890 /* expand() and fold_changed() are copied from SciTE (thanks) to fix #1923350. */
891 static void expand(ScintillaObject *sci, gint *line, gboolean doExpand,
892 gboolean force, gint visLevels, gint level)
894 gint lineMaxSubord = SSM(sci, SCI_GETLASTCHILD, *line, level & SC_FOLDLEVELNUMBERMASK);
895 gint levelLine = level;
896 (*line)++;
897 while (*line <= lineMaxSubord)
899 if (force)
901 if (visLevels > 0)
902 SSM(sci, SCI_SHOWLINES, *line, *line);
903 else
904 SSM(sci, SCI_HIDELINES, *line, *line);
906 else
908 if (doExpand)
909 SSM(sci, SCI_SHOWLINES, *line, *line);
911 if (levelLine == -1)
912 levelLine = SSM(sci, SCI_GETFOLDLEVEL, *line, 0);
913 if (levelLine & SC_FOLDLEVELHEADERFLAG)
915 if (force)
917 if (visLevels > 1)
918 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
919 else
920 SSM(sci, SCI_SETFOLDEXPANDED, *line, 0);
921 expand(sci, line, doExpand, force, visLevels - 1, -1);
923 else
925 if (doExpand)
927 if (!sci_get_fold_expanded(sci, *line))
928 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
929 expand(sci, line, TRUE, force, visLevels - 1, -1);
931 else
933 expand(sci, line, FALSE, force, visLevels - 1, -1);
937 else
939 (*line)++;
945 static void fold_changed(ScintillaObject *sci, gint line, gint levelNow, gint levelPrev)
947 if (levelNow & SC_FOLDLEVELHEADERFLAG)
949 if (! (levelPrev & SC_FOLDLEVELHEADERFLAG))
951 /* Adding a fold point */
952 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
953 if (!SSM(sci, SCI_GETALLLINESVISIBLE, 0, 0))
954 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
957 else if (levelPrev & SC_FOLDLEVELHEADERFLAG)
959 if (! sci_get_fold_expanded(sci, line))
960 { /* Removing the fold from one that has been contracted so should expand
961 * otherwise lines are left invisible with no way to make them visible */
962 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
963 if (!SSM(sci, SCI_GETALLLINESVISIBLE, 0, 0))
964 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
967 if (! (levelNow & SC_FOLDLEVELWHITEFLAG) &&
968 ((levelPrev & SC_FOLDLEVELNUMBERMASK) > (levelNow & SC_FOLDLEVELNUMBERMASK)))
970 if (!SSM(sci, SCI_GETALLLINESVISIBLE, 0, 0)) {
971 /* See if should still be hidden */
972 gint parentLine = sci_get_fold_parent(sci, line);
973 if (parentLine < 0)
975 SSM(sci, SCI_SHOWLINES, line, line);
977 else if (sci_get_fold_expanded(sci, parentLine) &&
978 sci_get_line_is_visible(sci, parentLine))
980 SSM(sci, SCI_SHOWLINES, line, line);
987 static void ensure_range_visible(ScintillaObject *sci, gint posStart, gint posEnd,
988 gboolean enforcePolicy)
990 gint lineStart = sci_get_line_from_position(sci, MIN(posStart, posEnd));
991 gint lineEnd = sci_get_line_from_position(sci, MAX(posStart, posEnd));
992 gint line;
994 for (line = lineStart; line <= lineEnd; line++)
996 SSM(sci, enforcePolicy ? SCI_ENSUREVISIBLEENFORCEPOLICY : SCI_ENSUREVISIBLE, line, 0);
1001 static void auto_update_margin_width(GeanyEditor *editor)
1003 gint next_linecount = 1;
1004 gint linecount = sci_get_line_count(editor->sci);
1005 GeanyDocument *doc = editor->document;
1007 while (next_linecount <= linecount)
1008 next_linecount *= 10;
1010 if (editor->document->priv->line_count != next_linecount)
1012 doc->priv->line_count = next_linecount;
1013 sci_set_line_numbers(editor->sci, TRUE);
1018 static void partial_complete(ScintillaObject *sci, const gchar *text)
1020 gint pos = sci_get_current_position(sci);
1022 sci_insert_text(sci, pos, text);
1023 sci_set_current_position(sci, pos + strlen(text), TRUE);
1027 /* Complete the next word part from @a entry */
1028 static gboolean check_partial_completion(GeanyEditor *editor, const gchar *entry)
1030 gchar *stem, *ptr, *text = utils_strdupa(entry);
1032 read_current_word(editor, -1, current_word, sizeof current_word, NULL, TRUE);
1033 stem = current_word;
1034 if (strstr(text, stem) != text)
1035 return FALSE; /* shouldn't happen */
1036 if (strlen(text) <= strlen(stem))
1037 return FALSE;
1039 text += strlen(stem); /* skip stem */
1040 ptr = strstr(text + 1, "_");
1041 if (ptr)
1043 ptr[1] = '\0';
1044 partial_complete(editor->sci, text);
1045 return TRUE;
1047 else
1049 /* CamelCase */
1050 foreach_str(ptr, text + 1)
1052 if (!ptr[0])
1053 break;
1054 if (g_ascii_isupper(*ptr) && g_ascii_islower(ptr[1]))
1056 ptr[0] = '\0';
1057 partial_complete(editor->sci, text);
1058 return TRUE;
1062 return FALSE;
1066 /* Callback for the "sci-notify" signal to emit a "editor-notify" signal.
1067 * Plugins can connect to the "editor-notify" signal. */
1068 void editor_sci_notify_cb(G_GNUC_UNUSED GtkWidget *widget, G_GNUC_UNUSED gint scn,
1069 gpointer scnt, gpointer data)
1071 GeanyEditor *editor = data;
1072 gboolean retval;
1074 g_return_if_fail(editor != NULL);
1076 g_signal_emit_by_name(geany_object, "editor-notify", editor, scnt, &retval);
1080 static gboolean on_editor_notify(G_GNUC_UNUSED GObject *object, GeanyEditor *editor,
1081 SCNotification *nt, G_GNUC_UNUSED gpointer data)
1083 ScintillaObject *sci = editor->sci;
1084 GeanyDocument *doc = editor->document;
1086 switch (nt->nmhdr.code)
1088 case SCN_SAVEPOINTLEFT:
1089 document_set_text_changed(doc, TRUE);
1090 break;
1092 case SCN_SAVEPOINTREACHED:
1093 document_set_text_changed(doc, FALSE);
1094 break;
1096 case SCN_MODIFYATTEMPTRO:
1097 utils_beep();
1098 break;
1100 case SCN_MARGINCLICK:
1101 on_margin_click(editor, nt);
1102 break;
1104 case SCN_UPDATEUI:
1105 on_update_ui(editor, nt);
1106 break;
1108 case SCN_PAINTED:
1109 /* Visible lines are only laid out accurately just before painting,
1110 * so we need to only call editor_scroll_to_line here, because the document
1111 * may have line wrapping and folding enabled.
1112 * http://scintilla.sourceforge.net/ScintillaDoc.html#LineWrapping
1113 * This is important e.g. when loading a session and switching pages
1114 * and having the cursor scroll in view. */
1115 /* FIXME: Really we want to do this just before painting, not after it
1116 * as it will cause repainting. */
1117 if (editor->scroll_percent > 0.0F)
1119 editor_scroll_to_line(editor, -1, editor->scroll_percent);
1120 /* disable further scrolling */
1121 editor->scroll_percent = -1.0F;
1123 break;
1125 case SCN_MODIFIED:
1126 if (editor_prefs.show_linenumber_margin && (nt->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT)) && nt->linesAdded)
1128 /* automatically adjust Scintilla's line numbers margin width */
1129 auto_update_margin_width(editor);
1131 if (nt->modificationType & SC_STARTACTION && ! ignore_callback)
1133 /* get notified about undo changes */
1134 document_undo_add(doc, UNDO_SCINTILLA, NULL);
1136 if (editor_prefs.folding && (nt->modificationType & SC_MOD_CHANGEFOLD) != 0)
1138 /* handle special fold cases, e.g. #1923350 */
1139 fold_changed(sci, nt->line, nt->foldLevelNow, nt->foldLevelPrev);
1141 if (nt->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT))
1143 document_update_tag_list_in_idle(doc);
1145 break;
1147 case SCN_CHARADDED:
1148 on_char_added(editor, nt);
1149 break;
1151 case SCN_USERLISTSELECTION:
1152 if (nt->listType == 1)
1154 sci_add_text(sci, nt->text);
1156 break;
1158 case SCN_AUTOCSELECTION:
1159 if (g_str_equal(nt->text, "..."))
1161 sci_cancel(sci);
1162 utils_beep();
1163 break;
1165 /* fall through */
1166 case SCN_AUTOCCANCELLED:
1167 /* now that autocomplete is finishing or was cancelled, reshow calltips
1168 * if they were showing */
1169 autocomplete_scope_shown = FALSE;
1170 request_reshowing_calltip(nt);
1171 break;
1172 case SCN_NEEDSHOWN:
1173 ensure_range_visible(sci, nt->position, nt->position + nt->length, FALSE);
1174 break;
1176 case SCN_URIDROPPED:
1177 if (nt->text != NULL)
1179 document_open_file_list(nt->text, strlen(nt->text));
1181 break;
1183 case SCN_CALLTIPCLICK:
1184 if (nt->position > 0)
1186 switch (nt->position)
1188 case 1: /* up arrow */
1189 if (calltip.tag_index > 0)
1190 calltip.tag_index--;
1191 break;
1193 case 2: calltip.tag_index++; break; /* down arrow */
1195 editor_show_calltip(editor, -1);
1197 break;
1199 case SCN_ZOOM:
1200 /* recalculate line margin width */
1201 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin);
1202 break;
1204 /* we always return FALSE here to let plugins handle the event too */
1205 return FALSE;
1209 /* Note: this is the same as sci_get_tab_width(), but is still useful when you don't have
1210 * a scintilla pointer. */
1211 static gint get_tab_width(const GeanyIndentPrefs *indent_prefs)
1213 if (indent_prefs->type == GEANY_INDENT_TYPE_BOTH)
1214 return indent_prefs->hard_tab_width;
1216 return indent_prefs->width; /* tab width = indent width */
1220 /* Returns a string containing width chars of whitespace, filled with simple space
1221 * characters or with the right number of tab characters, according to the indent prefs.
1222 * (Result is filled with tabs *and* spaces if width isn't a multiple of
1223 * the tab width). */
1224 static gchar *
1225 get_whitespace(const GeanyIndentPrefs *iprefs, gint width)
1227 g_return_val_if_fail(width >= 0, NULL);
1229 if (width == 0)
1230 return g_strdup("");
1232 if (iprefs->type == GEANY_INDENT_TYPE_SPACES)
1234 return g_strnfill(width, ' ');
1236 else
1237 { /* first fill text with tabs and fill the rest with spaces */
1238 const gint tab_width = get_tab_width(iprefs);
1239 gint tabs = width / tab_width;
1240 gint spaces = width % tab_width;
1241 gint len = tabs + spaces;
1242 gchar *str;
1244 str = g_malloc(len + 1);
1246 memset(str, '\t', tabs);
1247 memset(str + tabs, ' ', spaces);
1248 str[len] = '\0';
1249 return str;
1254 static const GeanyIndentPrefs *
1255 get_default_indent_prefs(void)
1257 static GeanyIndentPrefs iprefs;
1259 iprefs = app->project ? *app->project->priv->indentation : *editor_prefs.indentation;
1260 return &iprefs;
1264 /** Gets the indentation prefs for the editor.
1265 * Prefs can be different according to project or document.
1266 * @warning Always get a fresh result instead of keeping a pointer to it if the editor/project
1267 * settings may have changed, or if this function has been called for a different editor.
1268 * @param editor @nullable The editor, or @c NULL to get the default indent prefs.
1269 * @return The indent prefs. */
1270 GEANY_API_SYMBOL
1271 const GeanyIndentPrefs *
1272 editor_get_indent_prefs(GeanyEditor *editor)
1274 static GeanyIndentPrefs iprefs;
1275 const GeanyIndentPrefs *dprefs = get_default_indent_prefs();
1277 /* Return the address of the default prefs to allow returning default and editor
1278 * pref pointers without invalidating the contents of either. */
1279 if (editor == NULL)
1280 return dprefs;
1282 iprefs = *dprefs;
1283 iprefs.type = editor->indent_type;
1284 iprefs.width = editor->indent_width;
1286 /* if per-document auto-indent is enabled, but we don't have a global mode set,
1287 * just use basic auto-indenting */
1288 if (editor->auto_indent && iprefs.auto_indent_mode == GEANY_AUTOINDENT_NONE)
1289 iprefs.auto_indent_mode = GEANY_AUTOINDENT_BASIC;
1291 if (!editor->auto_indent)
1292 iprefs.auto_indent_mode = GEANY_AUTOINDENT_NONE;
1294 return &iprefs;
1298 static void on_new_line_added(GeanyEditor *editor)
1300 ScintillaObject *sci = editor->sci;
1301 gint line = sci_get_current_line(sci);
1303 /* simple indentation */
1304 if (editor->auto_indent)
1306 insert_indent_after_line(editor, line - 1);
1309 if (get_project_pref(auto_continue_multiline))
1310 { /* " * " auto completion in multiline C/C++/D/Java comments */
1311 auto_multiline(editor, line);
1314 if (editor_prefs.newline_strip)
1315 { /* strip the trailing spaces on the previous line */
1316 editor_strip_line_trailing_spaces(editor, line - 1);
1321 static gboolean lexer_has_braces(ScintillaObject *sci)
1323 gint lexer = sci_get_lexer(sci);
1325 switch (lexer)
1327 case SCLEX_CPP:
1328 case SCLEX_D:
1329 case SCLEX_HTML: /* for PHP & JS */
1330 case SCLEX_PHPSCRIPT:
1331 case SCLEX_PASCAL: /* for multiline comments? */
1332 case SCLEX_BASH:
1333 case SCLEX_PERL:
1334 case SCLEX_TCL:
1335 case SCLEX_R:
1336 case SCLEX_RUST:
1337 return TRUE;
1338 default:
1339 return FALSE;
1344 /* Read indent chars for the line that pos is on into indent global variable.
1345 * Note: Use sci_get_line_indentation() and get_whitespace()/editor_insert_text_block()
1346 * instead in any new code. */
1347 static void read_indent(GeanyEditor *editor, gint pos)
1349 ScintillaObject *sci = editor->sci;
1350 guint i, len, j = 0;
1351 gint line;
1352 gchar *linebuf;
1354 line = sci_get_line_from_position(sci, pos);
1356 len = sci_get_line_length(sci, line);
1357 linebuf = sci_get_line(sci, line);
1359 for (i = 0; i < len && j <= (sizeof(indent) - 1); i++)
1361 if (linebuf[i] == ' ' || linebuf[i] == '\t') /* simple indentation */
1362 indent[j++] = linebuf[i];
1363 else
1364 break;
1366 indent[j] = '\0';
1367 g_free(linebuf);
1371 static gint get_brace_indent(ScintillaObject *sci, gint line)
1373 gint start = sci_get_position_from_line(sci, line);
1374 gint end = sci_get_line_end_position(sci, line) - 1;
1375 gint lexer = sci_get_lexer(sci);
1376 gint count = 0;
1377 gint pos;
1379 for (pos = end; pos >= start && count < 1; pos--)
1381 if (highlighting_is_code_style(lexer, sci_get_style_at(sci, pos)))
1383 gchar c = sci_get_char_at(sci, pos);
1385 if (c == '{')
1386 count ++;
1387 else if (c == '}')
1388 count --;
1392 return count > 0 ? 1 : 0;
1396 /* gets the last code position on a line
1397 * warning: if there is no code position on the line, returns the start position */
1398 static gint get_sci_line_code_end_position(ScintillaObject *sci, gint line)
1400 gint start = sci_get_position_from_line(sci, line);
1401 gint lexer = sci_get_lexer(sci);
1402 gint pos;
1404 for (pos = sci_get_line_end_position(sci, line) - 1; pos > start; pos--)
1406 gint style = sci_get_style_at(sci, pos);
1408 if (highlighting_is_code_style(lexer, style) && ! isspace(sci_get_char_at(sci, pos)))
1409 break;
1412 return pos;
1416 static gint get_python_indent(ScintillaObject *sci, gint line)
1418 gint last_char = get_sci_line_code_end_position(sci, line);
1420 /* add extra indentation for Python after colon */
1421 if (sci_get_char_at(sci, last_char) == ':' &&
1422 sci_get_style_at(sci, last_char) == SCE_P_OPERATOR)
1424 return 1;
1426 return 0;
1430 static gint get_xml_indent(ScintillaObject *sci, gint line)
1432 gboolean need_close = FALSE;
1433 gint end = get_sci_line_code_end_position(sci, line);
1434 gint pos;
1436 /* don't indent if there's a closing tag to the right of the cursor */
1437 pos = sci_get_current_position(sci);
1438 if (sci_get_char_at(sci, pos) == '<' &&
1439 sci_get_char_at(sci, pos + 1) == '/')
1440 return 0;
1442 if (sci_get_char_at(sci, end) == '>' &&
1443 sci_get_char_at(sci, end - 1) != '/')
1445 gint style = sci_get_style_at(sci, end);
1447 if (style == SCE_H_TAG || style == SCE_H_TAGUNKNOWN)
1449 gint start = sci_get_position_from_line(sci, line);
1450 gchar *line_contents = sci_get_contents_range(sci, start, end + 1);
1451 gchar *opened_tag_name = utils_find_open_xml_tag(line_contents, end + 1 - start);
1453 if (!EMPTY(opened_tag_name))
1455 need_close = TRUE;
1456 if (sci_get_lexer(sci) == SCLEX_HTML && utils_is_short_html_tag(opened_tag_name))
1457 need_close = FALSE;
1459 g_free(line_contents);
1460 g_free(opened_tag_name);
1464 return need_close ? 1 : 0;
1468 static gint get_indent_size_after_line(GeanyEditor *editor, gint line)
1470 ScintillaObject *sci = editor->sci;
1471 gint size;
1472 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1474 g_return_val_if_fail(line >= 0, 0);
1476 size = sci_get_line_indentation(sci, line);
1478 if (iprefs->auto_indent_mode > GEANY_AUTOINDENT_BASIC)
1480 gint additional_indent = 0;
1482 if (lexer_has_braces(sci))
1483 additional_indent = iprefs->width * get_brace_indent(sci, line);
1484 else if (sci_get_lexer(sci) == SCLEX_PYTHON) /* Python/Cython */
1485 additional_indent = iprefs->width * get_python_indent(sci, line);
1487 /* HTML lexer "has braces" because of PHP and JavaScript. If get_brace_indent() did not
1488 * recommend us to insert additional indent, we are probably not in PHP/JavaScript chunk and
1489 * should make the XML-related check */
1490 if (additional_indent == 0 &&
1491 (sci_get_lexer(sci) == SCLEX_HTML ||
1492 sci_get_lexer(sci) == SCLEX_XML) &&
1493 editor->document->file_type->priv->xml_indent_tags)
1495 size += iprefs->width * get_xml_indent(sci, line);
1498 size += additional_indent;
1500 return size;
1504 static void insert_indent_after_line(GeanyEditor *editor, gint line)
1506 ScintillaObject *sci = editor->sci;
1507 gint line_indent = sci_get_line_indentation(sci, line);
1508 gint size = get_indent_size_after_line(editor, line);
1509 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1510 gchar *text;
1512 if (size == 0)
1513 return;
1515 if (iprefs->type == GEANY_INDENT_TYPE_TABS && size == line_indent)
1517 /* support tab indents, space aligns style - copy last line 'indent' exactly */
1518 gint start = sci_get_position_from_line(sci, line);
1519 gint end = sci_get_line_indent_position(sci, line);
1521 text = sci_get_contents_range(sci, start, end);
1523 else
1525 text = get_whitespace(iprefs, size);
1527 sci_add_text(sci, text);
1528 g_free(text);
1532 static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c)
1534 const gchar *closing_char = NULL;
1535 gint end_pos = -1;
1537 if (utils_isbrace(c, 0))
1538 end_pos = sci_find_matching_brace(sci, pos - 1);
1540 switch (c)
1542 case '(':
1543 if ((editor_prefs.autoclose_chars & GEANY_AC_PARENTHESIS) && end_pos == -1)
1544 closing_char = ")";
1545 break;
1546 case '{':
1547 if ((editor_prefs.autoclose_chars & GEANY_AC_CBRACKET) && end_pos == -1)
1548 closing_char = "}";
1549 break;
1550 case '[':
1551 if ((editor_prefs.autoclose_chars & GEANY_AC_SBRACKET) && end_pos == -1)
1552 closing_char = "]";
1553 break;
1554 case '\'':
1555 if (editor_prefs.autoclose_chars & GEANY_AC_SQUOTE)
1556 closing_char = "'";
1557 break;
1558 case '"':
1559 if (editor_prefs.autoclose_chars & GEANY_AC_DQUOTE)
1560 closing_char = "\"";
1561 break;
1564 if (closing_char != NULL)
1566 sci_add_text(sci, closing_char);
1567 sci_set_current_position(sci, pos, TRUE);
1572 /* Finds a corresponding matching brace to the given pos
1573 * (this is taken from Scintilla Editor.cxx,
1574 * fit to work with close_block) */
1575 static gint brace_match(ScintillaObject *sci, gint pos)
1577 gchar chBrace = sci_get_char_at(sci, pos);
1578 gchar chSeek = utils_brace_opposite(chBrace);
1579 gchar chAtPos;
1580 gint direction = -1;
1581 gint styBrace;
1582 gint depth = 1;
1583 gint styAtPos;
1585 /* Hack: we need the style at @p pos but it isn't computed yet, so force styling
1586 * of this very position */
1587 sci_colourise(sci, pos, pos + 1);
1589 styBrace = sci_get_style_at(sci, pos);
1591 if (utils_is_opening_brace(chBrace, editor_prefs.brace_match_ltgt))
1592 direction = 1;
1594 pos += direction;
1595 while ((pos >= 0) && (pos < sci_get_length(sci)))
1597 chAtPos = sci_get_char_at(sci, pos);
1598 styAtPos = sci_get_style_at(sci, pos);
1600 if ((pos > sci_get_end_styled(sci)) || (styAtPos == styBrace))
1602 if (chAtPos == chBrace)
1603 depth++;
1604 if (chAtPos == chSeek)
1605 depth--;
1606 if (depth == 0)
1607 return pos;
1609 pos += direction;
1611 return -1;
1615 /* Called after typing '}'. */
1616 static void close_block(GeanyEditor *editor, gint pos)
1618 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1619 gint x = 0, cnt = 0;
1620 gint line, line_len;
1621 gchar *line_buf;
1622 ScintillaObject *sci;
1623 gint line_indent, last_indent;
1625 if (iprefs->auto_indent_mode < GEANY_AUTOINDENT_CURRENTCHARS)
1626 return;
1627 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
1629 sci = editor->sci;
1631 if (! lexer_has_braces(sci))
1632 return;
1634 line = sci_get_line_from_position(sci, pos);
1635 line_len = sci_get_line_end_position(sci, line) - sci_get_position_from_line(sci, line);
1637 /* check that the line is empty, to not kill text in the line */
1638 line_buf = sci_get_line(sci, line);
1639 line_buf[line_len] = '\0';
1640 while (x < line_len)
1642 if (isspace(line_buf[x]))
1643 cnt++;
1644 x++;
1646 g_free(line_buf);
1648 if ((line_len - 1) != cnt)
1649 return;
1651 if (iprefs->auto_indent_mode == GEANY_AUTOINDENT_MATCHBRACES)
1653 gint start_brace = brace_match(sci, pos);
1655 if (start_brace >= 0)
1657 gint line_start;
1658 gint brace_line = sci_get_line_from_position(sci, start_brace);
1659 gint size = sci_get_line_indentation(sci, brace_line);
1660 gchar *ind = get_whitespace(iprefs, size);
1661 gchar *text = g_strconcat(ind, "}", NULL);
1663 line_start = sci_get_position_from_line(sci, line);
1664 sci_set_anchor(sci, line_start);
1665 sci_replace_sel(sci, text);
1666 g_free(text);
1667 g_free(ind);
1668 return;
1670 /* fall through - unmatched brace (possibly because of TCL, PHP lexer bugs) */
1673 /* GEANY_AUTOINDENT_CURRENTCHARS */
1674 line_indent = sci_get_line_indentation(sci, line);
1675 last_indent = sci_get_line_indentation(sci, line - 1);
1677 if (line_indent < last_indent)
1678 return;
1679 line_indent -= iprefs->width;
1680 line_indent = MAX(0, line_indent);
1681 sci_set_line_indentation(sci, line, line_indent);
1685 /* checks whether @p c is an ASCII character (e.g. < 0x80) */
1686 #define IS_ASCII(c) (((unsigned char)(c)) < 0x80)
1689 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1690 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1691 * position can be -1, then the current position is used.
1692 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1693 static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen,
1694 const gchar *wc, gboolean stem)
1696 gint line, line_start, startword, endword;
1697 gchar *chunk;
1698 ScintillaObject *sci;
1700 g_return_if_fail(editor != NULL);
1701 sci = editor->sci;
1703 if (pos == -1)
1704 pos = sci_get_current_position(sci);
1706 line = sci_get_line_from_position(sci, pos);
1707 line_start = sci_get_position_from_line(sci, line);
1708 startword = pos - line_start;
1709 endword = pos - line_start;
1711 word[0] = '\0';
1712 chunk = sci_get_line(sci, line);
1714 if (wc == NULL)
1715 wc = GEANY_WORDCHARS;
1717 /* the checks for "c < 0" are to allow any Unicode character which should make the code
1718 * a little bit more Unicode safe, anyway, this allows also any Unicode punctuation,
1719 * TODO: improve this code */
1720 while (startword > 0 && (strchr(wc, chunk[startword - 1]) || ! IS_ASCII(chunk[startword - 1])))
1721 startword--;
1722 if (!stem)
1724 while (chunk[endword] != 0 && (strchr(wc, chunk[endword]) || ! IS_ASCII(chunk[endword])))
1725 endword++;
1728 if (startword != endword)
1730 chunk[endword] = '\0';
1732 g_strlcpy(word, chunk + startword, wordlen); /* ensure null terminated */
1734 else
1735 g_strlcpy(word, "", wordlen);
1737 g_free(chunk);
1741 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1742 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1743 * position can be -1, then the current position is used.
1744 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1745 void editor_find_current_word(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen,
1746 const gchar *wc)
1748 read_current_word(editor, pos, word, wordlen, wc, FALSE);
1752 /* Same as editor_find_current_word() but uses editor's word boundaries to decide what the word
1753 * is. This should be used e.g. to get the word to search for */
1754 void editor_find_current_word_sciwc(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen)
1756 gint start;
1757 gint end;
1759 g_return_if_fail(editor != NULL);
1761 if (pos == -1)
1762 pos = sci_get_current_position(editor->sci);
1764 start = sci_word_start_position(editor->sci, pos, TRUE);
1765 end = sci_word_end_position(editor->sci, pos, TRUE);
1767 if (start == end) /* caret in whitespaces sequence */
1768 *word = 0;
1769 else
1771 if ((guint)(end - start) >= wordlen)
1772 end = start + (wordlen - 1);
1773 sci_get_text_range(editor->sci, start, end, word);
1779 * Finds the word at the position specified by @a pos. If any word is found, it is returned.
1780 * Otherwise NULL is returned.
1781 * Additional wordchars can be specified to define what to consider as a word.
1783 * @param editor The editor to operate on.
1784 * @param pos The position where the word should be read from.
1785 * May be @c -1 to use the current position.
1786 * @param wordchars The wordchars to separate words. wordchars mean all characters to count
1787 * as part of a word. May be @c NULL to use the default wordchars,
1788 * see @ref GEANY_WORDCHARS.
1790 * @return @nullable A newly-allocated string containing the word at the given @a pos or @c NULL.
1791 * Should be freed when no longer needed.
1793 * @since 0.16
1795 GEANY_API_SYMBOL
1796 gchar *editor_get_word_at_pos(GeanyEditor *editor, gint pos, const gchar *wordchars)
1798 static gchar cword[GEANY_MAX_WORD_LENGTH];
1800 g_return_val_if_fail(editor != NULL, FALSE);
1802 read_current_word(editor, pos, cword, sizeof(cword), wordchars, FALSE);
1804 return (*cword == '\0') ? NULL : g_strdup(cword);
1808 /* Read the word up to position @a pos. */
1809 static const gchar *
1810 editor_read_word_stem(GeanyEditor *editor, gint pos, const gchar *wordchars)
1812 static gchar word[GEANY_MAX_WORD_LENGTH];
1814 read_current_word(editor, pos, word, sizeof word, wordchars, TRUE);
1816 return (*word) ? word : NULL;
1820 static gint find_previous_brace(ScintillaObject *sci, gint pos)
1822 gint orig_pos = pos;
1824 while (pos >= 0 && pos > orig_pos - 300)
1826 gchar c = sci_get_char_at(sci, pos);
1827 if (utils_is_opening_brace(c, editor_prefs.brace_match_ltgt))
1828 return pos;
1829 pos--;
1831 return -1;
1835 static gint find_start_bracket(ScintillaObject *sci, gint pos)
1837 gint brackets = 0;
1838 gint orig_pos = pos;
1840 while (pos > 0 && pos > orig_pos - 300)
1842 gchar c = sci_get_char_at(sci, pos);
1844 if (c == ')') brackets++;
1845 else if (c == '(') brackets--;
1846 if (brackets < 0) return pos; /* found start bracket */
1847 pos--;
1849 return -1;
1853 static gboolean append_calltip(GString *str, const TMTag *tag, GeanyFiletypeID ft_id)
1855 if (! tag->arglist)
1856 return FALSE;
1858 if (ft_id != GEANY_FILETYPES_PASCAL && ft_id != GEANY_FILETYPES_GO)
1859 { /* usual calltips: "retval tagname (arglist)" */
1860 if (tag->var_type)
1862 guint i;
1864 g_string_append(str, tag->var_type);
1865 for (i = 0; i < tag->pointerOrder; i++)
1867 g_string_append_c(str, '*');
1869 g_string_append_c(str, ' ');
1871 if (tag->scope)
1873 const gchar *cosep = symbols_get_context_separator(ft_id);
1875 g_string_append(str, tag->scope);
1876 g_string_append(str, cosep);
1878 g_string_append(str, tag->name);
1879 g_string_append_c(str, ' ');
1880 g_string_append(str, tag->arglist);
1882 else
1883 { /* special case Pascal/Go calltips: "tagname (arglist) : retval"
1884 * (with ':' omitted for Go) */
1885 g_string_append(str, tag->name);
1886 g_string_append_c(str, ' ');
1887 g_string_append(str, tag->arglist);
1889 if (!EMPTY(tag->var_type))
1891 g_string_append(str, ft_id == GEANY_FILETYPES_PASCAL ? " : " : " ");
1892 g_string_append(str, tag->var_type);
1896 return TRUE;
1900 static gchar *find_calltip(const gchar *word, GeanyFiletype *ft)
1902 GPtrArray *tags;
1903 const TMTagType arg_types = tm_tag_function_t | tm_tag_prototype_t |
1904 tm_tag_method_t | tm_tag_macro_with_arg_t;
1905 TMTag *tag;
1906 GString *str = NULL;
1907 guint i;
1909 g_return_val_if_fail(ft && word && *word, NULL);
1911 /* use all types in case language uses wrong tag type e.g. python "members" instead of "methods" */
1912 tags = tm_workspace_find(word, NULL, tm_tag_max_t, NULL, ft->lang);
1913 if (tags->len == 0)
1915 g_ptr_array_free(tags, TRUE);
1916 return NULL;
1919 tag = TM_TAG(tags->pdata[0]);
1921 if (ft->id == GEANY_FILETYPES_D &&
1922 (tag->type == tm_tag_class_t || tag->type == tm_tag_struct_t))
1924 g_ptr_array_free(tags, TRUE);
1925 /* user typed e.g. 'new Classname(' so lookup D constructor Classname::this() */
1926 tags = tm_workspace_find("this", tag->name, arg_types, NULL, ft->lang);
1927 if (tags->len == 0)
1929 g_ptr_array_free(tags, TRUE);
1930 return NULL;
1934 /* remove tags with no argument list */
1935 for (i = 0; i < tags->len; i++)
1937 tag = TM_TAG(tags->pdata[i]);
1939 if (! tag->arglist)
1940 tags->pdata[i] = NULL;
1942 tm_tags_prune((GPtrArray *) tags);
1943 if (tags->len == 0)
1945 g_ptr_array_free(tags, TRUE);
1946 return NULL;
1948 else
1949 { /* remove duplicate calltips */
1950 TMTagAttrType sort_attr[] = {tm_tag_attr_name_t, tm_tag_attr_scope_t,
1951 tm_tag_attr_arglist_t, 0};
1953 tm_tags_sort((GPtrArray *) tags, sort_attr, TRUE, FALSE);
1956 /* if the current word has changed since last time, start with the first tag match */
1957 if (! utils_str_equal(word, calltip.last_word))
1958 calltip.tag_index = 0;
1959 /* cache the current word for next time */
1960 g_free(calltip.last_word);
1961 calltip.last_word = g_strdup(word);
1962 calltip.tag_index = MIN(calltip.tag_index, tags->len - 1); /* ensure tag_index is in range */
1964 for (i = calltip.tag_index; i < tags->len; i++)
1966 tag = TM_TAG(tags->pdata[i]);
1968 if (str == NULL)
1970 str = g_string_new(NULL);
1971 if (calltip.tag_index > 0)
1972 g_string_prepend(str, "\001 "); /* up arrow */
1973 append_calltip(str, tag, FILETYPE_ID(ft));
1975 else /* add a down arrow */
1977 if (calltip.tag_index > 0) /* already have an up arrow */
1978 g_string_insert_c(str, 1, '\002');
1979 else
1980 g_string_prepend(str, "\002 ");
1981 break;
1985 g_ptr_array_free(tags, TRUE);
1987 if (str)
1989 gchar *result = str->str;
1991 g_string_free(str, FALSE);
1992 return result;
1994 return NULL;
1998 /* use pos = -1 to search for the previous unmatched open bracket. */
1999 gboolean editor_show_calltip(GeanyEditor *editor, gint pos)
2001 gint orig_pos = pos; /* the position for the calltip */
2002 gint lexer;
2003 gint style;
2004 gchar word[GEANY_MAX_WORD_LENGTH];
2005 gchar *str;
2006 ScintillaObject *sci;
2008 g_return_val_if_fail(editor != NULL, FALSE);
2009 g_return_val_if_fail(editor->document->file_type != NULL, FALSE);
2011 sci = editor->sci;
2013 lexer = sci_get_lexer(sci);
2015 if (pos == -1)
2017 /* position of '(' is unknown, so go backwards from current position to find it */
2018 pos = sci_get_current_position(sci);
2019 pos--;
2020 orig_pos = pos;
2021 pos = (lexer == SCLEX_LATEX) ? find_previous_brace(sci, pos) :
2022 find_start_bracket(sci, pos);
2023 if (pos == -1)
2024 return FALSE;
2027 /* the style 1 before the brace (which may be highlighted) */
2028 style = sci_get_style_at(sci, pos - 1);
2029 if (! highlighting_is_code_style(lexer, style))
2030 return FALSE;
2032 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
2033 pos--;
2035 /* skip possible generic/template specification, like foo<int>() */
2036 if (sci_get_char_at(sci, pos - 1) == '>')
2038 pos = sci_find_matching_brace(sci, pos - 1);
2039 if (pos == -1)
2040 return FALSE;
2042 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
2043 pos--;
2046 word[0] = '\0';
2047 editor_find_current_word(editor, pos - 1, word, sizeof word, NULL);
2048 if (word[0] == '\0')
2049 return FALSE;
2051 str = find_calltip(word, editor->document->file_type);
2052 if (str)
2054 g_free(calltip.text); /* free the old calltip */
2055 calltip.text = str;
2056 calltip.pos = orig_pos;
2057 calltip.sci = sci;
2058 calltip.set = TRUE;
2059 utils_wrap_string(calltip.text, -1);
2060 SSM(sci, SCI_CALLTIPSHOW, orig_pos, (sptr_t) calltip.text);
2061 return TRUE;
2063 return FALSE;
2067 gchar *editor_get_calltip_text(GeanyEditor *editor, const TMTag *tag)
2069 GString *str;
2071 g_return_val_if_fail(editor != NULL, NULL);
2073 str = g_string_new(NULL);
2074 if (append_calltip(str, tag, editor->document->file_type->id))
2075 return g_string_free(str, FALSE);
2076 else
2077 return g_string_free(str, TRUE);
2081 /* Current document & global tags autocompletion */
2082 static gboolean
2083 autocomplete_tags(GeanyEditor *editor, GeanyFiletype *ft, const gchar *root, gsize rootlen)
2085 GPtrArray *tags;
2086 gboolean found;
2088 g_return_val_if_fail(editor, FALSE);
2090 tags = tm_workspace_find_prefix(root, ft->lang, editor_prefs.autocompletion_max_entries);
2091 found = tags->len > 0;
2092 if (found)
2093 show_tags_list(editor, tags, rootlen);
2094 g_ptr_array_free(tags, TRUE);
2096 return found;
2100 static gboolean autocomplete_check_html(GeanyEditor *editor, gint style, gint pos)
2102 GeanyFiletype *ft = editor->document->file_type;
2103 gboolean try = FALSE;
2105 /* use entity completion when style is not JavaScript, ASP, Python, PHP, ...
2106 * (everything after SCE_HJ_START is for embedded scripting languages) */
2107 if (ft->id == GEANY_FILETYPES_HTML && style < SCE_HJ_START)
2108 try = TRUE;
2109 else if (sci_get_lexer(editor->sci) == SCLEX_XML && style < SCE_HJ_START)
2110 try = TRUE;
2111 else if (ft->id == GEANY_FILETYPES_PHP)
2113 /* use entity completion when style is outside of PHP styles */
2114 if (! is_style_php(style))
2115 try = TRUE;
2117 if (try)
2119 gchar root[GEANY_MAX_WORD_LENGTH];
2120 gchar *tmp;
2122 read_current_word(editor, pos, root, sizeof(root), GEANY_WORDCHARS"&", TRUE);
2124 /* Allow something like "&quot;some text&quot;".
2125 * for entity completion we want to have completion for '&' within words. */
2126 tmp = strchr(root, '&');
2127 if (tmp != NULL)
2129 return autocomplete_tags(editor, filetypes_index(GEANY_FILETYPES_HTML), tmp, strlen(tmp));
2132 return FALSE;
2136 /* Algorithm based on based on Scite's StartAutoCompleteWord()
2137 * @returns a sorted list of words matching @p root */
2138 static GSList *get_doc_words(ScintillaObject *sci, gchar *root, gsize rootlen)
2140 gchar *word;
2141 gint len, current, word_end;
2142 gint pos_find, flags;
2143 guint word_length;
2144 gsize nmatches = 0;
2145 GSList *words = NULL;
2146 struct Sci_TextToFind ttf;
2148 len = sci_get_length(sci);
2149 current = sci_get_current_position(sci) - rootlen;
2151 ttf.lpstrText = root;
2152 ttf.chrg.cpMin = 0;
2153 ttf.chrg.cpMax = len;
2154 ttf.chrgText.cpMin = 0;
2155 ttf.chrgText.cpMax = 0;
2156 flags = SCFIND_WORDSTART | SCFIND_MATCHCASE;
2158 /* search the whole document for the word root and collect results */
2159 pos_find = scintilla_send_message(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
2160 while (pos_find >= 0 && pos_find < len)
2162 word_end = pos_find + rootlen;
2163 if (pos_find != current)
2165 word_end = sci_word_end_position(sci, word_end, TRUE);
2167 word_length = word_end - pos_find;
2168 if (word_length > rootlen)
2170 word = sci_get_contents_range(sci, pos_find, word_end);
2171 /* search whether we already have the word in, otherwise add it */
2172 if (g_slist_find_custom(words, word, (GCompareFunc)strcmp) != NULL)
2173 g_free(word);
2174 else
2176 words = g_slist_prepend(words, word);
2177 nmatches++;
2180 if (nmatches == editor_prefs.autocompletion_max_entries)
2181 break;
2184 ttf.chrg.cpMin = word_end;
2185 pos_find = scintilla_send_message(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
2188 return g_slist_sort(words, (GCompareFunc)utils_str_casecmp);
2192 static gboolean autocomplete_doc_word(GeanyEditor *editor, gchar *root, gsize rootlen)
2194 ScintillaObject *sci = editor->sci;
2195 GSList *words, *node;
2196 GString *str;
2197 guint n_words = 0;
2199 words = get_doc_words(sci, root, rootlen);
2200 if (!words)
2202 scintilla_send_message(sci, SCI_AUTOCCANCEL, 0, 0);
2203 return FALSE;
2206 str = g_string_sized_new(rootlen * 2 * 10);
2207 foreach_slist(node, words)
2209 g_string_append(str, node->data);
2210 g_free(node->data);
2211 if (node->next)
2212 g_string_append_c(str, '\n');
2213 n_words++;
2215 if (n_words >= editor_prefs.autocompletion_max_entries)
2216 g_string_append(str, "\n...");
2218 g_slist_free(words);
2220 show_autocomplete(sci, rootlen, str);
2221 g_string_free(str, TRUE);
2222 return TRUE;
2226 gboolean editor_start_auto_complete(GeanyEditor *editor, gint pos, gboolean force)
2228 gint rootlen, lexer, style;
2229 gchar *root;
2230 gchar cword[GEANY_MAX_WORD_LENGTH];
2231 ScintillaObject *sci;
2232 gboolean ret = FALSE;
2233 const gchar *wordchars;
2234 GeanyFiletype *ft;
2236 g_return_val_if_fail(editor != NULL, FALSE);
2238 if (! editor_prefs.auto_complete_symbols && ! force)
2239 return FALSE;
2241 /* If we are at the beginning of the document, we skip autocompletion as we can't determine the
2242 * necessary styling information */
2243 if (G_UNLIKELY(pos < 2))
2244 return FALSE;
2246 sci = editor->sci;
2247 ft = editor->document->file_type;
2249 lexer = sci_get_lexer(sci);
2250 style = sci_get_style_at(sci, pos - 2);
2252 /* don't autocomplete in comments and strings */
2253 if (!force && !highlighting_is_code_style(lexer, style))
2254 return FALSE;
2256 ret = autocomplete_check_html(editor, style, pos);
2258 if (ft->id == GEANY_FILETYPES_LATEX)
2259 wordchars = GEANY_WORDCHARS"\\"; /* add \ to word chars if we are in a LaTeX file */
2260 else if (ft->id == GEANY_FILETYPES_CSS)
2261 wordchars = GEANY_WORDCHARS"-"; /* add - because they are part of property names */
2262 else
2263 wordchars = GEANY_WORDCHARS;
2265 read_current_word(editor, pos, cword, sizeof(cword), wordchars, TRUE);
2266 root = cword;
2267 rootlen = strlen(root);
2269 if (ret || force)
2271 if (autocomplete_scope_shown)
2273 autocomplete_scope_shown = FALSE;
2274 if (!ret)
2275 sci_send_command(sci, SCI_AUTOCCANCEL);
2278 else
2280 ret = autocomplete_scope(editor, root, rootlen);
2281 if (!ret && autocomplete_scope_shown)
2282 sci_send_command(sci, SCI_AUTOCCANCEL);
2283 autocomplete_scope_shown = ret;
2286 if (!ret && rootlen > 0)
2288 if (ft->id == GEANY_FILETYPES_PHP && style == SCE_HPHP_DEFAULT &&
2289 rootlen == 3 && strcmp(root, "php") == 0 && pos >= 5 &&
2290 sci_get_char_at(sci, pos - 5) == '<' &&
2291 sci_get_char_at(sci, pos - 4) == '?')
2293 /* nothing, don't complete PHP open tags */
2295 else
2297 /* force is set when called by keyboard shortcut, otherwise start at the
2298 * editor_prefs.symbolcompletion_min_chars'th char */
2299 if (force || rootlen >= editor_prefs.symbolcompletion_min_chars)
2301 /* complete tags, except if forcing when completion is already visible */
2302 if (!(force && SSM(sci, SCI_AUTOCACTIVE, 0, 0)))
2303 ret = autocomplete_tags(editor, editor->document->file_type, root, rootlen);
2305 /* If forcing and there's nothing else to show, complete from words in document */
2306 if (!ret && (force || editor_prefs.autocomplete_doc_words))
2307 ret = autocomplete_doc_word(editor, root, rootlen);
2311 if (!ret && force)
2312 utils_beep();
2314 return ret;
2318 static const gchar *snippets_find_completion_by_name(const gchar *type, const gchar *name)
2320 gchar *result = NULL;
2321 GHashTable *tmp;
2323 g_return_val_if_fail(type != NULL && name != NULL, NULL);
2325 tmp = g_hash_table_lookup(snippet_hash, type);
2326 if (tmp != NULL)
2328 result = g_hash_table_lookup(tmp, name);
2330 /* whether nothing is set for the current filetype(tmp is NULL) or
2331 * the particular completion for this filetype is not set (result is NULL) */
2332 if (tmp == NULL || result == NULL)
2334 tmp = g_hash_table_lookup(snippet_hash, "Default");
2335 if (tmp != NULL)
2337 result = g_hash_table_lookup(tmp, name);
2340 /* if result is still NULL here, no completion could be found */
2342 /* result is owned by the hash table and will be freed when the table will destroyed */
2343 return result;
2347 static void snippets_replace_specials(gpointer key, gpointer value, gpointer user_data)
2349 gchar *needle;
2350 GString *pattern = user_data;
2352 g_return_if_fail(key != NULL);
2353 g_return_if_fail(value != NULL);
2355 needle = g_strconcat("%", (gchar*) key, "%", NULL);
2357 utils_string_replace_all(pattern, needle, (gchar*) value);
2358 g_free(needle);
2362 static void fix_indentation(GeanyEditor *editor, GString *buf)
2364 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
2365 gchar *whitespace;
2366 GRegex *regex;
2367 gint cflags = G_REGEX_MULTILINE;
2369 /* transform leading tabs into indent widths (in spaces) */
2370 whitespace = g_strnfill(iprefs->width, ' ');
2371 regex = g_regex_new("^ *(\t)", cflags, 0, NULL);
2372 while (utils_string_regex_replace_all(buf, regex, 1, whitespace, TRUE));
2373 g_regex_unref(regex);
2375 /* remaining tabs are for alignment */
2376 if (iprefs->type != GEANY_INDENT_TYPE_TABS)
2377 utils_string_replace_all(buf, "\t", whitespace);
2379 /* use leading tabs */
2380 if (iprefs->type != GEANY_INDENT_TYPE_SPACES)
2382 gchar *str;
2384 /* for tabs+spaces mode we want the real tab width, not indent width */
2385 SETPTR(whitespace, g_strnfill(sci_get_tab_width(editor->sci), ' '));
2386 str = g_strdup_printf("^\t*(%s)", whitespace);
2388 regex = g_regex_new(str, cflags, 0, NULL);
2389 while (utils_string_regex_replace_all(buf, regex, 1, "\t", TRUE));
2390 g_regex_unref(regex);
2391 g_free(str);
2393 g_free(whitespace);
2397 /** Inserts text, replacing \\t tab chars (@c 0x9) and \\n newline chars (@c 0xA)
2398 * accordingly for the document.
2399 * - Leading tabs are replaced with the correct indentation.
2400 * - Non-leading tabs are replaced with spaces (except when using 'Tabs' indent type).
2401 * - Newline chars are replaced with the correct line ending string.
2402 * This is very useful for inserting code without having to handle the indent
2403 * type yourself (Tabs & Spaces mode can be tricky).
2404 * @param editor Editor.
2405 * @param text Intended as e.g. @c "if (foo)\n\tbar();".
2406 * @param insert_pos Document position to insert text at.
2407 * @param cursor_index If >= 0, the index into @a text to place the cursor.
2408 * @param newline_indent_size Indentation size (in spaces) to insert for each newline; use
2409 * -1 to read the indent size from the line with @a insert_pos on it.
2410 * @param replace_newlines Whether to replace newlines. If
2411 * newlines have been replaced already, this should be false, to avoid errors e.g. on Windows.
2412 * @warning Make sure all \\t tab chars in @a text are intended as indent widths or alignment,
2413 * not hard tabs, as those won't be preserved.
2414 * @note This doesn't scroll the cursor in view afterwards. **/
2415 GEANY_API_SYMBOL
2416 void editor_insert_text_block(GeanyEditor *editor, const gchar *text, gint insert_pos,
2417 gint cursor_index, gint newline_indent_size, gboolean replace_newlines)
2419 ScintillaObject *sci = editor->sci;
2420 gint line_start = sci_get_line_from_position(sci, insert_pos);
2421 GString *buf;
2422 const gchar *eol = editor_get_eol_char(editor);
2423 gint idx;
2425 g_return_if_fail(text);
2426 g_return_if_fail(editor != NULL);
2427 g_return_if_fail(insert_pos >= 0);
2429 buf = g_string_new(text);
2431 if (cursor_index >= 0)
2432 g_string_insert(buf, cursor_index, geany_cursor_marker); /* remember cursor pos */
2434 if (newline_indent_size == -1)
2436 /* count indent size up to insert_pos instead of asking sci
2437 * because there may be spaces after it */
2438 gchar *tmp = sci_get_line(sci, line_start);
2440 idx = insert_pos - sci_get_position_from_line(sci, line_start);
2441 tmp[idx] = '\0';
2442 newline_indent_size = count_indent_size(editor, tmp);
2443 g_free(tmp);
2446 /* Add line indents (in spaces) */
2447 if (newline_indent_size > 0)
2449 const gchar *nl = replace_newlines ? "\n" : eol;
2450 gchar *whitespace;
2452 whitespace = g_strnfill(newline_indent_size, ' ');
2453 SETPTR(whitespace, g_strconcat(nl, whitespace, NULL));
2454 utils_string_replace_all(buf, nl, whitespace);
2455 g_free(whitespace);
2458 /* transform line endings */
2459 if (replace_newlines)
2460 utils_string_replace_all(buf, "\n", eol);
2462 fix_indentation(editor, buf);
2464 idx = replace_cursor_markers(editor, buf);
2465 if (idx >= 0)
2467 sci_insert_text(sci, insert_pos, buf->str);
2468 sci_set_current_position(sci, insert_pos + idx, FALSE);
2470 else
2471 sci_insert_text(sci, insert_pos, buf->str);
2473 snippet_cursor_insert_pos = sci_get_current_position(sci);
2475 g_string_free(buf, TRUE);
2479 /* Move the cursor to the next specified cursor position in an inserted snippet.
2480 * Can, and should, be optimized to give better results */
2481 void editor_goto_next_snippet_cursor(GeanyEditor *editor)
2483 ScintillaObject *sci = editor->sci;
2484 gint current_pos = sci_get_current_position(sci);
2486 if (snippet_offsets && !g_queue_is_empty(snippet_offsets))
2488 gint offset;
2490 offset = GPOINTER_TO_INT(g_queue_pop_head(snippet_offsets));
2491 if (current_pos > snippet_cursor_insert_pos)
2492 snippet_cursor_insert_pos = offset + current_pos;
2493 else
2494 snippet_cursor_insert_pos += offset;
2496 sci_set_current_position(sci, snippet_cursor_insert_pos, TRUE);
2498 else
2500 utils_beep();
2505 static void snippets_make_replacements(GeanyEditor *editor, GString *pattern)
2507 GHashTable *specials;
2509 /* replace 'special' completions */
2510 specials = g_hash_table_lookup(snippet_hash, "Special");
2511 if (G_LIKELY(specials != NULL))
2513 g_hash_table_foreach(specials, snippets_replace_specials, pattern);
2516 /* now transform other wildcards */
2517 utils_string_replace_all(pattern, "%newline%", "\n");
2518 utils_string_replace_all(pattern, "%ws%", "\t");
2520 /* replace %cursor% by a very unlikely string marker */
2521 utils_string_replace_all(pattern, "%cursor%", geany_cursor_marker);
2523 /* unescape '%' after all %wildcards% */
2524 templates_replace_valist(pattern, "{pc}", "%", NULL);
2526 /* replace any template {foo} wildcards */
2527 templates_replace_common(pattern, editor->document->file_name, editor->document->file_type, NULL);
2531 static gssize replace_cursor_markers(GeanyEditor *editor, GString *pattern)
2533 gssize cur_index = -1;
2534 gint i;
2535 GList *temp_list = NULL;
2536 gint cursor_steps = 0, old_cursor = 0;
2538 i = 0;
2539 while (1)
2541 cursor_steps = utils_string_find(pattern, cursor_steps, -1, geany_cursor_marker);
2542 if (cursor_steps == -1)
2543 break;
2545 g_string_erase(pattern, cursor_steps, strlen(geany_cursor_marker));
2547 if (i++ > 0)
2549 /* save the relative offset to each cursor position */
2550 temp_list = g_list_prepend(temp_list, GINT_TO_POINTER(cursor_steps - old_cursor));
2552 else
2554 /* first cursor already includes newline positions */
2555 cur_index = cursor_steps;
2557 old_cursor = cursor_steps;
2560 /* put the cursor positions for the most recent
2561 * parsed snippet first, followed by any remaining positions */
2562 i = 0;
2563 if (temp_list)
2565 GList *node;
2567 temp_list = g_list_reverse(temp_list);
2568 foreach_list(node, temp_list)
2569 g_queue_push_nth(snippet_offsets, node->data, i++);
2571 /* limit length of queue */
2572 while (g_queue_get_length(snippet_offsets) > 20)
2573 g_queue_pop_tail(snippet_offsets);
2575 g_list_free(temp_list);
2577 /* if there's no first cursor, skip whole snippet */
2578 if (cur_index < 0)
2579 cur_index = pattern->len;
2581 return cur_index;
2585 static gboolean snippets_complete_constructs(GeanyEditor *editor, gint pos, const gchar *word)
2587 ScintillaObject *sci = editor->sci;
2588 gchar *str;
2589 const gchar *completion;
2590 gint str_len;
2591 gint ft_id = editor->document->file_type->id;
2593 str = g_strdup(word);
2594 g_strstrip(str);
2596 completion = snippets_find_completion_by_name(filetypes[ft_id]->name, str);
2597 if (completion == NULL)
2599 g_free(str);
2600 return FALSE;
2603 /* remove the typed word, it will be added again by the used auto completion
2604 * (not really necessary but this makes the auto completion more flexible,
2605 * e.g. with a completion like hi=hello, so typing "hi<TAB>" will result in "hello") */
2606 str_len = strlen(str);
2607 sci_set_selection_start(sci, pos - str_len);
2608 sci_set_selection_end(sci, pos);
2609 sci_replace_sel(sci, "");
2610 pos -= str_len; /* pos has changed while deleting */
2612 editor_insert_snippet(editor, pos, completion);
2613 sci_scroll_caret(sci);
2615 g_free(str);
2616 return TRUE;
2620 static gboolean at_eol(ScintillaObject *sci, gint pos)
2622 gint line = sci_get_line_from_position(sci, pos);
2623 gchar c;
2625 /* skip any trailing spaces */
2626 while (TRUE)
2628 c = sci_get_char_at(sci, pos);
2629 if (c == ' ' || c == '\t')
2630 pos++;
2631 else
2632 break;
2635 return (pos == sci_get_line_end_position(sci, line));
2639 gboolean editor_complete_snippet(GeanyEditor *editor, gint pos)
2641 gboolean result = FALSE;
2642 const gchar *wc;
2643 const gchar *word;
2644 ScintillaObject *sci;
2646 g_return_val_if_fail(editor != NULL, FALSE);
2648 sci = editor->sci;
2649 if (sci_has_selection(sci))
2650 return FALSE;
2651 /* return if we are editing an existing line (chars on right of cursor) */
2652 if (keybindings_lookup_item(GEANY_KEY_GROUP_EDITOR,
2653 GEANY_KEYS_EDITOR_COMPLETESNIPPET)->key == GDK_space &&
2654 ! editor_prefs.complete_snippets_whilst_editing && ! at_eol(sci, pos))
2655 return FALSE;
2657 wc = snippets_find_completion_by_name("Special", "wordchars");
2658 word = editor_read_word_stem(editor, pos, wc);
2660 /* prevent completion of "for " */
2661 if (!EMPTY(word) &&
2662 ! isspace(sci_get_char_at(sci, pos - 1))) /* pos points to the line end char so use pos -1 */
2664 sci_start_undo_action(sci); /* needed because we insert a space separately from construct */
2665 result = snippets_complete_constructs(editor, pos, word);
2666 sci_end_undo_action(sci);
2667 if (result)
2668 sci_cancel(sci); /* cancel any autocompletion list, etc */
2670 return result;
2674 static void insert_closing_tag(GeanyEditor *editor, gint pos, gchar ch, const gchar *tag_name)
2676 ScintillaObject *sci = editor->sci;
2677 gchar *to_insert = NULL;
2679 if (ch == '/')
2681 const gchar *gt = ">";
2682 /* if there is already a '>' behind the cursor, don't add it */
2683 if (sci_get_char_at(sci, pos) == '>')
2684 gt = "";
2686 to_insert = g_strconcat(tag_name, gt, NULL);
2688 else
2689 to_insert = g_strconcat("</", tag_name, ">", NULL);
2691 sci_start_undo_action(sci);
2692 sci_replace_sel(sci, to_insert);
2693 if (ch == '>')
2694 sci_set_selection(sci, pos, pos);
2695 sci_end_undo_action(sci);
2696 g_free(to_insert);
2701 * (stolen from anjuta and heavily modified)
2702 * This routine will auto complete XML or HTML tags that are still open by closing them
2703 * @param ch The character we are dealing with, currently only works with the '>' character
2704 * @return True if handled, false otherwise
2706 static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch)
2708 ScintillaObject *sci = editor->sci;
2709 gint lexer = sci_get_lexer(sci);
2710 gint min, size, style;
2711 gchar *str_found, sel[512];
2712 gboolean result = FALSE;
2714 /* If the user has turned us off, quit now.
2715 * This may make sense only in certain languages */
2716 if (! editor_prefs.auto_close_xml_tags || (lexer != SCLEX_HTML && lexer != SCLEX_XML))
2717 return FALSE;
2719 /* return if we are inside any embedded script */
2720 style = sci_get_style_at(sci, pos);
2721 if (style > SCE_H_XCCOMMENT && ! highlighting_is_string_style(lexer, style))
2722 return FALSE;
2724 /* if ch is /, check for </, else quit */
2725 if (ch == '/' && sci_get_char_at(sci, pos - 2) != '<')
2726 return FALSE;
2728 /* Grab the last 512 characters or so */
2729 min = pos - (sizeof(sel) - 1);
2730 if (min < 0) min = 0;
2732 if (pos - min < 3)
2733 return FALSE; /* Smallest tag is 3 characters e.g. <p> */
2735 sci_get_text_range(sci, min, pos, sel);
2736 sel[sizeof(sel) - 1] = '\0';
2738 if (ch == '>' && sel[pos - min - 2] == '/')
2739 /* User typed something like "<br/>" */
2740 return FALSE;
2742 size = pos - min;
2743 if (ch == '/')
2744 size -= 2; /* skip </ */
2745 str_found = utils_find_open_xml_tag(sel, size);
2747 if (lexer == SCLEX_HTML && utils_is_short_html_tag(str_found))
2749 /* ignore tag */
2751 else if (!EMPTY(str_found))
2753 insert_closing_tag(editor, pos, ch, str_found);
2754 result = TRUE;
2756 g_free(str_found);
2757 return result;
2761 /* like sci_get_line_indentation(), but for a string. */
2762 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent)
2764 const gchar *ptr;
2765 gsize tab_size = sci_get_tab_width(editor->sci);
2766 gsize count = 0;
2768 g_return_val_if_fail(base_indent, 0);
2770 for (ptr = base_indent; *ptr != 0; ptr++)
2772 switch (*ptr)
2774 case ' ':
2775 count++;
2776 break;
2777 case '\t':
2778 count += tab_size;
2779 break;
2780 default:
2781 return count;
2784 return count;
2788 /* Handles special cases where HTML is embedded in another language or
2789 * another language is embedded in HTML */
2790 static GeanyFiletype *editor_get_filetype_at_line(GeanyEditor *editor, gint line)
2792 gint style, line_start;
2793 GeanyFiletype *current_ft;
2795 g_return_val_if_fail(editor != NULL, NULL);
2796 g_return_val_if_fail(editor->document->file_type != NULL, NULL);
2798 current_ft = editor->document->file_type;
2799 line_start = sci_get_position_from_line(editor->sci, line);
2800 style = sci_get_style_at(editor->sci, line_start);
2802 /* Handle PHP filetype with embedded HTML */
2803 if (current_ft->id == GEANY_FILETYPES_PHP && ! is_style_php(style))
2804 current_ft = filetypes[GEANY_FILETYPES_HTML];
2806 /* Handle languages embedded in HTML */
2807 if (current_ft->id == GEANY_FILETYPES_HTML)
2809 /* Embedded JS */
2810 if (style >= SCE_HJ_DEFAULT && style <= SCE_HJ_REGEX)
2811 current_ft = filetypes[GEANY_FILETYPES_JS];
2812 /* ASP JS */
2813 else if (style >= SCE_HJA_DEFAULT && style <= SCE_HJA_REGEX)
2814 current_ft = filetypes[GEANY_FILETYPES_JS];
2815 /* Embedded VB */
2816 else if (style >= SCE_HB_DEFAULT && style <= SCE_HB_STRINGEOL)
2817 current_ft = filetypes[GEANY_FILETYPES_BASIC];
2818 /* ASP VB */
2819 else if (style >= SCE_HBA_DEFAULT && style <= SCE_HBA_STRINGEOL)
2820 current_ft = filetypes[GEANY_FILETYPES_BASIC];
2821 /* Embedded Python */
2822 else if (style >= SCE_HP_DEFAULT && style <= SCE_HP_IDENTIFIER)
2823 current_ft = filetypes[GEANY_FILETYPES_PYTHON];
2824 /* ASP Python */
2825 else if (style >= SCE_HPA_DEFAULT && style <= SCE_HPA_IDENTIFIER)
2826 current_ft = filetypes[GEANY_FILETYPES_PYTHON];
2827 /* Embedded PHP */
2828 else if ((style >= SCE_HPHP_DEFAULT && style <= SCE_HPHP_OPERATOR) ||
2829 style == SCE_HPHP_COMPLEX_VARIABLE)
2831 current_ft = filetypes[GEANY_FILETYPES_PHP];
2835 /* Ensure the filetype's config is loaded */
2836 filetypes_load_config(current_ft->id, FALSE);
2838 return current_ft;
2842 static void real_comment_multiline(GeanyEditor *editor, gint line_start, gint last_line)
2844 const gchar *eol;
2845 gchar *str_begin, *str_end;
2846 const gchar *co, *cc;
2847 gint line_len;
2848 GeanyFiletype *ft;
2850 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2852 ft = editor_get_filetype_at_line(editor, line_start);
2854 eol = editor_get_eol_char(editor);
2855 if (! filetype_get_comment_open_close(ft, FALSE, &co, &cc))
2856 g_return_if_reached();
2857 str_begin = g_strdup_printf("%s%s", (co != NULL) ? co : "", eol);
2858 str_end = g_strdup_printf("%s%s", (cc != NULL) ? cc : "", eol);
2860 /* insert the comment strings */
2861 sci_insert_text(editor->sci, line_start, str_begin);
2862 line_len = sci_get_position_from_line(editor->sci, last_line + 2);
2863 sci_insert_text(editor->sci, line_len, str_end);
2865 g_free(str_begin);
2866 g_free(str_end);
2870 /* find @p text inside the range of the current style */
2871 static gint find_in_current_style(ScintillaObject *sci, const gchar *text, gboolean backwards)
2873 gint start = sci_get_current_position(sci);
2874 gint end = start;
2875 gint len = sci_get_length(sci);
2876 gint current_style = sci_get_style_at(sci, start);
2877 struct Sci_TextToFind ttf;
2879 while (start > 0 && sci_get_style_at(sci, start - 1) == current_style)
2880 start -= 1;
2881 while (end < len && sci_get_style_at(sci, end + 1) == current_style)
2882 end += 1;
2884 ttf.lpstrText = (gchar*) text;
2885 ttf.chrg.cpMin = backwards ? end + 1 : start;
2886 ttf.chrg.cpMax = backwards ? start : end + 1;
2887 return sci_find_text(sci, 0, &ttf);
2891 static void sci_delete_line(ScintillaObject *sci, gint line)
2893 gint start = sci_get_position_from_line(sci, line);
2894 gint len = sci_get_line_length(sci, line);
2895 SSM(sci, SCI_DELETERANGE, start, len);
2899 static gboolean real_uncomment_multiline(GeanyEditor *editor)
2901 /* find the beginning of the multi line comment */
2902 gint start, end, start_line, end_line;
2903 GeanyFiletype *ft;
2904 const gchar *co, *cc;
2906 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, FALSE);
2908 ft = editor_get_filetype_at_line(editor, sci_get_current_line(editor->sci));
2909 if (! filetype_get_comment_open_close(ft, FALSE, &co, &cc))
2910 g_return_val_if_reached(FALSE);
2912 start = find_in_current_style(editor->sci, co, TRUE);
2913 end = find_in_current_style(editor->sci, cc, FALSE);
2915 if (start < 0 || end < 0 || start > end /* who knows */)
2916 return FALSE;
2918 start_line = sci_get_line_from_position(editor->sci, start);
2919 end_line = sci_get_line_from_position(editor->sci, end);
2921 /* remove comment close chars */
2922 SSM(editor->sci, SCI_DELETERANGE, end, strlen(cc));
2923 if (sci_is_blank_line(editor->sci, end_line))
2924 sci_delete_line(editor->sci, end_line);
2926 /* remove comment open chars (do it last since it would move the end position) */
2927 SSM(editor->sci, SCI_DELETERANGE, start, strlen(co));
2928 if (sci_is_blank_line(editor->sci, start_line))
2929 sci_delete_line(editor->sci, start_line);
2931 return TRUE;
2935 static gint get_multiline_comment_style(GeanyEditor *editor, gint line_start)
2937 gint lexer = sci_get_lexer(editor->sci);
2938 gint style_comment;
2940 /* List only those lexers which support multi line comments */
2941 switch (lexer)
2943 case SCLEX_XML:
2944 case SCLEX_HTML:
2945 case SCLEX_PHPSCRIPT:
2947 if (is_style_php(sci_get_style_at(editor->sci, line_start)))
2948 style_comment = SCE_HPHP_COMMENT;
2949 else
2950 style_comment = SCE_H_COMMENT;
2951 break;
2953 case SCLEX_HASKELL:
2954 case SCLEX_LITERATEHASKELL:
2955 style_comment = SCE_HA_COMMENTBLOCK; break;
2956 case SCLEX_LUA: style_comment = SCE_LUA_COMMENT; break;
2957 case SCLEX_CSS: style_comment = SCE_CSS_COMMENT; break;
2958 case SCLEX_SQL: style_comment = SCE_SQL_COMMENT; break;
2959 case SCLEX_CAML: style_comment = SCE_CAML_COMMENT; break;
2960 case SCLEX_D: style_comment = SCE_D_COMMENT; break;
2961 case SCLEX_PASCAL: style_comment = SCE_PAS_COMMENT; break;
2962 case SCLEX_RUST: style_comment = SCE_RUST_COMMENTBLOCK; break;
2963 default: style_comment = SCE_C_COMMENT;
2966 return style_comment;
2970 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise
2971 * returns the amount of uncommented single comment lines, in case of multi line uncomment
2972 * it returns just 1 */
2973 gint editor_do_uncomment(GeanyEditor *editor, gint line, gboolean toggle)
2975 gint first_line, last_line;
2976 gint x, i, line_start, line_len;
2977 gint sel_start, sel_end;
2978 gint count = 0;
2979 gsize co_len;
2980 gchar sel[256];
2981 const gchar *co, *cc;
2982 gboolean single_line = FALSE;
2983 GeanyFiletype *ft;
2985 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, 0);
2987 if (line < 0)
2988 { /* use selection or current line */
2989 sel_start = sci_get_selection_start(editor->sci);
2990 sel_end = sci_get_selection_end(editor->sci);
2992 first_line = sci_get_line_from_position(editor->sci, sel_start);
2993 /* Find the last line with chars selected (not EOL char) */
2994 last_line = sci_get_line_from_position(editor->sci,
2995 sel_end - editor_get_eol_char_len(editor));
2996 last_line = MAX(first_line, last_line);
2998 else
3000 first_line = last_line = line;
3001 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
3004 ft = editor_get_filetype_at_line(editor, first_line);
3006 if (! filetype_get_comment_open_close(ft, TRUE, &co, &cc))
3007 return 0;
3009 co_len = strlen(co);
3010 if (co_len == 0)
3011 return 0;
3013 sci_start_undo_action(editor->sci);
3015 for (i = first_line; i <= last_line; i++)
3017 gint buf_len;
3019 line_start = sci_get_position_from_line(editor->sci, i);
3020 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
3021 x = 0;
3023 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
3024 if (buf_len <= 0)
3025 continue;
3026 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3027 sel[buf_len] = '\0';
3029 while (isspace(sel[x])) x++;
3031 /* to skip blank lines */
3032 if (x < line_len && sel[x] != '\0')
3034 /* use single line comment */
3035 if (EMPTY(cc))
3037 single_line = TRUE;
3039 if (toggle)
3041 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
3042 if (strncmp(sel + x, co, co_len) != 0 ||
3043 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) != 0)
3044 continue;
3046 co_len += tm_len;
3048 else
3050 if (strncmp(sel + x, co, co_len) != 0)
3051 continue;
3054 sci_set_selection(editor->sci, line_start + x, line_start + x + co_len);
3055 sci_replace_sel(editor->sci, "");
3056 count++;
3058 /* use multi line comment */
3059 else
3061 gint style_comment;
3063 /* skip lines which are already comments */
3064 style_comment = get_multiline_comment_style(editor, line_start);
3065 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3067 if (real_uncomment_multiline(editor))
3068 count = 1;
3071 /* break because we are already on the last line */
3072 break;
3076 sci_end_undo_action(editor->sci);
3078 /* restore selection if there is one
3079 * but don't touch the selection if caller is editor_do_comment_toggle */
3080 if (! toggle && sel_start < sel_end)
3082 if (single_line)
3084 sci_set_selection_start(editor->sci, sel_start - co_len);
3085 sci_set_selection_end(editor->sci, sel_end - (count * co_len));
3087 else
3089 gint eol_len = editor_get_eol_char_len(editor);
3090 sci_set_selection_start(editor->sci, sel_start - co_len - eol_len);
3091 sci_set_selection_end(editor->sci, sel_end - co_len - eol_len);
3095 return count;
3099 void editor_do_comment_toggle(GeanyEditor *editor)
3101 gint first_line, last_line;
3102 gint x, i, line_start, line_len, first_line_start, last_line_start;
3103 gint sel_start, sel_end;
3104 gint count_commented = 0, count_uncommented = 0;
3105 gchar sel[256];
3106 const gchar *co, *cc;
3107 gboolean break_loop = FALSE, single_line = FALSE;
3108 gboolean first_line_was_comment = FALSE;
3109 gboolean last_line_was_comment = FALSE;
3110 gsize co_len;
3111 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
3112 GeanyFiletype *ft;
3114 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
3116 sel_start = sci_get_selection_start(editor->sci);
3117 sel_end = sci_get_selection_end(editor->sci);
3119 first_line = sci_get_line_from_position(editor->sci, sel_start);
3120 /* Find the last line with chars selected (not EOL char) */
3121 last_line = sci_get_line_from_position(editor->sci,
3122 sel_end - editor_get_eol_char_len(editor));
3123 last_line = MAX(first_line, last_line);
3125 first_line_start = sci_get_position_from_line(editor->sci, first_line);
3126 last_line_start = sci_get_position_from_line(editor->sci, last_line);
3128 ft = editor_get_filetype_at_line(editor, first_line);
3130 if (! filetype_get_comment_open_close(ft, TRUE, &co, &cc))
3131 return;
3133 co_len = strlen(co);
3134 if (co_len == 0)
3135 return;
3137 sci_start_undo_action(editor->sci);
3139 for (i = first_line; (i <= last_line) && (! break_loop); i++)
3141 gint buf_len;
3143 line_start = sci_get_position_from_line(editor->sci, i);
3144 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
3145 x = 0;
3147 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
3148 if (buf_len < 0)
3149 continue;
3150 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3151 sel[buf_len] = '\0';
3153 while (isspace(sel[x])) x++;
3155 /* use single line comment */
3156 if (EMPTY(cc))
3158 gboolean do_continue = FALSE;
3159 single_line = TRUE;
3161 if (strncmp(sel + x, co, co_len) == 0 &&
3162 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) == 0)
3164 do_continue = TRUE;
3167 if (do_continue && i == first_line)
3168 first_line_was_comment = TRUE;
3169 last_line_was_comment = do_continue;
3171 if (do_continue)
3173 count_uncommented += editor_do_uncomment(editor, i, TRUE);
3174 continue;
3177 /* we are still here, so the above lines were not already comments, so comment it */
3178 count_commented += editor_do_comment(editor, i, FALSE, TRUE, TRUE);
3180 /* use multi line comment */
3181 else
3183 gint style_comment;
3185 /* skip lines which are already comments */
3186 style_comment = get_multiline_comment_style(editor, line_start);
3187 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3189 if (real_uncomment_multiline(editor))
3190 count_uncommented++;
3192 else
3194 real_comment_multiline(editor, line_start, last_line);
3195 count_commented++;
3198 /* break because we are already on the last line */
3199 break_loop = TRUE;
3200 break;
3204 sci_end_undo_action(editor->sci);
3206 co_len += tm_len;
3208 /* restore selection or caret position */
3209 if (single_line)
3211 gint a = (first_line_was_comment) ? - (gint) co_len : (gint) co_len;
3212 gint indent_len;
3214 /* don't modify sel_start when the selection starts within indentation */
3215 read_indent(editor, sel_start);
3216 indent_len = (gint) strlen(indent);
3217 if ((sel_start - first_line_start) <= indent_len)
3218 a = 0;
3219 /* if the selection start was inside the comment mark, adjust the position */
3220 else if (first_line_was_comment &&
3221 sel_start >= (first_line_start + indent_len) &&
3222 sel_start <= (first_line_start + indent_len + (gint) co_len))
3224 a = (first_line_start + indent_len) - sel_start;
3227 if (sel_start < sel_end)
3229 gint b = (count_commented * (gint) co_len) - (count_uncommented * (gint) co_len);
3231 /* same for selection end, but here we add an offset on the offset above */
3232 read_indent(editor, sel_end + b);
3233 indent_len = (gint) strlen(indent);
3234 if ((sel_end - last_line_start) < indent_len)
3235 b += last_line_was_comment ? (gint) co_len : -(gint) co_len;
3236 else if (last_line_was_comment &&
3237 sel_end >= (last_line_start + indent_len) &&
3238 sel_end <= (last_line_start + indent_len + (gint) co_len))
3240 b += (gint) co_len - (sel_end - (last_line_start + indent_len));
3243 sci_set_selection_start(editor->sci, sel_start + a);
3244 sci_set_selection_end(editor->sci, sel_end + b);
3246 else
3247 sci_set_current_position(editor->sci, sel_start + a, TRUE);
3249 else
3251 gint eol_len = editor_get_eol_char_len(editor);
3252 if (count_uncommented > 0)
3254 sci_set_selection_start(editor->sci, sel_start - (gint) co_len + eol_len);
3255 sci_set_selection_end(editor->sci, sel_end - (gint) co_len + eol_len);
3257 else if (count_commented > 0)
3259 sci_set_selection_start(editor->sci, sel_start + (gint) co_len - eol_len);
3260 sci_set_selection_end(editor->sci, sel_end + (gint) co_len - eol_len);
3262 if (sel_start >= sel_end)
3263 sci_scroll_caret(editor->sci);
3268 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise */
3269 gint editor_do_comment(GeanyEditor *editor, gint line, gboolean allow_empty_lines, gboolean toggle,
3270 gboolean single_comment)
3272 gint first_line, last_line;
3273 gint x, i, line_start, line_len;
3274 gint sel_start, sel_end, co_len;
3275 gint count = 0;
3276 gchar sel[256];
3277 const gchar *co, *cc;
3278 gboolean break_loop = FALSE, single_line = FALSE;
3279 GeanyFiletype *ft;
3281 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, 0);
3283 if (line < 0)
3284 { /* use selection or current line */
3285 sel_start = sci_get_selection_start(editor->sci);
3286 sel_end = sci_get_selection_end(editor->sci);
3288 first_line = sci_get_line_from_position(editor->sci, sel_start);
3289 /* Find the last line with chars selected (not EOL char) */
3290 last_line = sci_get_line_from_position(editor->sci,
3291 sel_end - editor_get_eol_char_len(editor));
3292 last_line = MAX(first_line, last_line);
3294 else
3296 first_line = last_line = line;
3297 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
3300 ft = editor_get_filetype_at_line(editor, first_line);
3302 if (! filetype_get_comment_open_close(ft, single_comment, &co, &cc))
3303 return 0;
3305 co_len = strlen(co);
3306 if (co_len == 0)
3307 return 0;
3309 sci_start_undo_action(editor->sci);
3311 for (i = first_line; (i <= last_line) && (! break_loop); i++)
3313 gint buf_len;
3315 line_start = sci_get_position_from_line(editor->sci, i);
3316 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
3317 x = 0;
3319 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
3320 if (buf_len < 0)
3321 continue;
3322 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3323 sel[buf_len] = '\0';
3325 while (isspace(sel[x])) x++;
3327 /* to skip blank lines */
3328 if (allow_empty_lines || (x < line_len && sel[x] != '\0'))
3330 /* use single line comment */
3331 if (EMPTY(cc))
3333 gint start = line_start;
3334 single_line = TRUE;
3336 if (ft->comment_use_indent)
3337 start = line_start + x;
3339 if (toggle)
3341 gchar *text = g_strconcat(co, editor_prefs.comment_toggle_mark, NULL);
3342 sci_insert_text(editor->sci, start, text);
3343 g_free(text);
3345 else
3346 sci_insert_text(editor->sci, start, co);
3347 count++;
3349 /* use multi line comment */
3350 else
3352 gint style_comment;
3354 /* skip lines which are already comments */
3355 style_comment = get_multiline_comment_style(editor, line_start);
3356 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3357 continue;
3359 real_comment_multiline(editor, line_start, last_line);
3360 count = 1;
3362 /* break because we are already on the last line */
3363 break_loop = TRUE;
3364 break;
3368 sci_end_undo_action(editor->sci);
3370 /* restore selection if there is one
3371 * but don't touch the selection if caller is editor_do_comment_toggle */
3372 if (! toggle && sel_start < sel_end)
3374 if (single_line)
3376 sci_set_selection_start(editor->sci, sel_start + co_len);
3377 sci_set_selection_end(editor->sci, sel_end + (count * co_len));
3379 else
3381 gint eol_len = editor_get_eol_char_len(editor);
3382 sci_set_selection_start(editor->sci, sel_start + co_len + eol_len);
3383 sci_set_selection_end(editor->sci, sel_end + co_len + eol_len);
3386 return count;
3390 static gboolean brace_timeout_active = FALSE;
3392 static gboolean delay_match_brace(G_GNUC_UNUSED gpointer user_data)
3394 GeanyDocument *doc = document_get_current();
3395 GeanyEditor *editor;
3396 gint brace_pos = GPOINTER_TO_INT(user_data);
3397 gint end_pos, cur_pos;
3399 brace_timeout_active = FALSE;
3400 if (!doc)
3401 return FALSE;
3403 editor = doc->editor;
3404 cur_pos = sci_get_current_position(editor->sci) - 1;
3406 if (cur_pos != brace_pos)
3408 cur_pos++;
3409 if (cur_pos != brace_pos)
3411 /* we have moved past the original brace_pos, but after the timeout
3412 * we may now be on a new brace, so check again */
3413 editor_highlight_braces(editor, cur_pos);
3414 return FALSE;
3417 if (!utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3419 editor_highlight_braces(editor, cur_pos);
3420 return FALSE;
3422 end_pos = sci_find_matching_brace(editor->sci, brace_pos);
3424 if (end_pos >= 0)
3426 gint col = MIN(sci_get_col_from_position(editor->sci, brace_pos),
3427 sci_get_col_from_position(editor->sci, end_pos));
3428 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, col, 0);
3429 SSM(editor->sci, SCI_BRACEHIGHLIGHT, brace_pos, end_pos);
3431 else
3433 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3434 SSM(editor->sci, SCI_BRACEBADLIGHT, brace_pos, 0);
3436 return FALSE;
3440 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos)
3442 gint brace_pos = cur_pos - 1;
3444 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3445 SSM(editor->sci, SCI_BRACEBADLIGHT, (uptr_t)-1, 0);
3447 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3449 brace_pos++;
3450 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3452 return;
3455 if (!brace_timeout_active)
3457 brace_timeout_active = TRUE;
3458 /* delaying matching makes scrolling faster e.g. holding down arrow keys */
3459 g_timeout_add(100, delay_match_brace, GINT_TO_POINTER(brace_pos));
3464 static gboolean in_block_comment(gint lexer, gint style)
3466 switch (lexer)
3468 case SCLEX_COBOL:
3469 case SCLEX_CPP:
3470 return (style == SCE_C_COMMENT ||
3471 style == SCE_C_COMMENTDOC);
3473 case SCLEX_PASCAL:
3474 return (style == SCE_PAS_COMMENT ||
3475 style == SCE_PAS_COMMENT2);
3477 case SCLEX_D:
3478 return (style == SCE_D_COMMENT ||
3479 style == SCE_D_COMMENTDOC ||
3480 style == SCE_D_COMMENTNESTED);
3482 case SCLEX_HTML:
3483 case SCLEX_PHPSCRIPT:
3484 return (style == SCE_HPHP_COMMENT);
3486 case SCLEX_CSS:
3487 return (style == SCE_CSS_COMMENT);
3489 case SCLEX_RUST:
3490 return (style == SCE_RUST_COMMENTBLOCK ||
3491 style == SCE_RUST_COMMENTBLOCKDOC);
3493 default:
3494 return FALSE;
3499 static gboolean is_comment_char(gchar c, gint lexer)
3501 if ((c == '*' || c == '+') && lexer == SCLEX_D)
3502 return TRUE;
3503 else
3504 if (c == '*')
3505 return TRUE;
3507 return FALSE;
3511 static void auto_multiline(GeanyEditor *editor, gint cur_line)
3513 ScintillaObject *sci = editor->sci;
3514 gint indent_pos, style;
3515 gint lexer = sci_get_lexer(sci);
3517 /* Use the start of the line enter was pressed on, to avoid any doc keyword styles */
3518 indent_pos = sci_get_line_indent_position(sci, cur_line - 1);
3519 style = sci_get_style_at(sci, indent_pos);
3520 if (!in_block_comment(lexer, style))
3521 return;
3523 /* Check whether the comment block continues on this line */
3524 indent_pos = sci_get_line_indent_position(sci, cur_line);
3525 if (sci_get_style_at(sci, indent_pos) == style || indent_pos >= sci_get_length(sci))
3527 gchar *previous_line = sci_get_line(sci, cur_line - 1);
3528 /* the type of comment, '*' (C/C++/Java), '+' and the others (D) */
3529 const gchar *continuation = "*";
3530 const gchar *whitespace = ""; /* to hold whitespace if needed */
3531 gchar *result;
3532 gint len = strlen(previous_line);
3533 gint i;
3535 /* find and stop at end of multi line comment */
3536 i = len - 1;
3537 while (i >= 0 && isspace(previous_line[i])) i--;
3538 if (i >= 1 && is_comment_char(previous_line[i - 1], lexer) && previous_line[i] == '/')
3540 gint indent_len, indent_width;
3542 indent_pos = sci_get_line_indent_position(sci, cur_line);
3543 indent_len = sci_get_col_from_position(sci, indent_pos);
3544 indent_width = editor_get_indent_prefs(editor)->width;
3546 /* if there is one too many spaces, delete the last space,
3547 * to return to the indent used before the multiline comment was started. */
3548 if (indent_len % indent_width == 1)
3549 SSM(sci, SCI_DELETEBACKNOTLINE, 0, 0); /* remove whitespace indent */
3550 g_free(previous_line);
3551 return;
3553 /* check whether we are on the second line of multi line comment */
3554 i = 0;
3555 while (i < len && isspace(previous_line[i])) i++; /* get to start of the line */
3557 if (i + 1 < len &&
3558 previous_line[i] == '/' && is_comment_char(previous_line[i + 1], lexer))
3559 { /* we are on the second line of a multi line comment, so we have to insert white space */
3560 whitespace = " ";
3563 if (style == SCE_D_COMMENTNESTED)
3564 continuation = "+"; /* for nested comments in D */
3566 result = g_strconcat(whitespace, continuation, " ", NULL);
3567 sci_add_text(sci, result);
3568 g_free(result);
3570 g_free(previous_line);
3575 #if 0
3576 static gboolean editor_lexer_is_c_like(gint lexer)
3578 switch (lexer)
3580 case SCLEX_CPP:
3581 case SCLEX_D:
3582 return TRUE;
3584 default:
3585 return FALSE;
3588 #endif
3591 /* inserts a three-line comment at one line above current cursor position */
3592 void editor_insert_multiline_comment(GeanyEditor *editor)
3594 gchar *text;
3595 gint text_len;
3596 gint line;
3597 gint pos;
3598 gboolean have_multiline_comment = FALSE;
3599 GeanyDocument *doc;
3600 const gchar *co, *cc;
3602 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
3604 if (! filetype_get_comment_open_close(editor->document->file_type, FALSE, &co, &cc))
3605 g_return_if_reached();
3606 if (!EMPTY(cc))
3607 have_multiline_comment = TRUE;
3609 sci_start_undo_action(editor->sci);
3611 doc = editor->document;
3613 /* insert three lines one line above of the current position */
3614 line = sci_get_line_from_position(editor->sci, editor_info.click_pos);
3615 pos = sci_get_position_from_line(editor->sci, line);
3617 /* use the indent on the current line but only when comment indentation is used
3618 * and we don't have multi line comment characters */
3619 if (editor->auto_indent &&
3620 ! have_multiline_comment && doc->file_type->comment_use_indent)
3622 read_indent(editor, editor_info.click_pos);
3623 text = g_strdup_printf("%s\n%s\n%s\n", indent, indent, indent);
3624 text_len = strlen(text);
3626 else
3628 text = g_strdup("\n\n\n");
3629 text_len = 3;
3631 sci_insert_text(editor->sci, pos, text);
3632 g_free(text);
3634 /* select the inserted lines for commenting */
3635 sci_set_selection_start(editor->sci, pos);
3636 sci_set_selection_end(editor->sci, pos + text_len);
3638 editor_do_comment(editor, -1, TRUE, FALSE, FALSE);
3640 /* set the current position to the start of the first inserted line */
3641 pos += strlen(co);
3643 /* on multi line comment jump to the next line, otherwise add the length of added indentation */
3644 if (have_multiline_comment)
3645 pos += 1;
3646 else
3647 pos += strlen(indent);
3649 sci_set_current_position(editor->sci, pos, TRUE);
3650 /* reset the selection */
3651 sci_set_anchor(editor->sci, pos);
3653 sci_end_undo_action(editor->sci);
3657 /* Note: If the editor is pending a redraw, set document::scroll_percent instead.
3658 * Scroll the view to make line appear at percent_of_view.
3659 * line can be -1 to use the current position. */
3660 void editor_scroll_to_line(GeanyEditor *editor, gint line, gfloat percent_of_view)
3662 gint los;
3663 GtkWidget *wid;
3665 g_return_if_fail(editor != NULL);
3667 wid = GTK_WIDGET(editor->sci);
3669 if (! gtk_widget_get_window(wid) || ! gdk_window_is_viewable(gtk_widget_get_window(wid)))
3670 return; /* prevent gdk_window_scroll warning */
3672 if (line == -1)
3673 line = sci_get_current_line(editor->sci);
3675 /* sci 'visible line' != doc line number because of folding and line wrapping */
3676 /* calling SCI_VISIBLEFROMDOCLINE for line is more accurate than calling
3677 * SCI_DOCLINEFROMVISIBLE for vis1. */
3678 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0);
3679 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
3680 line = line - los * percent_of_view;
3681 SSM(editor->sci, SCI_SETFIRSTVISIBLELINE, line, 0);
3682 sci_scroll_caret(editor->sci); /* needed for horizontal scrolling */
3686 /* creates and inserts one tab or whitespace of the amount of the tab width */
3687 void editor_insert_alternative_whitespace(GeanyEditor *editor)
3689 gchar *text;
3690 GeanyIndentPrefs iprefs = *editor_get_indent_prefs(editor);
3692 g_return_if_fail(editor != NULL);
3694 switch (iprefs.type)
3696 case GEANY_INDENT_TYPE_TABS:
3697 iprefs.type = GEANY_INDENT_TYPE_SPACES;
3698 break;
3699 case GEANY_INDENT_TYPE_SPACES:
3700 case GEANY_INDENT_TYPE_BOTH: /* most likely we want a tab */
3701 iprefs.type = GEANY_INDENT_TYPE_TABS;
3702 break;
3704 text = get_whitespace(&iprefs, iprefs.width);
3705 sci_add_text(editor->sci, text);
3706 g_free(text);
3710 void editor_select_word(GeanyEditor *editor)
3712 gint pos;
3713 gint start;
3714 gint end;
3716 g_return_if_fail(editor != NULL);
3718 pos = SSM(editor->sci, SCI_GETCURRENTPOS, 0, 0);
3719 start = sci_word_start_position(editor->sci, pos, TRUE);
3720 end = sci_word_end_position(editor->sci, pos, TRUE);
3722 if (start == end) /* caret in whitespaces sequence */
3724 /* look forward but reverse the selection direction,
3725 * so the caret end up stay as near as the original position. */
3726 end = sci_word_end_position(editor->sci, pos, FALSE);
3727 start = sci_word_end_position(editor->sci, end, TRUE);
3728 if (start == end)
3729 return;
3732 sci_set_selection(editor->sci, start, end);
3736 /* extra_line is for selecting the cursor line (or anchor line) at the bottom of a selection,
3737 * when those lines have no selection (cursor at start of line). */
3738 void editor_select_lines(GeanyEditor *editor, gboolean extra_line)
3740 gint start, end, line;
3742 g_return_if_fail(editor != NULL);
3744 start = sci_get_selection_start(editor->sci);
3745 end = sci_get_selection_end(editor->sci);
3747 /* check if whole lines are already selected */
3748 if (! extra_line && start != end &&
3749 sci_get_col_from_position(editor->sci, start) == 0 &&
3750 sci_get_col_from_position(editor->sci, end) == 0)
3751 return;
3753 line = sci_get_line_from_position(editor->sci, start);
3754 start = sci_get_position_from_line(editor->sci, line);
3756 line = sci_get_line_from_position(editor->sci, end);
3757 end = sci_get_position_from_line(editor->sci, line + 1);
3759 sci_set_selection(editor->sci, start, end);
3763 static gboolean sci_is_blank_line(ScintillaObject *sci, gint line)
3765 return sci_get_line_indent_position(sci, line) ==
3766 sci_get_line_end_position(sci, line);
3770 /* Returns first line of paragraph for GTK_DIR_UP, line after paragraph
3771 * ends for GTK_DIR_DOWN or -1 if called on an empty line. */
3772 static gint find_paragraph_stop(GeanyEditor *editor, gint line, gint direction)
3774 gint step;
3775 ScintillaObject *sci = editor->sci;
3777 /* first check current line and return -1 if it is empty to skip creating of a selection */
3778 if (sci_is_blank_line(sci, line))
3779 return -1;
3781 if (direction == GTK_DIR_UP)
3782 step = -1;
3783 else
3784 step = 1;
3786 while (TRUE)
3788 line += step;
3789 if (line == -1)
3791 /* start of document */
3792 line = 0;
3793 break;
3795 if (line == sci_get_line_count(sci))
3796 break;
3798 if (sci_is_blank_line(sci, line))
3800 /* return line paragraph starts on */
3801 if (direction == GTK_DIR_UP)
3802 line++;
3803 break;
3806 return line;
3810 void editor_select_paragraph(GeanyEditor *editor)
3812 gint pos_start, pos_end, line_start, line_found;
3814 g_return_if_fail(editor != NULL);
3816 line_start = sci_get_current_line(editor->sci);
3818 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_UP);
3819 if (line_found == -1)
3820 return;
3822 pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3824 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_DOWN);
3825 pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3827 sci_set_selection(editor->sci, pos_start, pos_end);
3831 /* Returns first line of block for GTK_DIR_UP, line after block
3832 * ends for GTK_DIR_DOWN or -1 if called on an empty line. */
3833 static gint find_block_stop(GeanyEditor *editor, gint line, gint direction)
3835 gint step, ind;
3836 ScintillaObject *sci = editor->sci;
3838 /* first check current line and return -1 if it is empty to skip creating of a selection */
3839 if (sci_is_blank_line(sci, line))
3840 return -1;
3842 if (direction == GTK_DIR_UP)
3843 step = -1;
3844 else
3845 step = 1;
3847 ind = sci_get_line_indentation(sci, line);
3848 while (TRUE)
3850 line += step;
3851 if (line == -1)
3853 /* start of document */
3854 line = 0;
3855 break;
3857 if (line == sci_get_line_count(sci))
3858 break;
3860 if (sci_get_line_indentation(sci, line) != ind ||
3861 sci_is_blank_line(sci, line))
3863 /* return line block starts on */
3864 if (direction == GTK_DIR_UP)
3865 line++;
3866 break;
3869 return line;
3873 void editor_select_indent_block(GeanyEditor *editor)
3875 gint pos_start, pos_end, line_start, line_found;
3877 g_return_if_fail(editor != NULL);
3879 line_start = sci_get_current_line(editor->sci);
3881 line_found = find_block_stop(editor, line_start, GTK_DIR_UP);
3882 if (line_found == -1)
3883 return;
3885 pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3887 line_found = find_block_stop(editor, line_start, GTK_DIR_DOWN);
3888 pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3890 sci_set_selection(editor->sci, pos_start, pos_end);
3894 /* simple indentation to indent the current line with the same indent as the previous one */
3895 static void smart_line_indentation(GeanyEditor *editor, gint first_line, gint last_line)
3897 gint i, sel_start = 0, sel_end = 0;
3899 /* get previous line and use it for read_indent to use that line
3900 * (otherwise it would fail on a line only containing "{" in advanced indentation mode) */
3901 read_indent(editor, sci_get_position_from_line(editor->sci, first_line - 1));
3903 for (i = first_line; i <= last_line; i++)
3905 /* skip the first line or if the indentation of the previous and current line are equal */
3906 if (i == 0 ||
3907 SSM(editor->sci, SCI_GETLINEINDENTATION, i - 1, 0) ==
3908 SSM(editor->sci, SCI_GETLINEINDENTATION, i, 0))
3909 continue;
3911 sel_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
3912 sel_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
3913 if (sel_start < sel_end)
3915 sci_set_selection(editor->sci, sel_start, sel_end);
3916 sci_replace_sel(editor->sci, "");
3918 sci_insert_text(editor->sci, sel_start, indent);
3923 /* simple indentation to indent the current line with the same indent as the previous one */
3924 void editor_smart_line_indentation(GeanyEditor *editor, gint pos)
3926 gint first_line, last_line;
3927 gint first_sel_start, first_sel_end;
3928 ScintillaObject *sci;
3930 g_return_if_fail(editor != NULL);
3932 sci = editor->sci;
3934 first_sel_start = sci_get_selection_start(sci);
3935 first_sel_end = sci_get_selection_end(sci);
3937 first_line = sci_get_line_from_position(sci, first_sel_start);
3938 /* Find the last line with chars selected (not EOL char) */
3939 last_line = sci_get_line_from_position(sci, first_sel_end - editor_get_eol_char_len(editor));
3940 last_line = MAX(first_line, last_line);
3942 if (pos == -1)
3943 pos = first_sel_start;
3945 sci_start_undo_action(sci);
3947 smart_line_indentation(editor, first_line, last_line);
3949 /* set cursor position if there was no selection */
3950 if (first_sel_start == first_sel_end)
3952 gint indent_pos = SSM(sci, SCI_GETLINEINDENTPOSITION, first_line, 0);
3954 /* use indent position as user may wish to change indentation afterwards */
3955 sci_set_current_position(sci, indent_pos, FALSE);
3957 else
3959 /* fully select all the lines affected */
3960 sci_set_selection_start(sci, sci_get_position_from_line(sci, first_line));
3961 sci_set_selection_end(sci, sci_get_position_from_line(sci, last_line + 1));
3964 sci_end_undo_action(sci);
3968 /* increase / decrease current line or selection by one space */
3969 void editor_indentation_by_one_space(GeanyEditor *editor, gint pos, gboolean decrease)
3971 gint i, first_line, last_line, line_start, indentation_end, count = 0;
3972 gint sel_start, sel_end, first_line_offset = 0;
3974 g_return_if_fail(editor != NULL);
3976 sel_start = sci_get_selection_start(editor->sci);
3977 sel_end = sci_get_selection_end(editor->sci);
3979 first_line = sci_get_line_from_position(editor->sci, sel_start);
3980 /* Find the last line with chars selected (not EOL char) */
3981 last_line = sci_get_line_from_position(editor->sci, sel_end - editor_get_eol_char_len(editor));
3982 last_line = MAX(first_line, last_line);
3984 if (pos == -1)
3985 pos = sel_start;
3987 sci_start_undo_action(editor->sci);
3989 for (i = first_line; i <= last_line; i++)
3991 indentation_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
3992 if (decrease)
3994 line_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
3995 /* searching backwards for a space to remove */
3996 while (sci_get_char_at(editor->sci, indentation_end) != ' ' && indentation_end > line_start)
3997 indentation_end--;
3999 if (sci_get_char_at(editor->sci, indentation_end) == ' ')
4001 sci_set_selection(editor->sci, indentation_end, indentation_end + 1);
4002 sci_replace_sel(editor->sci, "");
4003 count--;
4004 if (i == first_line)
4005 first_line_offset = -1;
4008 else
4010 sci_insert_text(editor->sci, indentation_end, " ");
4011 count++;
4012 if (i == first_line)
4013 first_line_offset = 1;
4017 /* set cursor position */
4018 if (sel_start < sel_end)
4020 gint start = sel_start + first_line_offset;
4021 if (first_line_offset < 0)
4022 start = MAX(sel_start + first_line_offset,
4023 SSM(editor->sci, SCI_POSITIONFROMLINE, first_line, 0));
4025 sci_set_selection_start(editor->sci, start);
4026 sci_set_selection_end(editor->sci, sel_end + count);
4028 else
4029 sci_set_current_position(editor->sci, pos + count, FALSE);
4031 sci_end_undo_action(editor->sci);
4035 void editor_finalize(void)
4037 scintilla_release_resources();
4041 /* wordchars: NULL or a string containing characters to match a word.
4042 * Returns: the current selection or the current word.
4044 * Passing NULL as wordchars is NOT the same as passing GEANY_WORDCHARS: NULL means
4045 * using Scintillas's word boundaries. */
4046 gchar *editor_get_default_selection(GeanyEditor *editor, gboolean use_current_word,
4047 const gchar *wordchars)
4049 gchar *s = NULL;
4051 g_return_val_if_fail(editor != NULL, NULL);
4053 if (sci_get_lines_selected(editor->sci) == 1)
4054 s = sci_get_selection_contents(editor->sci);
4055 else if (sci_get_lines_selected(editor->sci) == 0 && use_current_word)
4056 { /* use the word at current cursor position */
4057 gchar word[GEANY_MAX_WORD_LENGTH];
4059 if (wordchars != NULL)
4060 editor_find_current_word(editor, -1, word, sizeof(word), wordchars);
4061 else
4062 editor_find_current_word_sciwc(editor, -1, word, sizeof(word));
4064 if (word[0] != '\0')
4065 s = g_strdup(word);
4067 return s;
4071 /* Note: Usually the line should be made visible (not folded) before calling this.
4072 * Returns: TRUE if line is/will be displayed to the user, or FALSE if it is
4073 * outside the *vertical* view.
4074 * Warning: You may need horizontal scrolling to make the cursor visible - so always call
4075 * sci_scroll_caret() when this returns TRUE. */
4076 gboolean editor_line_in_view(GeanyEditor *editor, gint line)
4078 gint vis1, los;
4080 g_return_val_if_fail(editor != NULL, FALSE);
4082 /* If line is wrapped the result may occur on another virtual line than the first and may be
4083 * still hidden, so increase the line number to check for the next document line */
4084 if (SSM(editor->sci, SCI_WRAPCOUNT, line, 0) > 1)
4085 line++;
4087 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0); /* convert to visible line number */
4088 vis1 = SSM(editor->sci, SCI_GETFIRSTVISIBLELINE, 0, 0);
4089 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
4091 return (line >= vis1 && line < vis1 + los);
4095 /* If the current line is outside the current view window, scroll the line
4096 * so it appears at percent_of_view. */
4097 void editor_display_current_line(GeanyEditor *editor, gfloat percent_of_view)
4099 gint line;
4101 g_return_if_fail(editor != NULL);
4103 line = sci_get_current_line(editor->sci);
4105 /* unfold maybe folded results */
4106 sci_ensure_line_is_visible(editor->sci, line);
4108 /* scroll the line if it's off screen */
4109 if (! editor_line_in_view(editor, line))
4110 editor->scroll_percent = percent_of_view;
4111 else
4112 sci_scroll_caret(editor->sci); /* may need horizontal scrolling */
4117 * Deletes all currently set indicators in the @a editor window.
4118 * Error indicators (red squiggly underlines) and usual line markers are removed.
4120 * @param editor The editor to operate on.
4122 void editor_indicator_clear_errors(GeanyEditor *editor)
4124 editor_indicator_clear(editor, GEANY_INDICATOR_ERROR);
4125 sci_marker_delete_all(editor->sci, 0); /* remove the yellow error line marker */
4130 * Deletes all currently set indicators matching @a indic in the @a editor window.
4132 * @param editor The editor to operate on.
4133 * @param indic The indicator number to clear, this is a value of @ref GeanyIndicator.
4135 * @since 0.16
4137 GEANY_API_SYMBOL
4138 void editor_indicator_clear(GeanyEditor *editor, gint indic)
4140 glong last_pos;
4142 g_return_if_fail(editor != NULL);
4144 last_pos = sci_get_length(editor->sci);
4145 if (last_pos > 0)
4147 sci_indicator_set(editor->sci, indic);
4148 sci_indicator_clear(editor->sci, 0, last_pos);
4154 * Sets an indicator @a indic on @a line.
4155 * Whitespace at the start and the end of the line is not marked.
4157 * @param editor The editor to operate on.
4158 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4159 * @param line The line number which should be marked.
4161 * @since 0.16
4163 GEANY_API_SYMBOL
4164 void editor_indicator_set_on_line(GeanyEditor *editor, gint indic, gint line)
4166 gint start, end;
4167 guint i = 0, len;
4168 gchar *linebuf;
4170 g_return_if_fail(editor != NULL);
4171 g_return_if_fail(line >= 0);
4173 start = sci_get_position_from_line(editor->sci, line);
4174 end = sci_get_position_from_line(editor->sci, line + 1);
4176 /* skip blank lines */
4177 if ((start + 1) == end ||
4178 start > end ||
4179 (sci_get_line_end_position(editor->sci, line) - start) == 0)
4181 return;
4184 len = end - start;
4185 linebuf = sci_get_line(editor->sci, line);
4187 /* don't set the indicator on whitespace */
4188 while (isspace(linebuf[i]))
4189 i++;
4190 while (len > 1 && len > i && isspace(linebuf[len - 1]))
4192 len--;
4193 end--;
4195 g_free(linebuf);
4197 editor_indicator_set_on_range(editor, indic, start + i, end);
4202 * Sets an indicator on the range specified by @a start and @a end.
4203 * No error checking or whitespace removal is performed, this should be done by the calling
4204 * function if necessary.
4206 * @param editor The editor to operate on.
4207 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4208 * @param start The starting position for the marker.
4209 * @param end The ending position for the marker.
4211 * @since 0.16
4213 GEANY_API_SYMBOL
4214 void editor_indicator_set_on_range(GeanyEditor *editor, gint indic, gint start, gint end)
4216 g_return_if_fail(editor != NULL);
4217 if (start >= end)
4218 return;
4220 sci_indicator_set(editor->sci, indic);
4221 sci_indicator_fill(editor->sci, start, end - start);
4225 /* Inserts the given colour (format should be #...), if there is a selection starting with 0x...
4226 * the replacement will also start with 0x... */
4227 void editor_insert_color(GeanyEditor *editor, const gchar *colour)
4229 g_return_if_fail(editor != NULL);
4231 if (sci_has_selection(editor->sci))
4233 gint start = sci_get_selection_start(editor->sci);
4234 const gchar *replacement = colour;
4236 if (sci_get_char_at(editor->sci, start) == '0' &&
4237 sci_get_char_at(editor->sci, start + 1) == 'x')
4239 gint end = sci_get_selection_end(editor->sci);
4241 sci_set_selection_start(editor->sci, start + 2);
4242 /* we need to also re-set the selection end in case the anchor was located before
4243 * the cursor, since set_selection_start() always moves the cursor, not the anchor */
4244 sci_set_selection_end(editor->sci, end);
4245 replacement++; /* skip the leading "0x" */
4247 else if (sci_get_char_at(editor->sci, start - 1) == '#')
4248 { /* double clicking something like #00ffff may only select 00ffff because of wordchars */
4249 replacement++; /* so skip the '#' to only replace the colour value */
4251 sci_replace_sel(editor->sci, replacement);
4253 else
4254 sci_add_text(editor->sci, colour);
4259 * Retrieves the end of line characters mode (LF, CR/LF, CR) in the given editor.
4260 * If @a editor is @c NULL, the default end of line characters are used.
4262 * @param editor @nullable The editor to operate on, or @c NULL to query the default value.
4263 * @return The used end of line characters mode.
4265 * @since 0.20
4267 GEANY_API_SYMBOL
4268 gint editor_get_eol_char_mode(GeanyEditor *editor)
4270 gint mode = file_prefs.default_eol_character;
4272 if (editor != NULL)
4273 mode = sci_get_eol_mode(editor->sci);
4275 return mode;
4280 * Retrieves the localized name (for displaying) of the used end of line characters
4281 * (LF, CR/LF, CR) in the given editor.
4282 * If @a editor is @c NULL, the default end of line characters are used.
4284 * @param editor @nullable The editor to operate on, or @c NULL to query the default value.
4285 * @return The name of the end of line characters.
4287 * @since 0.19
4289 GEANY_API_SYMBOL
4290 const gchar *editor_get_eol_char_name(GeanyEditor *editor)
4292 gint mode = file_prefs.default_eol_character;
4294 if (editor != NULL)
4295 mode = sci_get_eol_mode(editor->sci);
4297 return utils_get_eol_name(mode);
4302 * Retrieves the length of the used end of line characters (LF, CR/LF, CR) in the given editor.
4303 * If @a editor is @c NULL, the default end of line characters are used.
4304 * The returned value is 1 for CR and LF and 2 for CR/LF.
4306 * @param editor @nullable The editor to operate on, or @c NULL to query the default value.
4307 * @return The length of the end of line characters.
4309 * @since 0.19
4311 GEANY_API_SYMBOL
4312 gint editor_get_eol_char_len(GeanyEditor *editor)
4314 gint mode = file_prefs.default_eol_character;
4316 if (editor != NULL)
4317 mode = sci_get_eol_mode(editor->sci);
4319 switch (mode)
4321 case SC_EOL_CRLF: return 2; break;
4322 default: return 1; break;
4328 * Retrieves the used end of line characters (LF, CR/LF, CR) in the given editor.
4329 * If @a editor is @c NULL, the default end of line characters are used.
4330 * The returned value is either "\n", "\r\n" or "\r".
4332 * @param editor @nullable The editor to operate on, or @c NULL to query the default value.
4333 * @return The end of line characters.
4335 * @since 0.19
4337 GEANY_API_SYMBOL
4338 const gchar *editor_get_eol_char(GeanyEditor *editor)
4340 gint mode = file_prefs.default_eol_character;
4342 if (editor != NULL)
4343 mode = sci_get_eol_mode(editor->sci);
4345 return utils_get_eol_char(mode);
4349 static void fold_all(GeanyEditor *editor, gboolean want_fold)
4351 gint lines, first, i;
4353 if (editor == NULL || ! editor_prefs.folding)
4354 return;
4356 lines = sci_get_line_count(editor->sci);
4357 first = sci_get_first_visible_line(editor->sci);
4359 for (i = 0; i < lines; i++)
4361 gint level = sci_get_fold_level(editor->sci, i);
4363 if (level & SC_FOLDLEVELHEADERFLAG)
4365 if (sci_get_fold_expanded(editor->sci, i) == want_fold)
4366 sci_toggle_fold(editor->sci, i);
4369 editor_scroll_to_line(editor, first, 0.0F);
4373 void editor_unfold_all(GeanyEditor *editor)
4375 fold_all(editor, FALSE);
4379 void editor_fold_all(GeanyEditor *editor)
4381 fold_all(editor, TRUE);
4385 void editor_replace_tabs(GeanyEditor *editor, gboolean ignore_selection)
4387 gint anchor_pos, caret_pos;
4388 struct Sci_TextToFind ttf;
4390 g_return_if_fail(editor != NULL);
4392 sci_start_undo_action(editor->sci);
4393 if (sci_has_selection(editor->sci) && !ignore_selection)
4395 ttf.chrg.cpMin = sci_get_selection_start(editor->sci);
4396 ttf.chrg.cpMax = sci_get_selection_end(editor->sci);
4398 else
4400 ttf.chrg.cpMin = 0;
4401 ttf.chrg.cpMax = sci_get_length(editor->sci);
4403 ttf.lpstrText = (gchar*) "\t";
4405 anchor_pos = SSM(editor->sci, SCI_GETANCHOR, 0, 0);
4406 caret_pos = sci_get_current_position(editor->sci);
4407 while (TRUE)
4409 gint search_pos, pos_in_line, current_tab_true_length;
4410 gint tab_len;
4411 gchar *tab_str;
4413 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4414 if (search_pos == -1)
4415 break;
4417 tab_len = sci_get_tab_width(editor->sci);
4418 pos_in_line = sci_get_col_from_position(editor->sci, search_pos);
4419 current_tab_true_length = tab_len - (pos_in_line % tab_len);
4420 tab_str = g_strnfill(current_tab_true_length, ' ');
4421 sci_set_target_start(editor->sci, search_pos);
4422 sci_set_target_end(editor->sci, search_pos + 1);
4423 sci_replace_target(editor->sci, tab_str, FALSE);
4424 /* next search starts after replacement */
4425 ttf.chrg.cpMin = search_pos + current_tab_true_length - 1;
4426 /* update end of range now text has changed */
4427 ttf.chrg.cpMax += current_tab_true_length - 1;
4428 g_free(tab_str);
4430 if (anchor_pos > search_pos)
4431 anchor_pos += current_tab_true_length - 1;
4432 if (caret_pos > search_pos)
4433 caret_pos += current_tab_true_length - 1;
4435 sci_set_selection(editor->sci, anchor_pos, caret_pos);
4436 sci_end_undo_action(editor->sci);
4440 /* Replaces all occurrences all spaces of the length of a given tab_width,
4441 * optionally restricting the search to the current selection. */
4442 void editor_replace_spaces(GeanyEditor *editor, gboolean ignore_selection)
4444 gint search_pos;
4445 gint anchor_pos, caret_pos;
4446 static gdouble tab_len_f = -1.0; /* keep the last used value */
4447 gint tab_len;
4448 gchar *text;
4449 struct Sci_TextToFind ttf;
4451 g_return_if_fail(editor != NULL);
4453 if (tab_len_f < 0.0)
4454 tab_len_f = sci_get_tab_width(editor->sci);
4456 if (! dialogs_show_input_numeric(
4457 _("Enter Tab Width"),
4458 _("Enter the amount of spaces which should be replaced by a tab character."),
4459 &tab_len_f, 1, 100, 1))
4461 return;
4463 tab_len = (gint) tab_len_f;
4464 text = g_strnfill(tab_len, ' ');
4466 sci_start_undo_action(editor->sci);
4467 if (sci_has_selection(editor->sci) && !ignore_selection)
4469 ttf.chrg.cpMin = sci_get_selection_start(editor->sci);
4470 ttf.chrg.cpMax = sci_get_selection_end(editor->sci);
4472 else
4474 ttf.chrg.cpMin = 0;
4475 ttf.chrg.cpMax = sci_get_length(editor->sci);
4477 ttf.lpstrText = text;
4479 anchor_pos = SSM(editor->sci, SCI_GETANCHOR, 0, 0);
4480 caret_pos = sci_get_current_position(editor->sci);
4481 while (TRUE)
4483 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4484 if (search_pos == -1)
4485 break;
4486 /* only replace indentation because otherwise we can mess up alignment */
4487 if (search_pos > sci_get_line_indent_position(editor->sci,
4488 sci_get_line_from_position(editor->sci, search_pos)))
4490 ttf.chrg.cpMin = search_pos + tab_len;
4491 continue;
4493 sci_set_target_start(editor->sci, search_pos);
4494 sci_set_target_end(editor->sci, search_pos + tab_len);
4495 sci_replace_target(editor->sci, "\t", FALSE);
4496 ttf.chrg.cpMin = search_pos;
4497 /* update end of range now text has changed */
4498 ttf.chrg.cpMax -= tab_len - 1;
4500 if (anchor_pos > search_pos)
4501 anchor_pos -= tab_len - 1;
4502 if (caret_pos > search_pos)
4503 caret_pos -= tab_len - 1;
4505 sci_set_selection(editor->sci, anchor_pos, caret_pos);
4506 sci_end_undo_action(editor->sci);
4507 g_free(text);
4511 void editor_strip_line_trailing_spaces(GeanyEditor *editor, gint line)
4513 gint line_start = sci_get_position_from_line(editor->sci, line);
4514 gint line_end = sci_get_line_end_position(editor->sci, line);
4515 gint i = line_end - 1;
4516 gchar ch = sci_get_char_at(editor->sci, i);
4518 /* Diff hunks should keep trailing spaces */
4519 if (sci_get_lexer(editor->sci) == SCLEX_DIFF)
4520 return;
4522 while ((i >= line_start) && ((ch == ' ') || (ch == '\t')))
4524 i--;
4525 ch = sci_get_char_at(editor->sci, i);
4527 if (i < (line_end - 1))
4529 sci_set_target_start(editor->sci, i + 1);
4530 sci_set_target_end(editor->sci, line_end);
4531 sci_replace_target(editor->sci, "", FALSE);
4536 void editor_strip_trailing_spaces(GeanyEditor *editor, gboolean ignore_selection)
4538 gint start_line;
4539 gint end_line;
4540 gint line;
4542 if (sci_has_selection(editor->sci) && !ignore_selection)
4544 gint selection_start = sci_get_selection_start(editor->sci);
4545 gint selection_end = sci_get_selection_end(editor->sci);
4547 start_line = sci_get_line_from_position(editor->sci, selection_start);
4548 end_line = sci_get_line_from_position(editor->sci, selection_end);
4550 if (sci_get_col_from_position(editor->sci, selection_end) > 0)
4551 end_line++;
4553 else
4555 start_line = 0;
4556 end_line = sci_get_line_count(editor->sci);
4559 sci_start_undo_action(editor->sci);
4561 for (line = start_line; line < end_line; line++)
4563 editor_strip_line_trailing_spaces(editor, line);
4565 sci_end_undo_action(editor->sci);
4569 void editor_ensure_final_newline(GeanyEditor *editor)
4571 gint max_lines = sci_get_line_count(editor->sci);
4572 gboolean append_newline = (max_lines == 1);
4573 gint end_document = sci_get_position_from_line(editor->sci, max_lines);
4575 if (max_lines > 1)
4577 append_newline = end_document > sci_get_position_from_line(editor->sci, max_lines - 1);
4579 if (append_newline)
4581 const gchar *eol = editor_get_eol_char(editor);
4583 sci_insert_text(editor->sci, end_document, eol);
4588 void editor_set_font(GeanyEditor *editor, const gchar *font)
4590 gint style, size;
4591 gchar *font_name;
4592 PangoFontDescription *pfd;
4594 g_return_if_fail(editor);
4596 pfd = pango_font_description_from_string(font);
4597 size = pango_font_description_get_size(pfd) / PANGO_SCALE;
4598 font_name = g_strdup_printf("!%s", pango_font_description_get_family(pfd));
4599 pango_font_description_free(pfd);
4601 for (style = 0; style <= STYLE_MAX; style++)
4602 sci_set_font(editor->sci, style, font_name, size);
4604 g_free(font_name);
4606 /* zoom to 100% to prevent confusion */
4607 sci_zoom_off(editor->sci);
4611 void editor_set_line_wrapping(GeanyEditor *editor, gboolean wrap)
4613 g_return_if_fail(editor != NULL);
4615 editor->line_wrapping = wrap;
4616 sci_set_lines_wrapped(editor->sci, wrap);
4620 /** Sets the indent type for @a editor.
4621 * @param editor Editor.
4622 * @param type Indent type.
4624 * @since 0.16
4626 GEANY_API_SYMBOL
4627 void editor_set_indent_type(GeanyEditor *editor, GeanyIndentType type)
4629 editor_set_indent(editor, type, editor->indent_width);
4633 /** Sets the indent width for @a editor.
4634 * @param editor Editor.
4635 * @param width New indent width.
4637 * @since 1.27 (API 227)
4639 GEANY_API_SYMBOL
4640 void editor_set_indent_width(GeanyEditor *editor, gint width)
4642 editor_set_indent(editor, editor->indent_type, width);
4646 void editor_set_indent(GeanyEditor *editor, GeanyIndentType type, gint width)
4648 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
4649 ScintillaObject *sci = editor->sci;
4650 gboolean use_tabs = type != GEANY_INDENT_TYPE_SPACES;
4652 editor->indent_type = type;
4653 editor->indent_width = width;
4654 sci_set_use_tabs(sci, use_tabs);
4656 if (type == GEANY_INDENT_TYPE_BOTH)
4658 sci_set_tab_width(sci, iprefs->hard_tab_width);
4659 if (iprefs->hard_tab_width != 8)
4661 static gboolean warn = TRUE;
4662 if (warn)
4663 ui_set_statusbar(TRUE, _("Warning: non-standard hard tab width: %d != 8!"),
4664 iprefs->hard_tab_width);
4665 warn = FALSE;
4668 else
4669 sci_set_tab_width(sci, width);
4671 SSM(sci, SCI_SETINDENT, width, 0);
4673 /* remove indent spaces on backspace, if using any spaces to indent */
4674 SSM(sci, SCI_SETBACKSPACEUNINDENTS, type != GEANY_INDENT_TYPE_TABS, 0);
4678 /* Convenience function for editor_goto_pos() to pass in a line number. */
4679 gboolean editor_goto_line(GeanyEditor *editor, gint line_no, gint offset)
4681 gint pos;
4683 g_return_val_if_fail(editor, FALSE);
4684 if (line_no < 0 || line_no >= sci_get_line_count(editor->sci))
4685 return FALSE;
4687 if (offset != 0)
4689 gint current_line = sci_get_current_line(editor->sci);
4690 line_no *= offset;
4691 line_no = current_line + line_no;
4694 pos = sci_get_position_from_line(editor->sci, line_no);
4695 return editor_goto_pos(editor, pos, TRUE);
4699 /** Moves to position @a pos, switching to the document if necessary,
4700 * setting a marker if @a mark is set.
4702 * @param editor Editor.
4703 * @param pos The position.
4704 * @param mark Whether to set a mark on the position.
4705 * @return @c TRUE if action has been performed, otherwise @c FALSE.
4707 * @since 0.20
4709 GEANY_API_SYMBOL
4710 gboolean editor_goto_pos(GeanyEditor *editor, gint pos, gboolean mark)
4712 g_return_val_if_fail(editor, FALSE);
4713 if (G_UNLIKELY(pos < 0))
4714 return FALSE;
4716 if (mark)
4718 gint line = sci_get_line_from_position(editor->sci, pos);
4720 /* mark the tag with the yellow arrow */
4721 sci_marker_delete_all(editor->sci, 0);
4722 sci_set_marker_at_line(editor->sci, line, 0);
4725 sci_goto_pos(editor->sci, pos, TRUE);
4726 editor->scroll_percent = 0.25F;
4728 /* finally switch to the page */
4729 document_show_tab(editor->document);
4730 return TRUE;
4734 static gboolean
4735 on_editor_scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer user_data)
4737 GeanyEditor *editor = user_data;
4739 /* Handle scroll events if Alt is pressed and scroll whole pages instead of a
4740 * few lines only, maybe this could/should be done in Scintilla directly */
4741 if (event->state & GDK_MOD1_MASK)
4743 sci_send_command(editor->sci, (event->direction == GDK_SCROLL_DOWN) ? SCI_PAGEDOWN : SCI_PAGEUP);
4744 return TRUE;
4746 else if (event->state & GDK_SHIFT_MASK)
4748 gint amount = (event->direction == GDK_SCROLL_DOWN) ? 8 : -8;
4750 sci_scroll_columns(editor->sci, amount);
4751 return TRUE;
4754 return FALSE; /* let Scintilla handle all other cases */
4758 static gboolean editor_check_colourise(GeanyEditor *editor)
4760 GeanyDocument *doc = editor->document;
4762 if (!doc->priv->colourise_needed)
4763 return FALSE;
4765 doc->priv->colourise_needed = FALSE;
4766 sci_colourise(editor->sci, 0, -1);
4768 /* now that the current document is colourised, fold points are now accurate,
4769 * so force an update of the current function/tag. */
4770 symbols_get_current_function(NULL, NULL);
4771 ui_update_statusbar(NULL, -1);
4773 return TRUE;
4777 /* We only want to colourise just before drawing, to save startup time and
4778 * prevent unnecessary recolouring other documents after one is saved.
4779 * Really we want a "draw" signal but there doesn't seem to be one (expose is too late,
4780 * and "show" doesn't work). */
4781 static gboolean on_editor_focus_in(GtkWidget *widget, GdkEventFocus *event, gpointer user_data)
4783 GeanyEditor *editor = user_data;
4785 editor_check_colourise(editor);
4786 return FALSE;
4790 static gboolean on_editor_expose_event(GtkWidget *widget, GdkEventExpose *event,
4791 gpointer user_data)
4793 GeanyEditor *editor = user_data;
4795 /* This is just to catch any uncolourised documents being drawn that didn't receive focus
4796 * for some reason, maybe it's not necessary but just in case. */
4797 editor_check_colourise(editor);
4798 return FALSE;
4802 #if GTK_CHECK_VERSION(3, 0, 0)
4803 static gboolean on_editor_draw(GtkWidget *widget, cairo_t *cr, gpointer user_data)
4805 return on_editor_expose_event(widget, NULL, user_data);
4807 #endif
4810 static void setup_sci_keys(ScintillaObject *sci)
4812 /* disable some Scintilla keybindings to be able to redefine them cleanly */
4813 sci_clear_cmdkey(sci, 'A' | (SCMOD_CTRL << 16)); /* select all */
4814 sci_clear_cmdkey(sci, 'D' | (SCMOD_CTRL << 16)); /* duplicate */
4815 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16)); /* line transpose */
4816 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line copy */
4817 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16)); /* line cut */
4818 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line delete */
4819 sci_clear_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line to end delete */
4820 sci_clear_cmdkey(sci, SCK_BACK | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line to beginning delete */
4821 sci_clear_cmdkey(sci, '/' | (SCMOD_CTRL << 16)); /* Previous word part */
4822 sci_clear_cmdkey(sci, '\\' | (SCMOD_CTRL << 16)); /* Next word part */
4823 sci_clear_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16)); /* scroll line up */
4824 sci_clear_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16)); /* scroll line down */
4825 sci_clear_cmdkey(sci, SCK_HOME); /* line start */
4826 sci_clear_cmdkey(sci, SCK_END); /* line end */
4827 sci_clear_cmdkey(sci, SCK_END | (SCMOD_ALT << 16)); /* visual line end */
4829 if (editor_prefs.use_gtk_word_boundaries)
4831 /* use GtkEntry-like word boundaries */
4832 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16), SCI_WORDRIGHTEND);
4833 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_WORDRIGHTENDEXTEND);
4834 sci_assign_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16), SCI_DELWORDRIGHTEND);
4836 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_ALT << 16), SCI_LINESCROLLUP);
4837 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_ALT << 16), SCI_LINESCROLLDOWN);
4838 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16), SCI_PARAUP);
4839 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARAUPEXTEND);
4840 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16), SCI_PARADOWN);
4841 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARADOWNEXTEND);
4843 sci_clear_cmdkey(sci, SCK_BACK | (SCMOD_ALT << 16)); /* clear Alt-Backspace (Undo) */
4847 /* registers a Scintilla image from a named icon from the theme */
4848 static gboolean register_named_icon(ScintillaObject *sci, guint id, const gchar *name)
4850 GError *error = NULL;
4851 GdkPixbuf *pixbuf;
4852 gint n_channels, rowstride, width, height;
4853 gint size;
4855 gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &size, NULL);
4856 pixbuf = gtk_icon_theme_load_icon(gtk_icon_theme_get_default(), name, size, 0, &error);
4857 if (! pixbuf)
4859 g_warning("failed to load icon '%s': %s", name, error->message);
4860 g_error_free(error);
4861 return FALSE;
4864 n_channels = gdk_pixbuf_get_n_channels(pixbuf);
4865 rowstride = gdk_pixbuf_get_rowstride(pixbuf);
4866 width = gdk_pixbuf_get_width(pixbuf);
4867 height = gdk_pixbuf_get_height(pixbuf);
4869 if (gdk_pixbuf_get_bits_per_sample(pixbuf) != 8 ||
4870 ! gdk_pixbuf_get_has_alpha(pixbuf) ||
4871 n_channels != 4 ||
4872 rowstride != width * n_channels)
4874 g_warning("incompatible image data for icon '%s'", name);
4875 g_object_unref(pixbuf);
4876 return FALSE;
4879 SSM(sci, SCI_RGBAIMAGESETWIDTH, width, 0);
4880 SSM(sci, SCI_RGBAIMAGESETHEIGHT, height, 0);
4881 SSM(sci, SCI_REGISTERRGBAIMAGE, id, (sptr_t)gdk_pixbuf_get_pixels(pixbuf));
4883 g_object_unref(pixbuf);
4884 return TRUE;
4888 /* Create new editor widget (scintilla).
4889 * @note The @c "sci-notify" signal is connected separately. */
4890 static ScintillaObject *create_new_sci(GeanyEditor *editor)
4892 ScintillaObject *sci;
4894 sci = SCINTILLA(scintilla_new());
4896 /* Scintilla doesn't support RTL languages properly and is primarily
4897 * intended to be used with LTR source code, so override the
4898 * GTK+ default text direction for the Scintilla widget. */
4899 gtk_widget_set_direction(GTK_WIDGET(sci), GTK_TEXT_DIR_LTR);
4901 gtk_widget_show(GTK_WIDGET(sci));
4903 sci_set_codepage(sci, SC_CP_UTF8);
4904 /*SSM(sci, SCI_SETWRAPSTARTINDENT, 4, 0);*/
4905 /* disable scintilla provided popup menu */
4906 sci_use_popup(sci, FALSE);
4908 setup_sci_keys(sci);
4910 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
4911 sci_set_lines_wrapped(sci, editor->line_wrapping);
4912 sci_set_caret_policy_x(sci, CARET_JUMPS | CARET_EVEN, 0);
4913 /* Y policy is set in editor_apply_update_prefs() */
4914 SSM(sci, SCI_AUTOCSETSEPARATOR, '\n', 0);
4915 SSM(sci, SCI_SETSCROLLWIDTHTRACKING, 1, 0);
4917 /* tag autocompletion images */
4918 register_named_icon(sci, 1, "classviewer-var");
4919 register_named_icon(sci, 2, "classviewer-method");
4921 /* necessary for column mode editing, implemented in Scintilla since 2.0 */
4922 SSM(sci, SCI_SETADDITIONALSELECTIONTYPING, 1, 0);
4924 /* virtual space */
4925 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
4927 #ifdef GDK_WINDOWING_QUARTZ
4928 # if ! GTK_CHECK_VERSION(3,16,0)
4929 /* "retina" (HiDPI) display support on OS X - requires disabling buffered draw
4930 * on older GTK versions */
4931 SSM(sci, SCI_SETBUFFEREDDRAW, 0, 0);
4932 # endif
4933 #endif
4935 /* only connect signals if this is for the document notebook, not split window */
4936 if (editor->sci == NULL)
4938 g_signal_connect(sci, "button-press-event", G_CALLBACK(on_editor_button_press_event), editor);
4939 g_signal_connect(sci, "scroll-event", G_CALLBACK(on_editor_scroll_event), editor);
4940 g_signal_connect(sci, "motion-notify-event", G_CALLBACK(on_motion_event), NULL);
4941 g_signal_connect(sci, "focus-in-event", G_CALLBACK(on_editor_focus_in), editor);
4942 #if GTK_CHECK_VERSION(3, 0, 0)
4943 g_signal_connect(sci, "draw", G_CALLBACK(on_editor_draw), editor);
4944 #else
4945 g_signal_connect(sci, "expose-event", G_CALLBACK(on_editor_expose_event), editor);
4946 #endif
4948 return sci;
4952 /** Creates a new Scintilla @c GtkWidget based on the settings for @a editor.
4953 * @param editor Editor settings.
4954 * @return @transfer{floating} The new widget.
4956 * @since 0.15
4958 GEANY_API_SYMBOL
4959 ScintillaObject *editor_create_widget(GeanyEditor *editor)
4961 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4962 ScintillaObject *old, *sci;
4963 GeanyIndentType old_indent_type = editor->indent_type;
4964 gint old_indent_width = editor->indent_width;
4966 /* temporarily change editor to use the new sci widget */
4967 old = editor->sci;
4968 sci = create_new_sci(editor);
4969 editor->sci = sci;
4971 editor_set_indent(editor, iprefs->type, iprefs->width);
4972 editor_set_font(editor, interface_prefs.editor_font);
4973 editor_apply_update_prefs(editor);
4975 /* if editor already had a widget, restore it */
4976 if (old)
4978 editor->indent_type = old_indent_type;
4979 editor->indent_width = old_indent_width;
4980 editor->sci = old;
4982 return sci;
4986 GeanyEditor *editor_create(GeanyDocument *doc)
4988 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4989 GeanyEditor *editor = g_new0(GeanyEditor, 1);
4991 editor->document = doc;
4992 doc->editor = editor; /* needed in case some editor functions/callbacks expect it */
4994 editor->auto_indent = (iprefs->auto_indent_mode != GEANY_AUTOINDENT_NONE);
4995 editor->line_wrapping = get_project_pref(line_wrapping);
4996 editor->scroll_percent = -1.0F;
4997 editor->line_breaking = FALSE;
4999 editor->sci = editor_create_widget(editor);
5000 return editor;
5004 /* in case we need to free some fields in future */
5005 void editor_destroy(GeanyEditor *editor)
5007 g_free(editor);
5011 static void on_document_save(GObject *obj, GeanyDocument *doc)
5013 gchar *f = g_build_filename(app->configdir, "snippets.conf", NULL);
5015 if (utils_str_equal(doc->real_path, f))
5017 /* reload snippets */
5018 editor_snippets_free();
5019 editor_snippets_init();
5021 g_free(f);
5025 gboolean editor_complete_word_part(GeanyEditor *editor)
5027 gchar *entry;
5029 g_return_val_if_fail(editor, FALSE);
5031 if (!SSM(editor->sci, SCI_AUTOCACTIVE, 0, 0))
5032 return FALSE;
5034 entry = sci_get_string(editor->sci, SCI_AUTOCGETCURRENTTEXT, 0);
5036 /* if no word part, complete normally */
5037 if (!check_partial_completion(editor, entry))
5038 SSM(editor->sci, SCI_AUTOCCOMPLETE, 0, 0);
5040 g_free(entry);
5041 return TRUE;
5045 void editor_init(void)
5047 static GeanyIndentPrefs indent_prefs;
5048 gchar *f;
5050 memset(&editor_prefs, 0, sizeof(GeanyEditorPrefs));
5051 memset(&indent_prefs, 0, sizeof(GeanyIndentPrefs));
5052 editor_prefs.indentation = &indent_prefs;
5054 /* use g_signal_connect_after() to allow plugins connecting to the signal before the default
5055 * handler (on_editor_notify) is called */
5056 g_signal_connect_after(geany_object, "editor-notify", G_CALLBACK(on_editor_notify), NULL);
5058 f = g_build_filename(app->configdir, "snippets.conf", NULL);
5059 ui_add_config_file_menu_item(f, NULL, NULL);
5060 g_free(f);
5061 g_signal_connect(geany_object, "document-save", G_CALLBACK(on_document_save), NULL);
5065 /* TODO: Should these be user-defined instead of hard-coded? */
5066 void editor_set_indentation_guides(GeanyEditor *editor)
5068 gint mode;
5069 gint lexer;
5071 g_return_if_fail(editor != NULL);
5073 if (! editor_prefs.show_indent_guide)
5075 sci_set_indentation_guides(editor->sci, SC_IV_NONE);
5076 return;
5079 lexer = sci_get_lexer(editor->sci);
5080 switch (lexer)
5082 /* Lines added/removed are prefixed with +/- characters, so
5083 * those lines will not be shown with any indentation guides.
5084 * It can be distracting that only a few of lines in a diff/patch
5085 * file will show the guides. */
5086 case SCLEX_DIFF:
5087 mode = SC_IV_NONE;
5088 break;
5090 /* These languages use indentation for control blocks; the "look forward" method works
5091 * best here */
5092 case SCLEX_PYTHON:
5093 case SCLEX_HASKELL:
5094 case SCLEX_MAKEFILE:
5095 case SCLEX_ASM:
5096 case SCLEX_SQL:
5097 case SCLEX_COBOL:
5098 case SCLEX_PROPERTIES:
5099 case SCLEX_FORTRAN: /* Is this the best option for Fortran? */
5100 case SCLEX_CAML:
5101 mode = SC_IV_LOOKFORWARD;
5102 break;
5104 /* C-like (structured) languages benefit from the "look both" method */
5105 case SCLEX_CPP:
5106 case SCLEX_HTML:
5107 case SCLEX_PHPSCRIPT:
5108 case SCLEX_XML:
5109 case SCLEX_PERL:
5110 case SCLEX_LATEX:
5111 case SCLEX_LUA:
5112 case SCLEX_PASCAL:
5113 case SCLEX_RUBY:
5114 case SCLEX_TCL:
5115 case SCLEX_F77:
5116 case SCLEX_CSS:
5117 case SCLEX_BASH:
5118 case SCLEX_VHDL:
5119 case SCLEX_FREEBASIC:
5120 case SCLEX_D:
5121 case SCLEX_OCTAVE:
5122 case SCLEX_RUST:
5123 mode = SC_IV_LOOKBOTH;
5124 break;
5126 default:
5127 mode = SC_IV_REAL;
5128 break;
5131 sci_set_indentation_guides(editor->sci, mode);
5135 /* Apply non-document prefs that can change in the Preferences dialog */
5136 void editor_apply_update_prefs(GeanyEditor *editor)
5138 ScintillaObject *sci;
5139 int caret_y_policy;
5141 g_return_if_fail(editor != NULL);
5143 if (main_status.quitting)
5144 return;
5146 sci = editor->sci;
5148 sci_set_mark_long_lines(sci, editor_get_long_line_type(),
5149 editor_get_long_line_column(), editor_prefs.long_line_color);
5151 /* update indent width, tab width */
5152 editor_set_indent(editor, editor->indent_type, editor->indent_width);
5153 sci_set_tab_indents(sci, editor_prefs.use_tab_to_indent);
5155 sci_assign_cmdkey(sci, SCK_HOME | (SCMOD_SHIFT << 16),
5156 editor_prefs.smart_home_key ? SCI_VCHOMEEXTEND : SCI_HOMEEXTEND);
5157 sci_assign_cmdkey(sci, SCK_HOME | ((SCMOD_SHIFT | SCMOD_ALT) << 16),
5158 editor_prefs.smart_home_key ? SCI_VCHOMERECTEXTEND : SCI_HOMERECTEXTEND);
5160 sci_set_autoc_max_height(sci, editor_prefs.symbolcompletion_max_height);
5161 SSM(sci, SCI_AUTOCSETDROPRESTOFWORD, editor_prefs.completion_drops_rest_of_word, 0);
5163 editor_set_indentation_guides(editor);
5165 sci_set_visible_white_spaces(sci, editor_prefs.show_white_space);
5166 sci_set_visible_eols(sci, editor_prefs.show_line_endings);
5167 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
5168 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin);
5170 sci_set_folding_margin_visible(sci, editor_prefs.folding);
5172 /* virtual space */
5173 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
5175 /* caret Y policy */
5176 caret_y_policy = CARET_EVEN;
5177 if (editor_prefs.scroll_lines_around_cursor > 0)
5178 caret_y_policy |= CARET_SLOP | CARET_STRICT;
5179 sci_set_caret_policy_y(sci, caret_y_policy, editor_prefs.scroll_lines_around_cursor);
5181 /* (dis)allow scrolling past end of document */
5182 sci_set_scroll_stop_at_last_line(sci, editor_prefs.scroll_stop_at_last_line);
5184 sci_set_scrollbar_mode(sci, editor_prefs.show_scrollbars);
5188 /* This is for tab-indents, space aligns formatted code. Spaces should be preserved. */
5189 static void change_tab_indentation(GeanyEditor *editor, gint line, gboolean increase)
5191 ScintillaObject *sci = editor->sci;
5192 gint pos = sci_get_position_from_line(sci, line);
5194 if (increase)
5196 sci_insert_text(sci, pos, "\t");
5198 else
5200 if (sci_get_char_at(sci, pos) == '\t')
5202 sci_set_selection(sci, pos, pos + 1);
5203 sci_replace_sel(sci, "");
5205 else /* remove spaces only if no tabs */
5207 gint width = sci_get_line_indentation(sci, line);
5209 width -= editor_get_indent_prefs(editor)->width;
5210 sci_set_line_indentation(sci, line, width);
5216 static void editor_change_line_indent(GeanyEditor *editor, gint line, gboolean increase)
5218 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
5219 ScintillaObject *sci = editor->sci;
5221 if (iprefs->type == GEANY_INDENT_TYPE_TABS)
5222 change_tab_indentation(editor, line, increase);
5223 else
5225 gint width = sci_get_line_indentation(sci, line);
5227 width += increase ? iprefs->width : -iprefs->width;
5228 sci_set_line_indentation(sci, line, width);
5233 void editor_indent(GeanyEditor *editor, gboolean increase)
5235 ScintillaObject *sci = editor->sci;
5236 gint caret_pos, caret_line, caret_offset, caret_indent_pos, caret_line_len;
5237 gint anchor_pos, anchor_line, anchor_offset, anchor_indent_pos, anchor_line_len;
5239 /* backup information needed to restore caret and anchor */
5240 caret_pos = sci_get_current_position(sci);
5241 anchor_pos = SSM(sci, SCI_GETANCHOR, 0, 0);
5242 caret_line = sci_get_line_from_position(sci, caret_pos);
5243 anchor_line = sci_get_line_from_position(sci, anchor_pos);
5244 caret_offset = caret_pos - sci_get_position_from_line(sci, caret_line);
5245 anchor_offset = anchor_pos - sci_get_position_from_line(sci, anchor_line);
5246 caret_indent_pos = sci_get_line_indent_position(sci, caret_line);
5247 anchor_indent_pos = sci_get_line_indent_position(sci, anchor_line);
5248 caret_line_len = sci_get_line_length(sci, caret_line);
5249 anchor_line_len = sci_get_line_length(sci, anchor_line);
5251 if (sci_get_lines_selected(sci) <= 1)
5253 editor_change_line_indent(editor, sci_get_current_line(sci), increase);
5255 else
5257 gint start, end;
5258 gint line, lstart, lend;
5260 editor_select_lines(editor, FALSE);
5261 start = sci_get_selection_start(sci);
5262 end = sci_get_selection_end(sci);
5263 lstart = sci_get_line_from_position(sci, start);
5264 lend = sci_get_line_from_position(sci, end);
5265 if (end == sci_get_length(sci))
5266 lend++; /* for last line with text on it */
5268 sci_start_undo_action(sci);
5269 for (line = lstart; line < lend; line++)
5271 editor_change_line_indent(editor, line, increase);
5273 sci_end_undo_action(sci);
5276 /* restore caret and anchor position */
5277 if (caret_pos >= caret_indent_pos)
5278 caret_offset += sci_get_line_length(sci, caret_line) - caret_line_len;
5279 if (anchor_pos >= anchor_indent_pos)
5280 anchor_offset += sci_get_line_length(sci, anchor_line) - anchor_line_len;
5282 SSM(sci, SCI_SETCURRENTPOS, sci_get_position_from_line(sci, caret_line) + caret_offset, 0);
5283 SSM(sci, SCI_SETANCHOR, sci_get_position_from_line(sci, anchor_line) + anchor_offset, 0);
5287 /** Gets snippet by name.
5289 * If @a editor is passed, returns a snippet specific to the document filetype.
5290 * If @a editor is @c NULL, returns a snippet from the default set.
5292 * @param editor @nullable Editor or @c NULL.
5293 * @param snippet_name Snippet name.
5294 * @return @nullable snippet or @c NULL if it was not found. Must not be freed.
5296 GEANY_API_SYMBOL
5297 const gchar *editor_find_snippet(GeanyEditor *editor, const gchar *snippet_name)
5299 const gchar *subhash_name = editor ? editor->document->file_type->name : "Default";
5300 GHashTable *subhash = g_hash_table_lookup(snippet_hash, subhash_name);
5302 return subhash ? g_hash_table_lookup(subhash, snippet_name) : NULL;
5306 /** Replaces all special sequences in @a snippet and inserts it at @a pos.
5307 * If you insert at the current position, consider calling @c sci_scroll_caret()
5308 * after this function.
5309 * @param editor .
5310 * @param pos .
5311 * @param snippet .
5313 GEANY_API_SYMBOL
5314 void editor_insert_snippet(GeanyEditor *editor, gint pos, const gchar *snippet)
5316 GString *pattern;
5318 pattern = g_string_new(snippet);
5319 snippets_make_replacements(editor, pattern);
5320 editor_insert_text_block(editor, pattern->str, pos, -1, -1, TRUE);
5321 g_string_free(pattern, TRUE);
5324 static void *copy_(void *src) { return src; }
5325 static void free_(void *doc) { }
5327 /** @gironly
5328 * Gets the GType of GeanyEditor
5330 * @return the GeanyEditor type */
5331 GEANY_API_SYMBOL
5332 GType editor_get_type (void);
5334 G_DEFINE_BOXED_TYPE(GeanyEditor, editor, copy_, free_);