Merge pull request #3011 from dolik-rce/fix-context-menus-on-wayland
[geany-mirror.git] / src / editor.c
blob7306418a88cf76b8e33895f5a665224fda6482cc
1 /*
2 * editor.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005 The Geany contributors
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21 /**
22 * @file editor.h
23 * Editor-related functions for @ref GeanyEditor.
24 * Geany uses the Scintilla editing widget, and this file is mostly built around
25 * Scintilla's functionality.
26 * @see sciwrappers.h.
28 /* Callbacks for the Scintilla widget (ScintillaObject).
29 * Most important is the sci-notify callback, handled in on_editor_notification().
30 * This includes auto-indentation, comments, auto-completion, calltips, etc.
31 * Also some general Scintilla-related functions.
34 #ifdef HAVE_CONFIG_H
35 # include "config.h"
36 #endif
38 #include "editor.h"
40 #include "app.h"
41 #include "callbacks.h"
42 #include "dialogs.h"
43 #include "documentprivate.h"
44 #include "filetypesprivate.h"
45 #include "geanyobject.h"
46 #include "highlighting.h"
47 #include "keybindings.h"
48 #include "main.h"
49 #include "prefs.h"
50 #include "projectprivate.h"
51 #include "sciwrappers.h"
52 #include "support.h"
53 #include "symbols.h"
54 #include "templates.h"
55 #include "ui_utils.h"
56 #include "utils.h"
58 #include "SciLexer.h"
60 #include <ctype.h>
61 #include <string.h>
63 #include <gtk/gtk.h>
64 #include <gdk/gdkkeysyms.h>
67 static GHashTable *snippet_hash = NULL;
68 static GtkAccelGroup *snippet_accel_group = NULL;
69 static gboolean autocomplete_scope_shown = FALSE;
71 static const gchar geany_cursor_marker[] = "__GEANY_CURSOR_MARKER__";
73 /* holds word under the mouse or keyboard cursor */
74 static gchar current_word[GEANY_MAX_WORD_LENGTH];
76 /* Initialised in keyfile.c. */
77 GeanyEditorPrefs editor_prefs;
79 EditorInfo editor_info = {current_word, -1};
81 static struct
83 gchar *text;
84 gboolean set;
85 gchar *last_word;
86 guint tag_index;
87 gint pos;
88 ScintillaObject *sci;
89 } calltip = {NULL, FALSE, NULL, 0, 0, NULL};
91 static gchar indent[100];
94 static void on_new_line_added(GeanyEditor *editor);
95 static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch);
96 static void insert_indent_after_line(GeanyEditor *editor, gint line);
97 static void auto_multiline(GeanyEditor *editor, gint pos);
98 static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c);
99 static void close_block(GeanyEditor *editor, gint pos);
100 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos);
101 static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen,
102 const gchar *wc, gboolean stem);
103 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent);
104 static const gchar *snippets_find_completion_by_name(const gchar *type, const gchar *name);
105 static void snippets_make_replacements(GeanyEditor *editor, GString *pattern);
106 static GeanyFiletype *editor_get_filetype_at_line(GeanyEditor *editor, gint line);
107 static gboolean sci_is_blank_line(ScintillaObject *sci, gint line);
110 void editor_snippets_free(void)
112 g_hash_table_destroy(snippet_hash);
113 gtk_window_remove_accel_group(GTK_WINDOW(main_widgets.window), snippet_accel_group);
117 static void snippets_load(GKeyFile *sysconfig, GKeyFile *userconfig)
119 gsize i, j, len = 0, len_keys = 0;
120 gchar **groups_user, **groups_sys;
121 gchar **keys_user, **keys_sys;
122 gchar *value;
123 GHashTable *tmp;
125 /* keys are strings, values are GHashTables, so use g_free and g_hash_table_destroy */
126 snippet_hash =
127 g_hash_table_new_full(g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_hash_table_destroy);
129 /* first read all globally defined auto completions */
130 groups_sys = g_key_file_get_groups(sysconfig, &len);
131 for (i = 0; i < len; i++)
133 if (strcmp(groups_sys[i], "Keybindings") == 0)
134 continue;
135 keys_sys = g_key_file_get_keys(sysconfig, groups_sys[i], &len_keys, NULL);
136 /* create new hash table for the read section (=> filetype) */
137 tmp = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
138 g_hash_table_insert(snippet_hash, g_strdup(groups_sys[i]), tmp);
140 for (j = 0; j < len_keys; j++)
142 g_hash_table_insert(tmp, g_strdup(keys_sys[j]),
143 utils_get_setting_string(sysconfig, groups_sys[i], keys_sys[j], ""));
145 g_strfreev(keys_sys);
147 g_strfreev(groups_sys);
149 /* now read defined completions in user's configuration directory and add / replace them */
150 groups_user = g_key_file_get_groups(userconfig, &len);
151 for (i = 0; i < len; i++)
153 if (strcmp(groups_user[i], "Keybindings") == 0)
154 continue;
155 keys_user = g_key_file_get_keys(userconfig, groups_user[i], &len_keys, NULL);
157 tmp = g_hash_table_lookup(snippet_hash, groups_user[i]);
158 if (tmp == NULL)
159 { /* new key found, create hash table */
160 tmp = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
161 g_hash_table_insert(snippet_hash, g_strdup(groups_user[i]), tmp);
163 for (j = 0; j < len_keys; j++)
165 value = g_hash_table_lookup(tmp, keys_user[j]);
166 if (value == NULL)
167 { /* value = NULL means the key doesn't yet exist, so insert */
168 g_hash_table_insert(tmp, g_strdup(keys_user[j]),
169 utils_get_setting_string(userconfig, groups_user[i], keys_user[j], ""));
171 else
172 { /* old key and value will be freed by destroy function (g_free) */
173 g_hash_table_replace(tmp, g_strdup(keys_user[j]),
174 utils_get_setting_string(userconfig, groups_user[i], keys_user[j], ""));
177 g_strfreev(keys_user);
179 g_strfreev(groups_user);
183 static gboolean on_snippet_keybinding_activate(gchar *key)
185 GeanyDocument *doc = document_get_current();
186 const gchar *s;
188 if (!doc || !gtk_widget_has_focus(GTK_WIDGET(doc->editor->sci)))
189 return FALSE;
191 s = snippets_find_completion_by_name(doc->file_type->name, key);
192 if (!s) /* allow user to specify keybindings for "special" snippets */
194 GHashTable *specials = g_hash_table_lookup(snippet_hash, "Special");
196 if (G_LIKELY(specials != NULL))
197 s = g_hash_table_lookup(specials, key);
199 if (!s)
201 utils_beep();
202 return FALSE;
205 editor_insert_snippet(doc->editor, sci_get_current_position(doc->editor->sci), s);
206 sci_scroll_caret(doc->editor->sci);
208 return TRUE;
212 static void add_kb(GKeyFile *keyfile, const gchar *group, gchar **keys)
214 gsize i;
216 if (!keys)
217 return;
218 for (i = 0; i < g_strv_length(keys); i++)
220 guint key;
221 GdkModifierType mods;
222 gchar *accel_string = g_key_file_get_value(keyfile, group, keys[i], NULL);
224 gtk_accelerator_parse(accel_string, &key, &mods);
226 if (key == 0 && mods == 0)
228 g_warning("Can not parse accelerator \"%s\" from user snippets.conf", accel_string);
229 g_free(accel_string);
230 continue;
232 g_free(accel_string);
234 gtk_accel_group_connect(snippet_accel_group, key, mods, 0,
235 g_cclosure_new_swap((GCallback)on_snippet_keybinding_activate,
236 g_strdup(keys[i]), (GClosureNotify)g_free));
241 static void load_kb(GKeyFile *sysconfig, GKeyFile *userconfig)
243 const gchar kb_group[] = "Keybindings";
244 gchar **keys = g_key_file_get_keys(userconfig, kb_group, NULL, NULL);
245 gchar **ptr;
247 /* remove overridden keys from system keyfile */
248 foreach_strv(ptr, keys)
249 g_key_file_remove_key(sysconfig, kb_group, *ptr, NULL);
251 add_kb(userconfig, kb_group, keys);
252 g_strfreev(keys);
254 keys = g_key_file_get_keys(sysconfig, kb_group, NULL, NULL);
255 add_kb(sysconfig, kb_group, keys);
256 g_strfreev(keys);
260 void editor_snippets_init(void)
262 gchar *sysconfigfile, *userconfigfile;
263 GKeyFile *sysconfig = g_key_file_new();
264 GKeyFile *userconfig = g_key_file_new();
266 sysconfigfile = g_build_filename(app->datadir, "snippets.conf", NULL);
267 userconfigfile = g_build_filename(app->configdir, "snippets.conf", NULL);
269 /* check for old autocomplete.conf files (backwards compatibility) */
270 if (! g_file_test(userconfigfile, G_FILE_TEST_IS_REGULAR))
271 SETPTR(userconfigfile, g_build_filename(app->configdir, "autocomplete.conf", NULL));
273 /* load the actual config files */
274 g_key_file_load_from_file(sysconfig, sysconfigfile, G_KEY_FILE_NONE, NULL);
275 g_key_file_load_from_file(userconfig, userconfigfile, G_KEY_FILE_NONE, NULL);
277 snippets_load(sysconfig, userconfig);
279 /* setup snippet keybindings */
280 snippet_accel_group = gtk_accel_group_new();
281 gtk_window_add_accel_group(GTK_WINDOW(main_widgets.window), snippet_accel_group);
282 load_kb(sysconfig, userconfig);
284 g_free(sysconfigfile);
285 g_free(userconfigfile);
286 g_key_file_free(sysconfig);
287 g_key_file_free(userconfig);
291 static gboolean on_editor_button_press_event(GtkWidget *widget, GdkEventButton *event,
292 gpointer data)
294 GeanyEditor *editor = data;
295 GeanyDocument *doc = editor->document;
297 /* it's very unlikely we got a 'real' click even on 0, 0, so assume it is a
298 * fake event to show the editor menu triggered by a key event where we want to use the
299 * text cursor position. */
300 if (event->x > 0.0 && event->y > 0.0)
301 editor_info.click_pos = sci_get_position_from_xy(editor->sci,
302 (gint)event->x, (gint)event->y, FALSE);
303 else
304 editor_info.click_pos = sci_get_current_position(editor->sci);
306 if (event->button == 1)
308 guint state = keybindings_get_modifiers(event->state);
310 if (event->type == GDK_BUTTON_PRESS && editor_prefs.disable_dnd)
312 gint ss = sci_get_selection_start(editor->sci);
313 sci_set_selection_end(editor->sci, ss);
315 if (event->type == GDK_BUTTON_PRESS && state == GEANY_PRIMARY_MOD_MASK)
317 sci_set_current_position(editor->sci, editor_info.click_pos, FALSE);
319 editor_find_current_word(editor, editor_info.click_pos,
320 current_word, sizeof current_word, NULL);
321 if (*current_word)
322 return symbols_goto_tag(current_word, TRUE);
323 else
324 keybindings_send_command(GEANY_KEY_GROUP_GOTO, GEANY_KEYS_GOTO_MATCHINGBRACE);
325 return TRUE;
327 return document_check_disk_status(doc, FALSE);
330 /* calls the edit popup menu in the editor */
331 if (event->button == 3)
333 gboolean can_goto;
335 /* ensure the editor widget has the focus after this operation */
336 gtk_widget_grab_focus(widget);
338 editor_find_current_word(editor, editor_info.click_pos,
339 current_word, sizeof current_word, NULL);
341 can_goto = sci_has_selection(editor->sci) || current_word[0] != '\0';
342 ui_update_popup_goto_items(can_goto);
343 ui_update_popup_copy_items(doc);
344 ui_update_insert_include_item(doc, 0);
346 g_signal_emit_by_name(geany_object, "update-editor-menu",
347 current_word, editor_info.click_pos, doc);
349 ui_menu_popup(GTK_MENU(main_widgets.editor_menu), NULL, NULL, event->button, event->time);
350 return TRUE;
352 return FALSE;
356 static gboolean is_style_php(gint style)
358 if ((style >= SCE_HPHP_DEFAULT && style <= SCE_HPHP_OPERATOR) ||
359 style == SCE_HPHP_COMPLEX_VARIABLE)
361 return TRUE;
364 return FALSE;
368 static gint editor_get_long_line_type(void)
370 if (app->project)
371 switch (app->project->priv->long_line_behaviour)
373 case 0: /* marker disabled */
374 return 2;
375 case 1: /* use global settings */
376 break;
377 case 2: /* custom (enabled) */
378 return editor_prefs.long_line_type;
381 if (!editor_prefs.long_line_enabled)
382 return 2;
383 else
384 return editor_prefs.long_line_type;
388 static gint editor_get_long_line_column(void)
390 if (app->project && app->project->priv->long_line_behaviour != 1 /* use global settings */)
391 return app->project->priv->long_line_column;
392 else
393 return editor_prefs.long_line_column;
397 #define get_project_pref(id)\
398 (app->project ? app->project->priv->id : editor_prefs.id)
400 static const GeanyEditorPrefs *
401 get_default_prefs(void)
403 static GeanyEditorPrefs eprefs;
405 eprefs = editor_prefs;
407 /* project overrides */
408 eprefs.indentation = (GeanyIndentPrefs*)editor_get_indent_prefs(NULL);
409 eprefs.long_line_type = editor_get_long_line_type();
410 eprefs.long_line_column = editor_get_long_line_column();
411 eprefs.line_wrapping = get_project_pref(line_wrapping);
412 eprefs.line_break_column = get_project_pref(line_break_column);
413 eprefs.auto_continue_multiline = get_project_pref(auto_continue_multiline);
414 return &eprefs;
418 /* Gets the prefs for the editor.
419 * Prefs can be different according to project or document.
420 * @warning Always get a fresh result instead of keeping a pointer to it if the editor/project
421 * settings may have changed, or if this function has been called for a different editor.
422 * @param editor The editor, or @c NULL to get the default prefs.
423 * @return The prefs. */
424 const GeanyEditorPrefs *editor_get_prefs(GeanyEditor *editor)
426 static GeanyEditorPrefs eprefs;
427 const GeanyEditorPrefs *dprefs = get_default_prefs();
429 /* Return the address of the default prefs to allow returning default and editor
430 * pref pointers without invalidating the contents of either. */
431 if (editor == NULL)
432 return dprefs;
434 eprefs = *dprefs;
435 eprefs.indentation = (GeanyIndentPrefs*)editor_get_indent_prefs(editor);
436 /* add other editor & document overrides as needed */
437 return &eprefs;
441 void editor_toggle_fold(GeanyEditor *editor, gint line, gint modifiers)
443 ScintillaObject *sci;
444 gint header;
446 g_return_if_fail(editor != NULL);
448 sci = editor->sci;
449 /* When collapsing a fold range whose starting line is offscreen,
450 * scroll the starting line to display at the top of the view.
451 * Otherwise it can be confusing when the document scrolls down to hide
452 * the folded lines. */
453 if ((sci_get_fold_level(sci, line) & SC_FOLDLEVELNUMBERMASK) > SC_FOLDLEVELBASE &&
454 !(sci_get_fold_level(sci, line) & SC_FOLDLEVELHEADERFLAG))
456 gint parent = sci_get_fold_parent(sci, line);
457 gint first = sci_get_first_visible_line(sci);
459 parent = SSM(sci, SCI_VISIBLEFROMDOCLINE, parent, 0);
460 if (first > parent)
461 SSM(sci, SCI_SETFIRSTVISIBLELINE, parent, 0);
464 /* find the fold header of the given line in case the one clicked isn't a fold point */
465 if (sci_get_fold_level(sci, line) & SC_FOLDLEVELHEADERFLAG)
466 header = line;
467 else
468 header = sci_get_fold_parent(sci, line);
470 if ((editor_prefs.unfold_all_children && ! (modifiers & SCMOD_SHIFT)) ||
471 (! editor_prefs.unfold_all_children && (modifiers & SCMOD_SHIFT)))
473 SSM(sci, SCI_FOLDCHILDREN, header, SC_FOLDACTION_TOGGLE);
475 else
477 SSM(sci, SCI_FOLDLINE, header, SC_FOLDACTION_TOGGLE);
482 static void on_margin_click(GeanyEditor *editor, SCNotification *nt)
484 /* left click to marker margin marks the line */
485 if (nt->margin == 1)
487 gint line = sci_get_line_from_position(editor->sci, nt->position);
489 /*sci_marker_delete_all(editor->sci, 1);*/
490 sci_toggle_marker_at_line(editor->sci, line, 1); /* toggle the marker */
492 /* left click on the folding margin to toggle folding state of current line */
493 else if (nt->margin == 2 && editor_prefs.folding)
495 gint line = sci_get_line_from_position(editor->sci, nt->position);
496 editor_toggle_fold(editor, line, nt->modifiers);
501 static void on_update_ui(GeanyEditor *editor, G_GNUC_UNUSED SCNotification *nt)
503 ScintillaObject *sci = editor->sci;
504 gint pos = sci_get_current_position(sci);
506 /* since Scintilla 2.24, SCN_UPDATEUI is also sent on scrolling though we don't need to handle
507 * this and so ignore every SCN_UPDATEUI events except for content and selection changes */
508 if (! (nt->updated & SC_UPDATE_CONTENT) && ! (nt->updated & SC_UPDATE_SELECTION))
509 return;
511 /* undo / redo menu update */
512 ui_update_popup_reundo_items(editor->document);
514 /* brace highlighting */
515 editor_highlight_braces(editor, pos);
517 ui_update_statusbar(editor->document, pos);
519 #if 0
520 /** experimental code for inverting selections */
522 gint i;
523 for (i = SSM(sci, SCI_GETSELECTIONSTART, 0, 0); i < SSM(sci, SCI_GETSELECTIONEND, 0, 0); i++)
525 /* need to get colour from getstyleat(), but how? */
526 SSM(sci, SCI_STYLESETFORE, STYLE_DEFAULT, 0);
527 SSM(sci, SCI_STYLESETBACK, STYLE_DEFAULT, 0);
530 sci_get_style_at(sci, pos);
532 #endif
536 static void check_line_breaking(GeanyEditor *editor, gint pos)
538 ScintillaObject *sci = editor->sci;
539 gint line, lstart, col;
540 gchar c;
542 if (!editor->line_breaking || sci_get_selection_mode(editor->sci) != SC_SEL_STREAM)
543 return;
545 col = sci_get_col_from_position(sci, pos);
547 line = sci_get_current_line(sci);
549 lstart = sci_get_position_from_line(sci, line);
551 /* use column instead of position which might be different with multibyte characters */
552 if (col < get_project_pref(line_break_column))
553 return;
555 /* look for the last space before line_break_column */
556 pos = sci_get_position_from_col(sci, line, get_project_pref(line_break_column));
558 while (pos > lstart)
560 c = sci_get_char_at(sci, --pos);
561 if (c == ' ')
563 gint diff, last_pos, last_col;
565 /* remember the distance between the current column and the last column on the line
566 * (we use column position in case the previous line gets altered, such as removing
567 * trailing spaces or in case it contains multibyte characters) */
568 last_pos = sci_get_line_end_position(sci, line);
569 last_col = sci_get_col_from_position(sci, last_pos);
570 diff = last_col - col;
572 /* break the line after the space */
573 sci_set_current_position(sci, pos + 1, FALSE);
574 sci_cancel(sci); /* don't select from completion list */
575 sci_send_command(sci, SCI_NEWLINE);
576 line++;
578 /* correct cursor position (might not be at line end) */
579 last_pos = sci_get_line_end_position(sci, line);
580 last_col = sci_get_col_from_position(sci, last_pos); /* get last column on line */
581 /* last column - distance is the desired column, then retrieve its document position */
582 pos = sci_get_position_from_col(sci, line, last_col - diff);
583 sci_set_current_position(sci, pos, FALSE);
584 sci_scroll_caret(sci);
585 return;
591 static void show_autocomplete(ScintillaObject *sci, gsize rootlen, GString *words)
593 /* hide autocompletion if only option is already typed */
594 if (rootlen >= words->len ||
595 (words->str[rootlen] == '?' && rootlen >= words->len - 2))
597 sci_send_command(sci, SCI_AUTOCCANCEL);
598 return;
600 /* store whether a calltip is showing, so we can reshow it after autocompletion */
601 calltip.set = (gboolean) SSM(sci, SCI_CALLTIPACTIVE, 0, 0);
602 SSM(sci, SCI_AUTOCSETORDER, SC_ORDER_CUSTOM, 0);
603 SSM(sci, SCI_AUTOCSHOW, rootlen, (sptr_t) words->str);
607 static void show_tags_list(GeanyEditor *editor, const GPtrArray *tags, gsize rootlen)
609 ScintillaObject *sci = editor->sci;
611 g_return_if_fail(tags);
613 if (tags->len > 0)
615 GString *words = g_string_sized_new(150);
616 guint j;
618 for (j = 0; j < tags->len; ++j)
620 TMTag *tag = tags->pdata[j];
621 gint group;
622 guint icon_id;
624 if (j > 0)
625 g_string_append_c(words, '\n');
627 if (j == editor_prefs.autocompletion_max_entries)
629 g_string_append(words, "...");
630 break;
632 g_string_append(words, tag->name);
634 group = tm_parser_get_sidebar_group(tag->lang, tag->type);
635 if (group >= 0 && tm_parser_get_sidebar_info(tag->lang, group, &icon_id))
637 gchar buf[10];
638 sprintf(buf, "?%u", icon_id + 1);
639 g_string_append(words, buf);
642 show_autocomplete(sci, rootlen, words);
643 g_string_free(words, TRUE);
648 static gint scope_autocomplete_suffix(ScintillaObject *sci, TMParserType lang,
649 gint pos, gboolean *scope_sep)
651 const gchar *sep = tm_parser_scope_separator(lang);
652 const gsize max_len = 3;
653 gboolean is_scope_sep;
654 gchar *buf;
656 buf = g_alloca(max_len + 1);
657 sci_get_text_range(sci, pos - max_len, pos, buf);
659 is_scope_sep = g_str_has_suffix(buf, sep);
660 if (scope_sep)
661 *scope_sep = is_scope_sep;
662 if (is_scope_sep)
663 return strlen(sep);
664 return tm_parser_scope_autocomplete_suffix(lang, buf);
668 static gboolean reshow_calltip(gpointer data)
670 GeanyDocument *doc;
672 g_return_val_if_fail(calltip.sci != NULL, FALSE);
674 SSM(calltip.sci, SCI_CALLTIPCANCEL, 0, 0);
675 doc = document_get_current();
677 if (doc && doc->editor->sci == calltip.sci)
679 /* we use the position where the calltip was previously started as SCI_GETCURRENTPOS
680 * may be completely wrong in case the user cancelled the auto completion with the mouse */
681 SSM(calltip.sci, SCI_CALLTIPSHOW, calltip.pos, (sptr_t) calltip.text);
683 return FALSE;
687 static void request_reshowing_calltip(SCNotification *nt)
689 if (calltip.set)
691 /* delay the reshow of the calltip window to make sure it is actually displayed,
692 * without it might be not visible on SCN_AUTOCCANCEL. the priority is set to
693 * low to hopefully make Scintilla's events happen before reshowing since they
694 * seem to re-cancel the calltip on autoc menu hiding too */
695 g_idle_add_full(G_PRIORITY_LOW, reshow_calltip, NULL, NULL);
700 static gboolean autocomplete_scope(GeanyEditor *editor, const gchar *root, gsize rootlen)
702 ScintillaObject *sci = editor->sci;
703 gint pos = sci_get_current_position(editor->sci);
704 gint line = sci_get_current_line(editor->sci) + 1;
705 gchar typed = sci_get_char_at(sci, pos - 1);
706 gchar brace_char;
707 gchar *name;
708 GeanyFiletype *ft = editor->document->file_type;
709 GPtrArray *tags;
710 gboolean function = FALSE;
711 gboolean member;
712 gboolean scope_sep_typed = FALSE;
713 gboolean ret = FALSE;
714 const gchar *current_scope;
715 gint autocomplete_suffix_len;
717 if (autocomplete_scope_shown)
719 /* move at the operator position */
720 pos -= rootlen;
722 /* allow for a space between word and operator */
723 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
724 pos--;
726 if (pos > 0)
727 typed = sci_get_char_at(sci, pos - 1);
730 autocomplete_suffix_len = scope_autocomplete_suffix(sci, ft->lang, pos,
731 &scope_sep_typed);
732 if (autocomplete_suffix_len == 0)
733 return FALSE;
735 pos -= autocomplete_suffix_len;
737 /* allow for a space between word and operator */
738 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
739 pos--;
741 /* if function or array index, skip to matching brace */
742 brace_char = sci_get_char_at(sci, pos - 1);
743 if (pos > 0 && (brace_char == ')' || brace_char == ']'))
745 gint brace_pos = sci_find_matching_brace(sci, pos - 1);
747 if (brace_pos != -1)
749 pos = brace_pos;
750 function = brace_char == ')';
753 /* allow for a space between opening brace and name */
754 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
755 pos--;
758 name = editor_get_word_at_pos(editor, pos, NULL);
759 if (!name)
760 return FALSE;
762 /* check if invoked on member */
763 pos -= strlen(name);
764 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
765 pos--;
766 member = scope_autocomplete_suffix(sci, ft->lang, pos, NULL) > 0;
768 if (symbols_get_current_scope(editor->document, &current_scope) == -1)
769 current_scope = "";
770 tags = tm_workspace_find_scope_members(editor->document->tm_file, name, function,
771 member, current_scope, line, scope_sep_typed);
772 if (tags)
774 GPtrArray *filtered = g_ptr_array_new();
775 TMTag *tag;
776 guint i;
778 foreach_ptr_array(tag, i, tags)
780 if (g_str_has_prefix(tag->name, root))
781 g_ptr_array_add(filtered, tag);
784 if (filtered->len > 0)
786 show_tags_list(editor, filtered, rootlen);
787 ret = TRUE;
790 g_ptr_array_free(tags, TRUE);
791 g_ptr_array_free(filtered, TRUE);
794 g_free(name);
795 return ret;
799 static void on_char_added(GeanyEditor *editor, SCNotification *nt)
801 ScintillaObject *sci = editor->sci;
802 gint pos = sci_get_current_position(sci);
804 switch (nt->ch)
806 case '\r':
807 { /* simple indentation (only for CR format) */
808 if (sci_get_eol_mode(sci) == SC_EOL_CR)
809 on_new_line_added(editor);
810 break;
812 case '\n':
813 { /* simple indentation (for CR/LF and LF format) */
814 on_new_line_added(editor);
815 break;
817 case '>':
818 editor_start_auto_complete(editor, pos, FALSE); /* C/C++ ptr-> scope completion */
819 /* fall through */
820 case '/':
821 { /* close xml-tags */
822 handle_xml(editor, pos, nt->ch);
823 break;
825 case '(':
827 auto_close_chars(sci, pos, nt->ch);
828 /* show calltips */
829 editor_show_calltip(editor, --pos);
830 break;
832 case ')':
833 { /* hide calltips */
834 if (SSM(sci, SCI_CALLTIPACTIVE, 0, 0))
836 SSM(sci, SCI_CALLTIPCANCEL, 0, 0);
838 g_free(calltip.text);
839 calltip.text = NULL;
840 calltip.pos = 0;
841 calltip.sci = NULL;
842 calltip.set = FALSE;
843 break;
845 case '{':
846 case '[':
847 case '"':
848 case '\'':
850 auto_close_chars(sci, pos, nt->ch);
851 break;
853 case '}':
854 { /* closing bracket handling */
855 if (editor->auto_indent)
856 close_block(editor, pos - 1);
857 break;
859 /* scope autocompletion */
860 case '.':
861 case ':': /* C/C++ class:: syntax */
862 /* tag autocompletion */
863 default:
864 #if 0
865 if (! editor_start_auto_complete(editor, pos, FALSE))
866 request_reshowing_calltip(nt);
867 #else
868 editor_start_auto_complete(editor, pos, FALSE);
869 #endif
871 check_line_breaking(editor, pos);
875 /* expand() and fold_changed() are copied from SciTE (thanks) to fix #1923350. */
876 static void expand(ScintillaObject *sci, gint *line, gboolean doExpand,
877 gboolean force, gint visLevels, gint level)
879 gint lineMaxSubord = SSM(sci, SCI_GETLASTCHILD, *line, level & SC_FOLDLEVELNUMBERMASK);
880 gint levelLine = level;
881 (*line)++;
882 while (*line <= lineMaxSubord)
884 if (force)
886 if (visLevels > 0)
887 SSM(sci, SCI_SHOWLINES, *line, *line);
888 else
889 SSM(sci, SCI_HIDELINES, *line, *line);
891 else
893 if (doExpand)
894 SSM(sci, SCI_SHOWLINES, *line, *line);
896 if (levelLine == -1)
897 levelLine = SSM(sci, SCI_GETFOLDLEVEL, *line, 0);
898 if (levelLine & SC_FOLDLEVELHEADERFLAG)
900 if (force)
902 if (visLevels > 1)
903 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
904 else
905 SSM(sci, SCI_SETFOLDEXPANDED, *line, 0);
906 expand(sci, line, doExpand, force, visLevels - 1, -1);
908 else
910 if (doExpand)
912 if (!sci_get_fold_expanded(sci, *line))
913 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
914 expand(sci, line, TRUE, force, visLevels - 1, -1);
916 else
918 expand(sci, line, FALSE, force, visLevels - 1, -1);
922 else
924 (*line)++;
930 static void fold_changed(ScintillaObject *sci, gint line, gint levelNow, gint levelPrev)
932 if (levelNow & SC_FOLDLEVELHEADERFLAG)
934 if (! (levelPrev & SC_FOLDLEVELHEADERFLAG))
936 /* Adding a fold point */
937 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
938 if (!SSM(sci, SCI_GETALLLINESVISIBLE, 0, 0))
939 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
942 else if (levelPrev & SC_FOLDLEVELHEADERFLAG)
944 if (! sci_get_fold_expanded(sci, line))
945 { /* Removing the fold from one that has been contracted so should expand
946 * otherwise lines are left invisible with no way to make them visible */
947 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
948 if (!SSM(sci, SCI_GETALLLINESVISIBLE, 0, 0))
949 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
952 if (! (levelNow & SC_FOLDLEVELWHITEFLAG) &&
953 ((levelPrev & SC_FOLDLEVELNUMBERMASK) > (levelNow & SC_FOLDLEVELNUMBERMASK)))
955 if (!SSM(sci, SCI_GETALLLINESVISIBLE, 0, 0)) {
956 /* See if should still be hidden */
957 gint parentLine = sci_get_fold_parent(sci, line);
958 if (parentLine < 0)
960 SSM(sci, SCI_SHOWLINES, line, line);
962 else if (sci_get_fold_expanded(sci, parentLine) &&
963 sci_get_line_is_visible(sci, parentLine))
965 SSM(sci, SCI_SHOWLINES, line, line);
972 static void ensure_range_visible(ScintillaObject *sci, gint posStart, gint posEnd,
973 gboolean enforcePolicy)
975 gint lineStart = sci_get_line_from_position(sci, MIN(posStart, posEnd));
976 gint lineEnd = sci_get_line_from_position(sci, MAX(posStart, posEnd));
977 gint line;
979 for (line = lineStart; line <= lineEnd; line++)
981 SSM(sci, enforcePolicy ? SCI_ENSUREVISIBLEENFORCEPOLICY : SCI_ENSUREVISIBLE, line, 0);
986 static void auto_update_margin_width(GeanyEditor *editor)
988 gint next_linecount = 1;
989 gint linecount = sci_get_line_count(editor->sci);
990 GeanyDocument *doc = editor->document;
992 while (next_linecount <= linecount)
993 next_linecount *= 10;
995 if (editor->document->priv->line_count != next_linecount)
997 doc->priv->line_count = next_linecount;
998 sci_set_line_numbers(editor->sci, TRUE);
1003 static void partial_complete(ScintillaObject *sci, const gchar *text)
1005 gint pos = sci_get_current_position(sci);
1007 sci_insert_text(sci, pos, text);
1008 sci_set_current_position(sci, pos + strlen(text), TRUE);
1012 /* Complete the next word part from @a entry */
1013 static gboolean check_partial_completion(GeanyEditor *editor, const gchar *entry)
1015 gchar *stem, *ptr, *text = utils_strdupa(entry);
1017 read_current_word(editor, -1, current_word, sizeof current_word, NULL, TRUE);
1018 stem = current_word;
1019 if (strstr(text, stem) != text)
1020 return FALSE; /* shouldn't happen */
1021 if (strlen(text) <= strlen(stem))
1022 return FALSE;
1024 text += strlen(stem); /* skip stem */
1025 ptr = strstr(text + 1, "_");
1026 if (ptr)
1028 ptr[1] = '\0';
1029 partial_complete(editor->sci, text);
1030 return TRUE;
1032 else
1034 /* CamelCase */
1035 foreach_str(ptr, text + 1)
1037 if (!ptr[0])
1038 break;
1039 if (g_ascii_isupper(*ptr) && g_ascii_islower(ptr[1]))
1041 ptr[0] = '\0';
1042 partial_complete(editor->sci, text);
1043 return TRUE;
1047 return FALSE;
1051 /* Callback for the "sci-notify" signal to emit a "editor-notify" signal.
1052 * Plugins can connect to the "editor-notify" signal. */
1053 void editor_sci_notify_cb(G_GNUC_UNUSED GtkWidget *widget, G_GNUC_UNUSED gint scn,
1054 gpointer scnt, gpointer data)
1056 GeanyEditor *editor = data;
1057 gboolean retval;
1059 g_return_if_fail(editor != NULL);
1061 g_signal_emit_by_name(geany_object, "editor-notify", editor, scnt, &retval);
1065 /* recalculate margins width */
1066 static void update_margins(ScintillaObject *sci)
1068 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin);
1069 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
1070 sci_set_folding_margin_visible(sci, editor_prefs.folding);
1074 static gboolean on_editor_notify(G_GNUC_UNUSED GObject *object, GeanyEditor *editor,
1075 SCNotification *nt, G_GNUC_UNUSED gpointer data)
1077 ScintillaObject *sci = editor->sci;
1078 GeanyDocument *doc = editor->document;
1080 switch (nt->nmhdr.code)
1082 case SCN_SAVEPOINTLEFT:
1083 document_set_text_changed(doc, TRUE);
1084 break;
1086 case SCN_SAVEPOINTREACHED:
1087 document_set_text_changed(doc, FALSE);
1088 break;
1090 case SCN_MODIFYATTEMPTRO:
1091 utils_beep();
1092 break;
1094 case SCN_MARGINCLICK:
1095 on_margin_click(editor, nt);
1096 break;
1098 case SCN_UPDATEUI:
1099 on_update_ui(editor, nt);
1100 break;
1102 case SCN_PAINTED:
1103 /* Visible lines are only laid out accurately just before painting,
1104 * so we need to only call editor_scroll_to_line here, because the document
1105 * may have line wrapping and folding enabled.
1106 * http://scintilla.sourceforge.net/ScintillaDoc.html#LineWrapping
1107 * This is important e.g. when loading a session and switching pages
1108 * and having the cursor scroll in view. */
1109 /* FIXME: Really we want to do this just before painting, not after it
1110 * as it will cause repainting. */
1111 if (editor->scroll_percent > 0.0F)
1113 editor_scroll_to_line(editor, -1, editor->scroll_percent);
1114 /* disable further scrolling */
1115 editor->scroll_percent = -1.0F;
1117 break;
1119 case SCN_MODIFIED:
1120 if (editor_prefs.show_linenumber_margin && (nt->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT)) && nt->linesAdded)
1122 /* automatically adjust Scintilla's line numbers margin width */
1123 auto_update_margin_width(editor);
1125 if (nt->modificationType & SC_STARTACTION && ! ignore_callback)
1127 /* get notified about undo changes */
1128 document_undo_add(doc, UNDO_SCINTILLA, NULL);
1130 if (editor_prefs.folding && (nt->modificationType & SC_MOD_CHANGEFOLD) != 0)
1132 /* handle special fold cases, e.g. #1923350 */
1133 fold_changed(sci, nt->line, nt->foldLevelNow, nt->foldLevelPrev);
1135 if (nt->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT))
1137 document_update_tag_list_in_idle(doc);
1139 break;
1141 case SCN_CHARADDED:
1142 on_char_added(editor, nt);
1143 break;
1145 case SCN_USERLISTSELECTION:
1146 if (nt->listType == 1)
1148 sci_add_text(sci, nt->text);
1150 break;
1152 case SCN_AUTOCSELECTION:
1153 if (g_str_equal(nt->text, "..."))
1155 sci_cancel(sci);
1156 utils_beep();
1157 break;
1159 /* fall through */
1160 case SCN_AUTOCCANCELLED:
1161 /* now that autocomplete is finishing or was cancelled, reshow calltips
1162 * if they were showing */
1163 autocomplete_scope_shown = FALSE;
1164 request_reshowing_calltip(nt);
1165 break;
1166 case SCN_NEEDSHOWN:
1167 ensure_range_visible(sci, nt->position, nt->position + nt->length, FALSE);
1168 break;
1170 case SCN_URIDROPPED:
1171 if (nt->text != NULL)
1173 document_open_file_list(nt->text, strlen(nt->text));
1175 break;
1177 case SCN_CALLTIPCLICK:
1178 if (nt->position > 0)
1180 switch (nt->position)
1182 case 1: /* up arrow */
1183 if (calltip.tag_index > 0)
1184 calltip.tag_index--;
1185 break;
1187 case 2: calltip.tag_index++; break; /* down arrow */
1189 editor_show_calltip(editor, -1);
1191 break;
1193 case SCN_ZOOM:
1194 update_margins(sci);
1195 break;
1197 /* we always return FALSE here to let plugins handle the event too */
1198 return FALSE;
1202 /* Note: this is the same as sci_get_tab_width(), but is still useful when you don't have
1203 * a scintilla pointer. */
1204 static gint get_tab_width(const GeanyIndentPrefs *indent_prefs)
1206 if (indent_prefs->type == GEANY_INDENT_TYPE_BOTH)
1207 return indent_prefs->hard_tab_width;
1209 return indent_prefs->width; /* tab width = indent width */
1213 /* Returns a string containing width chars of whitespace, filled with simple space
1214 * characters or with the right number of tab characters, according to the indent prefs.
1215 * (Result is filled with tabs *and* spaces if width isn't a multiple of
1216 * the tab width). */
1217 static gchar *
1218 get_whitespace(const GeanyIndentPrefs *iprefs, gint width)
1220 g_return_val_if_fail(width >= 0, NULL);
1222 if (width == 0)
1223 return g_strdup("");
1225 if (iprefs->type == GEANY_INDENT_TYPE_SPACES)
1227 return g_strnfill(width, ' ');
1229 else
1230 { /* first fill text with tabs and fill the rest with spaces */
1231 const gint tab_width = get_tab_width(iprefs);
1232 gint tabs = width / tab_width;
1233 gint spaces = width % tab_width;
1234 gint len = tabs + spaces;
1235 gchar *str;
1237 str = g_malloc(len + 1);
1239 memset(str, '\t', tabs);
1240 memset(str + tabs, ' ', spaces);
1241 str[len] = '\0';
1242 return str;
1247 static const GeanyIndentPrefs *
1248 get_default_indent_prefs(void)
1250 static GeanyIndentPrefs iprefs;
1252 iprefs = app->project ? *app->project->priv->indentation : *editor_prefs.indentation;
1253 return &iprefs;
1257 /** Gets the indentation prefs for the editor.
1258 * Prefs can be different according to project or document.
1259 * @warning Always get a fresh result instead of keeping a pointer to it if the editor/project
1260 * settings may have changed, or if this function has been called for a different editor.
1261 * @param editor @nullable The editor, or @c NULL to get the default indent prefs.
1262 * @return The indent prefs. */
1263 GEANY_API_SYMBOL
1264 const GeanyIndentPrefs *
1265 editor_get_indent_prefs(GeanyEditor *editor)
1267 static GeanyIndentPrefs iprefs;
1268 const GeanyIndentPrefs *dprefs = get_default_indent_prefs();
1270 /* Return the address of the default prefs to allow returning default and editor
1271 * pref pointers without invalidating the contents of either. */
1272 if (editor == NULL)
1273 return dprefs;
1275 iprefs = *dprefs;
1276 iprefs.type = editor->indent_type;
1277 iprefs.width = editor->indent_width;
1279 /* if per-document auto-indent is enabled, but we don't have a global mode set,
1280 * just use basic auto-indenting */
1281 if (editor->auto_indent && iprefs.auto_indent_mode == GEANY_AUTOINDENT_NONE)
1282 iprefs.auto_indent_mode = GEANY_AUTOINDENT_BASIC;
1284 if (!editor->auto_indent)
1285 iprefs.auto_indent_mode = GEANY_AUTOINDENT_NONE;
1287 return &iprefs;
1291 static void on_new_line_added(GeanyEditor *editor)
1293 ScintillaObject *sci = editor->sci;
1294 gint line = sci_get_current_line(sci);
1296 /* simple indentation */
1297 if (editor->auto_indent)
1299 insert_indent_after_line(editor, line - 1);
1302 if (get_project_pref(auto_continue_multiline))
1303 { /* " * " auto completion in multiline C/C++/D/Java comments */
1304 auto_multiline(editor, line);
1307 if (editor_prefs.newline_strip)
1308 { /* strip the trailing spaces on the previous line */
1309 editor_strip_line_trailing_spaces(editor, line - 1);
1314 static gboolean lexer_has_braces(ScintillaObject *sci)
1316 gint lexer = sci_get_lexer(sci);
1318 switch (lexer)
1320 case SCLEX_CPP:
1321 case SCLEX_D:
1322 case SCLEX_HTML: /* for PHP & JS */
1323 case SCLEX_PHPSCRIPT:
1324 case SCLEX_PASCAL: /* for multiline comments? */
1325 case SCLEX_BASH:
1326 case SCLEX_PERL:
1327 case SCLEX_TCL:
1328 case SCLEX_R:
1329 case SCLEX_RUST:
1330 return TRUE;
1331 default:
1332 return FALSE;
1337 /* Read indent chars for the line that pos is on into indent global variable.
1338 * Note: Use sci_get_line_indentation() and get_whitespace()/editor_insert_text_block()
1339 * instead in any new code. */
1340 static void read_indent(GeanyEditor *editor, gint pos)
1342 ScintillaObject *sci = editor->sci;
1343 guint i, len, j = 0;
1344 gint line;
1345 gchar *linebuf;
1347 line = sci_get_line_from_position(sci, pos);
1349 len = sci_get_line_length(sci, line);
1350 linebuf = sci_get_line(sci, line);
1352 for (i = 0; i < len && j <= (sizeof(indent) - 1); i++)
1354 if (linebuf[i] == ' ' || linebuf[i] == '\t') /* simple indentation */
1355 indent[j++] = linebuf[i];
1356 else
1357 break;
1359 indent[j] = '\0';
1360 g_free(linebuf);
1364 static gint get_brace_indent(ScintillaObject *sci, gint line)
1366 gint start = sci_get_position_from_line(sci, line);
1367 gint end = sci_get_line_end_position(sci, line) - 1;
1368 gint lexer = sci_get_lexer(sci);
1369 gint count = 0;
1370 gint pos;
1372 for (pos = end; pos >= start && count < 1; pos--)
1374 if (highlighting_is_code_style(lexer, sci_get_style_at(sci, pos)))
1376 gchar c = sci_get_char_at(sci, pos);
1378 if (c == '{')
1379 count ++;
1380 else if (c == '}')
1381 count --;
1385 return count > 0 ? 1 : 0;
1389 /* gets the last code position on a line
1390 * warning: if there is no code position on the line, returns the start position */
1391 static gint get_sci_line_code_end_position(ScintillaObject *sci, gint line)
1393 gint start = sci_get_position_from_line(sci, line);
1394 gint lexer = sci_get_lexer(sci);
1395 gint pos;
1397 for (pos = sci_get_line_end_position(sci, line) - 1; pos > start; pos--)
1399 gint style = sci_get_style_at(sci, pos);
1401 if (highlighting_is_code_style(lexer, style) && ! isspace(sci_get_char_at(sci, pos)))
1402 break;
1405 return pos;
1409 static gint get_python_indent(ScintillaObject *sci, gint line)
1411 gint last_char = get_sci_line_code_end_position(sci, line);
1413 /* add extra indentation for Python after colon */
1414 if (sci_get_char_at(sci, last_char) == ':' &&
1415 sci_get_style_at(sci, last_char) == SCE_P_OPERATOR)
1417 return 1;
1419 return 0;
1423 static gint get_xml_indent(ScintillaObject *sci, gint line)
1425 gboolean need_close = FALSE;
1426 gint end = get_sci_line_code_end_position(sci, line);
1427 gint pos;
1429 /* don't indent if there's a closing tag to the right of the cursor */
1430 pos = sci_get_current_position(sci);
1431 if (sci_get_char_at(sci, pos) == '<' &&
1432 sci_get_char_at(sci, pos + 1) == '/')
1433 return 0;
1435 if (sci_get_char_at(sci, end) == '>' &&
1436 sci_get_char_at(sci, end - 1) != '/')
1438 gint style = sci_get_style_at(sci, end);
1440 if (style == SCE_H_TAG || style == SCE_H_TAGUNKNOWN)
1442 gint start = sci_get_position_from_line(sci, line);
1443 gchar *line_contents = sci_get_contents_range(sci, start, end + 1);
1444 gchar *opened_tag_name = utils_find_open_xml_tag(line_contents, end + 1 - start);
1446 if (!EMPTY(opened_tag_name))
1448 need_close = TRUE;
1449 if (sci_get_lexer(sci) == SCLEX_HTML && utils_is_short_html_tag(opened_tag_name))
1450 need_close = FALSE;
1452 g_free(line_contents);
1453 g_free(opened_tag_name);
1457 return need_close ? 1 : 0;
1461 static gint get_indent_size_after_line(GeanyEditor *editor, gint line)
1463 ScintillaObject *sci = editor->sci;
1464 gint size;
1465 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1467 g_return_val_if_fail(line >= 0, 0);
1469 size = sci_get_line_indentation(sci, line);
1471 if (iprefs->auto_indent_mode > GEANY_AUTOINDENT_BASIC)
1473 gint additional_indent = 0;
1475 if (lexer_has_braces(sci))
1476 additional_indent = iprefs->width * get_brace_indent(sci, line);
1477 else if (sci_get_lexer(sci) == SCLEX_PYTHON) /* Python/Cython */
1478 additional_indent = iprefs->width * get_python_indent(sci, line);
1480 /* HTML lexer "has braces" because of PHP and JavaScript. If get_brace_indent() did not
1481 * recommend us to insert additional indent, we are probably not in PHP/JavaScript chunk and
1482 * should make the XML-related check */
1483 if (additional_indent == 0 &&
1484 (sci_get_lexer(sci) == SCLEX_HTML ||
1485 sci_get_lexer(sci) == SCLEX_XML) &&
1486 editor->document->file_type->priv->xml_indent_tags)
1488 size += iprefs->width * get_xml_indent(sci, line);
1491 size += additional_indent;
1493 return size;
1497 static void insert_indent_after_line(GeanyEditor *editor, gint line)
1499 ScintillaObject *sci = editor->sci;
1500 gint line_indent = sci_get_line_indentation(sci, line);
1501 gint size = get_indent_size_after_line(editor, line);
1502 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1503 gchar *text;
1505 if (size == 0)
1506 return;
1508 if (iprefs->type == GEANY_INDENT_TYPE_TABS && size == line_indent)
1510 /* support tab indents, space aligns style - copy last line 'indent' exactly */
1511 gint start = sci_get_position_from_line(sci, line);
1512 gint end = sci_get_line_indent_position(sci, line);
1514 text = sci_get_contents_range(sci, start, end);
1516 else
1518 text = get_whitespace(iprefs, size);
1520 sci_add_text(sci, text);
1521 g_free(text);
1525 static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c)
1527 const gchar *closing_char = NULL;
1528 gint end_pos = -1;
1530 if (utils_isbrace(c, 0))
1531 end_pos = sci_find_matching_brace(sci, pos - 1);
1533 switch (c)
1535 case '(':
1536 if ((editor_prefs.autoclose_chars & GEANY_AC_PARENTHESIS) && end_pos == -1)
1537 closing_char = ")";
1538 break;
1539 case '{':
1540 if ((editor_prefs.autoclose_chars & GEANY_AC_CBRACKET) && end_pos == -1)
1541 closing_char = "}";
1542 break;
1543 case '[':
1544 if ((editor_prefs.autoclose_chars & GEANY_AC_SBRACKET) && end_pos == -1)
1545 closing_char = "]";
1546 break;
1547 case '\'':
1548 if (editor_prefs.autoclose_chars & GEANY_AC_SQUOTE)
1549 closing_char = "'";
1550 break;
1551 case '"':
1552 if (editor_prefs.autoclose_chars & GEANY_AC_DQUOTE)
1553 closing_char = "\"";
1554 break;
1557 if (closing_char != NULL)
1559 sci_add_text(sci, closing_char);
1560 sci_set_current_position(sci, pos, TRUE);
1565 /* Finds a corresponding matching brace to the given pos
1566 * (this is taken from Scintilla Editor.cxx,
1567 * fit to work with close_block) */
1568 static gint brace_match(ScintillaObject *sci, gint pos)
1570 gchar chBrace = sci_get_char_at(sci, pos);
1571 gchar chSeek = utils_brace_opposite(chBrace);
1572 gchar chAtPos;
1573 gint direction = -1;
1574 gint styBrace;
1575 gint depth = 1;
1576 gint styAtPos;
1578 /* Hack: we need the style at @p pos but it isn't computed yet, so force styling
1579 * of this very position */
1580 sci_colourise(sci, pos, pos + 1);
1582 styBrace = sci_get_style_at(sci, pos);
1584 if (utils_is_opening_brace(chBrace, editor_prefs.brace_match_ltgt))
1585 direction = 1;
1587 pos += direction;
1588 while ((pos >= 0) && (pos < sci_get_length(sci)))
1590 chAtPos = sci_get_char_at(sci, pos);
1591 styAtPos = sci_get_style_at(sci, pos);
1593 if ((pos > sci_get_end_styled(sci)) || (styAtPos == styBrace))
1595 if (chAtPos == chBrace)
1596 depth++;
1597 if (chAtPos == chSeek)
1598 depth--;
1599 if (depth == 0)
1600 return pos;
1602 pos += direction;
1604 return -1;
1608 /* Called after typing '}'. */
1609 static void close_block(GeanyEditor *editor, gint pos)
1611 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1612 gint x = 0, cnt = 0;
1613 gint line, line_len;
1614 gchar *line_buf;
1615 ScintillaObject *sci;
1616 gint line_indent, last_indent;
1618 if (iprefs->auto_indent_mode < GEANY_AUTOINDENT_CURRENTCHARS)
1619 return;
1620 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
1622 sci = editor->sci;
1624 if (! lexer_has_braces(sci))
1625 return;
1627 line = sci_get_line_from_position(sci, pos);
1628 line_len = sci_get_line_end_position(sci, line) - sci_get_position_from_line(sci, line);
1630 /* check that the line is empty, to not kill text in the line */
1631 line_buf = sci_get_line(sci, line);
1632 line_buf[line_len] = '\0';
1633 while (x < line_len)
1635 if (isspace(line_buf[x]))
1636 cnt++;
1637 x++;
1639 g_free(line_buf);
1641 if ((line_len - 1) != cnt)
1642 return;
1644 if (iprefs->auto_indent_mode == GEANY_AUTOINDENT_MATCHBRACES)
1646 gint start_brace = brace_match(sci, pos);
1648 if (start_brace >= 0)
1650 gint line_start;
1651 gint brace_line = sci_get_line_from_position(sci, start_brace);
1652 gint size = sci_get_line_indentation(sci, brace_line);
1653 gchar *ind = get_whitespace(iprefs, size);
1654 gchar *text = g_strconcat(ind, "}", NULL);
1656 line_start = sci_get_position_from_line(sci, line);
1657 sci_set_anchor(sci, line_start);
1658 sci_replace_sel(sci, text);
1659 g_free(text);
1660 g_free(ind);
1661 return;
1663 /* fall through - unmatched brace (possibly because of TCL, PHP lexer bugs) */
1666 /* GEANY_AUTOINDENT_CURRENTCHARS */
1667 line_indent = sci_get_line_indentation(sci, line);
1668 last_indent = sci_get_line_indentation(sci, line - 1);
1670 if (line_indent < last_indent)
1671 return;
1672 line_indent -= iprefs->width;
1673 line_indent = MAX(0, line_indent);
1674 sci_set_line_indentation(sci, line, line_indent);
1678 /* checks whether @p c is an ASCII character (e.g. < 0x80) */
1679 #define IS_ASCII(c) (((unsigned char)(c)) < 0x80)
1682 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1683 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1684 * position can be -1, then the current position is used.
1685 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1686 static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen,
1687 const gchar *wc, gboolean stem)
1689 gint line, line_start, startword, endword;
1690 gchar *chunk;
1691 ScintillaObject *sci;
1693 g_return_if_fail(editor != NULL);
1694 sci = editor->sci;
1696 if (pos == -1)
1697 pos = sci_get_current_position(sci);
1699 line = sci_get_line_from_position(sci, pos);
1700 line_start = sci_get_position_from_line(sci, line);
1701 startword = pos - line_start;
1702 endword = pos - line_start;
1704 word[0] = '\0';
1705 chunk = sci_get_line(sci, line);
1707 if (wc == NULL)
1708 wc = GEANY_WORDCHARS;
1710 /* the checks for "c < 0" are to allow any Unicode character which should make the code
1711 * a little bit more Unicode safe, anyway, this allows also any Unicode punctuation,
1712 * TODO: improve this code */
1713 while (startword > 0 && (strchr(wc, chunk[startword - 1]) || ! IS_ASCII(chunk[startword - 1])))
1714 startword--;
1715 if (!stem)
1717 while (chunk[endword] != 0 && (strchr(wc, chunk[endword]) || ! IS_ASCII(chunk[endword])))
1718 endword++;
1721 if (startword != endword)
1723 chunk[endword] = '\0';
1725 g_strlcpy(word, chunk + startword, wordlen); /* ensure null terminated */
1727 else
1728 g_strlcpy(word, "", wordlen);
1730 g_free(chunk);
1734 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1735 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1736 * position can be -1, then the current position is used.
1737 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1738 void editor_find_current_word(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen,
1739 const gchar *wc)
1741 read_current_word(editor, pos, word, wordlen, wc, FALSE);
1745 /* Same as editor_find_current_word() but uses editor's word boundaries to decide what the word
1746 * is. This should be used e.g. to get the word to search for */
1747 void editor_find_current_word_sciwc(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen)
1749 gint start;
1750 gint end;
1752 g_return_if_fail(editor != NULL);
1754 if (pos == -1)
1755 pos = sci_get_current_position(editor->sci);
1757 start = sci_word_start_position(editor->sci, pos, TRUE);
1758 end = sci_word_end_position(editor->sci, pos, TRUE);
1760 if (start == end) /* caret in whitespaces sequence */
1761 *word = 0;
1762 else
1764 if ((guint)(end - start) >= wordlen)
1765 end = start + (wordlen - 1);
1766 sci_get_text_range(editor->sci, start, end, word);
1772 * Finds the word at the position specified by @a pos. If any word is found, it is returned.
1773 * Otherwise NULL is returned.
1774 * Additional wordchars can be specified to define what to consider as a word.
1776 * @param editor The editor to operate on.
1777 * @param pos The position where the word should be read from.
1778 * May be @c -1 to use the current position.
1779 * @param wordchars The wordchars to separate words. wordchars mean all characters to count
1780 * as part of a word. May be @c NULL to use the default wordchars,
1781 * see @ref GEANY_WORDCHARS.
1783 * @return @nullable A newly-allocated string containing the word at the given @a pos or @c NULL.
1784 * Should be freed when no longer needed.
1786 * @since 0.16
1788 GEANY_API_SYMBOL
1789 gchar *editor_get_word_at_pos(GeanyEditor *editor, gint pos, const gchar *wordchars)
1791 static gchar cword[GEANY_MAX_WORD_LENGTH];
1793 g_return_val_if_fail(editor != NULL, FALSE);
1795 read_current_word(editor, pos, cword, sizeof(cword), wordchars, FALSE);
1797 return (*cword == '\0') ? NULL : g_strdup(cword);
1801 /* Read the word up to position @a pos. */
1802 static const gchar *
1803 editor_read_word_stem(GeanyEditor *editor, gint pos, const gchar *wordchars)
1805 static gchar word[GEANY_MAX_WORD_LENGTH];
1807 read_current_word(editor, pos, word, sizeof word, wordchars, TRUE);
1809 return (*word) ? word : NULL;
1813 static gint find_previous_brace(ScintillaObject *sci, gint pos)
1815 gint orig_pos = pos;
1817 while (pos >= 0 && pos > orig_pos - 300)
1819 gchar c = sci_get_char_at(sci, pos);
1820 if (utils_is_opening_brace(c, editor_prefs.brace_match_ltgt))
1821 return pos;
1822 pos--;
1824 return -1;
1828 static gint find_start_bracket(ScintillaObject *sci, gint pos)
1830 gint brackets = 0;
1831 gint orig_pos = pos;
1833 while (pos > 0 && pos > orig_pos - 300)
1835 gchar c = sci_get_char_at(sci, pos);
1837 if (c == ')') brackets++;
1838 else if (c == '(') brackets--;
1839 if (brackets < 0) return pos; /* found start bracket */
1840 pos--;
1842 return -1;
1846 static gchar *find_calltip(const gchar *word, GeanyFiletype *ft)
1848 const gchar *constructor_method;
1849 GPtrArray *tags;
1850 TMTag *tag;
1851 GString *str = NULL;
1852 guint i;
1854 g_return_val_if_fail(ft && word && *word, NULL);
1856 /* use all types in case language uses wrong tag type e.g. python "members" instead of "methods" */
1857 tags = tm_workspace_find(word, NULL, tm_tag_max_t, NULL, ft->lang);
1858 if (tags->len == 0)
1860 g_ptr_array_free(tags, TRUE);
1861 return NULL;
1864 tag = TM_TAG(tags->pdata[0]);
1866 /* user typed e.g. 'a = Classname(' in Python so lookup __init__() arguments */
1867 constructor_method = tm_parser_get_constructor_method(tag->lang);
1868 if (constructor_method && (tag->type == tm_tag_class_t || tag->type == tm_tag_struct_t))
1870 const TMTagType arg_types = tm_tag_function_t | tm_tag_prototype_t |
1871 tm_tag_method_t | tm_tag_macro_with_arg_t;
1872 const gchar *scope_sep = tm_parser_scope_separator(ft->lang);
1873 gchar *scope = EMPTY(tag->scope) ? g_strdup(tag->name) :
1874 g_strjoin(scope_sep, tag->scope, tag->name, NULL);
1876 g_ptr_array_free(tags, TRUE);
1877 tags = tm_workspace_find(constructor_method, scope, arg_types, NULL, ft->lang);
1878 g_free(scope);
1879 if (tags->len == 0)
1881 g_ptr_array_free(tags, TRUE);
1882 return NULL;
1886 /* remove tags with no argument list */
1887 for (i = 0; i < tags->len; i++)
1889 tag = TM_TAG(tags->pdata[i]);
1891 if (! tag->arglist)
1892 tags->pdata[i] = NULL;
1894 tm_tags_prune((GPtrArray *) tags);
1895 if (tags->len == 0)
1897 g_ptr_array_free(tags, TRUE);
1898 return NULL;
1900 else
1901 { /* remove duplicate calltips */
1902 TMTagAttrType sort_attr[] = {tm_tag_attr_name_t, tm_tag_attr_scope_t,
1903 tm_tag_attr_arglist_t, 0};
1905 tm_tags_sort((GPtrArray *) tags, sort_attr, TRUE, FALSE);
1908 /* if the current word has changed since last time, start with the first tag match */
1909 if (! utils_str_equal(word, calltip.last_word))
1910 calltip.tag_index = 0;
1911 /* cache the current word for next time */
1912 g_free(calltip.last_word);
1913 calltip.last_word = g_strdup(word);
1914 calltip.tag_index = MIN(calltip.tag_index, tags->len - 1); /* ensure tag_index is in range */
1916 for (i = calltip.tag_index; i < tags->len; i++)
1918 tag = TM_TAG(tags->pdata[i]);
1920 if (str == NULL)
1922 gchar *f = tm_parser_format_function(tag->lang, tag->name,
1923 tag->arglist, tag->var_type, tag->scope);
1924 str = g_string_new(NULL);
1925 if (calltip.tag_index > 0)
1926 g_string_prepend(str, "\001 "); /* up arrow */
1927 g_string_append(str, f);
1928 g_free(f);
1930 else /* add a down arrow */
1932 if (calltip.tag_index > 0) /* already have an up arrow */
1933 g_string_insert_c(str, 1, '\002');
1934 else
1935 g_string_prepend(str, "\002 ");
1936 break;
1940 g_ptr_array_free(tags, TRUE);
1942 if (str)
1944 gchar *result = str->str;
1946 g_string_free(str, FALSE);
1947 return result;
1949 return NULL;
1953 /* use pos = -1 to search for the previous unmatched open bracket. */
1954 gboolean editor_show_calltip(GeanyEditor *editor, gint pos)
1956 gint orig_pos = pos; /* the position for the calltip */
1957 gint lexer;
1958 gint style;
1959 gchar word[GEANY_MAX_WORD_LENGTH];
1960 gchar *str;
1961 ScintillaObject *sci;
1963 g_return_val_if_fail(editor != NULL, FALSE);
1964 g_return_val_if_fail(editor->document->file_type != NULL, FALSE);
1966 sci = editor->sci;
1968 lexer = sci_get_lexer(sci);
1970 if (pos == -1)
1972 /* position of '(' is unknown, so go backwards from current position to find it */
1973 pos = sci_get_current_position(sci);
1974 pos--;
1975 orig_pos = pos;
1976 pos = (lexer == SCLEX_LATEX) ? find_previous_brace(sci, pos) :
1977 find_start_bracket(sci, pos);
1978 if (pos == -1)
1979 return FALSE;
1982 /* the style 1 before the brace (which may be highlighted) */
1983 style = sci_get_style_at(sci, pos - 1);
1984 if (! highlighting_is_code_style(lexer, style))
1985 return FALSE;
1987 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
1988 pos--;
1990 /* skip possible generic/template specification, like foo<int>() */
1991 if (sci_get_char_at(sci, pos - 1) == '>')
1993 pos = sci_find_matching_brace(sci, pos - 1);
1994 if (pos == -1)
1995 return FALSE;
1997 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
1998 pos--;
2001 word[0] = '\0';
2002 editor_find_current_word(editor, pos - 1, word, sizeof word, NULL);
2003 if (word[0] == '\0')
2004 return FALSE;
2006 str = find_calltip(word, editor->document->file_type);
2007 if (str)
2009 g_free(calltip.text); /* free the old calltip */
2010 calltip.text = str;
2011 calltip.pos = orig_pos;
2012 calltip.sci = sci;
2013 calltip.set = TRUE;
2014 utils_wrap_string(calltip.text, -1);
2015 SSM(sci, SCI_CALLTIPSHOW, orig_pos, (sptr_t) calltip.text);
2016 return TRUE;
2018 return FALSE;
2022 /* Current document & global tags autocompletion */
2023 static gboolean
2024 autocomplete_tags(GeanyEditor *editor, GeanyFiletype *ft, const gchar *root, gsize rootlen)
2026 GeanyDocument *doc = editor->document;
2027 const gchar *current_scope = NULL;
2028 guint current_line;
2029 GPtrArray *tags;
2030 gboolean found;
2032 g_return_val_if_fail(editor && doc, FALSE);
2034 symbols_get_current_function(doc, &current_scope);
2035 current_line = sci_get_current_line(editor->sci) + 1;
2037 tags = tm_workspace_find_prefix(root, doc->tm_file, current_line, current_scope,
2038 editor_prefs.autocompletion_max_entries);
2039 found = tags->len > 0;
2040 if (found)
2041 show_tags_list(editor, tags, rootlen);
2042 g_ptr_array_free(tags, TRUE);
2044 return found;
2048 static gboolean autocomplete_check_html(GeanyEditor *editor, gint style, gint pos)
2050 GeanyFiletype *ft = editor->document->file_type;
2051 gboolean try = FALSE;
2053 /* use entity completion when style is not JavaScript, ASP, Python, PHP, ...
2054 * (everything after SCE_HJ_START is for embedded scripting languages) */
2055 if (ft->id == GEANY_FILETYPES_HTML && style < SCE_HJ_START)
2056 try = TRUE;
2057 else if (sci_get_lexer(editor->sci) == SCLEX_XML && style < SCE_HJ_START)
2058 try = TRUE;
2059 else if (ft->id == GEANY_FILETYPES_PHP)
2061 /* use entity completion when style is outside of PHP styles */
2062 if (! is_style_php(style))
2063 try = TRUE;
2065 if (try)
2067 gchar root[GEANY_MAX_WORD_LENGTH];
2068 gchar *tmp;
2070 read_current_word(editor, pos, root, sizeof(root), GEANY_WORDCHARS"&", TRUE);
2072 /* Allow something like "&quot;some text&quot;".
2073 * for entity completion we want to have completion for '&' within words. */
2074 tmp = strchr(root, '&');
2075 if (tmp != NULL)
2077 return autocomplete_tags(editor, filetypes_index(GEANY_FILETYPES_HTML), tmp, strlen(tmp));
2080 return FALSE;
2084 /* Algorithm based on based on Scite's StartAutoCompleteWord()
2085 * @returns a sorted list of words matching @p root */
2086 static GSList *get_doc_words(ScintillaObject *sci, gchar *root, gsize rootlen)
2088 gchar *word;
2089 gint len, current, word_end;
2090 gint pos_find, flags;
2091 guint word_length;
2092 gsize nmatches = 0;
2093 GSList *words = NULL;
2094 struct Sci_TextToFind ttf;
2096 len = sci_get_length(sci);
2097 current = sci_get_current_position(sci) - rootlen;
2099 ttf.lpstrText = root;
2100 ttf.chrg.cpMin = 0;
2101 ttf.chrg.cpMax = len;
2102 ttf.chrgText.cpMin = 0;
2103 ttf.chrgText.cpMax = 0;
2104 flags = SCFIND_WORDSTART | SCFIND_MATCHCASE;
2106 /* search the whole document for the word root and collect results */
2107 pos_find = SSM(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
2108 while (pos_find >= 0 && pos_find < len)
2110 word_end = pos_find + rootlen;
2111 if (pos_find != current)
2113 word_end = sci_word_end_position(sci, word_end, TRUE);
2115 word_length = word_end - pos_find;
2116 if (word_length > rootlen)
2118 word = sci_get_contents_range(sci, pos_find, word_end);
2119 /* search whether we already have the word in, otherwise add it */
2120 if (g_slist_find_custom(words, word, (GCompareFunc)strcmp) != NULL)
2121 g_free(word);
2122 else
2124 words = g_slist_prepend(words, word);
2125 nmatches++;
2128 if (nmatches == editor_prefs.autocompletion_max_entries)
2129 break;
2132 ttf.chrg.cpMin = word_end;
2133 pos_find = SSM(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
2136 return g_slist_sort(words, (GCompareFunc)utils_str_casecmp);
2140 static gboolean autocomplete_doc_word(GeanyEditor *editor, gchar *root, gsize rootlen)
2142 ScintillaObject *sci = editor->sci;
2143 GSList *words, *node;
2144 GString *str;
2145 guint n_words = 0;
2147 words = get_doc_words(sci, root, rootlen);
2148 if (!words)
2150 SSM(sci, SCI_AUTOCCANCEL, 0, 0);
2151 return FALSE;
2154 str = g_string_sized_new(rootlen * 2 * 10);
2155 foreach_slist(node, words)
2157 g_string_append(str, node->data);
2158 g_free(node->data);
2159 if (node->next)
2160 g_string_append_c(str, '\n');
2161 n_words++;
2163 if (n_words >= editor_prefs.autocompletion_max_entries)
2164 g_string_append(str, "\n...");
2166 g_slist_free(words);
2168 show_autocomplete(sci, rootlen, str);
2169 g_string_free(str, TRUE);
2170 return TRUE;
2174 gboolean editor_start_auto_complete(GeanyEditor *editor, gint pos, gboolean force)
2176 gint rootlen, lexer, style;
2177 gchar *root;
2178 gchar cword[GEANY_MAX_WORD_LENGTH];
2179 ScintillaObject *sci;
2180 gboolean ret = FALSE;
2181 const gchar *wordchars;
2182 GeanyFiletype *ft;
2184 g_return_val_if_fail(editor != NULL, FALSE);
2186 if (! editor_prefs.auto_complete_symbols && ! force)
2187 return FALSE;
2189 /* If we are at the beginning of the document, we skip autocompletion as we can't determine the
2190 * necessary styling information */
2191 if (G_UNLIKELY(pos < 2))
2192 return FALSE;
2194 sci = editor->sci;
2195 ft = editor->document->file_type;
2197 lexer = sci_get_lexer(sci);
2198 style = sci_get_style_at(sci, pos - 2);
2200 /* don't autocomplete in comments and strings */
2201 if (!force && !highlighting_is_code_style(lexer, style))
2202 return FALSE;
2204 ret = autocomplete_check_html(editor, style, pos);
2206 if (ft->id == GEANY_FILETYPES_LATEX)
2207 wordchars = GEANY_WORDCHARS"\\"; /* add \ to word chars if we are in a LaTeX file */
2208 else if (ft->id == GEANY_FILETYPES_CSS)
2209 wordchars = GEANY_WORDCHARS"-"; /* add - because they are part of property names */
2210 else
2211 wordchars = GEANY_WORDCHARS;
2213 read_current_word(editor, pos, cword, sizeof(cword), wordchars, TRUE);
2214 root = cword;
2215 rootlen = strlen(root);
2217 if (ret || force)
2219 if (autocomplete_scope_shown)
2221 autocomplete_scope_shown = FALSE;
2222 if (!ret)
2223 sci_send_command(sci, SCI_AUTOCCANCEL);
2226 else
2228 ret = autocomplete_scope(editor, root, rootlen);
2229 if (!ret && autocomplete_scope_shown)
2230 sci_send_command(sci, SCI_AUTOCCANCEL);
2231 autocomplete_scope_shown = ret;
2234 if (!ret && rootlen > 0)
2236 if (ft->id == GEANY_FILETYPES_PHP && style == SCE_HPHP_DEFAULT &&
2237 rootlen == 3 && strcmp(root, "php") == 0 && pos >= 5 &&
2238 sci_get_char_at(sci, pos - 5) == '<' &&
2239 sci_get_char_at(sci, pos - 4) == '?')
2241 /* nothing, don't complete PHP open tags */
2243 else
2245 /* force is set when called by keyboard shortcut, otherwise start at the
2246 * editor_prefs.symbolcompletion_min_chars'th char */
2247 if (force || rootlen >= editor_prefs.symbolcompletion_min_chars)
2249 /* complete tags, except if forcing when completion is already visible */
2250 if (!(force && SSM(sci, SCI_AUTOCACTIVE, 0, 0)))
2251 ret = autocomplete_tags(editor, editor->document->file_type, root, rootlen);
2253 /* If forcing and there's nothing else to show, complete from words in document */
2254 if (!ret && (force || editor_prefs.autocomplete_doc_words))
2255 ret = autocomplete_doc_word(editor, root, rootlen);
2259 if (!ret && force)
2260 utils_beep();
2262 return ret;
2266 static const gchar *snippets_find_completion_by_name(const gchar *type, const gchar *name)
2268 gchar *result = NULL;
2269 GHashTable *tmp;
2271 g_return_val_if_fail(type != NULL && name != NULL, NULL);
2273 tmp = g_hash_table_lookup(snippet_hash, type);
2274 if (tmp != NULL)
2276 result = g_hash_table_lookup(tmp, name);
2278 /* whether nothing is set for the current filetype(tmp is NULL) or
2279 * the particular completion for this filetype is not set (result is NULL) */
2280 if (tmp == NULL || result == NULL)
2282 tmp = g_hash_table_lookup(snippet_hash, "Default");
2283 if (tmp != NULL)
2285 result = g_hash_table_lookup(tmp, name);
2288 /* if result is still NULL here, no completion could be found */
2290 /* result is owned by the hash table and will be freed when the table will destroyed */
2291 return result;
2295 static void snippets_replace_specials(gpointer key, gpointer value, gpointer user_data)
2297 gchar *needle;
2298 GString *pattern = user_data;
2300 g_return_if_fail(key != NULL);
2301 g_return_if_fail(value != NULL);
2303 needle = g_strconcat("%", (gchar*) key, "%", NULL);
2305 utils_string_replace_all(pattern, needle, (gchar*) value);
2306 g_free(needle);
2310 static void fix_indentation(GeanyEditor *editor, GString *buf)
2312 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
2313 gchar *whitespace;
2314 GRegex *regex;
2315 gint cflags = G_REGEX_MULTILINE;
2317 /* transform leading tabs into indent widths (in spaces) */
2318 whitespace = g_strnfill(iprefs->width, ' ');
2319 regex = g_regex_new("^ *(\t)", cflags, 0, NULL);
2320 while (utils_string_regex_replace_all(buf, regex, 1, whitespace, TRUE));
2321 g_regex_unref(regex);
2323 /* remaining tabs are for alignment */
2324 if (iprefs->type != GEANY_INDENT_TYPE_TABS)
2325 utils_string_replace_all(buf, "\t", whitespace);
2327 /* use leading tabs */
2328 if (iprefs->type != GEANY_INDENT_TYPE_SPACES)
2330 gchar *str;
2332 /* for tabs+spaces mode we want the real tab width, not indent width */
2333 SETPTR(whitespace, g_strnfill(sci_get_tab_width(editor->sci), ' '));
2334 str = g_strdup_printf("^\t*(%s)", whitespace);
2336 regex = g_regex_new(str, cflags, 0, NULL);
2337 while (utils_string_regex_replace_all(buf, regex, 1, "\t", TRUE));
2338 g_regex_unref(regex);
2339 g_free(str);
2341 g_free(whitespace);
2345 typedef struct
2347 Sci_Position start, len;
2348 } SelectionRange;
2351 #define CURSOR_PLACEHOLDER "_" /* Would rather use … but not all docs are unicode */
2354 /* Replaces the internal cursor markers with the placeholder suitable for
2355 * display. Except for the first cursor if indicator_for_first is FALSE,
2356 * which is simply deleted.
2358 * Returns insertion points as SelectionRange list, so that the caller
2359 * can use the positions (currently for indicators). */
2360 static GSList *replace_cursor_markers(GeanyEditor *editor, GString *template,
2361 gboolean indicator_for_first)
2363 gint i = 0;
2364 GSList *temp_list = NULL;
2365 gint cursor_steps = 0;
2366 SelectionRange *sel;
2368 while (TRUE)
2370 cursor_steps = utils_string_find(template, cursor_steps, -1, geany_cursor_marker);
2371 if (cursor_steps == -1)
2372 break;
2374 sel = g_new0(SelectionRange, 1);
2375 sel->start = cursor_steps;
2376 g_string_erase(template, cursor_steps, strlen(geany_cursor_marker));
2377 if (i > 0 || indicator_for_first)
2379 g_string_insert(template, cursor_steps, CURSOR_PLACEHOLDER);
2380 sel->len = sizeof(CURSOR_PLACEHOLDER) - 1;
2382 i += 1;
2383 temp_list = g_slist_append(temp_list, sel);
2386 return temp_list;
2390 /** Inserts text, replacing \\t tab chars (@c 0x9) and \\n newline chars (@c 0xA)
2391 * accordingly for the document.
2392 * - Leading tabs are replaced with the correct indentation.
2393 * - Non-leading tabs are replaced with spaces (except when using 'Tabs' indent type).
2394 * - Newline chars are replaced with the correct line ending string.
2395 * This is very useful for inserting code without having to handle the indent
2396 * type yourself (Tabs & Spaces mode can be tricky).
2397 * @param editor Editor.
2398 * @param text Intended as e.g. @c "if (foo)\n\tbar();".
2399 * @param insert_pos Document position to insert text at.
2400 * @param cursor_index If >= 0, the index into @a text to place the cursor.
2401 * @param newline_indent_size Indentation size (in spaces) to insert for each newline; use
2402 * -1 to read the indent size from the line with @a insert_pos on it.
2403 * @param replace_newlines Whether to replace newlines. If
2404 * newlines have been replaced already, this should be false, to avoid errors e.g. on Windows.
2405 * @warning Make sure all \\t tab chars in @a text are intended as indent widths or alignment,
2406 * not hard tabs, as those won't be preserved.
2407 * @note This doesn't scroll the cursor in view afterwards. **/
2408 GEANY_API_SYMBOL
2409 void editor_insert_text_block(GeanyEditor *editor, const gchar *text, gint insert_pos,
2410 gint cursor_index, gint newline_indent_size, gboolean replace_newlines)
2412 ScintillaObject *sci = editor->sci;
2413 gint line_start = sci_get_line_from_position(sci, insert_pos);
2414 GString *buf;
2415 const gchar *eol = editor_get_eol_char(editor);
2416 GSList *jump_locs, *item;
2418 g_return_if_fail(text);
2419 g_return_if_fail(editor != NULL);
2420 g_return_if_fail(insert_pos >= 0);
2422 buf = g_string_new(text);
2424 if (cursor_index >= 0)
2425 g_string_insert(buf, cursor_index, geany_cursor_marker); /* remember cursor pos */
2427 if (newline_indent_size == -1)
2429 /* count indent size up to insert_pos instead of asking sci
2430 * because there may be spaces after it */
2431 gchar *tmp = sci_get_line(sci, line_start);
2432 gint idx;
2434 idx = insert_pos - sci_get_position_from_line(sci, line_start);
2435 tmp[idx] = '\0';
2436 newline_indent_size = count_indent_size(editor, tmp);
2437 g_free(tmp);
2440 /* Add line indents (in spaces) */
2441 if (newline_indent_size > 0)
2443 const gchar *nl = replace_newlines ? "\n" : eol;
2444 gchar *whitespace;
2446 whitespace = g_strnfill(newline_indent_size, ' ');
2447 SETPTR(whitespace, g_strconcat(nl, whitespace, NULL));
2448 utils_string_replace_all(buf, nl, whitespace);
2449 g_free(whitespace);
2452 /* transform line endings */
2453 if (replace_newlines)
2454 utils_string_replace_all(buf, "\n", eol);
2456 fix_indentation(editor, buf);
2458 jump_locs = replace_cursor_markers(editor, buf, cursor_index < 0);
2459 sci_insert_text(sci, insert_pos, buf->str);
2461 foreach_list(item, jump_locs)
2463 SelectionRange *sel = item->data;
2464 gint start = insert_pos + sel->start;
2465 gint end = start + sel->len;
2466 editor_indicator_set_on_range(editor, GEANY_INDICATOR_SNIPPET, start, end);
2467 /* jump to first cursor position initially */
2468 if (item == jump_locs)
2469 sci_set_selection(sci, start, end);
2472 /* Set cursor to the requested index, or by default to after the snippet */
2473 if (cursor_index >= 0)
2474 sci_set_current_position(sci, insert_pos + cursor_index, FALSE);
2475 else if (jump_locs == NULL)
2476 sci_set_current_position(sci, insert_pos + buf->len, FALSE);
2478 g_slist_free_full(jump_locs, g_free);
2479 g_string_free(buf, TRUE);
2483 static gboolean find_next_snippet_indicator(GeanyEditor *editor, SelectionRange *sel)
2485 ScintillaObject *sci = editor->sci;
2486 gint pos = sci_get_current_position(sci);
2488 if (pos == sci_get_length(sci))
2489 return FALSE; /* EOF */
2491 /* Rewind the cursor a bit if we're in the middle (or start) of an indicator,
2492 * and treat that as the next indicator. */
2493 while (SSM(sci, SCI_INDICATORVALUEAT, GEANY_INDICATOR_SNIPPET, pos) && pos > 0)
2494 pos -= 1;
2496 /* Be careful at the beginning of the file */
2497 if (SSM(sci, SCI_INDICATORVALUEAT, GEANY_INDICATOR_SNIPPET, pos))
2498 sel->start = pos;
2499 else
2500 sel->start = SSM(sci, SCI_INDICATOREND, GEANY_INDICATOR_SNIPPET, pos);
2501 sel->len = SSM(sci, SCI_INDICATOREND, GEANY_INDICATOR_SNIPPET, sel->start) - sel->start;
2503 /* 0 if there is no remaining cursor */
2504 return sel->len > 0;
2508 /* Move the cursor to the next specified cursor position in an inserted snippet.
2509 * Can, and should, be optimized to give better results */
2510 gboolean editor_goto_next_snippet_cursor(GeanyEditor *editor)
2512 ScintillaObject *sci = editor->sci;
2513 SelectionRange sel;
2515 if (find_next_snippet_indicator(editor, &sel))
2517 sci_indicator_set(sci, GEANY_INDICATOR_SNIPPET);
2518 sci_set_selection(sci, sel.start, sel.start + sel.len);
2519 return TRUE;
2521 else
2523 return FALSE;
2528 static void snippets_make_replacements(GeanyEditor *editor, GString *pattern)
2530 GHashTable *specials;
2532 /* replace 'special' completions */
2533 specials = g_hash_table_lookup(snippet_hash, "Special");
2534 if (G_LIKELY(specials != NULL))
2536 g_hash_table_foreach(specials, snippets_replace_specials, pattern);
2539 /* now transform other wildcards */
2540 utils_string_replace_all(pattern, "%newline%", "\n");
2541 utils_string_replace_all(pattern, "%ws%", "\t");
2543 /* replace %cursor% by a very unlikely string marker */
2544 utils_string_replace_all(pattern, "%cursor%", geany_cursor_marker);
2546 /* unescape '%' after all %wildcards% */
2547 templates_replace_valist(pattern, "{pc}", "%", NULL);
2549 /* replace any template {foo} wildcards */
2550 templates_replace_common(pattern, editor->document->file_name, editor->document->file_type, NULL);
2554 static gboolean snippets_complete_constructs(GeanyEditor *editor, gint pos, const gchar *word)
2556 ScintillaObject *sci = editor->sci;
2557 gchar *str;
2558 const gchar *completion;
2559 gint str_len;
2560 gint ft_id = editor->document->file_type->id;
2562 str = g_strdup(word);
2563 g_strstrip(str);
2565 completion = snippets_find_completion_by_name(filetypes[ft_id]->name, str);
2566 if (completion == NULL)
2568 g_free(str);
2569 return FALSE;
2572 /* remove the typed word, it will be added again by the used auto completion
2573 * (not really necessary but this makes the auto completion more flexible,
2574 * e.g. with a completion like hi=hello, so typing "hi<TAB>" will result in "hello") */
2575 str_len = strlen(str);
2576 sci_set_selection_start(sci, pos - str_len);
2577 sci_set_selection_end(sci, pos);
2578 sci_replace_sel(sci, "");
2579 pos -= str_len; /* pos has changed while deleting */
2581 editor_insert_snippet(editor, pos, completion);
2582 sci_scroll_caret(sci);
2584 g_free(str);
2585 return TRUE;
2589 static gboolean at_eol(ScintillaObject *sci, gint pos)
2591 gint line = sci_get_line_from_position(sci, pos);
2592 gchar c;
2594 /* skip any trailing spaces */
2595 while (TRUE)
2597 c = sci_get_char_at(sci, pos);
2598 if (c == ' ' || c == '\t')
2599 pos++;
2600 else
2601 break;
2604 return (pos == sci_get_line_end_position(sci, line));
2608 gboolean editor_complete_snippet(GeanyEditor *editor, gint pos)
2610 gboolean result = FALSE;
2611 const gchar *wc;
2612 const gchar *word;
2613 ScintillaObject *sci;
2615 g_return_val_if_fail(editor != NULL, FALSE);
2617 sci = editor->sci;
2618 if (sci_has_selection(sci))
2619 return FALSE;
2620 /* return if we are editing an existing line (chars on right of cursor) */
2621 if (keybindings_lookup_item(GEANY_KEY_GROUP_EDITOR,
2622 GEANY_KEYS_EDITOR_COMPLETESNIPPET)->key == GDK_KEY_space &&
2623 ! editor_prefs.complete_snippets_whilst_editing && ! at_eol(sci, pos))
2624 return FALSE;
2626 wc = snippets_find_completion_by_name("Special", "wordchars");
2627 word = editor_read_word_stem(editor, pos, wc);
2629 /* prevent completion of "for " */
2630 if (!EMPTY(word) &&
2631 ! isspace(sci_get_char_at(sci, pos - 1))) /* pos points to the line end char so use pos -1 */
2633 sci_start_undo_action(sci); /* needed because we insert a space separately from construct */
2634 result = snippets_complete_constructs(editor, pos, word);
2635 sci_end_undo_action(sci);
2636 if (result)
2637 sci_cancel(sci); /* cancel any autocompletion list, etc */
2639 return result;
2643 static void insert_closing_tag(GeanyEditor *editor, gint pos, gchar ch, const gchar *tag_name)
2645 ScintillaObject *sci = editor->sci;
2646 gchar *to_insert = NULL;
2648 if (ch == '/')
2650 const gchar *gt = ">";
2651 /* if there is already a '>' behind the cursor, don't add it */
2652 if (sci_get_char_at(sci, pos) == '>')
2653 gt = "";
2655 to_insert = g_strconcat(tag_name, gt, NULL);
2657 else
2658 to_insert = g_strconcat("</", tag_name, ">", NULL);
2660 sci_start_undo_action(sci);
2661 sci_replace_sel(sci, to_insert);
2662 if (ch == '>')
2663 sci_set_selection(sci, pos, pos);
2664 sci_end_undo_action(sci);
2665 g_free(to_insert);
2670 * (stolen from anjuta and heavily modified)
2671 * This routine will auto complete XML or HTML tags that are still open by closing them
2672 * @param ch The character we are dealing with, currently only works with the '>' character
2673 * @return True if handled, false otherwise
2675 static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch)
2677 ScintillaObject *sci = editor->sci;
2678 gint lexer = sci_get_lexer(sci);
2679 gint min, size, style;
2680 gchar *str_found, sel[512];
2681 gboolean result = FALSE;
2683 /* If the user has turned us off, quit now.
2684 * This may make sense only in certain languages */
2685 if (! editor_prefs.auto_close_xml_tags || (lexer != SCLEX_HTML && lexer != SCLEX_XML))
2686 return FALSE;
2688 /* return if we are inside any embedded script */
2689 style = sci_get_style_at(sci, pos);
2690 if (style > SCE_H_XCCOMMENT && ! highlighting_is_string_style(lexer, style))
2691 return FALSE;
2693 /* if ch is /, check for </, else quit */
2694 if (ch == '/' && sci_get_char_at(sci, pos - 2) != '<')
2695 return FALSE;
2697 /* Grab the last 512 characters or so */
2698 min = pos - (sizeof(sel) - 1);
2699 if (min < 0) min = 0;
2701 if (pos - min < 3)
2702 return FALSE; /* Smallest tag is 3 characters e.g. <p> */
2704 sci_get_text_range(sci, min, pos, sel);
2705 sel[sizeof(sel) - 1] = '\0';
2707 if (ch == '>' && sel[pos - min - 2] == '/')
2708 /* User typed something like "<br/>" */
2709 return FALSE;
2711 size = pos - min;
2712 if (ch == '/')
2713 size -= 2; /* skip </ */
2714 str_found = utils_find_open_xml_tag(sel, size);
2716 if (lexer == SCLEX_HTML && utils_is_short_html_tag(str_found))
2718 /* ignore tag */
2720 else if (!EMPTY(str_found))
2722 insert_closing_tag(editor, pos, ch, str_found);
2723 result = TRUE;
2725 g_free(str_found);
2726 return result;
2730 /* like sci_get_line_indentation(), but for a string. */
2731 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent)
2733 const gchar *ptr;
2734 gsize tab_size = sci_get_tab_width(editor->sci);
2735 gsize count = 0;
2737 g_return_val_if_fail(base_indent, 0);
2739 for (ptr = base_indent; *ptr != 0; ptr++)
2741 switch (*ptr)
2743 case ' ':
2744 count++;
2745 break;
2746 case '\t':
2747 count += tab_size;
2748 break;
2749 default:
2750 return count;
2753 return count;
2757 /* Handles special cases where HTML is embedded in another language or
2758 * another language is embedded in HTML */
2759 static GeanyFiletype *editor_get_filetype_at_line(GeanyEditor *editor, gint line)
2761 gint style, line_start;
2762 GeanyFiletype *current_ft;
2764 g_return_val_if_fail(editor != NULL, NULL);
2765 g_return_val_if_fail(editor->document->file_type != NULL, NULL);
2767 current_ft = editor->document->file_type;
2768 line_start = sci_get_position_from_line(editor->sci, line);
2769 style = sci_get_style_at(editor->sci, line_start);
2771 /* Handle PHP filetype with embedded HTML */
2772 if (current_ft->id == GEANY_FILETYPES_PHP && ! is_style_php(style))
2773 current_ft = filetypes[GEANY_FILETYPES_HTML];
2775 /* Handle languages embedded in HTML */
2776 if (current_ft->id == GEANY_FILETYPES_HTML)
2778 /* Embedded JS */
2779 if (style >= SCE_HJ_DEFAULT && style <= SCE_HJ_REGEX)
2780 current_ft = filetypes[GEANY_FILETYPES_JS];
2781 /* ASP JS */
2782 else if (style >= SCE_HJA_DEFAULT && style <= SCE_HJA_REGEX)
2783 current_ft = filetypes[GEANY_FILETYPES_JS];
2784 /* Embedded VB */
2785 else if (style >= SCE_HB_DEFAULT && style <= SCE_HB_STRINGEOL)
2786 current_ft = filetypes[GEANY_FILETYPES_BASIC];
2787 /* ASP VB */
2788 else if (style >= SCE_HBA_DEFAULT && style <= SCE_HBA_STRINGEOL)
2789 current_ft = filetypes[GEANY_FILETYPES_BASIC];
2790 /* Embedded Python */
2791 else if (style >= SCE_HP_DEFAULT && style <= SCE_HP_IDENTIFIER)
2792 current_ft = filetypes[GEANY_FILETYPES_PYTHON];
2793 /* ASP Python */
2794 else if (style >= SCE_HPA_DEFAULT && style <= SCE_HPA_IDENTIFIER)
2795 current_ft = filetypes[GEANY_FILETYPES_PYTHON];
2796 /* Embedded PHP */
2797 else if ((style >= SCE_HPHP_DEFAULT && style <= SCE_HPHP_OPERATOR) ||
2798 style == SCE_HPHP_COMPLEX_VARIABLE)
2800 current_ft = filetypes[GEANY_FILETYPES_PHP];
2804 /* Ensure the filetype's config is loaded */
2805 filetypes_load_config(current_ft->id, FALSE);
2807 return current_ft;
2811 static void real_comment_multiline(GeanyEditor *editor, gint line_start, gint last_line)
2813 const gchar *eol;
2814 gchar *str_begin, *str_end;
2815 const gchar *co, *cc;
2816 gint line_len;
2817 GeanyFiletype *ft;
2819 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2821 ft = editor_get_filetype_at_line(editor, line_start);
2823 eol = editor_get_eol_char(editor);
2824 if (! filetype_get_comment_open_close(ft, FALSE, &co, &cc))
2825 g_return_if_reached();
2826 str_begin = g_strdup_printf("%s%s", (co != NULL) ? co : "", eol);
2827 str_end = g_strdup_printf("%s%s", (cc != NULL) ? cc : "", eol);
2829 /* insert the comment strings */
2830 sci_insert_text(editor->sci, line_start, str_begin);
2831 line_len = sci_get_position_from_line(editor->sci, last_line + 2);
2832 sci_insert_text(editor->sci, line_len, str_end);
2834 g_free(str_begin);
2835 g_free(str_end);
2839 /* find @p text inside the range of the current style */
2840 static gint find_in_current_style(ScintillaObject *sci, const gchar *text, gboolean backwards)
2842 gint start = sci_get_current_position(sci);
2843 gint end = start;
2844 gint len = sci_get_length(sci);
2845 gint current_style = sci_get_style_at(sci, start);
2846 struct Sci_TextToFind ttf;
2848 while (start > 0 && sci_get_style_at(sci, start - 1) == current_style)
2849 start -= 1;
2850 while (end < len && sci_get_style_at(sci, end + 1) == current_style)
2851 end += 1;
2853 ttf.lpstrText = (gchar*) text;
2854 ttf.chrg.cpMin = backwards ? end + 1 : start;
2855 ttf.chrg.cpMax = backwards ? start : end + 1;
2856 return sci_find_text(sci, 0, &ttf);
2860 static void sci_delete_line(ScintillaObject *sci, gint line)
2862 gint start = sci_get_position_from_line(sci, line);
2863 gint len = sci_get_line_length(sci, line);
2864 SSM(sci, SCI_DELETERANGE, start, len);
2868 static gboolean real_uncomment_multiline(GeanyEditor *editor)
2870 /* find the beginning of the multi line comment */
2871 gint start, end, start_line, end_line;
2872 GeanyFiletype *ft;
2873 const gchar *co, *cc;
2875 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, FALSE);
2877 ft = editor_get_filetype_at_line(editor, sci_get_current_line(editor->sci));
2878 if (! filetype_get_comment_open_close(ft, FALSE, &co, &cc))
2879 g_return_val_if_reached(FALSE);
2881 start = find_in_current_style(editor->sci, co, TRUE);
2882 end = find_in_current_style(editor->sci, cc, FALSE);
2884 if (start < 0 || end < 0 || start > end /* who knows */)
2885 return FALSE;
2887 start_line = sci_get_line_from_position(editor->sci, start);
2888 end_line = sci_get_line_from_position(editor->sci, end);
2890 /* remove comment close chars */
2891 SSM(editor->sci, SCI_DELETERANGE, end, strlen(cc));
2892 if (sci_is_blank_line(editor->sci, end_line))
2893 sci_delete_line(editor->sci, end_line);
2895 /* remove comment open chars (do it last since it would move the end position) */
2896 SSM(editor->sci, SCI_DELETERANGE, start, strlen(co));
2897 if (sci_is_blank_line(editor->sci, start_line))
2898 sci_delete_line(editor->sci, start_line);
2900 return TRUE;
2904 static gint get_multiline_comment_style(GeanyEditor *editor, gint line_start)
2906 gint lexer = sci_get_lexer(editor->sci);
2907 gint style_comment;
2909 /* List only those lexers which support multi line comments */
2910 switch (lexer)
2912 case SCLEX_XML:
2913 case SCLEX_HTML:
2914 case SCLEX_PHPSCRIPT:
2916 if (is_style_php(sci_get_style_at(editor->sci, line_start)))
2917 style_comment = SCE_HPHP_COMMENT;
2918 else
2919 style_comment = SCE_H_COMMENT;
2920 break;
2922 case SCLEX_HASKELL:
2923 case SCLEX_LITERATEHASKELL:
2924 style_comment = SCE_HA_COMMENTBLOCK; break;
2925 case SCLEX_LUA: style_comment = SCE_LUA_COMMENT; break;
2926 case SCLEX_CSS: style_comment = SCE_CSS_COMMENT; break;
2927 case SCLEX_SQL: style_comment = SCE_SQL_COMMENT; break;
2928 case SCLEX_CAML: style_comment = SCE_CAML_COMMENT; break;
2929 case SCLEX_D: style_comment = SCE_D_COMMENT; break;
2930 case SCLEX_PASCAL: style_comment = SCE_PAS_COMMENT; break;
2931 case SCLEX_RUST: style_comment = SCE_RUST_COMMENTBLOCK; break;
2932 default: style_comment = SCE_C_COMMENT;
2935 return style_comment;
2939 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise
2940 * returns the amount of uncommented single comment lines, in case of multi line uncomment
2941 * it returns just 1 */
2942 gint editor_do_uncomment(GeanyEditor *editor, gint line, gboolean toggle)
2944 gint first_line, last_line;
2945 gint x, i, line_start, line_len;
2946 gint sel_start, sel_end;
2947 gint count = 0;
2948 gsize co_len;
2949 gchar sel[256];
2950 const gchar *co, *cc;
2951 gboolean single_line = FALSE;
2952 GeanyFiletype *ft;
2954 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, 0);
2956 if (line < 0)
2957 { /* use selection or current line */
2958 sel_start = sci_get_selection_start(editor->sci);
2959 sel_end = sci_get_selection_end(editor->sci);
2961 first_line = sci_get_line_from_position(editor->sci, sel_start);
2962 /* Find the last line with chars selected (not EOL char) */
2963 last_line = sci_get_line_from_position(editor->sci,
2964 sel_end - editor_get_eol_char_len(editor));
2965 last_line = MAX(first_line, last_line);
2967 else
2969 first_line = last_line = line;
2970 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
2973 ft = editor_get_filetype_at_line(editor, first_line);
2975 if (! filetype_get_comment_open_close(ft, TRUE, &co, &cc))
2976 return 0;
2978 co_len = strlen(co);
2979 if (co_len == 0)
2980 return 0;
2982 sci_start_undo_action(editor->sci);
2984 for (i = first_line; i <= last_line; i++)
2986 gint buf_len;
2988 line_start = sci_get_position_from_line(editor->sci, i);
2989 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
2990 x = 0;
2992 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
2993 if (buf_len <= 0)
2994 continue;
2995 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
2996 sel[buf_len] = '\0';
2998 while (isspace(sel[x])) x++;
3000 /* to skip blank lines */
3001 if (x < line_len && sel[x] != '\0')
3003 /* use single line comment */
3004 if (EMPTY(cc))
3006 single_line = TRUE;
3008 if (toggle)
3010 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
3011 if (strncmp(sel + x, co, co_len) != 0 ||
3012 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) != 0)
3013 continue;
3015 co_len += tm_len;
3017 else
3019 if (strncmp(sel + x, co, co_len) != 0)
3020 continue;
3023 sci_set_selection(editor->sci, line_start + x, line_start + x + co_len);
3024 sci_replace_sel(editor->sci, "");
3025 count++;
3027 /* use multi line comment */
3028 else
3030 gint style_comment;
3032 /* skip lines which are already comments */
3033 style_comment = get_multiline_comment_style(editor, line_start);
3034 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3036 if (real_uncomment_multiline(editor))
3037 count = 1;
3040 /* break because we are already on the last line */
3041 break;
3045 sci_end_undo_action(editor->sci);
3047 /* restore selection if there is one
3048 * but don't touch the selection if caller is editor_do_comment_toggle */
3049 if (! toggle && sel_start < sel_end)
3051 if (single_line)
3053 sci_set_selection_start(editor->sci, sel_start - co_len);
3054 sci_set_selection_end(editor->sci, sel_end - (count * co_len));
3056 else
3058 gint eol_len = editor_get_eol_char_len(editor);
3059 sci_set_selection_start(editor->sci, sel_start - co_len - eol_len);
3060 sci_set_selection_end(editor->sci, sel_end - co_len - eol_len);
3064 return count;
3068 void editor_do_comment_toggle(GeanyEditor *editor)
3070 gint first_line, last_line;
3071 gint x, i, line_start, line_len, first_line_start, last_line_start;
3072 gint sel_start, sel_end;
3073 gint count_commented = 0, count_uncommented = 0;
3074 gchar sel[256];
3075 const gchar *co, *cc;
3076 gboolean single_line = FALSE;
3077 gboolean first_line_was_comment = FALSE;
3078 gboolean last_line_was_comment = FALSE;
3079 gsize co_len;
3080 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
3081 GeanyFiletype *ft;
3083 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
3085 sel_start = sci_get_selection_start(editor->sci);
3086 sel_end = sci_get_selection_end(editor->sci);
3088 first_line = sci_get_line_from_position(editor->sci, sel_start);
3089 /* Find the last line with chars selected (not EOL char) */
3090 last_line = sci_get_line_from_position(editor->sci,
3091 sel_end - editor_get_eol_char_len(editor));
3092 last_line = MAX(first_line, last_line);
3094 first_line_start = sci_get_position_from_line(editor->sci, first_line);
3095 last_line_start = sci_get_position_from_line(editor->sci, last_line);
3097 ft = editor_get_filetype_at_line(editor, first_line);
3099 if (! filetype_get_comment_open_close(ft, TRUE, &co, &cc))
3100 return;
3102 co_len = strlen(co);
3103 if (co_len == 0)
3104 return;
3106 sci_start_undo_action(editor->sci);
3108 for (i = first_line; i <= last_line; i++)
3110 gint buf_len;
3112 line_start = sci_get_position_from_line(editor->sci, i);
3113 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
3114 x = 0;
3116 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
3117 if (buf_len < 0)
3118 continue;
3119 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3120 sel[buf_len] = '\0';
3122 while (isspace(sel[x])) x++;
3124 /* use single line comment */
3125 if (EMPTY(cc))
3127 gboolean do_continue = FALSE;
3128 single_line = TRUE;
3130 if (strncmp(sel + x, co, co_len) == 0 &&
3131 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) == 0)
3133 do_continue = TRUE;
3136 if (do_continue && i == first_line)
3137 first_line_was_comment = TRUE;
3138 last_line_was_comment = do_continue;
3140 if (do_continue)
3142 count_uncommented += editor_do_uncomment(editor, i, TRUE);
3143 continue;
3146 /* we are still here, so the above lines were not already comments, so comment it */
3147 count_commented += editor_do_comment(editor, i, FALSE, TRUE, TRUE);
3149 /* use multi line comment */
3150 else
3152 gint style_comment;
3154 /* skip lines which are already comments */
3155 style_comment = get_multiline_comment_style(editor, line_start);
3156 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3158 if (real_uncomment_multiline(editor))
3159 count_uncommented++;
3161 else
3163 real_comment_multiline(editor, line_start, last_line);
3164 count_commented++;
3167 /* break because we are already on the last line */
3168 break;
3172 sci_end_undo_action(editor->sci);
3174 co_len += tm_len;
3176 /* restore selection or caret position */
3177 if (single_line)
3179 gint a = (first_line_was_comment) ? - (gint) co_len : (gint) co_len;
3180 gint indent_len;
3182 /* don't modify sel_start when the selection starts within indentation */
3183 read_indent(editor, sel_start);
3184 indent_len = (gint) strlen(indent);
3185 if ((sel_start - first_line_start) <= indent_len)
3186 a = 0;
3187 /* if the selection start was inside the comment mark, adjust the position */
3188 else if (first_line_was_comment &&
3189 sel_start >= (first_line_start + indent_len) &&
3190 sel_start <= (first_line_start + indent_len + (gint) co_len))
3192 a = (first_line_start + indent_len) - sel_start;
3195 if (sel_start < sel_end)
3197 gint b = (count_commented * (gint) co_len) - (count_uncommented * (gint) co_len);
3199 /* same for selection end, but here we add an offset on the offset above */
3200 read_indent(editor, sel_end + b);
3201 indent_len = (gint) strlen(indent);
3202 if ((sel_end - last_line_start) < indent_len)
3203 b += last_line_was_comment ? (gint) co_len : -(gint) co_len;
3204 else if (last_line_was_comment &&
3205 sel_end >= (last_line_start + indent_len) &&
3206 sel_end <= (last_line_start + indent_len + (gint) co_len))
3208 b += (gint) co_len - (sel_end - (last_line_start + indent_len));
3211 sci_set_selection_start(editor->sci, sel_start + a);
3212 sci_set_selection_end(editor->sci, sel_end + b);
3214 else
3215 sci_set_current_position(editor->sci, sel_start + a, TRUE);
3217 else
3219 gint eol_len = editor_get_eol_char_len(editor);
3220 if (count_uncommented > 0)
3222 sci_set_selection_start(editor->sci, sel_start - (gint) co_len + eol_len);
3223 sci_set_selection_end(editor->sci, sel_end - (gint) co_len + eol_len);
3225 else if (count_commented > 0)
3227 sci_set_selection_start(editor->sci, sel_start + (gint) co_len - eol_len);
3228 sci_set_selection_end(editor->sci, sel_end + (gint) co_len - eol_len);
3230 if (sel_start >= sel_end)
3231 sci_scroll_caret(editor->sci);
3236 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise */
3237 gint editor_do_comment(GeanyEditor *editor, gint line, gboolean allow_empty_lines, gboolean toggle,
3238 gboolean single_comment)
3240 gint first_line, last_line;
3241 gint x, i, line_start, line_len;
3242 gint sel_start, sel_end, co_len;
3243 gint count = 0;
3244 gchar sel[256];
3245 const gchar *co, *cc;
3246 gboolean single_line = FALSE;
3247 GeanyFiletype *ft;
3249 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, 0);
3251 if (line < 0)
3252 { /* use selection or current line */
3253 sel_start = sci_get_selection_start(editor->sci);
3254 sel_end = sci_get_selection_end(editor->sci);
3256 first_line = sci_get_line_from_position(editor->sci, sel_start);
3257 /* Find the last line with chars selected (not EOL char) */
3258 last_line = sci_get_line_from_position(editor->sci,
3259 sel_end - editor_get_eol_char_len(editor));
3260 last_line = MAX(first_line, last_line);
3262 else
3264 first_line = last_line = line;
3265 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
3268 ft = editor_get_filetype_at_line(editor, first_line);
3270 if (! filetype_get_comment_open_close(ft, single_comment, &co, &cc))
3271 return 0;
3273 co_len = strlen(co);
3274 if (co_len == 0)
3275 return 0;
3277 sci_start_undo_action(editor->sci);
3279 for (i = first_line; i <= last_line; i++)
3281 gint buf_len;
3283 line_start = sci_get_position_from_line(editor->sci, i);
3284 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
3285 x = 0;
3287 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
3288 if (buf_len < 0)
3289 continue;
3290 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3291 sel[buf_len] = '\0';
3293 while (isspace(sel[x])) x++;
3295 /* to skip blank lines */
3296 if (allow_empty_lines || (x < line_len && sel[x] != '\0'))
3298 /* use single line comment */
3299 if (EMPTY(cc))
3301 gint start = line_start;
3302 single_line = TRUE;
3304 if (ft->comment_use_indent)
3305 start = line_start + x;
3307 if (toggle)
3309 gchar *text = g_strconcat(co, editor_prefs.comment_toggle_mark, NULL);
3310 sci_insert_text(editor->sci, start, text);
3311 g_free(text);
3313 else
3314 sci_insert_text(editor->sci, start, co);
3315 count++;
3317 /* use multi line comment */
3318 else
3320 gint style_comment;
3322 /* skip lines which are already comments */
3323 style_comment = get_multiline_comment_style(editor, line_start);
3324 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3325 continue;
3327 real_comment_multiline(editor, line_start, last_line);
3328 count = 1;
3330 /* break because we are already on the last line */
3331 break;
3335 sci_end_undo_action(editor->sci);
3337 /* restore selection if there is one
3338 * but don't touch the selection if caller is editor_do_comment_toggle */
3339 if (! toggle && sel_start < sel_end)
3341 if (single_line)
3343 sci_set_selection_start(editor->sci, sel_start + co_len);
3344 sci_set_selection_end(editor->sci, sel_end + (count * co_len));
3346 else
3348 gint eol_len = editor_get_eol_char_len(editor);
3349 sci_set_selection_start(editor->sci, sel_start + co_len + eol_len);
3350 sci_set_selection_end(editor->sci, sel_end + co_len + eol_len);
3353 return count;
3357 static gboolean brace_timeout_active = FALSE;
3359 static gboolean delay_match_brace(G_GNUC_UNUSED gpointer user_data)
3361 GeanyDocument *doc = document_get_current();
3362 GeanyEditor *editor;
3363 gint brace_pos = GPOINTER_TO_INT(user_data);
3364 gint end_pos, cur_pos;
3366 brace_timeout_active = FALSE;
3367 if (!doc)
3368 return FALSE;
3370 editor = doc->editor;
3371 cur_pos = sci_get_current_position(editor->sci) - 1;
3373 if (cur_pos != brace_pos)
3375 cur_pos++;
3376 if (cur_pos != brace_pos)
3378 /* we have moved past the original brace_pos, but after the timeout
3379 * we may now be on a new brace, so check again */
3380 editor_highlight_braces(editor, cur_pos);
3381 return FALSE;
3384 if (!utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3386 editor_highlight_braces(editor, cur_pos);
3387 return FALSE;
3389 end_pos = sci_find_matching_brace(editor->sci, brace_pos);
3391 if (end_pos >= 0)
3393 gint col = MIN(sci_get_col_from_position(editor->sci, brace_pos),
3394 sci_get_col_from_position(editor->sci, end_pos));
3395 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, col, 0);
3396 SSM(editor->sci, SCI_BRACEHIGHLIGHT, brace_pos, end_pos);
3398 else
3400 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3401 SSM(editor->sci, SCI_BRACEBADLIGHT, brace_pos, 0);
3403 return FALSE;
3407 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos)
3409 gint brace_pos = cur_pos - 1;
3411 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3412 SSM(editor->sci, SCI_BRACEBADLIGHT, (uptr_t)-1, 0);
3414 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3416 brace_pos++;
3417 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3419 return;
3422 if (!brace_timeout_active)
3424 brace_timeout_active = TRUE;
3425 /* delaying matching makes scrolling faster e.g. holding down arrow keys */
3426 g_timeout_add(100, delay_match_brace, GINT_TO_POINTER(brace_pos));
3431 static gboolean in_block_comment(gint lexer, gint style)
3433 switch (lexer)
3435 case SCLEX_COBOL:
3436 case SCLEX_CPP:
3437 return (style == SCE_C_COMMENT ||
3438 style == SCE_C_COMMENTDOC);
3440 case SCLEX_PASCAL:
3441 return (style == SCE_PAS_COMMENT ||
3442 style == SCE_PAS_COMMENT2);
3444 case SCLEX_D:
3445 return (style == SCE_D_COMMENT ||
3446 style == SCE_D_COMMENTDOC ||
3447 style == SCE_D_COMMENTNESTED);
3449 case SCLEX_HTML:
3450 case SCLEX_PHPSCRIPT:
3451 return (style == SCE_HPHP_COMMENT);
3453 case SCLEX_CSS:
3454 return (style == SCE_CSS_COMMENT);
3456 case SCLEX_RUST:
3457 return (style == SCE_RUST_COMMENTBLOCK ||
3458 style == SCE_RUST_COMMENTBLOCKDOC);
3460 default:
3461 return FALSE;
3466 static gboolean is_comment_char(gchar c, gint lexer)
3468 if ((c == '*' || c == '+') && lexer == SCLEX_D)
3469 return TRUE;
3470 else
3471 if (c == '*')
3472 return TRUE;
3474 return FALSE;
3478 static void auto_multiline(GeanyEditor *editor, gint cur_line)
3480 ScintillaObject *sci = editor->sci;
3481 gint indent_pos, style;
3482 gint lexer = sci_get_lexer(sci);
3484 /* Use the start of the line enter was pressed on, to avoid any doc keyword styles */
3485 indent_pos = sci_get_line_indent_position(sci, cur_line - 1);
3486 style = sci_get_style_at(sci, indent_pos);
3487 if (!in_block_comment(lexer, style))
3488 return;
3490 /* Check whether the comment block continues on this line */
3491 indent_pos = sci_get_line_indent_position(sci, cur_line);
3492 if (sci_get_style_at(sci, indent_pos) == style || indent_pos >= sci_get_length(sci))
3494 gchar *previous_line = sci_get_line(sci, cur_line - 1);
3495 /* the type of comment, '*' (C/C++/Java), '+' and the others (D) */
3496 const gchar *continuation = "*";
3497 const gchar *whitespace = ""; /* to hold whitespace if needed */
3498 gchar *result;
3499 gint len = strlen(previous_line);
3500 gint i;
3502 /* find and stop at end of multi line comment */
3503 i = len - 1;
3504 while (i >= 0 && isspace(previous_line[i])) i--;
3505 if (i >= 1 && is_comment_char(previous_line[i - 1], lexer) && previous_line[i] == '/')
3507 gint indent_len, indent_width;
3509 indent_pos = sci_get_line_indent_position(sci, cur_line);
3510 indent_len = sci_get_col_from_position(sci, indent_pos);
3511 indent_width = editor_get_indent_prefs(editor)->width;
3513 /* if there is one too many spaces, delete the last space,
3514 * to return to the indent used before the multiline comment was started. */
3515 if (indent_len % indent_width == 1)
3516 SSM(sci, SCI_DELETEBACKNOTLINE, 0, 0); /* remove whitespace indent */
3517 g_free(previous_line);
3518 return;
3520 /* check whether we are on the second line of multi line comment */
3521 i = 0;
3522 while (i < len && isspace(previous_line[i])) i++; /* get to start of the line */
3524 if (i + 1 < len &&
3525 previous_line[i] == '/' && is_comment_char(previous_line[i + 1], lexer))
3526 { /* we are on the second line of a multi line comment, so we have to insert white space */
3527 whitespace = " ";
3530 if (style == SCE_D_COMMENTNESTED)
3531 continuation = "+"; /* for nested comments in D */
3533 result = g_strconcat(whitespace, continuation, " ", NULL);
3534 sci_add_text(sci, result);
3535 g_free(result);
3537 g_free(previous_line);
3542 #if 0
3543 static gboolean editor_lexer_is_c_like(gint lexer)
3545 switch (lexer)
3547 case SCLEX_CPP:
3548 case SCLEX_D:
3549 return TRUE;
3551 default:
3552 return FALSE;
3555 #endif
3558 /* inserts a three-line comment at one line above current cursor position */
3559 void editor_insert_multiline_comment(GeanyEditor *editor)
3561 gchar *text;
3562 gint text_len;
3563 gint line;
3564 gint pos;
3565 gboolean have_multiline_comment = FALSE;
3566 GeanyDocument *doc;
3567 const gchar *co, *cc;
3569 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
3571 if (! filetype_get_comment_open_close(editor->document->file_type, FALSE, &co, &cc))
3572 g_return_if_reached();
3573 if (!EMPTY(cc))
3574 have_multiline_comment = TRUE;
3576 sci_start_undo_action(editor->sci);
3578 doc = editor->document;
3580 /* insert three lines one line above of the current position */
3581 line = sci_get_line_from_position(editor->sci, editor_info.click_pos);
3582 pos = sci_get_position_from_line(editor->sci, line);
3584 /* use the indent on the current line but only when comment indentation is used
3585 * and we don't have multi line comment characters */
3586 if (editor->auto_indent &&
3587 ! have_multiline_comment && doc->file_type->comment_use_indent)
3589 read_indent(editor, editor_info.click_pos);
3590 text = g_strdup_printf("%s\n%s\n%s\n", indent, indent, indent);
3591 text_len = strlen(text);
3593 else
3595 text = g_strdup("\n\n\n");
3596 text_len = 3;
3598 sci_insert_text(editor->sci, pos, text);
3599 g_free(text);
3601 /* select the inserted lines for commenting */
3602 sci_set_selection_start(editor->sci, pos);
3603 sci_set_selection_end(editor->sci, pos + text_len);
3605 editor_do_comment(editor, -1, TRUE, FALSE, FALSE);
3607 /* set the current position to the start of the first inserted line */
3608 pos += strlen(co);
3610 /* on multi line comment jump to the next line, otherwise add the length of added indentation */
3611 if (have_multiline_comment)
3612 pos += 1;
3613 else
3614 pos += strlen(indent);
3616 sci_set_current_position(editor->sci, pos, TRUE);
3617 /* reset the selection */
3618 sci_set_anchor(editor->sci, pos);
3620 sci_end_undo_action(editor->sci);
3624 /* Note: If the editor is pending a redraw, set document::scroll_percent instead.
3625 * Scroll the view to make line appear at percent_of_view.
3626 * line can be -1 to use the current position. */
3627 void editor_scroll_to_line(GeanyEditor *editor, gint line, gfloat percent_of_view)
3629 gint los;
3630 GtkWidget *wid;
3632 g_return_if_fail(editor != NULL);
3634 wid = GTK_WIDGET(editor->sci);
3636 if (! gtk_widget_get_window(wid) || ! gdk_window_is_viewable(gtk_widget_get_window(wid)))
3637 return; /* prevent gdk_window_scroll warning */
3639 if (line == -1)
3640 line = sci_get_current_line(editor->sci);
3642 /* sci 'visible line' != doc line number because of folding and line wrapping */
3643 /* calling SCI_VISIBLEFROMDOCLINE for line is more accurate than calling
3644 * SCI_DOCLINEFROMVISIBLE for vis1. */
3645 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0);
3646 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
3647 line = line - los * percent_of_view;
3648 SSM(editor->sci, SCI_SETFIRSTVISIBLELINE, line, 0);
3649 sci_scroll_caret(editor->sci); /* needed for horizontal scrolling */
3653 /* creates and inserts one tab or whitespace of the amount of the tab width */
3654 void editor_insert_alternative_whitespace(GeanyEditor *editor)
3656 gchar *text;
3657 GeanyIndentPrefs iprefs = *editor_get_indent_prefs(editor);
3659 g_return_if_fail(editor != NULL);
3661 switch (iprefs.type)
3663 case GEANY_INDENT_TYPE_TABS:
3664 iprefs.type = GEANY_INDENT_TYPE_SPACES;
3665 break;
3666 case GEANY_INDENT_TYPE_SPACES:
3667 case GEANY_INDENT_TYPE_BOTH: /* most likely we want a tab */
3668 iprefs.type = GEANY_INDENT_TYPE_TABS;
3669 break;
3671 text = get_whitespace(&iprefs, iprefs.width);
3672 sci_add_text(editor->sci, text);
3673 g_free(text);
3677 void editor_select_word(GeanyEditor *editor)
3679 gint pos;
3680 gint start;
3681 gint end;
3683 g_return_if_fail(editor != NULL);
3685 pos = SSM(editor->sci, SCI_GETCURRENTPOS, 0, 0);
3686 start = sci_word_start_position(editor->sci, pos, TRUE);
3687 end = sci_word_end_position(editor->sci, pos, TRUE);
3689 if (start == end) /* caret in whitespaces sequence */
3691 /* look forward but reverse the selection direction,
3692 * so the caret end up stay as near as the original position. */
3693 end = sci_word_end_position(editor->sci, pos, FALSE);
3694 start = sci_word_end_position(editor->sci, end, TRUE);
3695 if (start == end)
3696 return;
3699 sci_set_selection(editor->sci, start, end);
3703 /* extra_line is for selecting the cursor line (or anchor line) at the bottom of a selection,
3704 * when those lines have no selection (cursor at start of line). */
3705 void editor_select_lines(GeanyEditor *editor, gboolean extra_line)
3707 gint start, end, line;
3709 g_return_if_fail(editor != NULL);
3711 start = sci_get_selection_start(editor->sci);
3712 end = sci_get_selection_end(editor->sci);
3714 /* check if whole lines are already selected */
3715 if (! extra_line && start != end &&
3716 sci_get_col_from_position(editor->sci, start) == 0 &&
3717 sci_get_col_from_position(editor->sci, end) == 0)
3718 return;
3720 line = sci_get_line_from_position(editor->sci, start);
3721 start = sci_get_position_from_line(editor->sci, line);
3723 line = sci_get_line_from_position(editor->sci, end);
3724 end = sci_get_position_from_line(editor->sci, line + 1);
3726 sci_set_selection(editor->sci, start, end);
3730 static gboolean sci_is_blank_line(ScintillaObject *sci, gint line)
3732 return sci_get_line_indent_position(sci, line) ==
3733 sci_get_line_end_position(sci, line);
3737 /* Returns first line of paragraph for GTK_DIR_UP, line after paragraph
3738 * ends for GTK_DIR_DOWN or -1 if called on an empty line. */
3739 static gint find_paragraph_stop(GeanyEditor *editor, gint line, gint direction)
3741 gint step;
3742 ScintillaObject *sci = editor->sci;
3744 /* first check current line and return -1 if it is empty to skip creating of a selection */
3745 if (sci_is_blank_line(sci, line))
3746 return -1;
3748 if (direction == GTK_DIR_UP)
3749 step = -1;
3750 else
3751 step = 1;
3753 while (TRUE)
3755 line += step;
3756 if (line == -1)
3758 /* start of document */
3759 line = 0;
3760 break;
3762 if (line == sci_get_line_count(sci))
3763 break;
3765 if (sci_is_blank_line(sci, line))
3767 /* return line paragraph starts on */
3768 if (direction == GTK_DIR_UP)
3769 line++;
3770 break;
3773 return line;
3777 void editor_select_paragraph(GeanyEditor *editor)
3779 gint pos_start, pos_end, line_start, line_found;
3781 g_return_if_fail(editor != NULL);
3783 line_start = sci_get_current_line(editor->sci);
3785 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_UP);
3786 if (line_found == -1)
3787 return;
3789 pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3791 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_DOWN);
3792 pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3794 sci_set_selection(editor->sci, pos_start, pos_end);
3798 /* Returns first line of block for GTK_DIR_UP, line after block
3799 * ends for GTK_DIR_DOWN or -1 if called on an empty line. */
3800 static gint find_block_stop(GeanyEditor *editor, gint line, gint direction)
3802 gint step, ind;
3803 ScintillaObject *sci = editor->sci;
3805 /* first check current line and return -1 if it is empty to skip creating of a selection */
3806 if (sci_is_blank_line(sci, line))
3807 return -1;
3809 if (direction == GTK_DIR_UP)
3810 step = -1;
3811 else
3812 step = 1;
3814 ind = sci_get_line_indentation(sci, line);
3815 while (TRUE)
3817 line += step;
3818 if (line == -1)
3820 /* start of document */
3821 line = 0;
3822 break;
3824 if (line == sci_get_line_count(sci))
3825 break;
3827 if (sci_get_line_indentation(sci, line) != ind ||
3828 sci_is_blank_line(sci, line))
3830 /* return line block starts on */
3831 if (direction == GTK_DIR_UP)
3832 line++;
3833 break;
3836 return line;
3840 void editor_select_indent_block(GeanyEditor *editor)
3842 gint pos_start, pos_end, line_start, line_found;
3844 g_return_if_fail(editor != NULL);
3846 line_start = sci_get_current_line(editor->sci);
3848 line_found = find_block_stop(editor, line_start, GTK_DIR_UP);
3849 if (line_found == -1)
3850 return;
3852 pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3854 line_found = find_block_stop(editor, line_start, GTK_DIR_DOWN);
3855 pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3857 sci_set_selection(editor->sci, pos_start, pos_end);
3861 /* simple indentation to indent the current line with the same indent as the previous one */
3862 static void smart_line_indentation(GeanyEditor *editor, gint first_line, gint last_line)
3864 gint i, sel_start = 0, sel_end = 0;
3866 /* get previous line and use it for read_indent to use that line
3867 * (otherwise it would fail on a line only containing "{" in advanced indentation mode) */
3868 read_indent(editor, sci_get_position_from_line(editor->sci, first_line - 1));
3870 for (i = first_line; i <= last_line; i++)
3872 /* skip the first line or if the indentation of the previous and current line are equal */
3873 if (i == 0 ||
3874 SSM(editor->sci, SCI_GETLINEINDENTATION, i - 1, 0) ==
3875 SSM(editor->sci, SCI_GETLINEINDENTATION, i, 0))
3876 continue;
3878 sel_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
3879 sel_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
3880 if (sel_start < sel_end)
3882 sci_set_selection(editor->sci, sel_start, sel_end);
3883 sci_replace_sel(editor->sci, "");
3885 sci_insert_text(editor->sci, sel_start, indent);
3890 /* simple indentation to indent the current line with the same indent as the previous one */
3891 void editor_smart_line_indentation(GeanyEditor *editor)
3893 gint first_line, last_line;
3894 gint first_sel_start, first_sel_end;
3895 ScintillaObject *sci;
3897 g_return_if_fail(editor != NULL);
3899 sci = editor->sci;
3901 first_sel_start = sci_get_selection_start(sci);
3902 first_sel_end = sci_get_selection_end(sci);
3904 first_line = sci_get_line_from_position(sci, first_sel_start);
3905 /* Find the last line with chars selected (not EOL char) */
3906 last_line = sci_get_line_from_position(sci, first_sel_end - editor_get_eol_char_len(editor));
3907 last_line = MAX(first_line, last_line);
3909 sci_start_undo_action(sci);
3911 smart_line_indentation(editor, first_line, last_line);
3913 /* set cursor position if there was no selection */
3914 if (first_sel_start == first_sel_end)
3916 gint indent_pos = SSM(sci, SCI_GETLINEINDENTPOSITION, first_line, 0);
3918 /* use indent position as user may wish to change indentation afterwards */
3919 sci_set_current_position(sci, indent_pos, FALSE);
3921 else
3923 /* fully select all the lines affected */
3924 sci_set_selection_start(sci, sci_get_position_from_line(sci, first_line));
3925 sci_set_selection_end(sci, sci_get_position_from_line(sci, last_line + 1));
3928 sci_end_undo_action(sci);
3932 /* increase / decrease current line or selection by one space */
3933 void editor_indentation_by_one_space(GeanyEditor *editor, gint pos, gboolean decrease)
3935 gint i, first_line, last_line, line_start, indentation_end, count = 0;
3936 gint sel_start, sel_end, first_line_offset = 0;
3938 g_return_if_fail(editor != NULL);
3940 sel_start = sci_get_selection_start(editor->sci);
3941 sel_end = sci_get_selection_end(editor->sci);
3943 first_line = sci_get_line_from_position(editor->sci, sel_start);
3944 /* Find the last line with chars selected (not EOL char) */
3945 last_line = sci_get_line_from_position(editor->sci, sel_end - editor_get_eol_char_len(editor));
3946 last_line = MAX(first_line, last_line);
3948 if (pos == -1)
3949 pos = sel_start;
3951 sci_start_undo_action(editor->sci);
3953 for (i = first_line; i <= last_line; i++)
3955 indentation_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
3956 if (decrease)
3958 line_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
3959 /* searching backwards for a space to remove */
3960 while (sci_get_char_at(editor->sci, indentation_end) != ' ' && indentation_end > line_start)
3961 indentation_end--;
3963 if (sci_get_char_at(editor->sci, indentation_end) == ' ')
3965 sci_set_selection(editor->sci, indentation_end, indentation_end + 1);
3966 sci_replace_sel(editor->sci, "");
3967 count--;
3968 if (i == first_line)
3969 first_line_offset = -1;
3972 else
3974 sci_insert_text(editor->sci, indentation_end, " ");
3975 count++;
3976 if (i == first_line)
3977 first_line_offset = 1;
3981 /* set cursor position */
3982 if (sel_start < sel_end)
3984 gint start = sel_start + first_line_offset;
3985 if (first_line_offset < 0)
3986 start = MAX(sel_start + first_line_offset,
3987 SSM(editor->sci, SCI_POSITIONFROMLINE, first_line, 0));
3989 sci_set_selection_start(editor->sci, start);
3990 sci_set_selection_end(editor->sci, sel_end + count);
3992 else
3993 sci_set_current_position(editor->sci, pos + count, FALSE);
3995 sci_end_undo_action(editor->sci);
3999 void editor_finalize(void)
4001 scintilla_release_resources();
4005 /* wordchars: NULL or a string containing characters to match a word.
4006 * Returns: the current selection or the current word.
4008 * Passing NULL as wordchars is NOT the same as passing GEANY_WORDCHARS: NULL means
4009 * using Scintillas's word boundaries. */
4010 gchar *editor_get_default_selection(GeanyEditor *editor, gboolean use_current_word,
4011 const gchar *wordchars)
4013 gchar *s = NULL;
4015 g_return_val_if_fail(editor != NULL, NULL);
4017 if (sci_get_lines_selected(editor->sci) == 1)
4018 s = sci_get_selection_contents(editor->sci);
4019 else if (sci_get_lines_selected(editor->sci) == 0 && use_current_word)
4020 { /* use the word at current cursor position */
4021 gchar word[GEANY_MAX_WORD_LENGTH];
4023 if (wordchars != NULL)
4024 editor_find_current_word(editor, -1, word, sizeof(word), wordchars);
4025 else
4026 editor_find_current_word_sciwc(editor, -1, word, sizeof(word));
4028 if (word[0] != '\0')
4029 s = g_strdup(word);
4031 return s;
4035 /* Note: Usually the line should be made visible (not folded) before calling this.
4036 * Returns: TRUE if line is/will be displayed to the user, or FALSE if it is
4037 * outside the *vertical* view.
4038 * Warning: You may need horizontal scrolling to make the cursor visible - so always call
4039 * sci_scroll_caret() when this returns TRUE. */
4040 gboolean editor_line_in_view(GeanyEditor *editor, gint line)
4042 gint vis1, los;
4044 g_return_val_if_fail(editor != NULL, FALSE);
4046 /* If line is wrapped the result may occur on another virtual line than the first and may be
4047 * still hidden, so increase the line number to check for the next document line */
4048 if (SSM(editor->sci, SCI_WRAPCOUNT, line, 0) > 1)
4049 line++;
4051 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0); /* convert to visible line number */
4052 vis1 = SSM(editor->sci, SCI_GETFIRSTVISIBLELINE, 0, 0);
4053 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
4055 return (line >= vis1 && line < vis1 + los);
4059 /* If the current line is outside the current view window, scroll the line
4060 * so it appears at percent_of_view. */
4061 void editor_display_current_line(GeanyEditor *editor, gfloat percent_of_view)
4063 gint line;
4065 g_return_if_fail(editor != NULL);
4067 line = sci_get_current_line(editor->sci);
4069 /* unfold maybe folded results */
4070 sci_ensure_line_is_visible(editor->sci, line);
4072 /* scroll the line if it's off screen */
4073 if (! editor_line_in_view(editor, line))
4074 editor->scroll_percent = percent_of_view;
4075 else
4076 sci_scroll_caret(editor->sci); /* may need horizontal scrolling */
4081 * Deletes all currently set indicators in the @a editor window.
4082 * Error indicators (red squiggly underlines) and usual line markers are removed.
4084 * @param editor The editor to operate on.
4086 void editor_indicator_clear_errors(GeanyEditor *editor)
4088 editor_indicator_clear(editor, GEANY_INDICATOR_ERROR);
4089 sci_marker_delete_all(editor->sci, 0); /* remove the yellow error line marker */
4094 * Deletes all currently set indicators matching @a indic in the @a editor window.
4096 * @param editor The editor to operate on.
4097 * @param indic The indicator number to clear, this is a value of @ref GeanyIndicator.
4099 * @since 0.16
4101 GEANY_API_SYMBOL
4102 void editor_indicator_clear(GeanyEditor *editor, gint indic)
4104 glong last_pos;
4106 g_return_if_fail(editor != NULL);
4108 last_pos = sci_get_length(editor->sci);
4109 if (last_pos > 0)
4111 sci_indicator_set(editor->sci, indic);
4112 sci_indicator_clear(editor->sci, 0, last_pos);
4118 * Sets an indicator @a indic on @a line.
4119 * Whitespace at the start and the end of the line is not marked.
4121 * @param editor The editor to operate on.
4122 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4123 * @param line The line number which should be marked.
4125 * @since 0.16
4127 GEANY_API_SYMBOL
4128 void editor_indicator_set_on_line(GeanyEditor *editor, gint indic, gint line)
4130 gint start, end;
4131 guint i = 0, len;
4132 gchar *linebuf;
4134 g_return_if_fail(editor != NULL);
4135 g_return_if_fail(line >= 0);
4137 start = sci_get_position_from_line(editor->sci, line);
4138 end = sci_get_position_from_line(editor->sci, line + 1);
4140 /* skip blank lines */
4141 if ((start + 1) == end ||
4142 start > end ||
4143 (sci_get_line_end_position(editor->sci, line) - start) == 0)
4145 return;
4148 len = end - start;
4149 linebuf = sci_get_line(editor->sci, line);
4151 /* don't set the indicator on whitespace */
4152 while (isspace(linebuf[i]))
4153 i++;
4154 while (len > 1 && len > i && isspace(linebuf[len - 1]))
4156 len--;
4157 end--;
4159 g_free(linebuf);
4161 editor_indicator_set_on_range(editor, indic, start + i, end);
4166 * Sets an indicator on the range specified by @a start and @a end.
4167 * No error checking or whitespace removal is performed, this should be done by the calling
4168 * function if necessary.
4170 * @param editor The editor to operate on.
4171 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4172 * @param start The starting position for the marker.
4173 * @param end The ending position for the marker.
4175 * @since 0.16
4177 GEANY_API_SYMBOL
4178 void editor_indicator_set_on_range(GeanyEditor *editor, gint indic, gint start, gint end)
4180 g_return_if_fail(editor != NULL);
4181 if (start >= end)
4182 return;
4184 sci_indicator_set(editor->sci, indic);
4185 sci_indicator_fill(editor->sci, start, end - start);
4189 /* Inserts the given colour (format should be #...), if there is a selection starting with 0x...
4190 * the replacement will also start with 0x... */
4191 void editor_insert_color(GeanyEditor *editor, const gchar *colour)
4193 g_return_if_fail(editor != NULL);
4195 if (sci_has_selection(editor->sci))
4197 gint start = sci_get_selection_start(editor->sci);
4198 const gchar *replacement = colour;
4200 if (sci_get_char_at(editor->sci, start) == '0' &&
4201 sci_get_char_at(editor->sci, start + 1) == 'x')
4203 gint end = sci_get_selection_end(editor->sci);
4205 sci_set_selection_start(editor->sci, start + 2);
4206 /* we need to also re-set the selection end in case the anchor was located before
4207 * the cursor, since set_selection_start() always moves the cursor, not the anchor */
4208 sci_set_selection_end(editor->sci, end);
4209 replacement++; /* skip the leading "0x" */
4211 else if (sci_get_char_at(editor->sci, start - 1) == '#')
4212 { /* double clicking something like #00ffff may only select 00ffff because of wordchars */
4213 replacement++; /* so skip the '#' to only replace the colour value */
4215 sci_replace_sel(editor->sci, replacement);
4217 else
4218 sci_add_text(editor->sci, colour);
4223 * Retrieves the end of line characters mode (LF, CR/LF, CR) in the given editor.
4224 * If @a editor is @c NULL, the default end of line characters are used.
4226 * @param editor @nullable The editor to operate on, or @c NULL to query the default value.
4227 * @return The used end of line characters mode.
4229 * @since 0.20
4231 GEANY_API_SYMBOL
4232 gint editor_get_eol_char_mode(GeanyEditor *editor)
4234 gint mode = file_prefs.default_eol_character;
4236 if (editor != NULL)
4237 mode = sci_get_eol_mode(editor->sci);
4239 return mode;
4244 * Retrieves the localized name (for displaying) of the used end of line characters
4245 * (LF, CR/LF, CR) in the given editor.
4246 * If @a editor is @c NULL, the default end of line characters are used.
4248 * @param editor @nullable The editor to operate on, or @c NULL to query the default value.
4249 * @return The name of the end of line characters.
4251 * @since 0.19
4253 GEANY_API_SYMBOL
4254 const gchar *editor_get_eol_char_name(GeanyEditor *editor)
4256 gint mode = file_prefs.default_eol_character;
4258 if (editor != NULL)
4259 mode = sci_get_eol_mode(editor->sci);
4261 return utils_get_eol_name(mode);
4266 * Retrieves the length of the used end of line characters (LF, CR/LF, CR) in the given editor.
4267 * If @a editor is @c NULL, the default end of line characters are used.
4268 * The returned value is 1 for CR and LF and 2 for CR/LF.
4270 * @param editor @nullable The editor to operate on, or @c NULL to query the default value.
4271 * @return The length of the end of line characters.
4273 * @since 0.19
4275 GEANY_API_SYMBOL
4276 gint editor_get_eol_char_len(GeanyEditor *editor)
4278 gint mode = file_prefs.default_eol_character;
4280 if (editor != NULL)
4281 mode = sci_get_eol_mode(editor->sci);
4283 switch (mode)
4285 case SC_EOL_CRLF: return 2; break;
4286 default: return 1; break;
4292 * Retrieves the used end of line characters (LF, CR/LF, CR) in the given editor.
4293 * If @a editor is @c NULL, the default end of line characters are used.
4294 * The returned value is either "\n", "\r\n" or "\r".
4296 * @param editor @nullable The editor to operate on, or @c NULL to query the default value.
4297 * @return The end of line characters.
4299 * @since 0.19
4301 GEANY_API_SYMBOL
4302 const gchar *editor_get_eol_char(GeanyEditor *editor)
4304 gint mode = file_prefs.default_eol_character;
4306 if (editor != NULL)
4307 mode = sci_get_eol_mode(editor->sci);
4309 return utils_get_eol_char(mode);
4313 static void fold_all(GeanyEditor *editor, gboolean want_fold)
4315 gint lines, first, i;
4317 if (editor == NULL || ! editor_prefs.folding)
4318 return;
4320 lines = sci_get_line_count(editor->sci);
4321 first = sci_get_first_visible_line(editor->sci);
4323 for (i = 0; i < lines; i++)
4325 gint level = sci_get_fold_level(editor->sci, i);
4327 if (level & SC_FOLDLEVELHEADERFLAG)
4329 if (sci_get_fold_expanded(editor->sci, i) == want_fold)
4330 sci_toggle_fold(editor->sci, i);
4333 editor_scroll_to_line(editor, first, 0.0F);
4337 void editor_unfold_all(GeanyEditor *editor)
4339 fold_all(editor, FALSE);
4343 void editor_fold_all(GeanyEditor *editor)
4345 fold_all(editor, TRUE);
4349 void editor_replace_tabs(GeanyEditor *editor, gboolean ignore_selection)
4351 gint anchor_pos, caret_pos;
4352 struct Sci_TextToFind ttf;
4354 g_return_if_fail(editor != NULL);
4356 sci_start_undo_action(editor->sci);
4357 if (sci_has_selection(editor->sci) && !ignore_selection)
4359 ttf.chrg.cpMin = sci_get_selection_start(editor->sci);
4360 ttf.chrg.cpMax = sci_get_selection_end(editor->sci);
4362 else
4364 ttf.chrg.cpMin = 0;
4365 ttf.chrg.cpMax = sci_get_length(editor->sci);
4367 ttf.lpstrText = (gchar*) "\t";
4369 anchor_pos = SSM(editor->sci, SCI_GETANCHOR, 0, 0);
4370 caret_pos = sci_get_current_position(editor->sci);
4371 while (TRUE)
4373 gint search_pos, pos_in_line, current_tab_true_length;
4374 gint tab_len;
4375 gchar *tab_str;
4377 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4378 if (search_pos == -1)
4379 break;
4381 tab_len = sci_get_tab_width(editor->sci);
4382 pos_in_line = sci_get_col_from_position(editor->sci, search_pos);
4383 current_tab_true_length = tab_len - (pos_in_line % tab_len);
4384 tab_str = g_strnfill(current_tab_true_length, ' ');
4385 sci_set_target_start(editor->sci, search_pos);
4386 sci_set_target_end(editor->sci, search_pos + 1);
4387 sci_replace_target(editor->sci, tab_str, FALSE);
4388 /* next search starts after replacement */
4389 ttf.chrg.cpMin = search_pos + current_tab_true_length - 1;
4390 /* update end of range now text has changed */
4391 ttf.chrg.cpMax += current_tab_true_length - 1;
4392 g_free(tab_str);
4394 if (anchor_pos > search_pos)
4395 anchor_pos += current_tab_true_length - 1;
4396 if (caret_pos > search_pos)
4397 caret_pos += current_tab_true_length - 1;
4399 sci_set_selection(editor->sci, anchor_pos, caret_pos);
4400 sci_end_undo_action(editor->sci);
4404 /* Replaces all occurrences all spaces of the length of a given tab_width,
4405 * optionally restricting the search to the current selection. */
4406 void editor_replace_spaces(GeanyEditor *editor, gboolean ignore_selection)
4408 gint search_pos;
4409 gint anchor_pos, caret_pos;
4410 static gdouble tab_len_f = -1.0; /* keep the last used value */
4411 gint tab_len;
4412 gchar *text;
4413 struct Sci_TextToFind ttf;
4415 g_return_if_fail(editor != NULL);
4417 if (tab_len_f < 0.0)
4418 tab_len_f = sci_get_tab_width(editor->sci);
4420 if (! dialogs_show_input_numeric(
4421 _("Enter Tab Width"),
4422 _("Enter the amount of spaces which should be replaced by a tab character."),
4423 &tab_len_f, 1, 100, 1))
4425 return;
4427 tab_len = (gint) tab_len_f;
4428 text = g_strnfill(tab_len, ' ');
4430 sci_start_undo_action(editor->sci);
4431 if (sci_has_selection(editor->sci) && !ignore_selection)
4433 ttf.chrg.cpMin = sci_get_selection_start(editor->sci);
4434 ttf.chrg.cpMax = sci_get_selection_end(editor->sci);
4436 else
4438 ttf.chrg.cpMin = 0;
4439 ttf.chrg.cpMax = sci_get_length(editor->sci);
4441 ttf.lpstrText = text;
4443 anchor_pos = SSM(editor->sci, SCI_GETANCHOR, 0, 0);
4444 caret_pos = sci_get_current_position(editor->sci);
4445 while (TRUE)
4447 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4448 if (search_pos == -1)
4449 break;
4450 /* only replace indentation because otherwise we can mess up alignment */
4451 if (search_pos > sci_get_line_indent_position(editor->sci,
4452 sci_get_line_from_position(editor->sci, search_pos)))
4454 ttf.chrg.cpMin = search_pos + tab_len;
4455 continue;
4457 sci_set_target_start(editor->sci, search_pos);
4458 sci_set_target_end(editor->sci, search_pos + tab_len);
4459 sci_replace_target(editor->sci, "\t", FALSE);
4460 ttf.chrg.cpMin = search_pos;
4461 /* update end of range now text has changed */
4462 ttf.chrg.cpMax -= tab_len - 1;
4464 if (anchor_pos > search_pos)
4465 anchor_pos -= tab_len - 1;
4466 if (caret_pos > search_pos)
4467 caret_pos -= tab_len - 1;
4469 sci_set_selection(editor->sci, anchor_pos, caret_pos);
4470 sci_end_undo_action(editor->sci);
4471 g_free(text);
4475 void editor_strip_line_trailing_spaces(GeanyEditor *editor, gint line)
4477 gint line_start = sci_get_position_from_line(editor->sci, line);
4478 gint line_end = sci_get_line_end_position(editor->sci, line);
4479 gint i = line_end - 1;
4480 gchar ch = sci_get_char_at(editor->sci, i);
4482 /* Diff hunks should keep trailing spaces */
4483 if (editor->document->file_type->id == GEANY_FILETYPES_DIFF)
4484 return;
4486 while ((i >= line_start) && ((ch == ' ') || (ch == '\t')))
4488 i--;
4489 ch = sci_get_char_at(editor->sci, i);
4491 if (i < (line_end - 1))
4493 sci_set_target_start(editor->sci, i + 1);
4494 sci_set_target_end(editor->sci, line_end);
4495 sci_replace_target(editor->sci, "", FALSE);
4500 void editor_strip_trailing_spaces(GeanyEditor *editor, gboolean ignore_selection)
4502 gint start_line;
4503 gint end_line;
4504 gint line;
4506 if (sci_has_selection(editor->sci) && !ignore_selection)
4508 gint selection_start = sci_get_selection_start(editor->sci);
4509 gint selection_end = sci_get_selection_end(editor->sci);
4511 start_line = sci_get_line_from_position(editor->sci, selection_start);
4512 end_line = sci_get_line_from_position(editor->sci, selection_end);
4514 if (sci_get_col_from_position(editor->sci, selection_end) > 0)
4515 end_line++;
4517 else
4519 start_line = 0;
4520 end_line = sci_get_line_count(editor->sci);
4523 sci_start_undo_action(editor->sci);
4525 for (line = start_line; line < end_line; line++)
4527 editor_strip_line_trailing_spaces(editor, line);
4529 sci_end_undo_action(editor->sci);
4533 void editor_ensure_final_newline(GeanyEditor *editor)
4535 gint max_lines = sci_get_line_count(editor->sci);
4536 gboolean append_newline = (max_lines == 1);
4537 gint end_document = sci_get_position_from_line(editor->sci, max_lines);
4539 if (max_lines > 1)
4541 append_newline = end_document > sci_get_position_from_line(editor->sci, max_lines - 1);
4543 if (append_newline)
4545 const gchar *eol = editor_get_eol_char(editor);
4547 sci_insert_text(editor->sci, end_document, eol);
4552 /* Similar to editor_set_font() but *only* sets the font, and doesn't take care
4553 * of updating properties that might depend on the font */
4554 static void set_font(ScintillaObject *sci, const gchar *font)
4556 gint style;
4557 gchar *font_name;
4558 PangoFontDescription *pfd;
4559 gdouble size;
4561 g_return_if_fail(sci);
4563 pfd = pango_font_description_from_string(font);
4564 size = pango_font_description_get_size(pfd) / (gdouble) PANGO_SCALE;
4565 font_name = g_strdup_printf("!%s", pango_font_description_get_family(pfd));
4566 pango_font_description_free(pfd);
4568 for (style = 0; style <= STYLE_MAX; style++)
4569 sci_set_font_fractional(sci, style, font_name, size);
4571 g_free(font_name);
4575 void editor_set_font(GeanyEditor *editor, const gchar *font)
4577 g_return_if_fail(editor);
4579 set_font(editor->sci, font);
4580 update_margins(editor->sci);
4581 /* zoom to 100% to prevent confusion */
4582 sci_zoom_off(editor->sci);
4586 void editor_set_line_wrapping(GeanyEditor *editor, gboolean wrap)
4588 g_return_if_fail(editor != NULL);
4590 editor->line_wrapping = wrap;
4591 sci_set_lines_wrapped(editor->sci, wrap);
4595 /** Sets the indent type for @a editor.
4596 * @param editor Editor.
4597 * @param type Indent type.
4599 * @since 0.16
4601 GEANY_API_SYMBOL
4602 void editor_set_indent_type(GeanyEditor *editor, GeanyIndentType type)
4604 editor_set_indent(editor, type, editor->indent_width);
4608 /** Sets the indent width for @a editor.
4609 * @param editor Editor.
4610 * @param width New indent width.
4612 * @since 1.27 (API 227)
4614 GEANY_API_SYMBOL
4615 void editor_set_indent_width(GeanyEditor *editor, gint width)
4617 editor_set_indent(editor, editor->indent_type, width);
4621 void editor_set_indent(GeanyEditor *editor, GeanyIndentType type, gint width)
4623 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
4624 ScintillaObject *sci = editor->sci;
4625 gboolean use_tabs = type != GEANY_INDENT_TYPE_SPACES;
4627 editor->indent_type = type;
4628 editor->indent_width = width;
4629 sci_set_use_tabs(sci, use_tabs);
4631 if (type == GEANY_INDENT_TYPE_BOTH)
4633 sci_set_tab_width(sci, iprefs->hard_tab_width);
4634 if (iprefs->hard_tab_width != 8)
4636 static gboolean warn = TRUE;
4637 if (warn)
4638 ui_set_statusbar(TRUE, _("Warning: non-standard hard tab width: %d != 8!"),
4639 iprefs->hard_tab_width);
4640 warn = FALSE;
4643 else
4644 sci_set_tab_width(sci, width);
4646 SSM(sci, SCI_SETINDENT, width, 0);
4648 /* remove indent spaces on backspace, if using any spaces to indent */
4649 SSM(sci, SCI_SETBACKSPACEUNINDENTS, type != GEANY_INDENT_TYPE_TABS, 0);
4653 /* Convenience function for editor_goto_pos() to pass a line number.
4654 * line_no is 1 based */
4655 gboolean editor_goto_line(GeanyEditor *editor, gint line_no, gboolean offset)
4657 g_return_val_if_fail(editor, FALSE);
4658 gint line_count = sci_get_line_count(editor->sci);
4660 if (offset)
4661 line_no += sci_get_current_line(editor->sci) + 1;
4663 /* ensure line_no is in bounds and determine whether to set line marker */
4664 gboolean set_marker = line_no > 0 && line_no < line_count;
4665 line_no = line_no <= 0 ? 0
4666 : line_no >= line_count ? line_count - 1
4667 : line_no - 1;
4669 gint pos = sci_get_position_from_line(editor->sci, line_no);
4670 return editor_goto_pos(editor, pos, set_marker);
4674 /** Moves to position @a pos, switching to the document if necessary,
4675 * setting a marker if @a mark is set.
4677 * @param editor Editor.
4678 * @param pos The position.
4679 * @param mark Whether to set a mark on the position.
4680 * @return @c TRUE if action has been performed, otherwise @c FALSE.
4682 * @since 0.20
4684 GEANY_API_SYMBOL
4685 gboolean editor_goto_pos(GeanyEditor *editor, gint pos, gboolean mark)
4687 g_return_val_if_fail(editor, FALSE);
4688 if (G_UNLIKELY(pos < 0))
4689 return FALSE;
4691 if (mark)
4693 gint line = sci_get_line_from_position(editor->sci, pos);
4695 /* mark the tag with the yellow arrow */
4696 sci_marker_delete_all(editor->sci, 0);
4697 sci_set_marker_at_line(editor->sci, line, 0);
4700 sci_goto_pos(editor->sci, pos, TRUE);
4701 editor->scroll_percent = 0.25F;
4703 /* finally switch to the page */
4704 document_show_tab(editor->document);
4705 return TRUE;
4709 static gboolean
4710 on_editor_scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer user_data)
4712 GeanyEditor *editor = user_data;
4714 /* we only handle up and down, leave the rest to Scintilla */
4715 if (event->direction != GDK_SCROLL_UP && event->direction != GDK_SCROLL_DOWN)
4716 return FALSE;
4718 /* Handle scroll events if Alt is pressed and scroll whole pages instead of a
4719 * few lines only, maybe this could/should be done in Scintilla directly */
4720 if (event->state & GDK_MOD1_MASK)
4722 sci_send_command(editor->sci, (event->direction == GDK_SCROLL_DOWN) ? SCI_PAGEDOWN : SCI_PAGEUP);
4723 return TRUE;
4725 else if (event->state & GDK_SHIFT_MASK)
4727 gint amount = (event->direction == GDK_SCROLL_DOWN) ? 8 : -8;
4729 sci_scroll_columns(editor->sci, amount);
4730 return TRUE;
4733 return FALSE; /* let Scintilla handle all other cases */
4737 static gboolean editor_check_colourise(GeanyEditor *editor)
4739 GeanyDocument *doc = editor->document;
4741 if (!doc->priv->colourise_needed)
4742 return FALSE;
4744 doc->priv->colourise_needed = FALSE;
4745 sci_colourise(editor->sci, 0, -1);
4747 /* now that the current document is colourised, fold points are now accurate,
4748 * so force an update of the current function/tag. */
4749 symbols_get_current_function(NULL, NULL);
4750 ui_update_statusbar(NULL, -1);
4752 return TRUE;
4756 /* We only want to colourise just before drawing, to save startup time and
4757 * prevent unnecessary recolouring other documents after one is saved.
4758 * Really we want a "draw" signal but there doesn't seem to be one (expose is too late,
4759 * and "show" doesn't work). */
4760 static gboolean on_editor_focus_in(GtkWidget *widget, GdkEventFocus *event, gpointer user_data)
4762 GeanyEditor *editor = user_data;
4764 editor_check_colourise(editor);
4765 return FALSE;
4769 static gboolean on_editor_draw(GtkWidget *widget, cairo_t *cr, gpointer user_data)
4771 GeanyEditor *editor = user_data;
4773 /* This is just to catch any uncolourised documents being drawn that didn't receive focus
4774 * for some reason, maybe it's not necessary but just in case. */
4775 editor_check_colourise(editor);
4776 return FALSE;
4780 static void setup_sci_keys(ScintillaObject *sci)
4782 /* disable some Scintilla keybindings to be able to redefine them cleanly */
4783 sci_clear_cmdkey(sci, 'A' | (SCMOD_CTRL << 16)); /* select all */
4784 sci_clear_cmdkey(sci, 'D' | (SCMOD_CTRL << 16)); /* duplicate */
4785 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16)); /* line transpose */
4786 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line copy */
4787 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16)); /* line cut */
4788 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line delete */
4789 sci_clear_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line to end delete */
4790 sci_clear_cmdkey(sci, SCK_BACK | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line to beginning delete */
4791 sci_clear_cmdkey(sci, '/' | (SCMOD_CTRL << 16)); /* Previous word part */
4792 sci_clear_cmdkey(sci, '\\' | (SCMOD_CTRL << 16)); /* Next word part */
4793 sci_clear_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16)); /* scroll line up */
4794 sci_clear_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16)); /* scroll line down */
4795 sci_clear_cmdkey(sci, SCK_HOME); /* line start */
4796 sci_clear_cmdkey(sci, SCK_END); /* line end */
4797 sci_clear_cmdkey(sci, SCK_END | (SCMOD_ALT << 16)); /* visual line end */
4799 if (editor_prefs.use_gtk_word_boundaries)
4801 /* use GtkEntry-like word boundaries */
4802 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16), SCI_WORDRIGHTEND);
4803 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_WORDRIGHTENDEXTEND);
4804 sci_assign_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16), SCI_DELWORDRIGHTEND);
4806 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_ALT << 16), SCI_LINESCROLLUP);
4807 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_ALT << 16), SCI_LINESCROLLDOWN);
4808 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16), SCI_PARAUP);
4809 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARAUPEXTEND);
4810 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16), SCI_PARADOWN);
4811 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARADOWNEXTEND);
4813 sci_clear_cmdkey(sci, SCK_BACK | (SCMOD_ALT << 16)); /* clear Alt-Backspace (Undo) */
4817 /* registers a Scintilla image from a named icon from the theme */
4818 static gboolean register_named_icon(ScintillaObject *sci, guint id, const gchar *name)
4820 GError *error = NULL;
4821 GdkPixbuf *pixbuf;
4822 gint n_channels, rowstride, width, height;
4823 gint size;
4825 gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &size, NULL);
4826 pixbuf = gtk_icon_theme_load_icon(gtk_icon_theme_get_default(), name, size, 0, &error);
4827 if (! pixbuf)
4829 g_warning("failed to load icon '%s': %s", name, error->message);
4830 g_error_free(error);
4831 return FALSE;
4834 n_channels = gdk_pixbuf_get_n_channels(pixbuf);
4835 rowstride = gdk_pixbuf_get_rowstride(pixbuf);
4836 width = gdk_pixbuf_get_width(pixbuf);
4837 height = gdk_pixbuf_get_height(pixbuf);
4839 if (gdk_pixbuf_get_bits_per_sample(pixbuf) != 8 ||
4840 ! gdk_pixbuf_get_has_alpha(pixbuf) ||
4841 n_channels != 4 ||
4842 rowstride != width * n_channels)
4844 g_warning("incompatible image data for icon '%s'", name);
4845 g_object_unref(pixbuf);
4846 return FALSE;
4849 SSM(sci, SCI_RGBAIMAGESETWIDTH, width, 0);
4850 SSM(sci, SCI_RGBAIMAGESETHEIGHT, height, 0);
4851 SSM(sci, SCI_REGISTERRGBAIMAGE, id, (sptr_t)gdk_pixbuf_get_pixels(pixbuf));
4853 g_object_unref(pixbuf);
4854 return TRUE;
4858 /* Create new editor widget (scintilla).
4859 * @note The @c "sci-notify" signal is connected separately. */
4860 static ScintillaObject *create_new_sci(GeanyEditor *editor)
4862 ScintillaObject *sci;
4863 int rectangular_selection_modifier;
4864 guint i;
4866 sci = SCINTILLA(scintilla_new());
4868 /* Scintilla doesn't support RTL languages properly and is primarily
4869 * intended to be used with LTR source code, so override the
4870 * GTK+ default text direction for the Scintilla widget. */
4871 gtk_widget_set_direction(GTK_WIDGET(sci), GTK_TEXT_DIR_LTR);
4873 gtk_widget_show(GTK_WIDGET(sci));
4875 sci_set_codepage(sci, SC_CP_UTF8);
4876 /*SSM(sci, SCI_SETWRAPSTARTINDENT, 4, 0);*/
4877 /* disable scintilla provided popup menu */
4878 sci_use_popup(sci, FALSE);
4880 setup_sci_keys(sci);
4882 sci_set_lines_wrapped(sci, editor->line_wrapping);
4883 sci_set_caret_policy_x(sci, CARET_JUMPS | CARET_EVEN, 0);
4884 /* Y policy is set in editor_apply_update_prefs() */
4885 SSM(sci, SCI_AUTOCSETSEPARATOR, '\n', 0);
4886 SSM(sci, SCI_SETSCROLLWIDTHTRACKING, 1, 0);
4888 /* tag autocompletion images */
4889 for (i = 0; i < TM_N_ICONS; i++)
4891 const gchar *icon_name = symbols_get_icon_name(i);
4892 register_named_icon(sci, i + 1, icon_name);
4895 /* necessary for column mode editing, implemented in Scintilla since 2.0 */
4896 SSM(sci, SCI_SETADDITIONALSELECTIONTYPING, 1, 0);
4898 /* rectangular selection modifier for creating rectangular selections with the mouse.
4899 * We use the historical Scintilla values by default. */
4900 #ifdef G_OS_WIN32
4901 rectangular_selection_modifier = SCMOD_ALT;
4902 #else
4903 rectangular_selection_modifier = SCMOD_CTRL;
4904 #endif
4905 SSM(sci, SCI_SETRECTANGULARSELECTIONMODIFIER, rectangular_selection_modifier, 0);
4907 /* virtual space */
4908 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
4910 /* input method editor's candidate window behaviour */
4911 SSM(sci, SCI_SETIMEINTERACTION, editor_prefs.ime_interaction, 0);
4913 #ifdef GDK_WINDOWING_QUARTZ
4914 # if ! GTK_CHECK_VERSION(3,16,0)
4915 /* "retina" (HiDPI) display support on OS X - requires disabling buffered draw
4916 * on older GTK versions */
4917 SSM(sci, SCI_SETBUFFEREDDRAW, 0, 0);
4918 # endif
4919 #endif
4921 /* only connect signals if this is for the document notebook, not split window */
4922 if (editor->sci == NULL)
4924 g_signal_connect(sci, "button-press-event", G_CALLBACK(on_editor_button_press_event), editor);
4925 g_signal_connect(sci, "scroll-event", G_CALLBACK(on_editor_scroll_event), editor);
4926 g_signal_connect(sci, "motion-notify-event", G_CALLBACK(on_motion_event), NULL);
4927 g_signal_connect(sci, "focus-in-event", G_CALLBACK(on_editor_focus_in), editor);
4928 g_signal_connect(sci, "draw", G_CALLBACK(on_editor_draw), editor);
4930 return sci;
4934 /** Creates a new Scintilla @c GtkWidget based on the settings for @a editor.
4935 * @param editor Editor settings.
4936 * @return @transfer{floating} The new widget.
4938 * @since 0.15
4940 GEANY_API_SYMBOL
4941 ScintillaObject *editor_create_widget(GeanyEditor *editor)
4943 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4944 ScintillaObject *old, *sci;
4945 GeanyIndentType old_indent_type = editor->indent_type;
4946 gint old_indent_width = editor->indent_width;
4948 /* temporarily change editor to use the new sci widget */
4949 old = editor->sci;
4950 sci = create_new_sci(editor);
4951 editor->sci = sci;
4953 editor_set_indent(editor, iprefs->type, iprefs->width);
4954 set_font(editor->sci, interface_prefs.editor_font);
4955 editor_apply_update_prefs(editor);
4957 /* if editor already had a widget, restore it */
4958 if (old)
4960 editor->indent_type = old_indent_type;
4961 editor->indent_width = old_indent_width;
4962 editor->sci = old;
4964 return sci;
4968 GeanyEditor *editor_create(GeanyDocument *doc)
4970 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4971 GeanyEditor *editor = g_new0(GeanyEditor, 1);
4973 editor->document = doc;
4974 doc->editor = editor; /* needed in case some editor functions/callbacks expect it */
4976 editor->auto_indent = (iprefs->auto_indent_mode != GEANY_AUTOINDENT_NONE);
4977 editor->line_wrapping = get_project_pref(line_wrapping);
4978 editor->scroll_percent = -1.0F;
4979 editor->line_breaking = FALSE;
4981 editor->sci = editor_create_widget(editor);
4982 return editor;
4986 /* in case we need to free some fields in future */
4987 void editor_destroy(GeanyEditor *editor)
4989 g_free(editor);
4993 static void on_document_save(GObject *obj, GeanyDocument *doc)
4995 gchar *f = g_build_filename(app->configdir, "snippets.conf", NULL);
4997 if (utils_str_equal(doc->real_path, f))
4999 /* reload snippets */
5000 editor_snippets_free();
5001 editor_snippets_init();
5003 g_free(f);
5007 gboolean editor_complete_word_part(GeanyEditor *editor)
5009 gchar *entry;
5011 g_return_val_if_fail(editor, FALSE);
5013 if (!SSM(editor->sci, SCI_AUTOCACTIVE, 0, 0))
5014 return FALSE;
5016 entry = sci_get_string(editor->sci, SCI_AUTOCGETCURRENTTEXT, 0);
5018 /* if no word part, complete normally */
5019 if (!check_partial_completion(editor, entry))
5020 SSM(editor->sci, SCI_AUTOCCOMPLETE, 0, 0);
5022 g_free(entry);
5023 return TRUE;
5027 void editor_init(void)
5029 static GeanyIndentPrefs indent_prefs;
5030 gchar *f;
5032 memset(&editor_prefs, 0, sizeof(GeanyEditorPrefs));
5033 memset(&indent_prefs, 0, sizeof(GeanyIndentPrefs));
5034 editor_prefs.indentation = &indent_prefs;
5036 /* use g_signal_connect_after() to allow plugins connecting to the signal before the default
5037 * handler (on_editor_notify) is called */
5038 g_signal_connect_after(geany_object, "editor-notify", G_CALLBACK(on_editor_notify), NULL);
5040 f = g_build_filename(app->configdir, "snippets.conf", NULL);
5041 ui_add_config_file_menu_item(f, NULL, NULL);
5042 g_free(f);
5043 g_signal_connect(geany_object, "document-save", G_CALLBACK(on_document_save), NULL);
5047 /* TODO: Should these be user-defined instead of hard-coded? */
5048 void editor_set_indentation_guides(GeanyEditor *editor)
5050 gint mode;
5051 gint lexer;
5053 g_return_if_fail(editor != NULL);
5055 if (! editor_prefs.show_indent_guide)
5057 sci_set_indentation_guides(editor->sci, SC_IV_NONE);
5058 return;
5061 lexer = sci_get_lexer(editor->sci);
5062 switch (lexer)
5064 /* Lines added/removed are prefixed with +/- characters, so
5065 * those lines will not be shown with any indentation guides.
5066 * It can be distracting that only a few of lines in a diff/patch
5067 * file will show the guides. */
5068 case SCLEX_DIFF:
5069 mode = SC_IV_NONE;
5070 break;
5072 /* These languages use indentation for control blocks; the "look forward" method works
5073 * best here */
5074 case SCLEX_PYTHON:
5075 case SCLEX_HASKELL:
5076 case SCLEX_MAKEFILE:
5077 case SCLEX_ASM:
5078 case SCLEX_SQL:
5079 case SCLEX_COBOL:
5080 case SCLEX_PROPERTIES:
5081 case SCLEX_FORTRAN: /* Is this the best option for Fortran? */
5082 case SCLEX_CAML:
5083 mode = SC_IV_LOOKFORWARD;
5084 break;
5086 /* C-like (structured) languages benefit from the "look both" method */
5087 case SCLEX_CPP:
5088 case SCLEX_HTML:
5089 case SCLEX_PHPSCRIPT:
5090 case SCLEX_XML:
5091 case SCLEX_PERL:
5092 case SCLEX_LATEX:
5093 case SCLEX_LUA:
5094 case SCLEX_PASCAL:
5095 case SCLEX_RUBY:
5096 case SCLEX_TCL:
5097 case SCLEX_F77:
5098 case SCLEX_CSS:
5099 case SCLEX_BASH:
5100 case SCLEX_VHDL:
5101 case SCLEX_FREEBASIC:
5102 case SCLEX_D:
5103 case SCLEX_OCTAVE:
5104 case SCLEX_RUST:
5105 mode = SC_IV_LOOKBOTH;
5106 break;
5108 default:
5109 mode = SC_IV_REAL;
5110 break;
5113 sci_set_indentation_guides(editor->sci, mode);
5117 /* Apply non-document prefs that can change in the Preferences dialog */
5118 void editor_apply_update_prefs(GeanyEditor *editor)
5120 ScintillaObject *sci;
5121 int caret_y_policy;
5123 g_return_if_fail(editor != NULL);
5125 if (main_status.quitting)
5126 return;
5128 sci = editor->sci;
5130 sci_set_mark_long_lines(sci, editor_get_long_line_type(),
5131 editor_get_long_line_column(), editor_prefs.long_line_color);
5133 /* update indent width, tab width */
5134 editor_set_indent(editor, editor->indent_type, editor->indent_width);
5135 sci_set_tab_indents(sci, editor_prefs.use_tab_to_indent);
5137 sci_assign_cmdkey(sci, SCK_HOME | (SCMOD_SHIFT << 16),
5138 editor_prefs.smart_home_key ? SCI_VCHOMEEXTEND : SCI_HOMEEXTEND);
5139 sci_assign_cmdkey(sci, SCK_HOME | ((SCMOD_SHIFT | SCMOD_ALT) << 16),
5140 editor_prefs.smart_home_key ? SCI_VCHOMERECTEXTEND : SCI_HOMERECTEXTEND);
5142 sci_set_autoc_max_height(sci, editor_prefs.symbolcompletion_max_height);
5143 SSM(sci, SCI_AUTOCSETDROPRESTOFWORD, editor_prefs.completion_drops_rest_of_word, 0);
5145 editor_set_indentation_guides(editor);
5147 sci_set_visible_white_spaces(sci, editor_prefs.show_white_space);
5148 sci_set_visible_eols(sci, editor_prefs.show_line_endings);
5149 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
5150 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin);
5152 sci_set_folding_margin_visible(sci, editor_prefs.folding);
5154 /* virtual space */
5155 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
5157 /* caret Y policy */
5158 caret_y_policy = CARET_EVEN;
5159 if (editor_prefs.scroll_lines_around_cursor > 0)
5160 caret_y_policy |= CARET_SLOP | CARET_STRICT;
5161 sci_set_caret_policy_y(sci, caret_y_policy, editor_prefs.scroll_lines_around_cursor);
5163 /* (dis)allow scrolling past end of document */
5164 sci_set_scroll_stop_at_last_line(sci, editor_prefs.scroll_stop_at_last_line);
5166 sci_set_scrollbar_mode(sci, editor_prefs.show_scrollbars);
5170 /* This is for tab-indents, space aligns formatted code. Spaces should be preserved. */
5171 static void change_tab_indentation(GeanyEditor *editor, gint line, gboolean increase)
5173 ScintillaObject *sci = editor->sci;
5174 gint pos = sci_get_position_from_line(sci, line);
5176 if (increase)
5178 sci_insert_text(sci, pos, "\t");
5180 else
5182 if (sci_get_char_at(sci, pos) == '\t')
5184 sci_set_selection(sci, pos, pos + 1);
5185 sci_replace_sel(sci, "");
5187 else /* remove spaces only if no tabs */
5189 gint width = sci_get_line_indentation(sci, line);
5191 width -= editor_get_indent_prefs(editor)->width;
5192 sci_set_line_indentation(sci, line, width);
5198 static void editor_change_line_indent(GeanyEditor *editor, gint line, gboolean increase)
5200 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
5201 ScintillaObject *sci = editor->sci;
5203 if (iprefs->type == GEANY_INDENT_TYPE_TABS)
5204 change_tab_indentation(editor, line, increase);
5205 else
5207 gint width = sci_get_line_indentation(sci, line);
5209 width += increase ? iprefs->width : -iprefs->width;
5210 sci_set_line_indentation(sci, line, width);
5215 void editor_indent(GeanyEditor *editor, gboolean increase)
5217 ScintillaObject *sci = editor->sci;
5218 gint caret_pos, caret_line, caret_offset, caret_indent_pos, caret_line_len;
5219 gint anchor_pos, anchor_line, anchor_offset, anchor_indent_pos, anchor_line_len;
5221 /* backup information needed to restore caret and anchor */
5222 caret_pos = sci_get_current_position(sci);
5223 anchor_pos = SSM(sci, SCI_GETANCHOR, 0, 0);
5224 caret_line = sci_get_line_from_position(sci, caret_pos);
5225 anchor_line = sci_get_line_from_position(sci, anchor_pos);
5226 caret_offset = caret_pos - sci_get_position_from_line(sci, caret_line);
5227 anchor_offset = anchor_pos - sci_get_position_from_line(sci, anchor_line);
5228 caret_indent_pos = sci_get_line_indent_position(sci, caret_line);
5229 anchor_indent_pos = sci_get_line_indent_position(sci, anchor_line);
5230 caret_line_len = sci_get_line_length(sci, caret_line);
5231 anchor_line_len = sci_get_line_length(sci, anchor_line);
5233 if (sci_get_lines_selected(sci) <= 1)
5235 editor_change_line_indent(editor, sci_get_current_line(sci), increase);
5237 else
5239 gint start, end;
5240 gint line, lstart, lend;
5242 editor_select_lines(editor, FALSE);
5243 start = sci_get_selection_start(sci);
5244 end = sci_get_selection_end(sci);
5245 lstart = sci_get_line_from_position(sci, start);
5246 lend = sci_get_line_from_position(sci, end);
5247 if (end == sci_get_length(sci))
5248 lend++; /* for last line with text on it */
5250 sci_start_undo_action(sci);
5251 for (line = lstart; line < lend; line++)
5253 editor_change_line_indent(editor, line, increase);
5255 sci_end_undo_action(sci);
5258 /* restore caret and anchor position */
5259 if (caret_pos >= caret_indent_pos)
5260 caret_offset += sci_get_line_length(sci, caret_line) - caret_line_len;
5261 if (anchor_pos >= anchor_indent_pos)
5262 anchor_offset += sci_get_line_length(sci, anchor_line) - anchor_line_len;
5264 SSM(sci, SCI_SETCURRENTPOS, sci_get_position_from_line(sci, caret_line) + caret_offset, 0);
5265 SSM(sci, SCI_SETANCHOR, sci_get_position_from_line(sci, anchor_line) + anchor_offset, 0);
5269 /** Gets snippet by name.
5271 * If @a editor is passed, returns a snippet specific to the document filetype.
5272 * If @a editor is @c NULL, returns a snippet from the default set.
5274 * @param editor @nullable Editor or @c NULL.
5275 * @param snippet_name Snippet name.
5276 * @return @nullable snippet or @c NULL if it was not found. Must not be freed.
5278 GEANY_API_SYMBOL
5279 const gchar *editor_find_snippet(GeanyEditor *editor, const gchar *snippet_name)
5281 const gchar *subhash_name = editor ? editor->document->file_type->name : "Default";
5282 GHashTable *subhash = g_hash_table_lookup(snippet_hash, subhash_name);
5284 return subhash ? g_hash_table_lookup(subhash, snippet_name) : NULL;
5288 /** Replaces all special sequences in @a snippet and inserts it at @a pos.
5289 * If you insert at the current position, consider calling @c sci_scroll_caret()
5290 * after this function.
5291 * @param editor .
5292 * @param pos .
5293 * @param snippet .
5295 GEANY_API_SYMBOL
5296 void editor_insert_snippet(GeanyEditor *editor, gint pos, const gchar *snippet)
5298 GString *pattern;
5300 pattern = g_string_new(snippet);
5301 snippets_make_replacements(editor, pattern);
5302 editor_insert_text_block(editor, pattern->str, pos, -1, -1, TRUE);
5303 g_string_free(pattern, TRUE);
5306 static void *copy_(void *src) { return src; }
5307 static void free_(void *doc) { }
5309 /** @gironly
5310 * Gets the GType of GeanyEditor
5312 * @return the GeanyEditor type */
5313 GEANY_API_SYMBOL
5314 GType editor_get_type (void);
5316 G_DEFINE_BOXED_TYPE(GeanyEditor, editor, copy_, free_);