Update HACKING for changed doc generation instructions
[geany-mirror.git] / src / editor.c
blob779e028362b19471a1c6f20157d23ff35b27684c
1 /*
2 * editor.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005-2012 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2012 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com>
6 * Copyright 2009-2012 Frank Lanitz <frank(at)frank(dot)uvena(dot)de>
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 /**
24 * @file editor.h
25 * Editor-related functions for @ref GeanyEditor.
26 * Geany uses the Scintilla editing widget, and this file is mostly built around
27 * Scintilla's functionality.
28 * @see sciwrappers.h.
30 /* Callbacks for the Scintilla widget (ScintillaObject).
31 * Most important is the sci-notify callback, handled in on_editor_notification().
32 * This includes auto-indentation, comments, auto-completion, calltips, etc.
33 * Also some general Scintilla-related functions.
36 #ifdef HAVE_CONFIG_H
37 # include "config.h"
38 #endif
40 #include "editor.h"
42 #include "app.h"
43 #include "callbacks.h"
44 #include "dialogs.h"
45 #include "documentprivate.h"
46 #include "filetypesprivate.h"
47 #include "geanyobject.h"
48 #include "highlighting.h"
49 #include "keybindings.h"
50 #include "main.h"
51 #include "prefs.h"
52 #include "projectprivate.h"
53 #include "sciwrappers.h"
54 #include "support.h"
55 #include "symbols.h"
56 #include "templates.h"
57 #include "ui_utils.h"
58 #include "utils.h"
60 #include "SciLexer.h"
62 #include "gtkcompat.h"
64 #include <ctype.h>
65 #include <string.h>
67 #include <gdk/gdkkeysyms.h>
70 /* Note: use sciwrappers.h instead where possible.
71 * Do not use SSM in files unrelated to scintilla. */
72 #define SSM(s, m, w, l) scintilla_send_message(s, m, w, l)
74 static GHashTable *snippet_hash = NULL;
75 static GQueue *snippet_offsets = NULL;
76 static gint snippet_cursor_insert_pos;
77 static GtkAccelGroup *snippet_accel_group = NULL;
79 static const gchar geany_cursor_marker[] = "__GEANY_CURSOR_MARKER__";
81 /* holds word under the mouse or keyboard cursor */
82 static gchar current_word[GEANY_MAX_WORD_LENGTH];
84 /* Initialised in keyfile.c. */
85 GeanyEditorPrefs editor_prefs;
87 EditorInfo editor_info = {current_word, -1};
89 static struct
91 gchar *text;
92 gboolean set;
93 gchar *last_word;
94 guint tag_index;
95 gint pos;
96 ScintillaObject *sci;
97 } calltip = {NULL, FALSE, NULL, 0, 0, NULL};
99 static gchar indent[100];
102 static void on_new_line_added(GeanyEditor *editor);
103 static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch);
104 static void insert_indent_after_line(GeanyEditor *editor, gint line);
105 static void auto_multiline(GeanyEditor *editor, gint pos);
106 static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c);
107 static void close_block(GeanyEditor *editor, gint pos);
108 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos);
109 static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen,
110 const gchar *wc, gboolean stem);
111 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent);
112 static const gchar *snippets_find_completion_by_name(const gchar *type, const gchar *name);
113 static void snippets_make_replacements(GeanyEditor *editor, GString *pattern);
114 static gssize replace_cursor_markers(GeanyEditor *editor, GString *pattern);
115 static GeanyFiletype *editor_get_filetype_at_line(GeanyEditor *editor, gint line);
116 static gboolean sci_is_blank_line(ScintillaObject *sci, gint line);
119 void editor_snippets_free(void)
121 g_hash_table_destroy(snippet_hash);
122 g_queue_free(snippet_offsets);
123 gtk_window_remove_accel_group(GTK_WINDOW(main_widgets.window), snippet_accel_group);
127 static void snippets_load(GKeyFile *sysconfig, GKeyFile *userconfig)
129 gsize i, j, len = 0, len_keys = 0;
130 gchar **groups_user, **groups_sys;
131 gchar **keys_user, **keys_sys;
132 gchar *value;
133 GHashTable *tmp;
135 /* keys are strings, values are GHashTables, so use g_free and g_hash_table_destroy */
136 snippet_hash =
137 g_hash_table_new_full(g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_hash_table_destroy);
139 /* first read all globally defined auto completions */
140 groups_sys = g_key_file_get_groups(sysconfig, &len);
141 for (i = 0; i < len; i++)
143 if (strcmp(groups_sys[i], "Keybindings") == 0)
144 continue;
145 keys_sys = g_key_file_get_keys(sysconfig, groups_sys[i], &len_keys, NULL);
146 /* create new hash table for the read section (=> filetype) */
147 tmp = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
148 g_hash_table_insert(snippet_hash, g_strdup(groups_sys[i]), tmp);
150 for (j = 0; j < len_keys; j++)
152 g_hash_table_insert(tmp, g_strdup(keys_sys[j]),
153 utils_get_setting_string(sysconfig, groups_sys[i], keys_sys[j], ""));
155 g_strfreev(keys_sys);
157 g_strfreev(groups_sys);
159 /* now read defined completions in user's configuration directory and add / replace them */
160 groups_user = g_key_file_get_groups(userconfig, &len);
161 for (i = 0; i < len; i++)
163 if (strcmp(groups_user[i], "Keybindings") == 0)
164 continue;
165 keys_user = g_key_file_get_keys(userconfig, groups_user[i], &len_keys, NULL);
167 tmp = g_hash_table_lookup(snippet_hash, groups_user[i]);
168 if (tmp == NULL)
169 { /* new key found, create hash table */
170 tmp = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
171 g_hash_table_insert(snippet_hash, g_strdup(groups_user[i]), tmp);
173 for (j = 0; j < len_keys; j++)
175 value = g_hash_table_lookup(tmp, keys_user[j]);
176 if (value == NULL)
177 { /* value = NULL means the key doesn't yet exist, so insert */
178 g_hash_table_insert(tmp, g_strdup(keys_user[j]),
179 utils_get_setting_string(userconfig, groups_user[i], keys_user[j], ""));
181 else
182 { /* old key and value will be freed by destroy function (g_free) */
183 g_hash_table_replace(tmp, g_strdup(keys_user[j]),
184 utils_get_setting_string(userconfig, groups_user[i], keys_user[j], ""));
187 g_strfreev(keys_user);
189 g_strfreev(groups_user);
193 static void on_snippet_keybinding_activate(gchar *key)
195 GeanyDocument *doc = document_get_current();
196 const gchar *s;
197 GHashTable *specials;
199 if (!doc || !gtk_widget_has_focus(GTK_WIDGET(doc->editor->sci)))
200 return;
202 s = snippets_find_completion_by_name(doc->file_type->name, key);
203 if (!s) /* allow user to specify keybindings for "special" snippets */
205 specials = g_hash_table_lookup(snippet_hash, "Special");
206 if (G_LIKELY(specials != NULL))
207 s = g_hash_table_lookup(specials, key);
209 if (!s)
211 utils_beep();
212 return;
215 editor_insert_snippet(doc->editor, sci_get_current_position(doc->editor->sci), s);
216 sci_scroll_caret(doc->editor->sci);
220 static void add_kb(GKeyFile *keyfile, const gchar *group, gchar **keys)
222 gsize i;
224 if (!keys)
225 return;
226 for (i = 0; i < g_strv_length(keys); i++)
228 guint key;
229 GdkModifierType mods;
230 gchar *accel_string = g_key_file_get_value(keyfile, group, keys[i], NULL);
232 gtk_accelerator_parse(accel_string, &key, &mods);
233 g_free(accel_string);
235 if (key == 0 && mods == 0)
237 g_warning("Can not parse accelerator \"%s\" from user snippets.conf", accel_string);
238 continue;
240 gtk_accel_group_connect(snippet_accel_group, key, mods, 0,
241 g_cclosure_new_swap((GCallback)on_snippet_keybinding_activate,
242 g_strdup(keys[i]), (GClosureNotify)g_free));
247 static void load_kb(GKeyFile *sysconfig, GKeyFile *userconfig)
249 const gchar kb_group[] = "Keybindings";
250 gchar **keys = g_key_file_get_keys(userconfig, kb_group, NULL, NULL);
251 gchar **ptr;
253 /* remove overridden keys from system keyfile */
254 foreach_strv(ptr, keys)
255 g_key_file_remove_key(sysconfig, kb_group, *ptr, NULL);
257 add_kb(userconfig, kb_group, keys);
258 g_strfreev(keys);
260 keys = g_key_file_get_keys(sysconfig, kb_group, NULL, NULL);
261 add_kb(sysconfig, kb_group, keys);
262 g_strfreev(keys);
266 void editor_snippets_init(void)
268 gchar *sysconfigfile, *userconfigfile;
269 GKeyFile *sysconfig = g_key_file_new();
270 GKeyFile *userconfig = g_key_file_new();
272 snippet_offsets = g_queue_new();
274 sysconfigfile = g_build_filename(app->datadir, "snippets.conf", NULL);
275 userconfigfile = g_build_filename(app->configdir, "snippets.conf", NULL);
277 /* check for old autocomplete.conf files (backwards compatibility) */
278 if (! g_file_test(userconfigfile, G_FILE_TEST_IS_REGULAR))
279 SETPTR(userconfigfile, g_build_filename(app->configdir, "autocomplete.conf", NULL));
281 /* load the actual config files */
282 g_key_file_load_from_file(sysconfig, sysconfigfile, G_KEY_FILE_NONE, NULL);
283 g_key_file_load_from_file(userconfig, userconfigfile, G_KEY_FILE_NONE, NULL);
285 snippets_load(sysconfig, userconfig);
287 /* setup snippet keybindings */
288 snippet_accel_group = gtk_accel_group_new();
289 gtk_window_add_accel_group(GTK_WINDOW(main_widgets.window), snippet_accel_group);
290 load_kb(sysconfig, userconfig);
292 g_free(sysconfigfile);
293 g_free(userconfigfile);
294 g_key_file_free(sysconfig);
295 g_key_file_free(userconfig);
299 static gboolean on_editor_button_press_event(GtkWidget *widget, GdkEventButton *event,
300 gpointer data)
302 GeanyEditor *editor = data;
303 GeanyDocument *doc = editor->document;
305 /* it's very unlikely we got a 'real' click even on 0, 0, so assume it is a
306 * fake event to show the editor menu triggered by a key event where we want to use the
307 * text cursor position. */
308 if (event->x > 0.0 && event->y > 0.0)
309 editor_info.click_pos = sci_get_position_from_xy(editor->sci,
310 (gint)event->x, (gint)event->y, FALSE);
311 else
312 editor_info.click_pos = sci_get_current_position(editor->sci);
314 if (event->button == 1)
316 guint state = event->state & gtk_accelerator_get_default_mod_mask();
318 if (event->type == GDK_BUTTON_PRESS && editor_prefs.disable_dnd)
320 gint ss = sci_get_selection_start(editor->sci);
321 sci_set_selection_end(editor->sci, ss);
323 if (event->type == GDK_BUTTON_PRESS && state == GDK_CONTROL_MASK)
325 sci_set_current_position(editor->sci, editor_info.click_pos, FALSE);
327 editor_find_current_word(editor, editor_info.click_pos,
328 current_word, sizeof current_word, NULL);
329 if (*current_word)
330 return symbols_goto_tag(current_word, TRUE);
331 else
332 keybindings_send_command(GEANY_KEY_GROUP_GOTO, GEANY_KEYS_GOTO_MATCHINGBRACE);
333 return TRUE;
335 return document_check_disk_status(doc, FALSE);
338 /* calls the edit popup menu in the editor */
339 if (event->button == 3)
341 gboolean can_goto;
343 /* ensure the editor widget has the focus after this operation */
344 gtk_widget_grab_focus(widget);
346 editor_find_current_word(editor, editor_info.click_pos,
347 current_word, sizeof current_word, NULL);
349 can_goto = sci_has_selection(editor->sci) || current_word[0] != '\0';
350 ui_update_popup_goto_items(can_goto);
351 ui_update_popup_copy_items(doc);
352 ui_update_insert_include_item(doc, 0);
354 g_signal_emit_by_name(geany_object, "update-editor-menu",
355 current_word, editor_info.click_pos, doc);
357 gtk_menu_popup(GTK_MENU(main_widgets.editor_menu),
358 NULL, NULL, NULL, NULL, event->button, event->time);
360 return TRUE;
362 return FALSE;
366 static gboolean is_style_php(gint style)
368 if ((style >= SCE_HPHP_DEFAULT && style <= SCE_HPHP_OPERATOR) ||
369 style == SCE_HPHP_COMPLEX_VARIABLE)
371 return TRUE;
374 return FALSE;
378 static gint editor_get_long_line_type(void)
380 if (app->project)
381 switch (app->project->priv->long_line_behaviour)
383 case 0: /* marker disabled */
384 return 2;
385 case 1: /* use global settings */
386 break;
387 case 2: /* custom (enabled) */
388 return editor_prefs.long_line_type;
391 if (!editor_prefs.long_line_enabled)
392 return 2;
393 else
394 return editor_prefs.long_line_type;
398 static gint editor_get_long_line_column(void)
400 if (app->project && app->project->priv->long_line_behaviour != 1 /* use global settings */)
401 return app->project->priv->long_line_column;
402 else
403 return editor_prefs.long_line_column;
407 static const GeanyEditorPrefs *
408 get_default_prefs(void)
410 static GeanyEditorPrefs eprefs;
412 eprefs = editor_prefs;
414 /* project overrides */
415 eprefs.indentation = (GeanyIndentPrefs*)editor_get_indent_prefs(NULL);
416 eprefs.long_line_type = editor_get_long_line_type();
417 eprefs.long_line_column = editor_get_long_line_column();
418 return &eprefs;
422 /* Gets the prefs for the editor.
423 * Prefs can be different according to project or document.
424 * @warning Always get a fresh result instead of keeping a pointer to it if the editor/project
425 * settings may have changed, or if this function has been called for a different editor.
426 * @param editor The editor, or @c NULL to get the default prefs.
427 * @return The prefs. */
428 const GeanyEditorPrefs *editor_get_prefs(GeanyEditor *editor)
430 static GeanyEditorPrefs eprefs;
431 const GeanyEditorPrefs *dprefs = get_default_prefs();
433 /* Return the address of the default prefs to allow returning default and editor
434 * pref pointers without invalidating the contents of either. */
435 if (editor == NULL)
436 return dprefs;
438 eprefs = *dprefs;
439 eprefs.indentation = (GeanyIndentPrefs*)editor_get_indent_prefs(editor);
440 /* add other editor & document overrides as needed */
441 return &eprefs;
445 void editor_toggle_fold(GeanyEditor *editor, gint line, gint modifiers)
447 ScintillaObject *sci;
448 gint header;
450 g_return_if_fail(editor != NULL);
452 sci = editor->sci;
453 /* When collapsing a fold range whose starting line is offscreen,
454 * scroll the starting line to display at the top of the view.
455 * Otherwise it can be confusing when the document scrolls down to hide
456 * the folded lines. */
457 if ((sci_get_fold_level(sci, line) & SC_FOLDLEVELNUMBERMASK) > SC_FOLDLEVELBASE &&
458 !(sci_get_fold_level(sci, line) & SC_FOLDLEVELHEADERFLAG))
460 gint parent = sci_get_fold_parent(sci, line);
461 gint first = sci_get_first_visible_line(sci);
463 parent = SSM(sci, SCI_VISIBLEFROMDOCLINE, parent, 0);
464 if (first > parent)
465 SSM(sci, SCI_SETFIRSTVISIBLELINE, parent, 0);
468 /* find the fold header of the given line in case the one clicked isn't a fold point */
469 if (sci_get_fold_level(sci, line) & SC_FOLDLEVELHEADERFLAG)
470 header = line;
471 else
472 header = sci_get_fold_parent(sci, line);
474 if ((editor_prefs.unfold_all_children && ! (modifiers & SCMOD_SHIFT)) ||
475 (! editor_prefs.unfold_all_children && (modifiers & SCMOD_SHIFT)))
477 SSM(sci, SCI_FOLDCHILDREN, header, SC_FOLDACTION_TOGGLE);
479 else
481 SSM(sci, SCI_FOLDLINE, header, SC_FOLDACTION_TOGGLE);
486 static void on_margin_click(GeanyEditor *editor, SCNotification *nt)
488 /* left click to marker margin marks the line */
489 if (nt->margin == 1)
491 gint line = sci_get_line_from_position(editor->sci, nt->position);
493 /*sci_marker_delete_all(editor->sci, 1);*/
494 sci_toggle_marker_at_line(editor->sci, line, 1); /* toggle the marker */
496 /* left click on the folding margin to toggle folding state of current line */
497 else if (nt->margin == 2 && editor_prefs.folding)
499 gint line = sci_get_line_from_position(editor->sci, nt->position);
500 editor_toggle_fold(editor, line, nt->modifiers);
505 static void on_update_ui(GeanyEditor *editor, G_GNUC_UNUSED SCNotification *nt)
507 ScintillaObject *sci = editor->sci;
508 gint pos = sci_get_current_position(sci);
510 /* since Scintilla 2.24, SCN_UPDATEUI is also sent on scrolling though we don't need to handle
511 * this and so ignore every SCN_UPDATEUI events except for content and selection changes */
512 if (! (nt->updated & SC_UPDATE_CONTENT) && ! (nt->updated & SC_UPDATE_SELECTION))
513 return;
515 /* undo / redo menu update */
516 ui_update_popup_reundo_items(editor->document);
518 /* brace highlighting */
519 editor_highlight_braces(editor, pos);
521 ui_update_statusbar(editor->document, pos);
523 #if 0
524 /** experimental code for inverting selections */
526 gint i;
527 for (i = SSM(sci, SCI_GETSELECTIONSTART, 0, 0); i < SSM(sci, SCI_GETSELECTIONEND, 0, 0); i++)
529 /* need to get colour from getstyleat(), but how? */
530 SSM(sci, SCI_STYLESETFORE, STYLE_DEFAULT, 0);
531 SSM(sci, SCI_STYLESETBACK, STYLE_DEFAULT, 0);
534 sci_get_style_at(sci, pos);
536 #endif
540 static void check_line_breaking(GeanyEditor *editor, gint pos)
542 ScintillaObject *sci = editor->sci;
543 gint line, lstart, col;
544 gchar c;
546 if (!editor->line_breaking)
547 return;
549 col = sci_get_col_from_position(sci, pos);
551 line = sci_get_current_line(sci);
553 lstart = sci_get_position_from_line(sci, line);
555 /* use column instead of position which might be different with multibyte characters */
556 if (col < editor_prefs.line_break_column)
557 return;
559 /* look for the last space before line_break_column */
560 pos = MIN(pos, lstart + editor_prefs.line_break_column);
562 while (pos > lstart)
564 c = sci_get_char_at(sci, --pos);
565 if (c == GDK_space)
567 gint diff, last_pos, last_col;
569 /* remember the distance between the current column and the last column on the line
570 * (we use column position in case the previous line gets altered, such as removing
571 * trailing spaces or in case it contains multibyte characters) */
572 last_pos = sci_get_line_end_position(sci, line);
573 last_col = sci_get_col_from_position(sci, last_pos);
574 diff = last_col - col;
576 /* break the line after the space */
577 sci_set_current_position(sci, pos + 1, FALSE);
578 sci_cancel(sci); /* don't select from completion list */
579 sci_send_command(sci, SCI_NEWLINE);
580 line++;
582 /* correct cursor position (might not be at line end) */
583 last_pos = sci_get_line_end_position(sci, line);
584 last_col = sci_get_col_from_position(sci, last_pos); /* get last column on line */
585 /* last column - distance is the desired column, then retrieve its document position */
586 pos = sci_get_position_from_col(sci, line, last_col - diff);
587 sci_set_current_position(sci, pos, FALSE);
588 sci_scroll_caret(sci);
589 return;
595 static void show_autocomplete(ScintillaObject *sci, gsize rootlen, GString *words)
597 /* hide autocompletion if only option is already typed */
598 if (rootlen >= words->len ||
599 (words->str[rootlen] == '?' && rootlen >= words->len - 2))
601 sci_send_command(sci, SCI_AUTOCCANCEL);
602 return;
604 /* store whether a calltip is showing, so we can reshow it after autocompletion */
605 calltip.set = (gboolean) SSM(sci, SCI_CALLTIPACTIVE, 0, 0);
606 SSM(sci, SCI_AUTOCSHOW, rootlen, (sptr_t) words->str);
610 static void show_tags_list(GeanyEditor *editor, const GPtrArray *tags, gsize rootlen)
612 ScintillaObject *sci = editor->sci;
614 g_return_if_fail(tags);
616 if (tags->len > 0)
618 GString *words = g_string_sized_new(150);
619 guint j;
621 for (j = 0; j < tags->len; ++j)
623 TMTag *tag = tags->pdata[j];
625 if (j > 0)
626 g_string_append_c(words, '\n');
628 if (j == editor_prefs.autocompletion_max_entries)
630 g_string_append(words, "...");
631 break;
633 g_string_append(words, tag->name);
635 /* for now, tag types don't all follow C, so just look at arglist */
636 if (!EMPTY(tag->atts.entry.arglist))
637 g_string_append(words, "?2");
638 else
639 g_string_append(words, "?1");
641 show_autocomplete(sci, rootlen, words);
642 g_string_free(words, TRUE);
647 /* do not use with long strings */
648 static gboolean match_last_chars(ScintillaObject *sci, gint pos, const gchar *str)
650 gsize len = strlen(str);
651 gchar *buf;
653 g_return_val_if_fail(len < 100, FALSE);
654 g_return_val_if_fail((gint)len <= pos, FALSE);
656 buf = g_alloca(len + 1);
657 sci_get_text_range(sci, pos - len, pos, buf);
658 return strcmp(str, buf) == 0;
662 static gboolean reshow_calltip(gpointer data)
664 GeanyDocument *doc;
666 g_return_val_if_fail(calltip.sci != NULL, FALSE);
668 SSM(calltip.sci, SCI_CALLTIPCANCEL, 0, 0);
669 doc = document_get_current();
671 if (doc && doc->editor->sci == calltip.sci)
673 /* we use the position where the calltip was previously started as SCI_GETCURRENTPOS
674 * may be completely wrong in case the user cancelled the auto completion with the mouse */
675 SSM(calltip.sci, SCI_CALLTIPSHOW, calltip.pos, (sptr_t) calltip.text);
677 return FALSE;
681 static void request_reshowing_calltip(SCNotification *nt)
683 if (calltip.set)
685 /* delay the reshow of the calltip window to make sure it is actually displayed,
686 * without it might be not visible on SCN_AUTOCCANCEL. the priority is set to
687 * low to hopefully make Scintilla's events happen before reshowing since they
688 * seem to re-cancel the calltip on autoc menu hiding too */
689 g_idle_add_full(G_PRIORITY_LOW, reshow_calltip, NULL, NULL);
694 static void autocomplete_scope(GeanyEditor *editor)
696 ScintillaObject *sci = editor->sci;
697 gint pos = sci_get_current_position(editor->sci);
698 gchar typed = sci_get_char_at(sci, pos - 1);
699 gchar *name;
700 const GPtrArray *tags = NULL;
701 const TMTag *tag;
702 GeanyFiletype *ft = editor->document->file_type;
704 if (ft->id == GEANY_FILETYPES_C || ft->id == GEANY_FILETYPES_CPP)
706 if (match_last_chars(sci, pos, "->") || match_last_chars(sci, pos, "::"))
707 pos--;
708 else if (ft->id == GEANY_FILETYPES_CPP && match_last_chars(sci, pos, "->*"))
709 pos-=2;
710 else if (typed != '.')
711 return;
713 else if (typed != '.')
714 return;
716 /* allow for a space between word and operator */
717 if (isspace(sci_get_char_at(sci, pos - 2)))
718 pos--;
719 name = editor_get_word_at_pos(editor, pos - 1, NULL);
720 if (!name)
721 return;
723 tags = tm_workspace_find(name, tm_tag_max_t, NULL, FALSE, ft->lang);
724 g_free(name);
725 if (!tags || tags->len == 0)
726 return;
728 tag = g_ptr_array_index(tags, 0);
729 name = tag->atts.entry.var_type;
730 if (name)
732 TMWorkObject *obj = editor->document->tm_file;
734 tags = tm_workspace_find_scope_members(obj ? obj->tags_array : NULL,
735 name, TRUE, FALSE);
736 if (tags)
737 show_tags_list(editor, tags, 0);
742 static void on_char_added(GeanyEditor *editor, SCNotification *nt)
744 ScintillaObject *sci = editor->sci;
745 gint pos = sci_get_current_position(sci);
747 switch (nt->ch)
749 case '\r':
750 { /* simple indentation (only for CR format) */
751 if (sci_get_eol_mode(sci) == SC_EOL_CR)
752 on_new_line_added(editor);
753 break;
755 case '\n':
756 { /* simple indentation (for CR/LF and LF format) */
757 on_new_line_added(editor);
758 break;
760 case '>':
761 editor_start_auto_complete(editor, pos, FALSE); /* C/C++ ptr-> scope completion */
762 /* fall through */
763 case '/':
764 { /* close xml-tags */
765 handle_xml(editor, pos, nt->ch);
766 break;
768 case '(':
770 auto_close_chars(sci, pos, nt->ch);
771 /* show calltips */
772 editor_show_calltip(editor, --pos);
773 break;
775 case ')':
776 { /* hide calltips */
777 if (SSM(sci, SCI_CALLTIPACTIVE, 0, 0))
779 SSM(sci, SCI_CALLTIPCANCEL, 0, 0);
781 g_free(calltip.text);
782 calltip.text = NULL;
783 calltip.pos = 0;
784 calltip.sci = NULL;
785 calltip.set = FALSE;
786 break;
788 case '{':
789 case '[':
790 case '"':
791 case '\'':
793 auto_close_chars(sci, pos, nt->ch);
794 break;
796 case '}':
797 { /* closing bracket handling */
798 if (editor->auto_indent)
799 close_block(editor, pos - 1);
800 break;
802 /* scope autocompletion */
803 case '.':
804 case ':': /* C/C++ class:: syntax */
805 /* tag autocompletion */
806 default:
807 #if 0
808 if (! editor_start_auto_complete(editor, pos, FALSE))
809 request_reshowing_calltip(nt);
810 #else
811 editor_start_auto_complete(editor, pos, FALSE);
812 #endif
814 check_line_breaking(editor, pos);
818 /* expand() and fold_changed() are copied from SciTE (thanks) to fix #1923350. */
819 static void expand(ScintillaObject *sci, gint *line, gboolean doExpand,
820 gboolean force, gint visLevels, gint level)
822 gint lineMaxSubord = SSM(sci, SCI_GETLASTCHILD, *line, level & SC_FOLDLEVELNUMBERMASK);
823 gint levelLine = level;
824 (*line)++;
825 while (*line <= lineMaxSubord)
827 if (force)
829 if (visLevels > 0)
830 SSM(sci, SCI_SHOWLINES, *line, *line);
831 else
832 SSM(sci, SCI_HIDELINES, *line, *line);
834 else
836 if (doExpand)
837 SSM(sci, SCI_SHOWLINES, *line, *line);
839 if (levelLine == -1)
840 levelLine = SSM(sci, SCI_GETFOLDLEVEL, *line, 0);
841 if (levelLine & SC_FOLDLEVELHEADERFLAG)
843 if (force)
845 if (visLevels > 1)
846 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
847 else
848 SSM(sci, SCI_SETFOLDEXPANDED, *line, 0);
849 expand(sci, line, doExpand, force, visLevels - 1, -1);
851 else
853 if (doExpand)
855 if (!sci_get_fold_expanded(sci, *line))
856 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
857 expand(sci, line, TRUE, force, visLevels - 1, -1);
859 else
861 expand(sci, line, FALSE, force, visLevels - 1, -1);
865 else
867 (*line)++;
873 static void fold_changed(ScintillaObject *sci, gint line, gint levelNow, gint levelPrev)
875 if (levelNow & SC_FOLDLEVELHEADERFLAG)
877 if (! (levelPrev & SC_FOLDLEVELHEADERFLAG))
879 /* Adding a fold point */
880 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
881 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
884 else if (levelPrev & SC_FOLDLEVELHEADERFLAG)
886 if (! sci_get_fold_expanded(sci, line))
887 { /* Removing the fold from one that has been contracted so should expand
888 * otherwise lines are left invisible with no way to make them visible */
889 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
890 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
893 if (! (levelNow & SC_FOLDLEVELWHITEFLAG) &&
894 ((levelPrev & SC_FOLDLEVELNUMBERMASK) > (levelNow & SC_FOLDLEVELNUMBERMASK)))
896 /* See if should still be hidden */
897 gint parentLine = sci_get_fold_parent(sci, line);
898 if (parentLine < 0)
900 SSM(sci, SCI_SHOWLINES, line, line);
902 else if (sci_get_fold_expanded(sci, parentLine) &&
903 sci_get_line_is_visible(sci, parentLine))
905 SSM(sci, SCI_SHOWLINES, line, line);
911 static void ensure_range_visible(ScintillaObject *sci, gint posStart, gint posEnd,
912 gboolean enforcePolicy)
914 gint lineStart = sci_get_line_from_position(sci, MIN(posStart, posEnd));
915 gint lineEnd = sci_get_line_from_position(sci, MAX(posStart, posEnd));
916 gint line;
918 for (line = lineStart; line <= lineEnd; line++)
920 SSM(sci, enforcePolicy ? SCI_ENSUREVISIBLEENFORCEPOLICY : SCI_ENSUREVISIBLE, line, 0);
925 static void auto_update_margin_width(GeanyEditor *editor)
927 gint next_linecount = 1;
928 gint linecount = sci_get_line_count(editor->sci);
929 GeanyDocument *doc = editor->document;
931 while (next_linecount <= linecount)
932 next_linecount *= 10;
934 if (editor->document->priv->line_count != next_linecount)
936 doc->priv->line_count = next_linecount;
937 sci_set_line_numbers(editor->sci, TRUE);
942 static void partial_complete(ScintillaObject *sci, const gchar *text)
944 gint pos = sci_get_current_position(sci);
946 sci_insert_text(sci, pos, text);
947 sci_set_current_position(sci, pos + strlen(text), TRUE);
951 /* Complete the next word part from @a entry */
952 static gboolean check_partial_completion(GeanyEditor *editor, const gchar *entry)
954 gchar *stem, *ptr, *text = utils_strdupa(entry);
956 read_current_word(editor, -1, current_word, sizeof current_word, NULL, TRUE);
957 stem = current_word;
958 if (strstr(text, stem) != text)
959 return FALSE; /* shouldn't happen */
960 if (strlen(text) <= strlen(stem))
961 return FALSE;
963 text += strlen(stem); /* skip stem */
964 ptr = strstr(text + 1, "_");
965 if (ptr)
967 ptr[1] = '\0';
968 partial_complete(editor->sci, text);
969 return TRUE;
971 else
973 /* CamelCase */
974 foreach_str(ptr, text + 1)
976 if (!ptr[0])
977 break;
978 if (g_ascii_isupper(*ptr) && g_ascii_islower(ptr[1]))
980 ptr[0] = '\0';
981 partial_complete(editor->sci, text);
982 return TRUE;
986 return FALSE;
990 /* Callback for the "sci-notify" signal to emit a "editor-notify" signal.
991 * Plugins can connect to the "editor-notify" signal. */
992 void editor_sci_notify_cb(G_GNUC_UNUSED GtkWidget *widget, G_GNUC_UNUSED gint scn,
993 gpointer scnt, gpointer data)
995 GeanyEditor *editor = data;
996 gboolean retval;
998 g_return_if_fail(editor != NULL);
1000 g_signal_emit_by_name(geany_object, "editor-notify", editor, scnt, &retval);
1004 static gboolean on_editor_notify(G_GNUC_UNUSED GObject *object, GeanyEditor *editor,
1005 SCNotification *nt, G_GNUC_UNUSED gpointer data)
1007 ScintillaObject *sci = editor->sci;
1008 GeanyDocument *doc = editor->document;
1010 switch (nt->nmhdr.code)
1012 case SCN_SAVEPOINTLEFT:
1013 document_set_text_changed(doc, TRUE);
1014 break;
1016 case SCN_SAVEPOINTREACHED:
1017 document_set_text_changed(doc, FALSE);
1018 break;
1020 case SCN_MODIFYATTEMPTRO:
1021 utils_beep();
1022 break;
1024 case SCN_MARGINCLICK:
1025 on_margin_click(editor, nt);
1026 break;
1028 case SCN_UPDATEUI:
1029 on_update_ui(editor, nt);
1030 break;
1032 case SCN_PAINTED:
1033 /* Visible lines are only laid out accurately just before painting,
1034 * so we need to only call editor_scroll_to_line here, because the document
1035 * may have line wrapping and folding enabled.
1036 * http://scintilla.sourceforge.net/ScintillaDoc.html#LineWrapping
1037 * This is important e.g. when loading a session and switching pages
1038 * and having the cursor scroll in view. */
1039 /* FIXME: Really we want to do this just before painting, not after it
1040 * as it will cause repainting. */
1041 if (editor->scroll_percent > 0.0F)
1043 editor_scroll_to_line(editor, -1, editor->scroll_percent);
1044 /* disable further scrolling */
1045 editor->scroll_percent = -1.0F;
1047 break;
1049 case SCN_MODIFIED:
1050 if (editor_prefs.show_linenumber_margin && (nt->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT)) && nt->linesAdded)
1052 /* automatically adjust Scintilla's line numbers margin width */
1053 auto_update_margin_width(editor);
1055 if (nt->modificationType & SC_STARTACTION && ! ignore_callback)
1057 /* get notified about undo changes */
1058 document_undo_add(doc, UNDO_SCINTILLA, NULL);
1060 if (editor_prefs.folding && (nt->modificationType & SC_MOD_CHANGEFOLD) != 0)
1062 /* handle special fold cases, e.g. #1923350 */
1063 fold_changed(sci, nt->line, nt->foldLevelNow, nt->foldLevelPrev);
1065 if (nt->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT))
1067 document_update_tag_list_in_idle(doc);
1069 break;
1071 case SCN_CHARADDED:
1072 on_char_added(editor, nt);
1073 break;
1075 case SCN_USERLISTSELECTION:
1076 if (nt->listType == 1)
1078 sci_add_text(sci, nt->text);
1080 break;
1082 case SCN_AUTOCSELECTION:
1083 if (g_str_equal(nt->text, "..."))
1085 sci_cancel(sci);
1086 utils_beep();
1087 break;
1089 /* fall through */
1090 case SCN_AUTOCCANCELLED:
1091 /* now that autocomplete is finishing or was cancelled, reshow calltips
1092 * if they were showing */
1093 request_reshowing_calltip(nt);
1094 break;
1096 #ifdef GEANY_DEBUG
1097 case SCN_STYLENEEDED:
1098 geany_debug("style");
1099 break;
1100 #endif
1101 case SCN_NEEDSHOWN:
1102 ensure_range_visible(sci, nt->position, nt->position + nt->length, FALSE);
1103 break;
1105 case SCN_URIDROPPED:
1106 if (nt->text != NULL)
1108 document_open_file_list(nt->text, strlen(nt->text));
1110 break;
1112 case SCN_CALLTIPCLICK:
1113 if (nt->position > 0)
1115 switch (nt->position)
1117 case 1: /* up arrow */
1118 if (calltip.tag_index > 0)
1119 calltip.tag_index--;
1120 break;
1122 case 2: calltip.tag_index++; break; /* down arrow */
1124 editor_show_calltip(editor, -1);
1126 break;
1128 case SCN_ZOOM:
1129 /* recalculate line margin width */
1130 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin);
1131 break;
1133 /* we always return FALSE here to let plugins handle the event too */
1134 return FALSE;
1138 /* Note: this is the same as sci_get_tab_width(), but is still useful when you don't have
1139 * a scintilla pointer. */
1140 static gint get_tab_width(const GeanyIndentPrefs *indent_prefs)
1142 if (indent_prefs->type == GEANY_INDENT_TYPE_BOTH)
1143 return indent_prefs->hard_tab_width;
1145 return indent_prefs->width; /* tab width = indent width */
1149 /* Returns a string containing width chars of whitespace, filled with simple space
1150 * characters or with the right number of tab characters, according to the indent prefs.
1151 * (Result is filled with tabs *and* spaces if width isn't a multiple of
1152 * the tab width). */
1153 static gchar *
1154 get_whitespace(const GeanyIndentPrefs *iprefs, gint width)
1156 g_return_val_if_fail(width >= 0, NULL);
1158 if (width == 0)
1159 return g_strdup("");
1161 if (iprefs->type == GEANY_INDENT_TYPE_SPACES)
1163 return g_strnfill(width, ' ');
1165 else
1166 { /* first fill text with tabs and fill the rest with spaces */
1167 const gint tab_width = get_tab_width(iprefs);
1168 gint tabs = width / tab_width;
1169 gint spaces = width % tab_width;
1170 gint len = tabs + spaces;
1171 gchar *str;
1173 str = g_malloc(len + 1);
1175 memset(str, '\t', tabs);
1176 memset(str + tabs, ' ', spaces);
1177 str[len] = '\0';
1178 return str;
1183 static const GeanyIndentPrefs *
1184 get_default_indent_prefs(void)
1186 static GeanyIndentPrefs iprefs;
1188 iprefs = app->project ? *app->project->priv->indentation : *editor_prefs.indentation;
1189 return &iprefs;
1193 /** Gets the indentation prefs for the editor.
1194 * Prefs can be different according to project or document.
1195 * @warning Always get a fresh result instead of keeping a pointer to it if the editor/project
1196 * settings may have changed, or if this function has been called for a different editor.
1197 * @param editor The editor, or @c NULL to get the default indent prefs.
1198 * @return The indent prefs. */
1199 const GeanyIndentPrefs *
1200 editor_get_indent_prefs(GeanyEditor *editor)
1202 static GeanyIndentPrefs iprefs;
1203 const GeanyIndentPrefs *dprefs = get_default_indent_prefs();
1205 /* Return the address of the default prefs to allow returning default and editor
1206 * pref pointers without invalidating the contents of either. */
1207 if (editor == NULL)
1208 return dprefs;
1210 iprefs = *dprefs;
1211 iprefs.type = editor->indent_type;
1212 iprefs.width = editor->indent_width;
1214 /* if per-document auto-indent is enabled, but we don't have a global mode set,
1215 * just use basic auto-indenting */
1216 if (editor->auto_indent && iprefs.auto_indent_mode == GEANY_AUTOINDENT_NONE)
1217 iprefs.auto_indent_mode = GEANY_AUTOINDENT_BASIC;
1219 if (!editor->auto_indent)
1220 iprefs.auto_indent_mode = GEANY_AUTOINDENT_NONE;
1222 return &iprefs;
1226 static void on_new_line_added(GeanyEditor *editor)
1228 ScintillaObject *sci = editor->sci;
1229 gint line = sci_get_current_line(sci);
1231 /* simple indentation */
1232 if (editor->auto_indent)
1234 insert_indent_after_line(editor, line - 1);
1237 if (editor_prefs.auto_continue_multiline)
1238 { /* " * " auto completion in multiline C/C++/D/Java comments */
1239 auto_multiline(editor, line);
1242 if (editor_prefs.newline_strip)
1243 { /* strip the trailing spaces on the previous line */
1244 editor_strip_line_trailing_spaces(editor, line - 1);
1249 static gboolean lexer_has_braces(ScintillaObject *sci)
1251 gint lexer = sci_get_lexer(sci);
1253 switch (lexer)
1255 case SCLEX_CPP:
1256 case SCLEX_D:
1257 case SCLEX_HTML: /* for PHP & JS */
1258 case SCLEX_PASCAL: /* for multiline comments? */
1259 case SCLEX_BASH:
1260 case SCLEX_PERL:
1261 case SCLEX_TCL:
1262 case SCLEX_R:
1263 case SCLEX_RUST:
1264 return TRUE;
1265 default:
1266 return FALSE;
1271 /* Read indent chars for the line that pos is on into indent global variable.
1272 * Note: Use sci_get_line_indentation() and get_whitespace()/editor_insert_text_block()
1273 * instead in any new code. */
1274 static void read_indent(GeanyEditor *editor, gint pos)
1276 ScintillaObject *sci = editor->sci;
1277 guint i, len, j = 0;
1278 gint line;
1279 gchar *linebuf;
1281 line = sci_get_line_from_position(sci, pos);
1283 len = sci_get_line_length(sci, line);
1284 linebuf = sci_get_line(sci, line);
1286 for (i = 0; i < len && j <= (sizeof(indent) - 1); i++)
1288 if (linebuf[i] == ' ' || linebuf[i] == '\t') /* simple indentation */
1289 indent[j++] = linebuf[i];
1290 else
1291 break;
1293 indent[j] = '\0';
1294 g_free(linebuf);
1298 static gint get_brace_indent(ScintillaObject *sci, gint line)
1300 gint start = sci_get_position_from_line(sci, line);
1301 gint end = sci_get_line_end_position(sci, line) - 1;
1302 gint lexer = sci_get_lexer(sci);
1303 gint count = 0;
1304 gint pos;
1306 for (pos = end; pos >= start && count < 1; pos--)
1308 if (highlighting_is_code_style(lexer, sci_get_style_at(sci, pos)))
1310 gchar c = sci_get_char_at(sci, pos);
1312 if (c == '{')
1313 count ++;
1314 else if (c == '}')
1315 count --;
1319 return count > 0 ? 1 : 0;
1323 /* gets the last code position on a line
1324 * warning: if there is no code position on the line, returns the start position */
1325 static gint get_sci_line_code_end_position(ScintillaObject *sci, gint line)
1327 gint start = sci_get_position_from_line(sci, line);
1328 gint lexer = sci_get_lexer(sci);
1329 gint pos;
1331 for (pos = sci_get_line_end_position(sci, line) - 1; pos > start; pos--)
1333 gint style = sci_get_style_at(sci, pos);
1335 if (highlighting_is_code_style(lexer, style) && ! isspace(sci_get_char_at(sci, pos)))
1336 break;
1339 return pos;
1343 static gint get_python_indent(ScintillaObject *sci, gint line)
1345 gint last_char = get_sci_line_code_end_position(sci, line);
1347 /* add extra indentation for Python after colon */
1348 if (sci_get_char_at(sci, last_char) == ':' &&
1349 sci_get_style_at(sci, last_char) == SCE_P_OPERATOR)
1351 return 1;
1353 return 0;
1357 static gint get_xml_indent(ScintillaObject *sci, gint line)
1359 gboolean need_close = FALSE;
1360 gint end = get_sci_line_code_end_position(sci, line);
1361 gint pos;
1363 /* don't indent if there's a closing tag to the right of the cursor */
1364 pos = sci_get_current_position(sci);
1365 if (sci_get_char_at(sci, pos) == '<' &&
1366 sci_get_char_at(sci, pos + 1) == '/')
1367 return 0;
1369 if (sci_get_char_at(sci, end) == '>' &&
1370 sci_get_char_at(sci, end - 1) != '/')
1372 gint style = sci_get_style_at(sci, end);
1374 if (style == SCE_H_TAG || style == SCE_H_TAGUNKNOWN)
1376 gint start = sci_get_position_from_line(sci, line);
1377 gchar *line_contents = sci_get_contents_range(sci, start, end + 1);
1378 gchar *opened_tag_name = utils_find_open_xml_tag(line_contents, end + 1 - start);
1380 if (!EMPTY(opened_tag_name))
1382 need_close = TRUE;
1383 if (sci_get_lexer(sci) == SCLEX_HTML && utils_is_short_html_tag(opened_tag_name))
1384 need_close = FALSE;
1386 g_free(line_contents);
1387 g_free(opened_tag_name);
1391 return need_close ? 1 : 0;
1395 static gint get_indent_size_after_line(GeanyEditor *editor, gint line)
1397 ScintillaObject *sci = editor->sci;
1398 gint size;
1399 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1401 g_return_val_if_fail(line >= 0, 0);
1403 size = sci_get_line_indentation(sci, line);
1405 if (iprefs->auto_indent_mode > GEANY_AUTOINDENT_BASIC)
1407 gint additional_indent = 0;
1409 if (lexer_has_braces(sci))
1410 additional_indent = iprefs->width * get_brace_indent(sci, line);
1411 else if (sci_get_lexer(sci) == SCLEX_PYTHON) /* Python/Cython */
1412 additional_indent = iprefs->width * get_python_indent(sci, line);
1414 /* HTML lexer "has braces" because of PHP and JavaScript. If get_brace_indent() did not
1415 * recommend us to insert additional indent, we are probably not in PHP/JavaScript chunk and
1416 * should make the XML-related check */
1417 if (additional_indent == 0 &&
1418 (sci_get_lexer(sci) == SCLEX_HTML ||
1419 sci_get_lexer(sci) == SCLEX_XML) &&
1420 editor->document->file_type->priv->xml_indent_tags)
1422 size += iprefs->width * get_xml_indent(sci, line);
1425 size += additional_indent;
1427 return size;
1431 static void insert_indent_after_line(GeanyEditor *editor, gint line)
1433 ScintillaObject *sci = editor->sci;
1434 gint line_indent = sci_get_line_indentation(sci, line);
1435 gint size = get_indent_size_after_line(editor, line);
1436 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1437 gchar *text;
1439 if (size == 0)
1440 return;
1442 if (iprefs->type == GEANY_INDENT_TYPE_TABS && size == line_indent)
1444 /* support tab indents, space aligns style - copy last line 'indent' exactly */
1445 gint start = sci_get_position_from_line(sci, line);
1446 gint end = sci_get_line_indent_position(sci, line);
1448 text = sci_get_contents_range(sci, start, end);
1450 else
1452 text = get_whitespace(iprefs, size);
1454 sci_add_text(sci, text);
1455 g_free(text);
1459 static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c)
1461 const gchar *closing_char = NULL;
1462 gint end_pos = -1;
1464 if (utils_isbrace(c, 0))
1465 end_pos = sci_find_matching_brace(sci, pos - 1);
1467 switch (c)
1469 case '(':
1470 if ((editor_prefs.autoclose_chars & GEANY_AC_PARENTHESIS) && end_pos == -1)
1471 closing_char = ")";
1472 break;
1473 case '{':
1474 if ((editor_prefs.autoclose_chars & GEANY_AC_CBRACKET) && end_pos == -1)
1475 closing_char = "}";
1476 break;
1477 case '[':
1478 if ((editor_prefs.autoclose_chars & GEANY_AC_SBRACKET) && end_pos == -1)
1479 closing_char = "]";
1480 break;
1481 case '\'':
1482 if (editor_prefs.autoclose_chars & GEANY_AC_SQUOTE)
1483 closing_char = "'";
1484 break;
1485 case '"':
1486 if (editor_prefs.autoclose_chars & GEANY_AC_DQUOTE)
1487 closing_char = "\"";
1488 break;
1491 if (closing_char != NULL)
1493 sci_add_text(sci, closing_char);
1494 sci_set_current_position(sci, pos, TRUE);
1499 /* Finds a corresponding matching brace to the given pos
1500 * (this is taken from Scintilla Editor.cxx,
1501 * fit to work with close_block) */
1502 static gint brace_match(ScintillaObject *sci, gint pos)
1504 gchar chBrace = sci_get_char_at(sci, pos);
1505 gchar chSeek = utils_brace_opposite(chBrace);
1506 gchar chAtPos;
1507 gint direction = -1;
1508 gint styBrace;
1509 gint depth = 1;
1510 gint styAtPos;
1512 /* Hack: we need the style at @p pos but it isn't computed yet, so force styling
1513 * of this very position */
1514 sci_colourise(sci, pos, pos + 1);
1516 styBrace = sci_get_style_at(sci, pos);
1518 if (utils_is_opening_brace(chBrace, editor_prefs.brace_match_ltgt))
1519 direction = 1;
1521 pos += direction;
1522 while ((pos >= 0) && (pos < sci_get_length(sci)))
1524 chAtPos = sci_get_char_at(sci, pos);
1525 styAtPos = sci_get_style_at(sci, pos);
1527 if ((pos > sci_get_end_styled(sci)) || (styAtPos == styBrace))
1529 if (chAtPos == chBrace)
1530 depth++;
1531 if (chAtPos == chSeek)
1532 depth--;
1533 if (depth == 0)
1534 return pos;
1536 pos += direction;
1538 return -1;
1542 /* Called after typing '}'. */
1543 static void close_block(GeanyEditor *editor, gint pos)
1545 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1546 gint x = 0, cnt = 0;
1547 gint line, line_len;
1548 gchar *text, *line_buf;
1549 ScintillaObject *sci;
1550 gint line_indent, last_indent;
1552 if (iprefs->auto_indent_mode < GEANY_AUTOINDENT_CURRENTCHARS)
1553 return;
1554 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
1556 sci = editor->sci;
1558 if (! lexer_has_braces(sci))
1559 return;
1561 line = sci_get_line_from_position(sci, pos);
1562 line_len = sci_get_line_end_position(sci, line) - sci_get_position_from_line(sci, line);
1564 /* check that the line is empty, to not kill text in the line */
1565 line_buf = sci_get_line(sci, line);
1566 line_buf[line_len] = '\0';
1567 while (x < line_len)
1569 if (isspace(line_buf[x]))
1570 cnt++;
1571 x++;
1573 g_free(line_buf);
1575 if ((line_len - 1) != cnt)
1576 return;
1578 if (iprefs->auto_indent_mode == GEANY_AUTOINDENT_MATCHBRACES)
1580 gint start_brace = brace_match(sci, pos);
1582 if (start_brace >= 0)
1584 gint line_start;
1585 gint brace_line = sci_get_line_from_position(sci, start_brace);
1586 gint size = sci_get_line_indentation(sci, brace_line);
1587 gchar *ind = get_whitespace(iprefs, size);
1589 text = g_strconcat(ind, "}", NULL);
1590 line_start = sci_get_position_from_line(sci, line);
1591 sci_set_anchor(sci, line_start);
1592 sci_replace_sel(sci, text);
1593 g_free(text);
1594 g_free(ind);
1595 return;
1597 /* fall through - unmatched brace (possibly because of TCL, PHP lexer bugs) */
1600 /* GEANY_AUTOINDENT_CURRENTCHARS */
1601 line_indent = sci_get_line_indentation(sci, line);
1602 last_indent = sci_get_line_indentation(sci, line - 1);
1604 if (line_indent < last_indent)
1605 return;
1606 line_indent -= iprefs->width;
1607 line_indent = MAX(0, line_indent);
1608 sci_set_line_indentation(sci, line, line_indent);
1612 /* checks whether @p c is an ASCII character (e.g. < 0x80) */
1613 #define IS_ASCII(c) (((unsigned char)(c)) < 0x80)
1616 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1617 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1618 * position can be -1, then the current position is used.
1619 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1620 static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen,
1621 const gchar *wc, gboolean stem)
1623 gint line, line_start, startword, endword;
1624 gchar *chunk;
1625 ScintillaObject *sci;
1627 g_return_if_fail(editor != NULL);
1628 sci = editor->sci;
1630 if (pos == -1)
1631 pos = sci_get_current_position(sci);
1633 line = sci_get_line_from_position(sci, pos);
1634 line_start = sci_get_position_from_line(sci, line);
1635 startword = pos - line_start;
1636 endword = pos - line_start;
1638 word[0] = '\0';
1639 chunk = sci_get_line(sci, line);
1641 if (wc == NULL)
1642 wc = GEANY_WORDCHARS;
1644 /* the checks for "c < 0" are to allow any Unicode character which should make the code
1645 * a little bit more Unicode safe, anyway, this allows also any Unicode punctuation,
1646 * TODO: improve this code */
1647 while (startword > 0 && (strchr(wc, chunk[startword - 1]) || ! IS_ASCII(chunk[startword - 1])))
1648 startword--;
1649 if (!stem)
1651 while (chunk[endword] != 0 && (strchr(wc, chunk[endword]) || ! IS_ASCII(chunk[endword])))
1652 endword++;
1655 if (startword != endword)
1657 chunk[endword] = '\0';
1659 g_strlcpy(word, chunk + startword, wordlen); /* ensure null terminated */
1661 else
1662 g_strlcpy(word, "", wordlen);
1664 g_free(chunk);
1668 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1669 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1670 * position can be -1, then the current position is used.
1671 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1672 void editor_find_current_word(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen,
1673 const gchar *wc)
1675 read_current_word(editor, pos, word, wordlen, wc, FALSE);
1679 /* Same as editor_find_current_word() but uses editor's word boundaries to decide what the word
1680 * is. This should be used e.g. to get the word to search for */
1681 void editor_find_current_word_sciwc(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen)
1683 gint start;
1684 gint end;
1686 g_return_if_fail(editor != NULL);
1688 if (pos == -1)
1689 pos = sci_get_current_position(editor->sci);
1691 start = sci_word_start_position(editor->sci, pos, TRUE);
1692 end = sci_word_end_position(editor->sci, pos, TRUE);
1694 if (start == end) /* caret in whitespaces sequence */
1695 *word = 0;
1696 else
1698 if ((guint)(end - start) >= wordlen)
1699 end = start + (wordlen - 1);
1700 sci_get_text_range(editor->sci, start, end, word);
1706 * Finds the word at the position specified by @a pos. If any word is found, it is returned.
1707 * Otherwise NULL is returned.
1708 * Additional wordchars can be specified to define what to consider as a word.
1710 * @param editor The editor to operate on.
1711 * @param pos The position where the word should be read from.
1712 * May be @c -1 to use the current position.
1713 * @param wordchars The wordchars to separate words. wordchars mean all characters to count
1714 * as part of a word. May be @c NULL to use the default wordchars,
1715 * see @ref GEANY_WORDCHARS.
1717 * @return A newly-allocated string containing the word at the given @a pos or @c NULL.
1718 * Should be freed when no longer needed.
1720 * @since 0.16
1722 gchar *editor_get_word_at_pos(GeanyEditor *editor, gint pos, const gchar *wordchars)
1724 static gchar cword[GEANY_MAX_WORD_LENGTH];
1726 g_return_val_if_fail(editor != NULL, FALSE);
1728 read_current_word(editor, pos, cword, sizeof(cword), wordchars, FALSE);
1730 return (*cword == '\0') ? NULL : g_strdup(cword);
1734 /* Read the word up to position @a pos. */
1735 static const gchar *
1736 editor_read_word_stem(GeanyEditor *editor, gint pos, const gchar *wordchars)
1738 static gchar word[GEANY_MAX_WORD_LENGTH];
1740 read_current_word(editor, pos, word, sizeof word, wordchars, TRUE);
1742 return (*word) ? word : NULL;
1746 static gint find_previous_brace(ScintillaObject *sci, gint pos)
1748 gint orig_pos = pos;
1750 while (pos >= 0 && pos > orig_pos - 300)
1752 gchar c = sci_get_char_at(sci, pos);
1753 if (utils_is_opening_brace(c, editor_prefs.brace_match_ltgt))
1754 return pos;
1755 pos--;
1757 return -1;
1761 static gint find_start_bracket(ScintillaObject *sci, gint pos)
1763 gint brackets = 0;
1764 gint orig_pos = pos;
1766 while (pos > 0 && pos > orig_pos - 300)
1768 gchar c = sci_get_char_at(sci, pos);
1770 if (c == ')') brackets++;
1771 else if (c == '(') brackets--;
1772 if (brackets < 0) return pos; /* found start bracket */
1773 pos--;
1775 return -1;
1779 static gboolean append_calltip(GString *str, const TMTag *tag, filetype_id ft_id)
1781 if (! tag->atts.entry.arglist)
1782 return FALSE;
1784 if (ft_id != GEANY_FILETYPES_PASCAL)
1785 { /* usual calltips: "retval tagname (arglist)" */
1786 if (tag->atts.entry.var_type)
1788 guint i;
1790 g_string_append(str, tag->atts.entry.var_type);
1791 for (i = 0; i < tag->atts.entry.pointerOrder; i++)
1793 g_string_append_c(str, '*');
1795 g_string_append_c(str, ' ');
1797 if (tag->atts.entry.scope)
1799 const gchar *cosep = symbols_get_context_separator(ft_id);
1801 g_string_append(str, tag->atts.entry.scope);
1802 g_string_append(str, cosep);
1804 g_string_append(str, tag->name);
1805 g_string_append_c(str, ' ');
1806 g_string_append(str, tag->atts.entry.arglist);
1808 else
1809 { /* special case Pascal calltips: "tagname (arglist) : retval" */
1810 g_string_append(str, tag->name);
1811 g_string_append_c(str, ' ');
1812 g_string_append(str, tag->atts.entry.arglist);
1814 if (!EMPTY(tag->atts.entry.var_type))
1816 g_string_append(str, " : ");
1817 g_string_append(str, tag->atts.entry.var_type);
1821 return TRUE;
1825 static gchar *find_calltip(const gchar *word, GeanyFiletype *ft)
1827 const GPtrArray *tags;
1828 const gint arg_types = tm_tag_function_t | tm_tag_prototype_t |
1829 tm_tag_method_t | tm_tag_macro_with_arg_t;
1830 TMTagAttrType *attrs = NULL;
1831 TMTag *tag;
1832 GString *str = NULL;
1833 guint i;
1835 g_return_val_if_fail(ft && word && *word, NULL);
1837 /* use all types in case language uses wrong tag type e.g. python "members" instead of "methods" */
1838 tags = tm_workspace_find(word, tm_tag_max_t, attrs, FALSE, ft->lang);
1839 if (tags->len == 0)
1840 return NULL;
1842 tag = TM_TAG(tags->pdata[0]);
1844 if (ft->id == GEANY_FILETYPES_D &&
1845 (tag->type == tm_tag_class_t || tag->type == tm_tag_struct_t))
1847 /* user typed e.g. 'new Classname(' so lookup D constructor Classname::this() */
1848 tags = tm_workspace_find_scoped("this", tag->name,
1849 arg_types, attrs, FALSE, ft->lang, TRUE);
1850 if (tags->len == 0)
1851 return NULL;
1854 /* remove tags with no argument list */
1855 for (i = 0; i < tags->len; i++)
1857 tag = TM_TAG(tags->pdata[i]);
1859 if (! tag->atts.entry.arglist)
1860 tags->pdata[i] = NULL;
1862 tm_tags_prune((GPtrArray *) tags);
1863 if (tags->len == 0)
1864 return NULL;
1865 else
1866 { /* remove duplicate calltips */
1867 TMTagAttrType sort_attr[] = {tm_tag_attr_name_t, tm_tag_attr_scope_t,
1868 tm_tag_attr_arglist_t, 0};
1870 tm_tags_sort((GPtrArray *) tags, sort_attr, TRUE);
1873 /* if the current word has changed since last time, start with the first tag match */
1874 if (! utils_str_equal(word, calltip.last_word))
1875 calltip.tag_index = 0;
1876 /* cache the current word for next time */
1877 g_free(calltip.last_word);
1878 calltip.last_word = g_strdup(word);
1879 calltip.tag_index = MIN(calltip.tag_index, tags->len - 1); /* ensure tag_index is in range */
1881 for (i = calltip.tag_index; i < tags->len; i++)
1883 tag = TM_TAG(tags->pdata[i]);
1885 if (str == NULL)
1887 str = g_string_new(NULL);
1888 if (calltip.tag_index > 0)
1889 g_string_prepend(str, "\001 "); /* up arrow */
1890 append_calltip(str, tag, FILETYPE_ID(ft));
1892 else /* add a down arrow */
1894 if (calltip.tag_index > 0) /* already have an up arrow */
1895 g_string_insert_c(str, 1, '\002');
1896 else
1897 g_string_prepend(str, "\002 ");
1898 break;
1901 if (str)
1903 gchar *result = str->str;
1905 g_string_free(str, FALSE);
1906 return result;
1908 return NULL;
1912 /* use pos = -1 to search for the previous unmatched open bracket. */
1913 gboolean editor_show_calltip(GeanyEditor *editor, gint pos)
1915 gint orig_pos = pos; /* the position for the calltip */
1916 gint lexer;
1917 gint style;
1918 gchar word[GEANY_MAX_WORD_LENGTH];
1919 gchar *str;
1920 ScintillaObject *sci;
1922 g_return_val_if_fail(editor != NULL, FALSE);
1923 g_return_val_if_fail(editor->document->file_type != NULL, FALSE);
1925 sci = editor->sci;
1927 lexer = sci_get_lexer(sci);
1929 if (pos == -1)
1931 /* position of '(' is unknown, so go backwards from current position to find it */
1932 pos = sci_get_current_position(sci);
1933 pos--;
1934 orig_pos = pos;
1935 pos = (lexer == SCLEX_LATEX) ? find_previous_brace(sci, pos) :
1936 find_start_bracket(sci, pos);
1937 if (pos == -1)
1938 return FALSE;
1941 /* the style 1 before the brace (which may be highlighted) */
1942 style = sci_get_style_at(sci, pos - 1);
1943 if (! highlighting_is_code_style(lexer, style))
1944 return FALSE;
1946 word[0] = '\0';
1947 editor_find_current_word(editor, pos - 1, word, sizeof word, NULL);
1948 if (word[0] == '\0')
1949 return FALSE;
1951 str = find_calltip(word, editor->document->file_type);
1952 if (str)
1954 g_free(calltip.text); /* free the old calltip */
1955 calltip.text = str;
1956 calltip.pos = orig_pos;
1957 calltip.sci = sci;
1958 calltip.set = TRUE;
1959 utils_wrap_string(calltip.text, -1);
1960 SSM(sci, SCI_CALLTIPSHOW, orig_pos, (sptr_t) calltip.text);
1961 return TRUE;
1963 return FALSE;
1967 gchar *editor_get_calltip_text(GeanyEditor *editor, const TMTag *tag)
1969 GString *str;
1971 g_return_val_if_fail(editor != NULL, NULL);
1973 str = g_string_new(NULL);
1974 if (append_calltip(str, tag, editor->document->file_type->id))
1975 return g_string_free(str, FALSE);
1976 else
1977 return g_string_free(str, TRUE);
1981 /* HTML entities auto completion from html_entities.tags text file */
1982 static gboolean
1983 autocomplete_html(ScintillaObject *sci, const gchar *root, gsize rootlen)
1985 guint i;
1986 gboolean found = FALSE;
1987 GString *words;
1988 const gchar **entities = symbols_get_html_entities();
1990 if (*root != '&' || entities == NULL)
1991 return FALSE;
1993 words = g_string_sized_new(500);
1994 for (i = 0; ; i++)
1996 if (entities[i] == NULL)
1997 break;
1998 else if (entities[i][0] == '#')
1999 continue;
2001 if (! strncmp(entities[i], root, rootlen))
2003 if (words->len)
2004 g_string_append_c(words, '\n');
2006 g_string_append(words, entities[i]);
2007 found = TRUE;
2010 if (found)
2011 show_autocomplete(sci, rootlen, words);
2013 g_string_free(words, TRUE);
2014 return found;
2018 /* Current document & global tags autocompletion */
2019 static gboolean
2020 autocomplete_tags(GeanyEditor *editor, const gchar *root, gsize rootlen)
2022 TMTagAttrType attrs[] = { tm_tag_attr_name_t, 0 };
2023 const GPtrArray *tags;
2024 GeanyDocument *doc;
2026 g_return_val_if_fail(editor, FALSE);
2028 doc = editor->document;
2030 tags = tm_workspace_find(root, tm_tag_max_t, attrs, TRUE, doc->file_type->lang);
2031 if (tags)
2033 show_tags_list(editor, tags, rootlen);
2034 return tags->len > 0;
2036 return FALSE;
2040 static gboolean autocomplete_check_html(GeanyEditor *editor, gint style, gint pos)
2042 GeanyFiletype *ft = editor->document->file_type;
2043 gboolean try = FALSE;
2045 /* use entity completion when style is not JavaScript, ASP, Python, PHP, ...
2046 * (everything after SCE_HJ_START is for embedded scripting languages) */
2047 if (ft->id == GEANY_FILETYPES_HTML && style < SCE_HJ_START)
2048 try = TRUE;
2049 else if (sci_get_lexer(editor->sci) == SCLEX_XML && style < SCE_HJ_START)
2050 try = TRUE;
2051 else if (ft->id == GEANY_FILETYPES_PHP)
2053 /* use entity completion when style is outside of PHP styles */
2054 if (! is_style_php(style))
2055 try = TRUE;
2057 if (try)
2059 gchar root[GEANY_MAX_WORD_LENGTH];
2060 gchar *tmp;
2062 read_current_word(editor, pos, root, sizeof(root), GEANY_WORDCHARS"&", TRUE);
2064 /* Allow something like "&quot;some text&quot;".
2065 * for entity completion we want to have completion for '&' within words. */
2066 tmp = strchr(root, '&');
2067 if (tmp != NULL)
2069 return autocomplete_html(editor->sci, tmp, strlen(tmp));
2072 return FALSE;
2076 /* Algorithm based on based on Scite's StartAutoCompleteWord()
2077 * @returns a sorted list of words matching @p root */
2078 static GSList *get_doc_words(ScintillaObject *sci, gchar *root, gsize rootlen)
2080 gchar *word;
2081 gint len, current, word_end;
2082 gint pos_find, flags;
2083 guint word_length;
2084 gsize nmatches = 0;
2085 GSList *words = NULL;
2086 struct Sci_TextToFind ttf;
2088 len = sci_get_length(sci);
2089 current = sci_get_current_position(sci) - rootlen;
2091 ttf.lpstrText = root;
2092 ttf.chrg.cpMin = 0;
2093 ttf.chrg.cpMax = len;
2094 ttf.chrgText.cpMin = 0;
2095 ttf.chrgText.cpMax = 0;
2096 flags = SCFIND_WORDSTART | SCFIND_MATCHCASE;
2098 /* search the whole document for the word root and collect results */
2099 pos_find = scintilla_send_message(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
2100 while (pos_find >= 0 && pos_find < len)
2102 word_end = pos_find + rootlen;
2103 if (pos_find != current)
2105 word_end = sci_word_end_position(sci, word_end, TRUE);
2107 word_length = word_end - pos_find;
2108 if (word_length > rootlen)
2110 word = sci_get_contents_range(sci, pos_find, word_end);
2111 /* search whether we already have the word in, otherwise add it */
2112 if (g_slist_find_custom(words, word, (GCompareFunc)strcmp) != NULL)
2113 g_free(word);
2114 else
2116 words = g_slist_prepend(words, word);
2117 nmatches++;
2120 if (nmatches == editor_prefs.autocompletion_max_entries)
2121 break;
2124 ttf.chrg.cpMin = word_end;
2125 pos_find = scintilla_send_message(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
2128 return g_slist_sort(words, (GCompareFunc)utils_str_casecmp);
2132 static gboolean autocomplete_doc_word(GeanyEditor *editor, gchar *root, gsize rootlen)
2134 ScintillaObject *sci = editor->sci;
2135 GSList *words, *node;
2136 GString *str;
2137 guint n_words = 0;
2139 words = get_doc_words(sci, root, rootlen);
2140 if (!words)
2142 scintilla_send_message(sci, SCI_AUTOCCANCEL, 0, 0);
2143 return FALSE;
2146 str = g_string_sized_new(rootlen * 2 * 10);
2147 foreach_slist(node, words)
2149 g_string_append(str, node->data);
2150 g_free(node->data);
2151 if (node->next)
2152 g_string_append_c(str, '\n');
2153 n_words++;
2155 if (n_words >= editor_prefs.autocompletion_max_entries)
2156 g_string_append(str, "\n...");
2158 g_slist_free(words);
2160 show_autocomplete(sci, rootlen, str);
2161 g_string_free(str, TRUE);
2162 return TRUE;
2166 gboolean editor_start_auto_complete(GeanyEditor *editor, gint pos, gboolean force)
2168 gint rootlen, lexer, style;
2169 gchar *root;
2170 gchar cword[GEANY_MAX_WORD_LENGTH];
2171 ScintillaObject *sci;
2172 gboolean ret = FALSE;
2173 const gchar *wordchars;
2174 GeanyFiletype *ft;
2176 g_return_val_if_fail(editor != NULL, FALSE);
2178 if (! editor_prefs.auto_complete_symbols && ! force)
2179 return FALSE;
2181 /* If we are at the beginning of the document, we skip autocompletion as we can't determine the
2182 * necessary styling information */
2183 if (G_UNLIKELY(pos < 2))
2184 return FALSE;
2186 sci = editor->sci;
2187 ft = editor->document->file_type;
2189 lexer = sci_get_lexer(sci);
2190 style = sci_get_style_at(sci, pos - 2);
2192 /* don't autocomplete in comments and strings */
2193 if (!force && !highlighting_is_code_style(lexer, style))
2194 return FALSE;
2196 autocomplete_scope(editor);
2197 ret = autocomplete_check_html(editor, style, pos);
2199 if (ft->id == GEANY_FILETYPES_LATEX)
2200 wordchars = GEANY_WORDCHARS"\\"; /* add \ to word chars if we are in a LaTeX file */
2201 else if (ft->id == GEANY_FILETYPES_CSS)
2202 wordchars = GEANY_WORDCHARS"-"; /* add - because they are part of property names */
2203 else
2204 wordchars = GEANY_WORDCHARS;
2206 read_current_word(editor, pos, cword, sizeof(cword), wordchars, TRUE);
2207 root = cword;
2208 rootlen = strlen(root);
2210 if (!ret && rootlen > 0)
2212 if (ft->id == GEANY_FILETYPES_PHP && style == SCE_HPHP_DEFAULT &&
2213 rootlen == 3 && strcmp(root, "php") == 0 && pos >= 5 &&
2214 sci_get_char_at(sci, pos - 5) == '<' &&
2215 sci_get_char_at(sci, pos - 4) == '?')
2217 /* nothing, don't complete PHP open tags */
2219 else
2221 /* force is set when called by keyboard shortcut, otherwise start at the
2222 * editor_prefs.symbolcompletion_min_chars'th char */
2223 if (force || rootlen >= editor_prefs.symbolcompletion_min_chars)
2225 /* complete tags, except if forcing when completion is already visible */
2226 if (!(force && SSM(sci, SCI_AUTOCACTIVE, 0, 0)))
2227 ret = autocomplete_tags(editor, root, rootlen);
2229 /* If forcing and there's nothing else to show, complete from words in document */
2230 if (!ret && (force || editor_prefs.autocomplete_doc_words))
2231 ret = autocomplete_doc_word(editor, root, rootlen);
2235 if (!ret && force)
2236 utils_beep();
2238 return ret;
2242 static const gchar *snippets_find_completion_by_name(const gchar *type, const gchar *name)
2244 gchar *result = NULL;
2245 GHashTable *tmp;
2247 g_return_val_if_fail(type != NULL && name != NULL, NULL);
2249 tmp = g_hash_table_lookup(snippet_hash, type);
2250 if (tmp != NULL)
2252 result = g_hash_table_lookup(tmp, name);
2254 /* whether nothing is set for the current filetype(tmp is NULL) or
2255 * the particular completion for this filetype is not set (result is NULL) */
2256 if (tmp == NULL || result == NULL)
2258 tmp = g_hash_table_lookup(snippet_hash, "Default");
2259 if (tmp != NULL)
2261 result = g_hash_table_lookup(tmp, name);
2264 /* if result is still NULL here, no completion could be found */
2266 /* result is owned by the hash table and will be freed when the table will destroyed */
2267 return result;
2271 static void snippets_replace_specials(gpointer key, gpointer value, gpointer user_data)
2273 gchar *needle;
2274 GString *pattern = user_data;
2276 g_return_if_fail(key != NULL);
2277 g_return_if_fail(value != NULL);
2279 needle = g_strconcat("%", (gchar*) key, "%", NULL);
2281 utils_string_replace_all(pattern, needle, (gchar*) value);
2282 g_free(needle);
2286 static void fix_indentation(GeanyEditor *editor, GString *buf)
2288 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
2289 gchar *whitespace;
2290 GRegex *regex;
2291 gint cflags = G_REGEX_MULTILINE;
2293 /* transform leading tabs into indent widths (in spaces) */
2294 whitespace = g_strnfill(iprefs->width, ' ');
2295 regex = g_regex_new("^ *(\t)", cflags, 0, NULL);
2296 while (utils_string_regex_replace_all(buf, regex, 1, whitespace, TRUE));
2297 g_regex_unref(regex);
2299 /* remaining tabs are for alignment */
2300 if (iprefs->type != GEANY_INDENT_TYPE_TABS)
2301 utils_string_replace_all(buf, "\t", whitespace);
2303 /* use leading tabs */
2304 if (iprefs->type != GEANY_INDENT_TYPE_SPACES)
2306 gchar *str;
2308 /* for tabs+spaces mode we want the real tab width, not indent width */
2309 SETPTR(whitespace, g_strnfill(sci_get_tab_width(editor->sci), ' '));
2310 str = g_strdup_printf("^\t*(%s)", whitespace);
2312 regex = g_regex_new(str, cflags, 0, NULL);
2313 while (utils_string_regex_replace_all(buf, regex, 1, "\t", TRUE));
2314 g_regex_unref(regex);
2315 g_free(str);
2317 g_free(whitespace);
2321 /** Inserts text, replacing \\t tab chars (@c 0x9) and \\n newline chars (@c 0xA)
2322 * accordingly for the document.
2323 * - Leading tabs are replaced with the correct indentation.
2324 * - Non-leading tabs are replaced with spaces (except when using 'Tabs' indent type).
2325 * - Newline chars are replaced with the correct line ending string.
2326 * This is very useful for inserting code without having to handle the indent
2327 * type yourself (Tabs & Spaces mode can be tricky).
2328 * @param editor Editor.
2329 * @param text Intended as e.g. @c "if (foo)\n\tbar();".
2330 * @param insert_pos Document position to insert text at.
2331 * @param cursor_index If >= 0, the index into @a text to place the cursor.
2332 * @param newline_indent_size Indentation size (in spaces) to insert for each newline; use
2333 * -1 to read the indent size from the line with @a insert_pos on it.
2334 * @param replace_newlines Whether to replace newlines. If
2335 * newlines have been replaced already, this should be false, to avoid errors e.g. on Windows.
2336 * @warning Make sure all \\t tab chars in @a text are intended as indent widths or alignment,
2337 * not hard tabs, as those won't be preserved.
2338 * @note This doesn't scroll the cursor in view afterwards. **/
2339 void editor_insert_text_block(GeanyEditor *editor, const gchar *text, gint insert_pos,
2340 gint cursor_index, gint newline_indent_size, gboolean replace_newlines)
2342 ScintillaObject *sci = editor->sci;
2343 gint line_start = sci_get_line_from_position(sci, insert_pos);
2344 GString *buf;
2345 const gchar *eol = editor_get_eol_char(editor);
2346 gint idx;
2348 g_return_if_fail(text);
2349 g_return_if_fail(editor != NULL);
2350 g_return_if_fail(insert_pos >= 0);
2352 buf = g_string_new(text);
2354 if (cursor_index >= 0)
2355 g_string_insert(buf, cursor_index, geany_cursor_marker); /* remember cursor pos */
2357 if (newline_indent_size == -1)
2359 /* count indent size up to insert_pos instead of asking sci
2360 * because there may be spaces after it */
2361 gchar *tmp = sci_get_line(sci, line_start);
2363 idx = insert_pos - sci_get_position_from_line(sci, line_start);
2364 tmp[idx] = '\0';
2365 newline_indent_size = count_indent_size(editor, tmp);
2366 g_free(tmp);
2369 /* Add line indents (in spaces) */
2370 if (newline_indent_size > 0)
2372 const gchar *nl = replace_newlines ? "\n" : eol;
2373 gchar *whitespace;
2375 whitespace = g_strnfill(newline_indent_size, ' ');
2376 SETPTR(whitespace, g_strconcat(nl, whitespace, NULL));
2377 utils_string_replace_all(buf, nl, whitespace);
2378 g_free(whitespace);
2381 /* transform line endings */
2382 if (replace_newlines)
2383 utils_string_replace_all(buf, "\n", eol);
2385 fix_indentation(editor, buf);
2387 idx = replace_cursor_markers(editor, buf);
2388 if (idx >= 0)
2390 sci_insert_text(sci, insert_pos, buf->str);
2391 sci_set_current_position(sci, insert_pos + idx, FALSE);
2393 else
2394 sci_insert_text(sci, insert_pos, buf->str);
2396 snippet_cursor_insert_pos = sci_get_current_position(sci);
2398 g_string_free(buf, TRUE);
2402 /* Move the cursor to the next specified cursor position in an inserted snippet.
2403 * Can, and should, be optimized to give better results */
2404 void editor_goto_next_snippet_cursor(GeanyEditor *editor)
2406 ScintillaObject *sci = editor->sci;
2407 gint current_pos = sci_get_current_position(sci);
2409 if (snippet_offsets && !g_queue_is_empty(snippet_offsets))
2411 gint offset;
2413 offset = GPOINTER_TO_INT(g_queue_pop_head(snippet_offsets));
2414 if (current_pos > snippet_cursor_insert_pos)
2415 snippet_cursor_insert_pos = offset + current_pos;
2416 else
2417 snippet_cursor_insert_pos += offset;
2419 sci_set_current_position(sci, snippet_cursor_insert_pos, TRUE);
2421 else
2423 utils_beep();
2428 static void snippets_make_replacements(GeanyEditor *editor, GString *pattern)
2430 GHashTable *specials;
2432 /* replace 'special' completions */
2433 specials = g_hash_table_lookup(snippet_hash, "Special");
2434 if (G_LIKELY(specials != NULL))
2436 g_hash_table_foreach(specials, snippets_replace_specials, pattern);
2439 /* now transform other wildcards */
2440 utils_string_replace_all(pattern, "%newline%", "\n");
2441 utils_string_replace_all(pattern, "%ws%", "\t");
2443 /* replace %cursor% by a very unlikely string marker */
2444 utils_string_replace_all(pattern, "%cursor%", geany_cursor_marker);
2446 /* unescape '%' after all %wildcards% */
2447 templates_replace_valist(pattern, "{pc}", "%", NULL);
2449 /* replace any template {foo} wildcards */
2450 templates_replace_common(pattern, editor->document->file_name, editor->document->file_type, NULL);
2454 static gssize replace_cursor_markers(GeanyEditor *editor, GString *pattern)
2456 gssize cur_index = -1;
2457 gint i;
2458 GList *temp_list = NULL;
2459 gint cursor_steps = 0, old_cursor = 0;
2461 i = 0;
2462 while (1)
2464 cursor_steps = utils_string_find(pattern, cursor_steps, -1, geany_cursor_marker);
2465 if (cursor_steps == -1)
2466 break;
2468 g_string_erase(pattern, cursor_steps, strlen(geany_cursor_marker));
2470 if (i++ > 0)
2472 /* save the relative offset to each cursor position */
2473 temp_list = g_list_prepend(temp_list, GINT_TO_POINTER(cursor_steps - old_cursor));
2475 else
2477 /* first cursor already includes newline positions */
2478 cur_index = cursor_steps;
2480 old_cursor = cursor_steps;
2483 /* put the cursor positions for the most recent
2484 * parsed snippet first, followed by any remaining positions */
2485 i = 0;
2486 if (temp_list)
2488 GList *node;
2490 temp_list = g_list_reverse(temp_list);
2491 foreach_list(node, temp_list)
2492 g_queue_push_nth(snippet_offsets, node->data, i++);
2494 /* limit length of queue */
2495 while (g_queue_get_length(snippet_offsets) > 20)
2496 g_queue_pop_tail(snippet_offsets);
2498 g_list_free(temp_list);
2500 /* if there's no first cursor, skip whole snippet */
2501 if (cur_index < 0)
2502 cur_index = pattern->len;
2504 return cur_index;
2508 static gboolean snippets_complete_constructs(GeanyEditor *editor, gint pos, const gchar *word)
2510 ScintillaObject *sci = editor->sci;
2511 gchar *str;
2512 const gchar *completion;
2513 gint str_len;
2514 gint ft_id = editor->document->file_type->id;
2516 str = g_strdup(word);
2517 g_strstrip(str);
2519 completion = snippets_find_completion_by_name(filetypes[ft_id]->name, str);
2520 if (completion == NULL)
2522 g_free(str);
2523 return FALSE;
2526 /* remove the typed word, it will be added again by the used auto completion
2527 * (not really necessary but this makes the auto completion more flexible,
2528 * e.g. with a completion like hi=hello, so typing "hi<TAB>" will result in "hello") */
2529 str_len = strlen(str);
2530 sci_set_selection_start(sci, pos - str_len);
2531 sci_set_selection_end(sci, pos);
2532 sci_replace_sel(sci, "");
2533 pos -= str_len; /* pos has changed while deleting */
2535 editor_insert_snippet(editor, pos, completion);
2536 sci_scroll_caret(sci);
2538 g_free(str);
2539 return TRUE;
2543 static gboolean at_eol(ScintillaObject *sci, gint pos)
2545 gint line = sci_get_line_from_position(sci, pos);
2546 gchar c;
2548 /* skip any trailing spaces */
2549 while (TRUE)
2551 c = sci_get_char_at(sci, pos);
2552 if (c == ' ' || c == '\t')
2553 pos++;
2554 else
2555 break;
2558 return (pos == sci_get_line_end_position(sci, line));
2562 gboolean editor_complete_snippet(GeanyEditor *editor, gint pos)
2564 gboolean result = FALSE;
2565 const gchar *wc;
2566 const gchar *word;
2567 ScintillaObject *sci;
2569 g_return_val_if_fail(editor != NULL, FALSE);
2571 sci = editor->sci;
2572 if (sci_has_selection(sci))
2573 return FALSE;
2574 /* return if we are editing an existing line (chars on right of cursor) */
2575 if (keybindings_lookup_item(GEANY_KEY_GROUP_EDITOR,
2576 GEANY_KEYS_EDITOR_COMPLETESNIPPET)->key == GDK_space &&
2577 ! editor_prefs.complete_snippets_whilst_editing && ! at_eol(sci, pos))
2578 return FALSE;
2580 wc = snippets_find_completion_by_name("Special", "wordchars");
2581 word = editor_read_word_stem(editor, pos, wc);
2583 /* prevent completion of "for " */
2584 if (!EMPTY(word) &&
2585 ! isspace(sci_get_char_at(sci, pos - 1))) /* pos points to the line end char so use pos -1 */
2587 sci_start_undo_action(sci); /* needed because we insert a space separately from construct */
2588 result = snippets_complete_constructs(editor, pos, word);
2589 sci_end_undo_action(sci);
2590 if (result)
2591 sci_cancel(sci); /* cancel any autocompletion list, etc */
2593 return result;
2597 void editor_show_macro_list(GeanyEditor *editor)
2599 GString *words;
2601 if (editor == NULL || editor->document->file_type == NULL)
2602 return;
2604 words = symbols_get_macro_list(editor->document->file_type->lang);
2605 if (words == NULL)
2606 return;
2608 SSM(editor->sci, SCI_USERLISTSHOW, 1, (sptr_t) words->str);
2609 g_string_free(words, TRUE);
2613 static void insert_closing_tag(GeanyEditor *editor, gint pos, gchar ch, const gchar *tag_name)
2615 ScintillaObject *sci = editor->sci;
2616 gchar *to_insert = NULL;
2618 if (ch == '/')
2620 const gchar *gt = ">";
2621 /* if there is already a '>' behind the cursor, don't add it */
2622 if (sci_get_char_at(sci, pos) == '>')
2623 gt = "";
2625 to_insert = g_strconcat(tag_name, gt, NULL);
2627 else
2628 to_insert = g_strconcat("</", tag_name, ">", NULL);
2630 sci_start_undo_action(sci);
2631 sci_replace_sel(sci, to_insert);
2632 if (ch == '>')
2633 sci_set_selection(sci, pos, pos);
2634 sci_end_undo_action(sci);
2635 g_free(to_insert);
2640 * (stolen from anjuta and heavily modified)
2641 * This routine will auto complete XML or HTML tags that are still open by closing them
2642 * @param ch The character we are dealing with, currently only works with the '>' character
2643 * @return True if handled, false otherwise
2645 static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch)
2647 ScintillaObject *sci = editor->sci;
2648 gint lexer = sci_get_lexer(sci);
2649 gint min, size, style;
2650 gchar *str_found, sel[512];
2651 gboolean result = FALSE;
2653 /* If the user has turned us off, quit now.
2654 * This may make sense only in certain languages */
2655 if (! editor_prefs.auto_close_xml_tags || (lexer != SCLEX_HTML && lexer != SCLEX_XML))
2656 return FALSE;
2658 /* return if we are inside any embedded script */
2659 style = sci_get_style_at(sci, pos);
2660 if (style > SCE_H_XCCOMMENT && ! highlighting_is_string_style(lexer, style))
2661 return FALSE;
2663 /* if ch is /, check for </, else quit */
2664 if (ch == '/' && sci_get_char_at(sci, pos - 2) != '<')
2665 return FALSE;
2667 /* Grab the last 512 characters or so */
2668 min = pos - (sizeof(sel) - 1);
2669 if (min < 0) min = 0;
2671 if (pos - min < 3)
2672 return FALSE; /* Smallest tag is 3 characters e.g. <p> */
2674 sci_get_text_range(sci, min, pos, sel);
2675 sel[sizeof(sel) - 1] = '\0';
2677 if (ch == '>' && sel[pos - min - 2] == '/')
2678 /* User typed something like "<br/>" */
2679 return FALSE;
2681 size = pos - min;
2682 if (ch == '/')
2683 size -= 2; /* skip </ */
2684 str_found = utils_find_open_xml_tag(sel, size);
2686 if (lexer == SCLEX_HTML && utils_is_short_html_tag(str_found))
2688 /* ignore tag */
2690 else if (!EMPTY(str_found))
2692 insert_closing_tag(editor, pos, ch, str_found);
2693 result = TRUE;
2695 g_free(str_found);
2696 return result;
2700 /* like sci_get_line_indentation(), but for a string. */
2701 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent)
2703 const gchar *ptr;
2704 gsize tab_size = sci_get_tab_width(editor->sci);
2705 gsize count = 0;
2707 g_return_val_if_fail(base_indent, 0);
2709 for (ptr = base_indent; *ptr != 0; ptr++)
2711 switch (*ptr)
2713 case ' ':
2714 count++;
2715 break;
2716 case '\t':
2717 count += tab_size;
2718 break;
2719 default:
2720 return count;
2723 return count;
2727 /* Handles special cases where HTML is embedded in another language or
2728 * another language is embedded in HTML */
2729 static GeanyFiletype *editor_get_filetype_at_line(GeanyEditor *editor, gint line)
2731 gint style, line_start;
2732 GeanyFiletype *current_ft;
2734 g_return_val_if_fail(editor != NULL, NULL);
2735 g_return_val_if_fail(editor->document->file_type != NULL, NULL);
2737 current_ft = editor->document->file_type;
2738 line_start = sci_get_position_from_line(editor->sci, line);
2739 style = sci_get_style_at(editor->sci, line_start);
2741 /* Handle PHP filetype with embedded HTML */
2742 if (current_ft->id == GEANY_FILETYPES_PHP && ! is_style_php(style))
2743 current_ft = filetypes[GEANY_FILETYPES_HTML];
2745 /* Handle languages embedded in HTML */
2746 if (current_ft->id == GEANY_FILETYPES_HTML)
2748 /* Embedded JS */
2749 if (style >= SCE_HJ_DEFAULT && style <= SCE_HJ_REGEX)
2750 current_ft = filetypes[GEANY_FILETYPES_JS];
2751 /* ASP JS */
2752 else if (style >= SCE_HJA_DEFAULT && style <= SCE_HJA_REGEX)
2753 current_ft = filetypes[GEANY_FILETYPES_JS];
2754 /* Embedded VB */
2755 else if (style >= SCE_HB_DEFAULT && style <= SCE_HB_STRINGEOL)
2756 current_ft = filetypes[GEANY_FILETYPES_BASIC];
2757 /* ASP VB */
2758 else if (style >= SCE_HBA_DEFAULT && style <= SCE_HBA_STRINGEOL)
2759 current_ft = filetypes[GEANY_FILETYPES_BASIC];
2760 /* Embedded Python */
2761 else if (style >= SCE_HP_DEFAULT && style <= SCE_HP_IDENTIFIER)
2762 current_ft = filetypes[GEANY_FILETYPES_PYTHON];
2763 /* ASP Python */
2764 else if (style >= SCE_HPA_DEFAULT && style <= SCE_HPA_IDENTIFIER)
2765 current_ft = filetypes[GEANY_FILETYPES_PYTHON];
2766 /* Embedded PHP */
2767 else if ((style >= SCE_HPHP_DEFAULT && style <= SCE_HPHP_OPERATOR) ||
2768 style == SCE_HPHP_COMPLEX_VARIABLE)
2770 current_ft = filetypes[GEANY_FILETYPES_PHP];
2774 /* Ensure the filetype's config is loaded */
2775 filetypes_load_config(current_ft->id, FALSE);
2777 return current_ft;
2781 static void real_comment_multiline(GeanyEditor *editor, gint line_start, gint last_line)
2783 const gchar *eol;
2784 gchar *str_begin, *str_end;
2785 const gchar *co, *cc;
2786 gint line_len;
2787 GeanyFiletype *ft;
2789 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2791 ft = editor_get_filetype_at_line(editor, line_start);
2793 eol = editor_get_eol_char(editor);
2794 if (! filetype_get_comment_open_close(ft, FALSE, &co, &cc))
2795 g_return_if_reached();
2796 str_begin = g_strdup_printf("%s%s", (co != NULL) ? co : "", eol);
2797 str_end = g_strdup_printf("%s%s", (cc != NULL) ? cc : "", eol);
2799 /* insert the comment strings */
2800 sci_insert_text(editor->sci, line_start, str_begin);
2801 line_len = sci_get_position_from_line(editor->sci, last_line + 2);
2802 sci_insert_text(editor->sci, line_len, str_end);
2804 g_free(str_begin);
2805 g_free(str_end);
2809 /* find @p text inside the range of the current style */
2810 static gint find_in_current_style(ScintillaObject *sci, const gchar *text, gboolean backwards)
2812 gint start = sci_get_current_position(sci);
2813 gint end = start;
2814 gint len = sci_get_length(sci);
2815 gint current_style = sci_get_style_at(sci, start);
2816 struct Sci_TextToFind ttf;
2818 while (start > 0 && sci_get_style_at(sci, start - 1) == current_style)
2819 start -= 1;
2820 while (end < len && sci_get_style_at(sci, end + 1) == current_style)
2821 end += 1;
2823 ttf.lpstrText = (gchar*) text;
2824 ttf.chrg.cpMin = backwards ? end + 1 : start;
2825 ttf.chrg.cpMax = backwards ? start : end + 1;
2826 return sci_find_text(sci, 0, &ttf);
2830 static void sci_delete_line(ScintillaObject *sci, gint line)
2832 gint start = sci_get_position_from_line(sci, line);
2833 gint len = sci_get_line_length(sci, line);
2834 SSM(sci, SCI_DELETERANGE, start, len);
2838 static gboolean real_uncomment_multiline(GeanyEditor *editor)
2840 /* find the beginning of the multi line comment */
2841 gint start, end, start_line, end_line;
2842 GeanyFiletype *ft;
2843 const gchar *co, *cc;
2845 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, FALSE);
2847 ft = editor_get_filetype_at_line(editor, sci_get_current_line(editor->sci));
2848 if (! filetype_get_comment_open_close(ft, FALSE, &co, &cc))
2849 g_return_val_if_reached(FALSE);
2851 start = find_in_current_style(editor->sci, co, TRUE);
2852 end = find_in_current_style(editor->sci, cc, FALSE);
2854 if (start < 0 || end < 0 || start > end /* who knows */)
2855 return FALSE;
2857 start_line = sci_get_line_from_position(editor->sci, start);
2858 end_line = sci_get_line_from_position(editor->sci, end);
2860 /* remove comment close chars */
2861 SSM(editor->sci, SCI_DELETERANGE, end, strlen(cc));
2862 if (sci_is_blank_line(editor->sci, end_line))
2863 sci_delete_line(editor->sci, end_line);
2865 /* remove comment open chars (do it last since it would move the end position) */
2866 SSM(editor->sci, SCI_DELETERANGE, start, strlen(co));
2867 if (sci_is_blank_line(editor->sci, start_line))
2868 sci_delete_line(editor->sci, start_line);
2870 return TRUE;
2874 static gint get_multiline_comment_style(GeanyEditor *editor, gint line_start)
2876 gint lexer = sci_get_lexer(editor->sci);
2877 gint style_comment;
2879 /* List only those lexers which support multi line comments */
2880 switch (lexer)
2882 case SCLEX_XML:
2883 case SCLEX_HTML:
2885 if (is_style_php(sci_get_style_at(editor->sci, line_start)))
2886 style_comment = SCE_HPHP_COMMENT;
2887 else
2888 style_comment = SCE_H_COMMENT;
2889 break;
2891 case SCLEX_HASKELL:
2892 case SCLEX_LITERATEHASKELL:
2893 style_comment = SCE_HA_COMMENTBLOCK; break;
2894 case SCLEX_LUA: style_comment = SCE_LUA_COMMENT; break;
2895 case SCLEX_CSS: style_comment = SCE_CSS_COMMENT; break;
2896 case SCLEX_SQL: style_comment = SCE_SQL_COMMENT; break;
2897 case SCLEX_CAML: style_comment = SCE_CAML_COMMENT; break;
2898 case SCLEX_D: style_comment = SCE_D_COMMENT; break;
2899 case SCLEX_PASCAL: style_comment = SCE_PAS_COMMENT; break;
2900 case SCLEX_RUST: style_comment = SCE_RUST_COMMENTBLOCK; break;
2901 default: style_comment = SCE_C_COMMENT;
2904 return style_comment;
2908 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise
2909 * returns the amount of uncommented single comment lines, in case of multi line uncomment
2910 * it returns just 1 */
2911 gint editor_do_uncomment(GeanyEditor *editor, gint line, gboolean toggle)
2913 gint first_line, last_line;
2914 gint x, i, line_start, line_len;
2915 gint sel_start, sel_end;
2916 gint count = 0;
2917 gsize co_len;
2918 gchar sel[256];
2919 const gchar *co, *cc;
2920 gboolean single_line = FALSE;
2921 GeanyFiletype *ft;
2923 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, 0);
2925 if (line < 0)
2926 { /* use selection or current line */
2927 sel_start = sci_get_selection_start(editor->sci);
2928 sel_end = sci_get_selection_end(editor->sci);
2930 first_line = sci_get_line_from_position(editor->sci, sel_start);
2931 /* Find the last line with chars selected (not EOL char) */
2932 last_line = sci_get_line_from_position(editor->sci,
2933 sel_end - editor_get_eol_char_len(editor));
2934 last_line = MAX(first_line, last_line);
2936 else
2938 first_line = last_line = line;
2939 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
2942 ft = editor_get_filetype_at_line(editor, first_line);
2944 if (! filetype_get_comment_open_close(ft, TRUE, &co, &cc))
2945 return 0;
2947 co_len = strlen(co);
2948 if (co_len == 0)
2949 return 0;
2951 sci_start_undo_action(editor->sci);
2953 for (i = first_line; i <= last_line; i++)
2955 gint buf_len;
2957 line_start = sci_get_position_from_line(editor->sci, i);
2958 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
2959 x = 0;
2961 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
2962 if (buf_len <= 0)
2963 continue;
2964 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
2965 sel[buf_len] = '\0';
2967 while (isspace(sel[x])) x++;
2969 /* to skip blank lines */
2970 if (x < line_len && sel[x] != '\0')
2972 /* use single line comment */
2973 if (EMPTY(cc))
2975 single_line = TRUE;
2977 if (toggle)
2979 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
2980 if (strncmp(sel + x, co, co_len) != 0 ||
2981 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) != 0)
2982 continue;
2984 co_len += tm_len;
2986 else
2988 if (strncmp(sel + x, co, co_len) != 0)
2989 continue;
2992 sci_set_selection(editor->sci, line_start + x, line_start + x + co_len);
2993 sci_replace_sel(editor->sci, "");
2994 count++;
2996 /* use multi line comment */
2997 else
2999 gint style_comment;
3001 /* skip lines which are already comments */
3002 style_comment = get_multiline_comment_style(editor, line_start);
3003 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3005 if (real_uncomment_multiline(editor))
3006 count = 1;
3009 /* break because we are already on the last line */
3010 break;
3014 sci_end_undo_action(editor->sci);
3016 /* restore selection if there is one
3017 * but don't touch the selection if caller is editor_do_comment_toggle */
3018 if (! toggle && sel_start < sel_end)
3020 if (single_line)
3022 sci_set_selection_start(editor->sci, sel_start - co_len);
3023 sci_set_selection_end(editor->sci, sel_end - (count * co_len));
3025 else
3027 gint eol_len = editor_get_eol_char_len(editor);
3028 sci_set_selection_start(editor->sci, sel_start - co_len - eol_len);
3029 sci_set_selection_end(editor->sci, sel_end - co_len - eol_len);
3033 return count;
3037 void editor_do_comment_toggle(GeanyEditor *editor)
3039 gint first_line, last_line;
3040 gint x, i, line_start, line_len, first_line_start, last_line_start;
3041 gint sel_start, sel_end;
3042 gint count_commented = 0, count_uncommented = 0;
3043 gchar sel[256];
3044 const gchar *co, *cc;
3045 gboolean break_loop = FALSE, single_line = FALSE;
3046 gboolean first_line_was_comment = FALSE;
3047 gboolean last_line_was_comment = FALSE;
3048 gsize co_len;
3049 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
3050 GeanyFiletype *ft;
3052 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
3054 sel_start = sci_get_selection_start(editor->sci);
3055 sel_end = sci_get_selection_end(editor->sci);
3057 first_line = sci_get_line_from_position(editor->sci, sel_start);
3058 /* Find the last line with chars selected (not EOL char) */
3059 last_line = sci_get_line_from_position(editor->sci,
3060 sel_end - editor_get_eol_char_len(editor));
3061 last_line = MAX(first_line, last_line);
3063 first_line_start = sci_get_position_from_line(editor->sci, first_line);
3064 last_line_start = sci_get_position_from_line(editor->sci, last_line);
3066 ft = editor_get_filetype_at_line(editor, first_line);
3068 if (! filetype_get_comment_open_close(ft, TRUE, &co, &cc))
3069 return;
3071 co_len = strlen(co);
3072 if (co_len == 0)
3073 return;
3075 sci_start_undo_action(editor->sci);
3077 for (i = first_line; (i <= last_line) && (! break_loop); i++)
3079 gint buf_len;
3081 line_start = sci_get_position_from_line(editor->sci, i);
3082 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
3083 x = 0;
3085 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
3086 if (buf_len < 0)
3087 continue;
3088 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3089 sel[buf_len] = '\0';
3091 while (isspace(sel[x])) x++;
3093 /* use single line comment */
3094 if (EMPTY(cc))
3096 gboolean do_continue = FALSE;
3097 single_line = TRUE;
3099 if (strncmp(sel + x, co, co_len) == 0 &&
3100 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) == 0)
3102 do_continue = TRUE;
3105 if (do_continue && i == first_line)
3106 first_line_was_comment = TRUE;
3107 last_line_was_comment = do_continue;
3109 if (do_continue)
3111 count_uncommented += editor_do_uncomment(editor, i, TRUE);
3112 continue;
3115 /* we are still here, so the above lines were not already comments, so comment it */
3116 count_commented += editor_do_comment(editor, i, FALSE, TRUE, TRUE);
3118 /* use multi line comment */
3119 else
3121 gint style_comment;
3123 /* skip lines which are already comments */
3124 style_comment = get_multiline_comment_style(editor, line_start);
3125 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3127 if (real_uncomment_multiline(editor))
3128 count_uncommented++;
3130 else
3132 real_comment_multiline(editor, line_start, last_line);
3133 count_commented++;
3136 /* break because we are already on the last line */
3137 break_loop = TRUE;
3138 break;
3142 sci_end_undo_action(editor->sci);
3144 co_len += tm_len;
3146 /* restore selection or caret position */
3147 if (single_line)
3149 gint a = (first_line_was_comment) ? - (gint) co_len : (gint) co_len;
3150 gint indent_len;
3152 /* don't modify sel_start when the selection starts within indentation */
3153 read_indent(editor, sel_start);
3154 indent_len = (gint) strlen(indent);
3155 if ((sel_start - first_line_start) <= indent_len)
3156 a = 0;
3157 /* if the selection start was inside the comment mark, adjust the position */
3158 else if (first_line_was_comment &&
3159 sel_start >= (first_line_start + indent_len) &&
3160 sel_start <= (first_line_start + indent_len + (gint) co_len))
3162 a = (first_line_start + indent_len) - sel_start;
3165 if (sel_start < sel_end)
3167 gint b = (count_commented * (gint) co_len) - (count_uncommented * (gint) co_len);
3169 /* same for selection end, but here we add an offset on the offset above */
3170 read_indent(editor, sel_end + b);
3171 indent_len = (gint) strlen(indent);
3172 if ((sel_end - last_line_start) < indent_len)
3173 b += last_line_was_comment ? (gint) co_len : -(gint) co_len;
3174 else if (last_line_was_comment &&
3175 sel_end >= (last_line_start + indent_len) &&
3176 sel_end <= (last_line_start + indent_len + (gint) co_len))
3178 b += (gint) co_len - (sel_end - (last_line_start + indent_len));
3181 sci_set_selection_start(editor->sci, sel_start + a);
3182 sci_set_selection_end(editor->sci, sel_end + b);
3184 else
3185 sci_set_current_position(editor->sci, sel_start + a, TRUE);
3187 else
3189 gint eol_len = editor_get_eol_char_len(editor);
3190 if (count_uncommented > 0)
3192 sci_set_selection_start(editor->sci, sel_start - (gint) co_len + eol_len);
3193 sci_set_selection_end(editor->sci, sel_end - (gint) co_len + eol_len);
3195 else if (count_commented > 0)
3197 sci_set_selection_start(editor->sci, sel_start + (gint) co_len - eol_len);
3198 sci_set_selection_end(editor->sci, sel_end + (gint) co_len - eol_len);
3200 if (sel_start >= sel_end)
3201 sci_scroll_caret(editor->sci);
3206 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise */
3207 gint editor_do_comment(GeanyEditor *editor, gint line, gboolean allow_empty_lines, gboolean toggle,
3208 gboolean single_comment)
3210 gint first_line, last_line;
3211 gint x, i, line_start, line_len;
3212 gint sel_start, sel_end, co_len;
3213 gint count = 0;
3214 gchar sel[256];
3215 const gchar *co, *cc;
3216 gboolean break_loop = FALSE, single_line = FALSE;
3217 GeanyFiletype *ft;
3219 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, 0);
3221 if (line < 0)
3222 { /* use selection or current line */
3223 sel_start = sci_get_selection_start(editor->sci);
3224 sel_end = sci_get_selection_end(editor->sci);
3226 first_line = sci_get_line_from_position(editor->sci, sel_start);
3227 /* Find the last line with chars selected (not EOL char) */
3228 last_line = sci_get_line_from_position(editor->sci,
3229 sel_end - editor_get_eol_char_len(editor));
3230 last_line = MAX(first_line, last_line);
3232 else
3234 first_line = last_line = line;
3235 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
3238 ft = editor_get_filetype_at_line(editor, first_line);
3240 if (! filetype_get_comment_open_close(ft, single_comment, &co, &cc))
3241 return 0;
3243 co_len = strlen(co);
3244 if (co_len == 0)
3245 return 0;
3247 sci_start_undo_action(editor->sci);
3249 for (i = first_line; (i <= last_line) && (! break_loop); i++)
3251 gint buf_len;
3253 line_start = sci_get_position_from_line(editor->sci, i);
3254 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
3255 x = 0;
3257 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
3258 if (buf_len < 0)
3259 continue;
3260 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3261 sel[buf_len] = '\0';
3263 while (isspace(sel[x])) x++;
3265 /* to skip blank lines */
3266 if (allow_empty_lines || (x < line_len && sel[x] != '\0'))
3268 /* use single line comment */
3269 if (EMPTY(cc))
3271 gint start = line_start;
3272 single_line = TRUE;
3274 if (ft->comment_use_indent)
3275 start = line_start + x;
3277 if (toggle)
3279 gchar *text = g_strconcat(co, editor_prefs.comment_toggle_mark, NULL);
3280 sci_insert_text(editor->sci, start, text);
3281 g_free(text);
3283 else
3284 sci_insert_text(editor->sci, start, co);
3285 count++;
3287 /* use multi line comment */
3288 else
3290 gint style_comment;
3292 /* skip lines which are already comments */
3293 style_comment = get_multiline_comment_style(editor, line_start);
3294 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3295 continue;
3297 real_comment_multiline(editor, line_start, last_line);
3298 count = 1;
3300 /* break because we are already on the last line */
3301 break_loop = TRUE;
3302 break;
3306 sci_end_undo_action(editor->sci);
3308 /* restore selection if there is one
3309 * but don't touch the selection if caller is editor_do_comment_toggle */
3310 if (! toggle && sel_start < sel_end)
3312 if (single_line)
3314 sci_set_selection_start(editor->sci, sel_start + co_len);
3315 sci_set_selection_end(editor->sci, sel_end + (count * co_len));
3317 else
3319 gint eol_len = editor_get_eol_char_len(editor);
3320 sci_set_selection_start(editor->sci, sel_start + co_len + eol_len);
3321 sci_set_selection_end(editor->sci, sel_end + co_len + eol_len);
3324 return count;
3328 static gboolean brace_timeout_active = FALSE;
3330 static gboolean delay_match_brace(G_GNUC_UNUSED gpointer user_data)
3332 GeanyDocument *doc = document_get_current();
3333 GeanyEditor *editor;
3334 gint brace_pos = GPOINTER_TO_INT(user_data);
3335 gint end_pos, cur_pos;
3337 brace_timeout_active = FALSE;
3338 if (!doc)
3339 return FALSE;
3341 editor = doc->editor;
3342 cur_pos = sci_get_current_position(editor->sci) - 1;
3344 if (cur_pos != brace_pos)
3346 cur_pos++;
3347 if (cur_pos != brace_pos)
3349 /* we have moved past the original brace_pos, but after the timeout
3350 * we may now be on a new brace, so check again */
3351 editor_highlight_braces(editor, cur_pos);
3352 return FALSE;
3355 if (!utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3357 editor_highlight_braces(editor, cur_pos);
3358 return FALSE;
3360 end_pos = sci_find_matching_brace(editor->sci, brace_pos);
3362 if (end_pos >= 0)
3364 gint col = MIN(sci_get_col_from_position(editor->sci, brace_pos),
3365 sci_get_col_from_position(editor->sci, end_pos));
3366 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, col, 0);
3367 SSM(editor->sci, SCI_BRACEHIGHLIGHT, brace_pos, end_pos);
3369 else
3371 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3372 SSM(editor->sci, SCI_BRACEBADLIGHT, brace_pos, 0);
3374 return FALSE;
3378 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos)
3380 gint brace_pos = cur_pos - 1;
3382 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3383 SSM(editor->sci, SCI_BRACEBADLIGHT, (uptr_t)-1, 0);
3385 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3387 brace_pos++;
3388 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3390 return;
3393 if (!brace_timeout_active)
3395 brace_timeout_active = TRUE;
3396 /* delaying matching makes scrolling faster e.g. holding down arrow keys */
3397 g_timeout_add(100, delay_match_brace, GINT_TO_POINTER(brace_pos));
3402 static gboolean in_block_comment(gint lexer, gint style)
3404 switch (lexer)
3406 case SCLEX_COBOL:
3407 case SCLEX_CPP:
3408 return (style == SCE_C_COMMENT ||
3409 style == SCE_C_COMMENTDOC);
3411 case SCLEX_PASCAL:
3412 return (style == SCE_PAS_COMMENT ||
3413 style == SCE_PAS_COMMENT2);
3415 case SCLEX_D:
3416 return (style == SCE_D_COMMENT ||
3417 style == SCE_D_COMMENTDOC ||
3418 style == SCE_D_COMMENTNESTED);
3420 case SCLEX_HTML:
3421 return (style == SCE_HPHP_COMMENT);
3423 case SCLEX_CSS:
3424 return (style == SCE_CSS_COMMENT);
3426 case SCLEX_RUST:
3427 return (style == SCE_RUST_COMMENTBLOCK ||
3428 style == SCE_RUST_COMMENTBLOCKDOC);
3430 default:
3431 return FALSE;
3436 static gboolean is_comment_char(gchar c, gint lexer)
3438 if ((c == '*' || c == '+') && lexer == SCLEX_D)
3439 return TRUE;
3440 else
3441 if (c == '*')
3442 return TRUE;
3444 return FALSE;
3448 static void auto_multiline(GeanyEditor *editor, gint cur_line)
3450 ScintillaObject *sci = editor->sci;
3451 gint indent_pos, style;
3452 gint lexer = sci_get_lexer(sci);
3454 /* Use the start of the line enter was pressed on, to avoid any doc keyword styles */
3455 indent_pos = sci_get_line_indent_position(sci, cur_line - 1);
3456 style = sci_get_style_at(sci, indent_pos);
3457 if (!in_block_comment(lexer, style))
3458 return;
3460 /* Check whether the comment block continues on this line */
3461 indent_pos = sci_get_line_indent_position(sci, cur_line);
3462 if (sci_get_style_at(sci, indent_pos) == style || indent_pos >= sci_get_length(sci))
3464 gchar *previous_line = sci_get_line(sci, cur_line - 1);
3465 /* the type of comment, '*' (C/C++/Java), '+' and the others (D) */
3466 const gchar *continuation = "*";
3467 const gchar *whitespace = ""; /* to hold whitespace if needed */
3468 gchar *result;
3469 gint len = strlen(previous_line);
3470 gint i;
3472 /* find and stop at end of multi line comment */
3473 i = len - 1;
3474 while (i >= 0 && isspace(previous_line[i])) i--;
3475 if (i >= 1 && is_comment_char(previous_line[i - 1], lexer) && previous_line[i] == '/')
3477 gint indent_len, indent_width;
3479 indent_pos = sci_get_line_indent_position(sci, cur_line);
3480 indent_len = sci_get_col_from_position(sci, indent_pos);
3481 indent_width = editor_get_indent_prefs(editor)->width;
3483 /* if there is one too many spaces, delete the last space,
3484 * to return to the indent used before the multiline comment was started. */
3485 if (indent_len % indent_width == 1)
3486 SSM(sci, SCI_DELETEBACKNOTLINE, 0, 0); /* remove whitespace indent */
3487 g_free(previous_line);
3488 return;
3490 /* check whether we are on the second line of multi line comment */
3491 i = 0;
3492 while (i < len && isspace(previous_line[i])) i++; /* get to start of the line */
3494 if (i + 1 < len &&
3495 previous_line[i] == '/' && is_comment_char(previous_line[i + 1], lexer))
3496 { /* we are on the second line of a multi line comment, so we have to insert white space */
3497 whitespace = " ";
3500 if (style == SCE_D_COMMENTNESTED)
3501 continuation = "+"; /* for nested comments in D */
3503 result = g_strconcat(whitespace, continuation, " ", NULL);
3504 sci_add_text(sci, result);
3505 g_free(result);
3507 g_free(previous_line);
3512 #if 0
3513 static gboolean editor_lexer_is_c_like(gint lexer)
3515 switch (lexer)
3517 case SCLEX_CPP:
3518 case SCLEX_D:
3519 return TRUE;
3521 default:
3522 return FALSE;
3525 #endif
3528 /* inserts a three-line comment at one line above current cursor position */
3529 void editor_insert_multiline_comment(GeanyEditor *editor)
3531 gchar *text;
3532 gint text_len;
3533 gint line;
3534 gint pos;
3535 gboolean have_multiline_comment = FALSE;
3536 GeanyDocument *doc;
3537 const gchar *co, *cc;
3539 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
3541 if (! filetype_get_comment_open_close(editor->document->file_type, FALSE, &co, &cc))
3542 g_return_if_reached();
3543 if (!EMPTY(cc))
3544 have_multiline_comment = TRUE;
3546 sci_start_undo_action(editor->sci);
3548 doc = editor->document;
3550 /* insert three lines one line above of the current position */
3551 line = sci_get_line_from_position(editor->sci, editor_info.click_pos);
3552 pos = sci_get_position_from_line(editor->sci, line);
3554 /* use the indent on the current line but only when comment indentation is used
3555 * and we don't have multi line comment characters */
3556 if (editor->auto_indent &&
3557 ! have_multiline_comment && doc->file_type->comment_use_indent)
3559 read_indent(editor, editor_info.click_pos);
3560 text = g_strdup_printf("%s\n%s\n%s\n", indent, indent, indent);
3561 text_len = strlen(text);
3563 else
3565 text = g_strdup("\n\n\n");
3566 text_len = 3;
3568 sci_insert_text(editor->sci, pos, text);
3569 g_free(text);
3571 /* select the inserted lines for commenting */
3572 sci_set_selection_start(editor->sci, pos);
3573 sci_set_selection_end(editor->sci, pos + text_len);
3575 editor_do_comment(editor, -1, TRUE, FALSE, FALSE);
3577 /* set the current position to the start of the first inserted line */
3578 pos += strlen(co);
3580 /* on multi line comment jump to the next line, otherwise add the length of added indentation */
3581 if (have_multiline_comment)
3582 pos += 1;
3583 else
3584 pos += strlen(indent);
3586 sci_set_current_position(editor->sci, pos, TRUE);
3587 /* reset the selection */
3588 sci_set_anchor(editor->sci, pos);
3590 sci_end_undo_action(editor->sci);
3594 /* Note: If the editor is pending a redraw, set document::scroll_percent instead.
3595 * Scroll the view to make line appear at percent_of_view.
3596 * line can be -1 to use the current position. */
3597 void editor_scroll_to_line(GeanyEditor *editor, gint line, gfloat percent_of_view)
3599 gint los;
3600 GtkWidget *wid;
3602 g_return_if_fail(editor != NULL);
3604 wid = GTK_WIDGET(editor->sci);
3606 if (! gtk_widget_get_window(wid) || ! gdk_window_is_viewable(gtk_widget_get_window(wid)))
3607 return; /* prevent gdk_window_scroll warning */
3609 if (line == -1)
3610 line = sci_get_current_line(editor->sci);
3612 /* sci 'visible line' != doc line number because of folding and line wrapping */
3613 /* calling SCI_VISIBLEFROMDOCLINE for line is more accurate than calling
3614 * SCI_DOCLINEFROMVISIBLE for vis1. */
3615 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0);
3616 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
3617 line = line - los * percent_of_view;
3618 SSM(editor->sci, SCI_SETFIRSTVISIBLELINE, line, 0);
3619 sci_scroll_caret(editor->sci); /* needed for horizontal scrolling */
3623 /* creates and inserts one tab or whitespace of the amount of the tab width */
3624 void editor_insert_alternative_whitespace(GeanyEditor *editor)
3626 gchar *text;
3627 GeanyIndentPrefs iprefs = *editor_get_indent_prefs(editor);
3629 g_return_if_fail(editor != NULL);
3631 switch (iprefs.type)
3633 case GEANY_INDENT_TYPE_TABS:
3634 iprefs.type = GEANY_INDENT_TYPE_SPACES;
3635 break;
3636 case GEANY_INDENT_TYPE_SPACES:
3637 case GEANY_INDENT_TYPE_BOTH: /* most likely we want a tab */
3638 iprefs.type = GEANY_INDENT_TYPE_TABS;
3639 break;
3641 text = get_whitespace(&iprefs, iprefs.width);
3642 sci_add_text(editor->sci, text);
3643 g_free(text);
3647 void editor_select_word(GeanyEditor *editor)
3649 gint pos;
3650 gint start;
3651 gint end;
3653 g_return_if_fail(editor != NULL);
3655 pos = SSM(editor->sci, SCI_GETCURRENTPOS, 0, 0);
3656 start = sci_word_start_position(editor->sci, pos, TRUE);
3657 end = sci_word_end_position(editor->sci, pos, TRUE);
3659 if (start == end) /* caret in whitespaces sequence */
3661 /* look forward but reverse the selection direction,
3662 * so the caret end up stay as near as the original position. */
3663 end = sci_word_end_position(editor->sci, pos, FALSE);
3664 start = sci_word_end_position(editor->sci, end, TRUE);
3665 if (start == end)
3666 return;
3669 sci_set_selection(editor->sci, start, end);
3673 /* extra_line is for selecting the cursor line (or anchor line) at the bottom of a selection,
3674 * when those lines have no selection (cursor at start of line). */
3675 void editor_select_lines(GeanyEditor *editor, gboolean extra_line)
3677 gint start, end, line;
3679 g_return_if_fail(editor != NULL);
3681 start = sci_get_selection_start(editor->sci);
3682 end = sci_get_selection_end(editor->sci);
3684 /* check if whole lines are already selected */
3685 if (! extra_line && start != end &&
3686 sci_get_col_from_position(editor->sci, start) == 0 &&
3687 sci_get_col_from_position(editor->sci, end) == 0)
3688 return;
3690 line = sci_get_line_from_position(editor->sci, start);
3691 start = sci_get_position_from_line(editor->sci, line);
3693 line = sci_get_line_from_position(editor->sci, end);
3694 end = sci_get_position_from_line(editor->sci, line + 1);
3696 sci_set_selection(editor->sci, start, end);
3700 static gboolean sci_is_blank_line(ScintillaObject *sci, gint line)
3702 return sci_get_line_indent_position(sci, line) ==
3703 sci_get_line_end_position(sci, line);
3707 /* Returns first line of paragraph for GTK_DIR_UP, line after paragraph
3708 * ends for GTK_DIR_DOWN or -1 if called on an empty line. */
3709 static gint find_paragraph_stop(GeanyEditor *editor, gint line, gint direction)
3711 gint step;
3712 ScintillaObject *sci = editor->sci;
3714 /* first check current line and return -1 if it is empty to skip creating of a selection */
3715 if (sci_is_blank_line(sci, line))
3716 return -1;
3718 if (direction == GTK_DIR_UP)
3719 step = -1;
3720 else
3721 step = 1;
3723 while (TRUE)
3725 line += step;
3726 if (line == -1)
3728 /* start of document */
3729 line = 0;
3730 break;
3732 if (line == sci_get_line_count(sci))
3733 break;
3735 if (sci_is_blank_line(sci, line))
3737 /* return line paragraph starts on */
3738 if (direction == GTK_DIR_UP)
3739 line++;
3740 break;
3743 return line;
3747 void editor_select_paragraph(GeanyEditor *editor)
3749 gint pos_start, pos_end, line_start, line_found;
3751 g_return_if_fail(editor != NULL);
3753 line_start = sci_get_current_line(editor->sci);
3755 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_UP);
3756 if (line_found == -1)
3757 return;
3759 pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3761 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_DOWN);
3762 pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3764 sci_set_selection(editor->sci, pos_start, pos_end);
3768 /* Returns first line of block for GTK_DIR_UP, line after block
3769 * ends for GTK_DIR_DOWN or -1 if called on an empty line. */
3770 static gint find_block_stop(GeanyEditor *editor, gint line, gint direction)
3772 gint step, ind;
3773 ScintillaObject *sci = editor->sci;
3775 /* first check current line and return -1 if it is empty to skip creating of a selection */
3776 if (sci_is_blank_line(sci, line))
3777 return -1;
3779 if (direction == GTK_DIR_UP)
3780 step = -1;
3781 else
3782 step = 1;
3784 ind = sci_get_line_indentation(sci, line);
3785 while (TRUE)
3787 line += step;
3788 if (line == -1)
3790 /* start of document */
3791 line = 0;
3792 break;
3794 if (line == sci_get_line_count(sci))
3795 break;
3797 if (sci_get_line_indentation(sci, line) != ind ||
3798 sci_is_blank_line(sci, line))
3800 /* return line block starts on */
3801 if (direction == GTK_DIR_UP)
3802 line++;
3803 break;
3806 return line;
3810 void editor_select_indent_block(GeanyEditor *editor)
3812 gint pos_start, pos_end, line_start, line_found;
3814 g_return_if_fail(editor != NULL);
3816 line_start = sci_get_current_line(editor->sci);
3818 line_found = find_block_stop(editor, line_start, GTK_DIR_UP);
3819 if (line_found == -1)
3820 return;
3822 pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3824 line_found = find_block_stop(editor, line_start, GTK_DIR_DOWN);
3825 pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3827 sci_set_selection(editor->sci, pos_start, pos_end);
3831 /* simple indentation to indent the current line with the same indent as the previous one */
3832 static void smart_line_indentation(GeanyEditor *editor, gint first_line, gint last_line)
3834 gint i, sel_start = 0, sel_end = 0;
3836 /* get previous line and use it for read_indent to use that line
3837 * (otherwise it would fail on a line only containing "{" in advanced indentation mode) */
3838 read_indent(editor, sci_get_position_from_line(editor->sci, first_line - 1));
3840 for (i = first_line; i <= last_line; i++)
3842 /* skip the first line or if the indentation of the previous and current line are equal */
3843 if (i == 0 ||
3844 SSM(editor->sci, SCI_GETLINEINDENTATION, i - 1, 0) ==
3845 SSM(editor->sci, SCI_GETLINEINDENTATION, i, 0))
3846 continue;
3848 sel_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
3849 sel_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
3850 if (sel_start < sel_end)
3852 sci_set_selection(editor->sci, sel_start, sel_end);
3853 sci_replace_sel(editor->sci, "");
3855 sci_insert_text(editor->sci, sel_start, indent);
3860 /* simple indentation to indent the current line with the same indent as the previous one */
3861 void editor_smart_line_indentation(GeanyEditor *editor, gint pos)
3863 gint first_line, last_line;
3864 gint first_sel_start, first_sel_end;
3865 ScintillaObject *sci;
3867 g_return_if_fail(editor != NULL);
3869 sci = editor->sci;
3871 first_sel_start = sci_get_selection_start(sci);
3872 first_sel_end = sci_get_selection_end(sci);
3874 first_line = sci_get_line_from_position(sci, first_sel_start);
3875 /* Find the last line with chars selected (not EOL char) */
3876 last_line = sci_get_line_from_position(sci, first_sel_end - editor_get_eol_char_len(editor));
3877 last_line = MAX(first_line, last_line);
3879 if (pos == -1)
3880 pos = first_sel_start;
3882 sci_start_undo_action(sci);
3884 smart_line_indentation(editor, first_line, last_line);
3886 /* set cursor position if there was no selection */
3887 if (first_sel_start == first_sel_end)
3889 gint indent_pos = SSM(sci, SCI_GETLINEINDENTPOSITION, first_line, 0);
3891 /* use indent position as user may wish to change indentation afterwards */
3892 sci_set_current_position(sci, indent_pos, FALSE);
3894 else
3896 /* fully select all the lines affected */
3897 sci_set_selection_start(sci, sci_get_position_from_line(sci, first_line));
3898 sci_set_selection_end(sci, sci_get_position_from_line(sci, last_line + 1));
3901 sci_end_undo_action(sci);
3905 /* increase / decrease current line or selection by one space */
3906 void editor_indentation_by_one_space(GeanyEditor *editor, gint pos, gboolean decrease)
3908 gint i, first_line, last_line, line_start, indentation_end, count = 0;
3909 gint sel_start, sel_end, first_line_offset = 0;
3911 g_return_if_fail(editor != NULL);
3913 sel_start = sci_get_selection_start(editor->sci);
3914 sel_end = sci_get_selection_end(editor->sci);
3916 first_line = sci_get_line_from_position(editor->sci, sel_start);
3917 /* Find the last line with chars selected (not EOL char) */
3918 last_line = sci_get_line_from_position(editor->sci, sel_end - editor_get_eol_char_len(editor));
3919 last_line = MAX(first_line, last_line);
3921 if (pos == -1)
3922 pos = sel_start;
3924 sci_start_undo_action(editor->sci);
3926 for (i = first_line; i <= last_line; i++)
3928 indentation_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
3929 if (decrease)
3931 line_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
3932 /* searching backwards for a space to remove */
3933 while (sci_get_char_at(editor->sci, indentation_end) != ' ' && indentation_end > line_start)
3934 indentation_end--;
3936 if (sci_get_char_at(editor->sci, indentation_end) == ' ')
3938 sci_set_selection(editor->sci, indentation_end, indentation_end + 1);
3939 sci_replace_sel(editor->sci, "");
3940 count--;
3941 if (i == first_line)
3942 first_line_offset = -1;
3945 else
3947 sci_insert_text(editor->sci, indentation_end, " ");
3948 count++;
3949 if (i == first_line)
3950 first_line_offset = 1;
3954 /* set cursor position */
3955 if (sel_start < sel_end)
3957 gint start = sel_start + first_line_offset;
3958 if (first_line_offset < 0)
3959 start = MAX(sel_start + first_line_offset,
3960 SSM(editor->sci, SCI_POSITIONFROMLINE, first_line, 0));
3962 sci_set_selection_start(editor->sci, start);
3963 sci_set_selection_end(editor->sci, sel_end + count);
3965 else
3966 sci_set_current_position(editor->sci, pos + count, FALSE);
3968 sci_end_undo_action(editor->sci);
3972 void editor_finalize(void)
3974 scintilla_release_resources();
3978 /* wordchars: NULL or a string containing characters to match a word.
3979 * Returns: the current selection or the current word.
3981 * Passing NULL as wordchars is NOT the same as passing GEANY_WORDCHARS: NULL means
3982 * using Scintillas's word boundaries. */
3983 gchar *editor_get_default_selection(GeanyEditor *editor, gboolean use_current_word,
3984 const gchar *wordchars)
3986 gchar *s = NULL;
3988 g_return_val_if_fail(editor != NULL, NULL);
3990 if (sci_get_lines_selected(editor->sci) == 1)
3991 s = sci_get_selection_contents(editor->sci);
3992 else if (sci_get_lines_selected(editor->sci) == 0 && use_current_word)
3993 { /* use the word at current cursor position */
3994 gchar word[GEANY_MAX_WORD_LENGTH];
3996 if (wordchars != NULL)
3997 editor_find_current_word(editor, -1, word, sizeof(word), wordchars);
3998 else
3999 editor_find_current_word_sciwc(editor, -1, word, sizeof(word));
4001 if (word[0] != '\0')
4002 s = g_strdup(word);
4004 return s;
4008 /* Note: Usually the line should be made visible (not folded) before calling this.
4009 * Returns: TRUE if line is/will be displayed to the user, or FALSE if it is
4010 * outside the *vertical* view.
4011 * Warning: You may need horizontal scrolling to make the cursor visible - so always call
4012 * sci_scroll_caret() when this returns TRUE. */
4013 gboolean editor_line_in_view(GeanyEditor *editor, gint line)
4015 gint vis1, los;
4017 g_return_val_if_fail(editor != NULL, FALSE);
4019 /* If line is wrapped the result may occur on another virtual line than the first and may be
4020 * still hidden, so increase the line number to check for the next document line */
4021 if (SSM(editor->sci, SCI_WRAPCOUNT, line, 0) > 1)
4022 line++;
4024 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0); /* convert to visible line number */
4025 vis1 = SSM(editor->sci, SCI_GETFIRSTVISIBLELINE, 0, 0);
4026 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
4028 return (line >= vis1 && line < vis1 + los);
4032 /* If the current line is outside the current view window, scroll the line
4033 * so it appears at percent_of_view. */
4034 void editor_display_current_line(GeanyEditor *editor, gfloat percent_of_view)
4036 gint line;
4038 g_return_if_fail(editor != NULL);
4040 line = sci_get_current_line(editor->sci);
4042 /* unfold maybe folded results */
4043 sci_ensure_line_is_visible(editor->sci, line);
4045 /* scroll the line if it's off screen */
4046 if (! editor_line_in_view(editor, line))
4047 editor->scroll_percent = percent_of_view;
4048 else
4049 sci_scroll_caret(editor->sci); /* may need horizontal scrolling */
4054 * Deletes all currently set indicators in the @a editor window.
4055 * Error indicators (red squiggly underlines) and usual line markers are removed.
4057 * @param editor The editor to operate on.
4059 void editor_indicator_clear_errors(GeanyEditor *editor)
4061 editor_indicator_clear(editor, GEANY_INDICATOR_ERROR);
4062 sci_marker_delete_all(editor->sci, 0); /* remove the yellow error line marker */
4067 * Deletes all currently set indicators matching @a indic in the @a editor window.
4069 * @param editor The editor to operate on.
4070 * @param indic The indicator number to clear, this is a value of @ref GeanyIndicator.
4072 * @since 0.16
4074 void editor_indicator_clear(GeanyEditor *editor, gint indic)
4076 glong last_pos;
4078 g_return_if_fail(editor != NULL);
4080 last_pos = sci_get_length(editor->sci);
4081 if (last_pos > 0)
4083 sci_indicator_set(editor->sci, indic);
4084 sci_indicator_clear(editor->sci, 0, last_pos);
4090 * Sets an indicator @a indic on @a line.
4091 * Whitespace at the start and the end of the line is not marked.
4093 * @param editor The editor to operate on.
4094 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4095 * @param line The line number which should be marked.
4097 * @since 0.16
4099 void editor_indicator_set_on_line(GeanyEditor *editor, gint indic, gint line)
4101 gint start, end;
4102 guint i = 0, len;
4103 gchar *linebuf;
4105 g_return_if_fail(editor != NULL);
4106 g_return_if_fail(line >= 0);
4108 start = sci_get_position_from_line(editor->sci, line);
4109 end = sci_get_position_from_line(editor->sci, line + 1);
4111 /* skip blank lines */
4112 if ((start + 1) == end ||
4113 start > end ||
4114 (sci_get_line_end_position(editor->sci, line) - start) == 0)
4116 return;
4119 len = end - start;
4120 linebuf = sci_get_line(editor->sci, line);
4122 /* don't set the indicator on whitespace */
4123 while (isspace(linebuf[i]))
4124 i++;
4125 while (len > 1 && len > i && isspace(linebuf[len - 1]))
4127 len--;
4128 end--;
4130 g_free(linebuf);
4132 editor_indicator_set_on_range(editor, indic, start + i, end);
4137 * Sets an indicator on the range specified by @a start and @a end.
4138 * No error checking or whitespace removal is performed, this should be done by the calling
4139 * function if necessary.
4141 * @param editor The editor to operate on.
4142 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4143 * @param start The starting position for the marker.
4144 * @param end The ending position for the marker.
4146 * @since 0.16
4148 void editor_indicator_set_on_range(GeanyEditor *editor, gint indic, gint start, gint end)
4150 g_return_if_fail(editor != NULL);
4151 if (start >= end)
4152 return;
4154 sci_indicator_set(editor->sci, indic);
4155 sci_indicator_fill(editor->sci, start, end - start);
4159 /* Inserts the given colour (format should be #...), if there is a selection starting with 0x...
4160 * the replacement will also start with 0x... */
4161 void editor_insert_color(GeanyEditor *editor, const gchar *colour)
4163 g_return_if_fail(editor != NULL);
4165 if (sci_has_selection(editor->sci))
4167 gint start = sci_get_selection_start(editor->sci);
4168 const gchar *replacement = colour;
4170 if (sci_get_char_at(editor->sci, start) == '0' &&
4171 sci_get_char_at(editor->sci, start + 1) == 'x')
4173 gint end = sci_get_selection_end(editor->sci);
4175 sci_set_selection_start(editor->sci, start + 2);
4176 /* we need to also re-set the selection end in case the anchor was located before
4177 * the cursor, since set_selection_start() always moves the cursor, not the anchor */
4178 sci_set_selection_end(editor->sci, end);
4179 replacement++; /* skip the leading "0x" */
4181 else if (sci_get_char_at(editor->sci, start - 1) == '#')
4182 { /* double clicking something like #00ffff may only select 00ffff because of wordchars */
4183 replacement++; /* so skip the '#' to only replace the colour value */
4185 sci_replace_sel(editor->sci, replacement);
4187 else
4188 sci_add_text(editor->sci, colour);
4193 * Retrieves the end of line characters mode (LF, CR/LF, CR) in the given editor.
4194 * If @a editor is @c NULL, the default end of line characters are used.
4196 * @param editor The editor to operate on, or @c NULL to query the default value.
4197 * @return The used end of line characters mode.
4199 * @since 0.20
4201 gint editor_get_eol_char_mode(GeanyEditor *editor)
4203 gint mode = file_prefs.default_eol_character;
4205 if (editor != NULL)
4206 mode = sci_get_eol_mode(editor->sci);
4208 return mode;
4213 * Retrieves the localized name (for displaying) of the used end of line characters
4214 * (LF, CR/LF, CR) in the given editor.
4215 * If @a editor is @c NULL, the default end of line characters are used.
4217 * @param editor The editor to operate on, or @c NULL to query the default value.
4218 * @return The name of the end of line characters.
4220 * @since 0.19
4222 const gchar *editor_get_eol_char_name(GeanyEditor *editor)
4224 gint mode = file_prefs.default_eol_character;
4226 if (editor != NULL)
4227 mode = sci_get_eol_mode(editor->sci);
4229 return utils_get_eol_name(mode);
4234 * Retrieves the length of the used end of line characters (LF, CR/LF, CR) in the given editor.
4235 * If @a editor is @c NULL, the default end of line characters are used.
4236 * The returned value is 1 for CR and LF and 2 for CR/LF.
4238 * @param editor The editor to operate on, or @c NULL to query the default value.
4239 * @return The length of the end of line characters.
4241 * @since 0.19
4243 gint editor_get_eol_char_len(GeanyEditor *editor)
4245 gint mode = file_prefs.default_eol_character;
4247 if (editor != NULL)
4248 mode = sci_get_eol_mode(editor->sci);
4250 switch (mode)
4252 case SC_EOL_CRLF: return 2; break;
4253 default: return 1; break;
4259 * Retrieves the used end of line characters (LF, CR/LF, CR) in the given editor.
4260 * If @a editor is @c NULL, the default end of line characters are used.
4261 * The returned value is either "\n", "\r\n" or "\r".
4263 * @param editor The editor to operate on, or @c NULL to query the default value.
4264 * @return The end of line characters.
4266 * @since 0.19
4268 const gchar *editor_get_eol_char(GeanyEditor *editor)
4270 gint mode = file_prefs.default_eol_character;
4272 if (editor != NULL)
4273 mode = sci_get_eol_mode(editor->sci);
4275 return utils_get_eol_char(mode);
4279 static void fold_all(GeanyEditor *editor, gboolean want_fold)
4281 gint lines, first, i;
4283 if (editor == NULL || ! editor_prefs.folding)
4284 return;
4286 lines = sci_get_line_count(editor->sci);
4287 first = sci_get_first_visible_line(editor->sci);
4289 for (i = 0; i < lines; i++)
4291 gint level = sci_get_fold_level(editor->sci, i);
4293 if (level & SC_FOLDLEVELHEADERFLAG)
4295 if (sci_get_fold_expanded(editor->sci, i) == want_fold)
4296 sci_toggle_fold(editor->sci, i);
4299 editor_scroll_to_line(editor, first, 0.0F);
4303 void editor_unfold_all(GeanyEditor *editor)
4305 fold_all(editor, FALSE);
4309 void editor_fold_all(GeanyEditor *editor)
4311 fold_all(editor, TRUE);
4315 void editor_replace_tabs(GeanyEditor *editor)
4317 gint search_pos, pos_in_line, current_tab_true_length;
4318 gint tab_len;
4319 gchar *tab_str;
4320 struct Sci_TextToFind ttf;
4322 g_return_if_fail(editor != NULL);
4324 sci_start_undo_action(editor->sci);
4325 tab_len = sci_get_tab_width(editor->sci);
4326 ttf.chrg.cpMin = 0;
4327 ttf.chrg.cpMax = sci_get_length(editor->sci);
4328 ttf.lpstrText = (gchar*) "\t";
4330 while (TRUE)
4332 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4333 if (search_pos == -1)
4334 break;
4336 pos_in_line = sci_get_col_from_position(editor->sci, search_pos);
4337 current_tab_true_length = tab_len - (pos_in_line % tab_len);
4338 tab_str = g_strnfill(current_tab_true_length, ' ');
4339 sci_set_target_start(editor->sci, search_pos);
4340 sci_set_target_end(editor->sci, search_pos + 1);
4341 sci_replace_target(editor->sci, tab_str, FALSE);
4342 /* next search starts after replacement */
4343 ttf.chrg.cpMin = search_pos + current_tab_true_length - 1;
4344 /* update end of range now text has changed */
4345 ttf.chrg.cpMax += current_tab_true_length - 1;
4346 g_free(tab_str);
4348 sci_end_undo_action(editor->sci);
4352 /* Replaces all occurrences all spaces of the length of a given tab_width. */
4353 void editor_replace_spaces(GeanyEditor *editor)
4355 gint search_pos;
4356 static gdouble tab_len_f = -1.0; /* keep the last used value */
4357 gint tab_len;
4358 gchar *text;
4359 struct Sci_TextToFind ttf;
4361 g_return_if_fail(editor != NULL);
4363 if (tab_len_f < 0.0)
4364 tab_len_f = sci_get_tab_width(editor->sci);
4366 if (! dialogs_show_input_numeric(
4367 _("Enter Tab Width"),
4368 _("Enter the amount of spaces which should be replaced by a tab character."),
4369 &tab_len_f, 1, 100, 1))
4371 return;
4373 tab_len = (gint) tab_len_f;
4374 text = g_strnfill(tab_len, ' ');
4376 sci_start_undo_action(editor->sci);
4377 ttf.chrg.cpMin = 0;
4378 ttf.chrg.cpMax = sci_get_length(editor->sci);
4379 ttf.lpstrText = text;
4381 while (TRUE)
4383 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4384 if (search_pos == -1)
4385 break;
4386 /* only replace indentation because otherwise we can mess up alignment */
4387 if (search_pos > sci_get_line_indent_position(editor->sci,
4388 sci_get_line_from_position(editor->sci, search_pos)))
4390 ttf.chrg.cpMin = search_pos + tab_len;
4391 continue;
4393 sci_set_target_start(editor->sci, search_pos);
4394 sci_set_target_end(editor->sci, search_pos + tab_len);
4395 sci_replace_target(editor->sci, "\t", FALSE);
4396 ttf.chrg.cpMin = search_pos;
4397 /* update end of range now text has changed */
4398 ttf.chrg.cpMax -= tab_len - 1;
4400 sci_end_undo_action(editor->sci);
4401 g_free(text);
4405 void editor_strip_line_trailing_spaces(GeanyEditor *editor, gint line)
4407 gint line_start = sci_get_position_from_line(editor->sci, line);
4408 gint line_end = sci_get_line_end_position(editor->sci, line);
4409 gint i = line_end - 1;
4410 gchar ch = sci_get_char_at(editor->sci, i);
4412 /* Diff hunks should keep trailing spaces */
4413 if (sci_get_lexer(editor->sci) == SCLEX_DIFF)
4414 return;
4416 while ((i >= line_start) && ((ch == ' ') || (ch == '\t')))
4418 i--;
4419 ch = sci_get_char_at(editor->sci, i);
4421 if (i < (line_end - 1))
4423 sci_set_target_start(editor->sci, i + 1);
4424 sci_set_target_end(editor->sci, line_end);
4425 sci_replace_target(editor->sci, "", FALSE);
4430 void editor_strip_trailing_spaces(GeanyEditor *editor)
4432 gint max_lines = sci_get_line_count(editor->sci);
4433 gint line;
4435 sci_start_undo_action(editor->sci);
4437 for (line = 0; line < max_lines; line++)
4439 editor_strip_line_trailing_spaces(editor, line);
4441 sci_end_undo_action(editor->sci);
4445 void editor_ensure_final_newline(GeanyEditor *editor)
4447 gint max_lines = sci_get_line_count(editor->sci);
4448 gboolean append_newline = (max_lines == 1);
4449 gint end_document = sci_get_position_from_line(editor->sci, max_lines);
4451 if (max_lines > 1)
4453 append_newline = end_document > sci_get_position_from_line(editor->sci, max_lines - 1);
4455 if (append_newline)
4457 const gchar *eol = editor_get_eol_char(editor);
4459 sci_insert_text(editor->sci, end_document, eol);
4464 void editor_set_font(GeanyEditor *editor, const gchar *font)
4466 gint style, size;
4467 gchar *font_name;
4468 PangoFontDescription *pfd;
4470 g_return_if_fail(editor);
4472 pfd = pango_font_description_from_string(font);
4473 size = pango_font_description_get_size(pfd) / PANGO_SCALE;
4474 font_name = g_strdup_printf("!%s", pango_font_description_get_family(pfd));
4475 pango_font_description_free(pfd);
4477 for (style = 0; style <= STYLE_MAX; style++)
4478 sci_set_font(editor->sci, style, font_name, size);
4480 g_free(font_name);
4482 /* zoom to 100% to prevent confusion */
4483 sci_zoom_off(editor->sci);
4487 void editor_set_line_wrapping(GeanyEditor *editor, gboolean wrap)
4489 g_return_if_fail(editor != NULL);
4491 editor->line_wrapping = wrap;
4492 sci_set_lines_wrapped(editor->sci, wrap);
4496 /** Sets the indent type for @a editor.
4497 * @param editor Editor.
4498 * @param type Indent type.
4500 * @since 0.16
4502 void editor_set_indent_type(GeanyEditor *editor, GeanyIndentType type)
4504 editor_set_indent(editor, type, editor->indent_width);
4508 void editor_set_indent_width(GeanyEditor *editor, gint width)
4510 editor_set_indent(editor, editor->indent_type, width);
4514 void editor_set_indent(GeanyEditor *editor, GeanyIndentType type, gint width)
4516 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
4517 ScintillaObject *sci = editor->sci;
4518 gboolean use_tabs = type != GEANY_INDENT_TYPE_SPACES;
4520 editor->indent_type = type;
4521 editor->indent_width = width;
4522 sci_set_use_tabs(sci, use_tabs);
4524 if (type == GEANY_INDENT_TYPE_BOTH)
4526 sci_set_tab_width(sci, iprefs->hard_tab_width);
4527 if (iprefs->hard_tab_width != 8)
4529 static gboolean warn = TRUE;
4530 if (warn)
4531 ui_set_statusbar(TRUE, _("Warning: non-standard hard tab width: %d != 8!"),
4532 iprefs->hard_tab_width);
4533 warn = FALSE;
4536 else
4537 sci_set_tab_width(sci, width);
4539 SSM(sci, SCI_SETINDENT, width, 0);
4541 /* remove indent spaces on backspace, if using any spaces to indent */
4542 SSM(sci, SCI_SETBACKSPACEUNINDENTS, type != GEANY_INDENT_TYPE_TABS, 0);
4546 /* Convenience function for editor_goto_pos() to pass in a line number. */
4547 gboolean editor_goto_line(GeanyEditor *editor, gint line_no, gint offset)
4549 gint pos;
4551 g_return_val_if_fail(editor, FALSE);
4552 if (line_no < 0 || line_no >= sci_get_line_count(editor->sci))
4553 return FALSE;
4555 if (offset != 0)
4557 gint current_line = sci_get_current_line(editor->sci);
4558 line_no *= offset;
4559 line_no = current_line + line_no;
4562 pos = sci_get_position_from_line(editor->sci, line_no);
4563 return editor_goto_pos(editor, pos, TRUE);
4567 /** Moves to position @a pos, switching to the document if necessary,
4568 * setting a marker if @a mark is set.
4570 * @param editor Editor.
4571 * @param pos The position.
4572 * @param mark Whether to set a mark on the position.
4573 * @return @c TRUE if action has been performed, otherwise @c FALSE.
4575 * @since 0.20
4577 gboolean editor_goto_pos(GeanyEditor *editor, gint pos, gboolean mark)
4579 g_return_val_if_fail(editor, FALSE);
4580 if (G_UNLIKELY(pos < 0))
4581 return FALSE;
4583 if (mark)
4585 gint line = sci_get_line_from_position(editor->sci, pos);
4587 /* mark the tag with the yellow arrow */
4588 sci_marker_delete_all(editor->sci, 0);
4589 sci_set_marker_at_line(editor->sci, line, 0);
4592 sci_goto_pos(editor->sci, pos, TRUE);
4593 editor->scroll_percent = 0.25F;
4595 /* finally switch to the page */
4596 document_show_tab(editor->document);
4597 return TRUE;
4601 static gboolean
4602 on_editor_scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer user_data)
4604 GeanyEditor *editor = user_data;
4606 /* Handle scroll events if Alt is pressed and scroll whole pages instead of a
4607 * few lines only, maybe this could/should be done in Scintilla directly */
4608 if (event->state & GDK_MOD1_MASK)
4610 sci_send_command(editor->sci, (event->direction == GDK_SCROLL_DOWN) ? SCI_PAGEDOWN : SCI_PAGEUP);
4611 return TRUE;
4613 else if (event->state & GDK_SHIFT_MASK)
4615 gint amount = (event->direction == GDK_SCROLL_DOWN) ? 8 : -8;
4617 sci_scroll_columns(editor->sci, amount);
4618 return TRUE;
4621 return FALSE; /* let Scintilla handle all other cases */
4625 static gboolean editor_check_colourise(GeanyEditor *editor)
4627 GeanyDocument *doc = editor->document;
4629 if (!doc->priv->colourise_needed)
4630 return FALSE;
4632 doc->priv->colourise_needed = FALSE;
4633 sci_colourise(editor->sci, 0, -1);
4635 /* now that the current document is colourised, fold points are now accurate,
4636 * so force an update of the current function/tag. */
4637 symbols_get_current_function(NULL, NULL);
4638 ui_update_statusbar(NULL, -1);
4640 return TRUE;
4644 /* We only want to colourise just before drawing, to save startup time and
4645 * prevent unnecessary recolouring other documents after one is saved.
4646 * Really we want a "draw" signal but there doesn't seem to be one (expose is too late,
4647 * and "show" doesn't work). */
4648 static gboolean on_editor_focus_in(GtkWidget *widget, GdkEventFocus *event, gpointer user_data)
4650 GeanyEditor *editor = user_data;
4652 editor_check_colourise(editor);
4653 return FALSE;
4657 static gboolean on_editor_expose_event(GtkWidget *widget, GdkEventExpose *event,
4658 gpointer user_data)
4660 GeanyEditor *editor = user_data;
4662 /* This is just to catch any uncolourised documents being drawn that didn't receive focus
4663 * for some reason, maybe it's not necessary but just in case. */
4664 editor_check_colourise(editor);
4665 return FALSE;
4669 #if GTK_CHECK_VERSION(3, 0, 0)
4670 static gboolean on_editor_draw(GtkWidget *widget, cairo_t *cr, gpointer user_data)
4672 return on_editor_expose_event(widget, NULL, user_data);
4674 #endif
4677 static void setup_sci_keys(ScintillaObject *sci)
4679 /* disable some Scintilla keybindings to be able to redefine them cleanly */
4680 sci_clear_cmdkey(sci, 'A' | (SCMOD_CTRL << 16)); /* select all */
4681 sci_clear_cmdkey(sci, 'D' | (SCMOD_CTRL << 16)); /* duplicate */
4682 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16)); /* line transpose */
4683 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line copy */
4684 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16)); /* line cut */
4685 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line delete */
4686 sci_clear_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line to end delete */
4687 sci_clear_cmdkey(sci, '/' | (SCMOD_CTRL << 16)); /* Previous word part */
4688 sci_clear_cmdkey(sci, '\\' | (SCMOD_CTRL << 16)); /* Next word part */
4689 sci_clear_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16)); /* scroll line up */
4690 sci_clear_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16)); /* scroll line down */
4691 sci_clear_cmdkey(sci, SCK_HOME); /* line start */
4692 sci_clear_cmdkey(sci, SCK_END); /* line end */
4693 sci_clear_cmdkey(sci, SCK_END | (SCMOD_ALT << 16)); /* visual line end */
4695 if (editor_prefs.use_gtk_word_boundaries)
4697 /* use GtkEntry-like word boundaries */
4698 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16), SCI_WORDRIGHTEND);
4699 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_WORDRIGHTENDEXTEND);
4700 sci_assign_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16), SCI_DELWORDRIGHTEND);
4702 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_ALT << 16), SCI_LINESCROLLUP);
4703 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_ALT << 16), SCI_LINESCROLLDOWN);
4704 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16), SCI_PARAUP);
4705 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARAUPEXTEND);
4706 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16), SCI_PARADOWN);
4707 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARADOWNEXTEND);
4709 sci_clear_cmdkey(sci, SCK_BACK | (SCMOD_ALT << 16)); /* clear Alt-Backspace (Undo) */
4713 /* registers a Scintilla image from a named icon from the theme */
4714 static gboolean register_named_icon(ScintillaObject *sci, guint id, const gchar *name)
4716 GError *error = NULL;
4717 GdkPixbuf *pixbuf;
4718 gint n_channels, rowstride, width, height;
4719 gint size;
4721 gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &size, NULL);
4722 pixbuf = gtk_icon_theme_load_icon(gtk_icon_theme_get_default(), name, size, 0, &error);
4723 if (! pixbuf)
4725 g_warning("failed to load icon '%s': %s", name, error->message);
4726 g_error_free(error);
4727 return FALSE;
4730 n_channels = gdk_pixbuf_get_n_channels(pixbuf);
4731 rowstride = gdk_pixbuf_get_rowstride(pixbuf);
4732 width = gdk_pixbuf_get_width(pixbuf);
4733 height = gdk_pixbuf_get_height(pixbuf);
4735 if (gdk_pixbuf_get_bits_per_sample(pixbuf) != 8 ||
4736 ! gdk_pixbuf_get_has_alpha(pixbuf) ||
4737 n_channels != 4 ||
4738 rowstride != width * n_channels)
4740 g_warning("incompatible image data for icon '%s'", name);
4741 g_object_unref(pixbuf);
4742 return FALSE;
4745 SSM(sci, SCI_RGBAIMAGESETWIDTH, width, 0);
4746 SSM(sci, SCI_RGBAIMAGESETHEIGHT, height, 0);
4747 SSM(sci, SCI_REGISTERRGBAIMAGE, id, (sptr_t)gdk_pixbuf_get_pixels(pixbuf));
4749 g_object_unref(pixbuf);
4750 return TRUE;
4754 /* Create new editor widget (scintilla).
4755 * @note The @c "sci-notify" signal is connected separately. */
4756 static ScintillaObject *create_new_sci(GeanyEditor *editor)
4758 ScintillaObject *sci;
4760 sci = SCINTILLA(scintilla_new());
4762 /* Scintilla doesn't support RTL languages properly and is primarily
4763 * intended to be used with LTR source code, so override the
4764 * GTK+ default text direction for the Scintilla widget. */
4765 gtk_widget_set_direction(GTK_WIDGET(sci), GTK_TEXT_DIR_LTR);
4767 gtk_widget_show(GTK_WIDGET(sci));
4769 sci_set_codepage(sci, SC_CP_UTF8);
4770 /*SSM(sci, SCI_SETWRAPSTARTINDENT, 4, 0);*/
4771 /* disable scintilla provided popup menu */
4772 sci_use_popup(sci, FALSE);
4774 setup_sci_keys(sci);
4776 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
4777 sci_set_lines_wrapped(sci, editor_prefs.line_wrapping);
4778 sci_set_caret_policy_x(sci, CARET_JUMPS | CARET_EVEN, 0);
4779 /*sci_set_caret_policy_y(sci, CARET_JUMPS | CARET_EVEN, 0);*/
4780 SSM(sci, SCI_AUTOCSETSEPARATOR, '\n', 0);
4781 SSM(sci, SCI_SETSCROLLWIDTHTRACKING, 1, 0);
4783 /* tag autocompletion images */
4784 register_named_icon(sci, 1, "classviewer-var");
4785 register_named_icon(sci, 2, "classviewer-method");
4787 /* necessary for column mode editing, implemented in Scintilla since 2.0 */
4788 SSM(sci, SCI_SETADDITIONALSELECTIONTYPING, 1, 0);
4790 /* virtual space */
4791 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
4793 /* only connect signals if this is for the document notebook, not split window */
4794 if (editor->sci == NULL)
4796 g_signal_connect(sci, "button-press-event", G_CALLBACK(on_editor_button_press_event), editor);
4797 g_signal_connect(sci, "scroll-event", G_CALLBACK(on_editor_scroll_event), editor);
4798 g_signal_connect(sci, "motion-notify-event", G_CALLBACK(on_motion_event), NULL);
4799 g_signal_connect(sci, "focus-in-event", G_CALLBACK(on_editor_focus_in), editor);
4800 #if GTK_CHECK_VERSION(3, 0, 0)
4801 g_signal_connect(sci, "draw", G_CALLBACK(on_editor_draw), editor);
4802 #else
4803 g_signal_connect(sci, "expose-event", G_CALLBACK(on_editor_expose_event), editor);
4804 #endif
4806 return sci;
4810 /** Creates a new Scintilla @c GtkWidget based on the settings for @a editor.
4811 * @param editor Editor settings.
4812 * @return The new widget.
4814 * @since 0.15
4816 ScintillaObject *editor_create_widget(GeanyEditor *editor)
4818 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4819 ScintillaObject *old, *sci;
4821 /* temporarily change editor to use the new sci widget */
4822 old = editor->sci;
4823 sci = create_new_sci(editor);
4824 editor->sci = sci;
4826 editor_set_indent(editor, iprefs->type, iprefs->width);
4827 editor_set_font(editor, interface_prefs.editor_font);
4828 editor_apply_update_prefs(editor);
4830 /* if editor already had a widget, restore it */
4831 if (old)
4832 editor->sci = old;
4833 return sci;
4837 GeanyEditor *editor_create(GeanyDocument *doc)
4839 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4840 GeanyEditor *editor = g_new0(GeanyEditor, 1);
4842 editor->document = doc;
4843 doc->editor = editor; /* needed in case some editor functions/callbacks expect it */
4845 editor->auto_indent = (iprefs->auto_indent_mode != GEANY_AUTOINDENT_NONE);
4846 editor->line_wrapping = editor_prefs.line_wrapping;
4847 editor->scroll_percent = -1.0F;
4848 editor->line_breaking = FALSE;
4850 editor->sci = editor_create_widget(editor);
4851 return editor;
4855 /* in case we need to free some fields in future */
4856 void editor_destroy(GeanyEditor *editor)
4858 g_free(editor);
4862 static void on_document_save(GObject *obj, GeanyDocument *doc)
4864 gchar *f = g_build_filename(app->configdir, "snippets.conf", NULL);
4866 if (utils_str_equal(doc->real_path, f))
4868 /* reload snippets */
4869 editor_snippets_free();
4870 editor_snippets_init();
4872 g_free(f);
4876 gboolean editor_complete_word_part(GeanyEditor *editor)
4878 gchar *entry;
4880 g_return_val_if_fail(editor, FALSE);
4882 if (!SSM(editor->sci, SCI_AUTOCACTIVE, 0, 0))
4883 return FALSE;
4885 entry = sci_get_string(editor->sci, SCI_AUTOCGETCURRENTTEXT, 0);
4887 /* if no word part, complete normally */
4888 if (!check_partial_completion(editor, entry))
4889 SSM(editor->sci, SCI_AUTOCCOMPLETE, 0, 0);
4891 g_free(entry);
4892 return TRUE;
4896 void editor_init(void)
4898 static GeanyIndentPrefs indent_prefs;
4899 gchar *f;
4901 memset(&editor_prefs, 0, sizeof(GeanyEditorPrefs));
4902 memset(&indent_prefs, 0, sizeof(GeanyIndentPrefs));
4903 editor_prefs.indentation = &indent_prefs;
4905 /* use g_signal_connect_after() to allow plugins connecting to the signal before the default
4906 * handler (on_editor_notify) is called */
4907 g_signal_connect_after(geany_object, "editor-notify", G_CALLBACK(on_editor_notify), NULL);
4909 f = g_build_filename(app->configdir, "snippets.conf", NULL);
4910 ui_add_config_file_menu_item(f, NULL, NULL);
4911 g_free(f);
4912 g_signal_connect(geany_object, "document-save", G_CALLBACK(on_document_save), NULL);
4916 /* TODO: Should these be user-defined instead of hard-coded? */
4917 void editor_set_indentation_guides(GeanyEditor *editor)
4919 gint mode;
4920 gint lexer;
4922 g_return_if_fail(editor != NULL);
4924 if (! editor_prefs.show_indent_guide)
4926 sci_set_indentation_guides(editor->sci, SC_IV_NONE);
4927 return;
4930 lexer = sci_get_lexer(editor->sci);
4931 switch (lexer)
4933 /* Lines added/removed are prefixed with +/- characters, so
4934 * those lines will not be shown with any indentation guides.
4935 * It can be distracting that only a few of lines in a diff/patch
4936 * file will show the guides. */
4937 case SCLEX_DIFF:
4938 mode = SC_IV_NONE;
4939 break;
4941 /* These languages use indentation for control blocks; the "look forward" method works
4942 * best here */
4943 case SCLEX_PYTHON:
4944 case SCLEX_HASKELL:
4945 case SCLEX_MAKEFILE:
4946 case SCLEX_ASM:
4947 case SCLEX_SQL:
4948 case SCLEX_COBOL:
4949 case SCLEX_PROPERTIES:
4950 case SCLEX_FORTRAN: /* Is this the best option for Fortran? */
4951 case SCLEX_CAML:
4952 mode = SC_IV_LOOKFORWARD;
4953 break;
4955 /* C-like (structured) languages benefit from the "look both" method */
4956 case SCLEX_CPP:
4957 case SCLEX_HTML:
4958 case SCLEX_XML:
4959 case SCLEX_PERL:
4960 case SCLEX_LATEX:
4961 case SCLEX_LUA:
4962 case SCLEX_PASCAL:
4963 case SCLEX_RUBY:
4964 case SCLEX_TCL:
4965 case SCLEX_F77:
4966 case SCLEX_CSS:
4967 case SCLEX_BASH:
4968 case SCLEX_VHDL:
4969 case SCLEX_FREEBASIC:
4970 case SCLEX_D:
4971 case SCLEX_OCTAVE:
4972 case SCLEX_RUST:
4973 mode = SC_IV_LOOKBOTH;
4974 break;
4976 default:
4977 mode = SC_IV_REAL;
4978 break;
4981 sci_set_indentation_guides(editor->sci, mode);
4985 /* Apply just the prefs that can change in the Preferences dialog */
4986 void editor_apply_update_prefs(GeanyEditor *editor)
4988 ScintillaObject *sci;
4990 g_return_if_fail(editor != NULL);
4992 if (main_status.quitting)
4993 return;
4995 sci = editor->sci;
4997 sci_set_mark_long_lines(sci, editor_get_long_line_type(),
4998 editor_get_long_line_column(), editor_prefs.long_line_color);
5000 /* update indent width, tab width */
5001 editor_set_indent(editor, editor->indent_type, editor->indent_width);
5002 sci_set_tab_indents(sci, editor_prefs.use_tab_to_indent);
5004 sci_assign_cmdkey(sci, SCK_HOME | (SCMOD_SHIFT << 16),
5005 editor_prefs.smart_home_key ? SCI_VCHOMEEXTEND : SCI_HOMEEXTEND);
5006 sci_assign_cmdkey(sci, SCK_HOME | ((SCMOD_SHIFT | SCMOD_ALT) << 16),
5007 editor_prefs.smart_home_key ? SCI_VCHOMERECTEXTEND : SCI_HOMERECTEXTEND);
5009 sci_set_autoc_max_height(sci, editor_prefs.symbolcompletion_max_height);
5010 SSM(sci, SCI_AUTOCSETDROPRESTOFWORD, editor_prefs.completion_drops_rest_of_word, 0);
5012 editor_set_indentation_guides(editor);
5014 sci_set_visible_white_spaces(sci, editor_prefs.show_white_space);
5015 sci_set_visible_eols(sci, editor_prefs.show_line_endings);
5016 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
5017 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin);
5019 sci_set_folding_margin_visible(sci, editor_prefs.folding);
5021 /* virtual space */
5022 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
5024 /* (dis)allow scrolling past end of document */
5025 sci_set_scroll_stop_at_last_line(sci, editor_prefs.scroll_stop_at_last_line);
5027 sci_set_scrollbar_mode(sci, editor_prefs.show_scrollbars);
5031 /* This is for tab-indents, space aligns formatted code. Spaces should be preserved. */
5032 static void change_tab_indentation(GeanyEditor *editor, gint line, gboolean increase)
5034 ScintillaObject *sci = editor->sci;
5035 gint pos = sci_get_position_from_line(sci, line);
5037 if (increase)
5039 sci_insert_text(sci, pos, "\t");
5041 else
5043 if (sci_get_char_at(sci, pos) == '\t')
5045 sci_set_selection(sci, pos, pos + 1);
5046 sci_replace_sel(sci, "");
5048 else /* remove spaces only if no tabs */
5050 gint width = sci_get_line_indentation(sci, line);
5052 width -= editor_get_indent_prefs(editor)->width;
5053 sci_set_line_indentation(sci, line, width);
5059 static void editor_change_line_indent(GeanyEditor *editor, gint line, gboolean increase)
5061 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
5062 ScintillaObject *sci = editor->sci;
5064 if (iprefs->type == GEANY_INDENT_TYPE_TABS)
5065 change_tab_indentation(editor, line, increase);
5066 else
5068 gint width = sci_get_line_indentation(sci, line);
5070 width += increase ? iprefs->width : -iprefs->width;
5071 sci_set_line_indentation(sci, line, width);
5076 void editor_indent(GeanyEditor *editor, gboolean increase)
5078 ScintillaObject *sci = editor->sci;
5079 gint caret_pos, caret_line, caret_offset, caret_indent_pos, caret_line_len;
5080 gint anchor_pos, anchor_line, anchor_offset, anchor_indent_pos, anchor_line_len;
5082 /* backup information needed to restore caret and anchor */
5083 caret_pos = sci_get_current_position(sci);
5084 anchor_pos = SSM(sci, SCI_GETANCHOR, 0, 0);
5085 caret_line = sci_get_line_from_position(sci, caret_pos);
5086 anchor_line = sci_get_line_from_position(sci, anchor_pos);
5087 caret_offset = caret_pos - sci_get_position_from_line(sci, caret_line);
5088 anchor_offset = anchor_pos - sci_get_position_from_line(sci, anchor_line);
5089 caret_indent_pos = sci_get_line_indent_position(sci, caret_line);
5090 anchor_indent_pos = sci_get_line_indent_position(sci, anchor_line);
5091 caret_line_len = sci_get_line_length(sci, caret_line);
5092 anchor_line_len = sci_get_line_length(sci, anchor_line);
5094 if (sci_get_lines_selected(sci) <= 1)
5096 editor_change_line_indent(editor, sci_get_current_line(sci), increase);
5098 else
5100 gint start, end;
5101 gint line, lstart, lend;
5103 editor_select_lines(editor, FALSE);
5104 start = sci_get_selection_start(sci);
5105 end = sci_get_selection_end(sci);
5106 lstart = sci_get_line_from_position(sci, start);
5107 lend = sci_get_line_from_position(sci, end);
5108 if (end == sci_get_length(sci))
5109 lend++; /* for last line with text on it */
5111 sci_start_undo_action(sci);
5112 for (line = lstart; line < lend; line++)
5114 editor_change_line_indent(editor, line, increase);
5116 sci_end_undo_action(sci);
5119 /* restore caret and anchor position */
5120 if (caret_pos >= caret_indent_pos)
5121 caret_offset += sci_get_line_length(sci, caret_line) - caret_line_len;
5122 if (anchor_pos >= anchor_indent_pos)
5123 anchor_offset += sci_get_line_length(sci, anchor_line) - anchor_line_len;
5125 SSM(sci, SCI_SETCURRENTPOS, sci_get_position_from_line(sci, caret_line) + caret_offset, 0);
5126 SSM(sci, SCI_SETANCHOR, sci_get_position_from_line(sci, anchor_line) + anchor_offset, 0);
5130 /** Gets snippet by name.
5132 * If @a editor is passed, returns a snippet specific to the document filetype.
5133 * If @a editor is @c NULL, returns a snippet from the default set.
5135 * @param editor Editor or @c NULL.
5136 * @param snippet_name Snippet name.
5137 * @return snippet or @c NULL if it was not found. Must not be freed.
5139 const gchar *editor_find_snippet(GeanyEditor *editor, const gchar *snippet_name)
5141 const gchar *subhash_name = editor ? editor->document->file_type->name : "Default";
5142 GHashTable *subhash = g_hash_table_lookup(snippet_hash, subhash_name);
5144 return subhash ? g_hash_table_lookup(subhash, snippet_name) : NULL;
5148 /** Replaces all special sequences in @a snippet and inserts it at @a pos.
5149 * If you insert at the current position, consider calling @c sci_scroll_caret()
5150 * after this function.
5151 * @param editor .
5152 * @param pos .
5153 * @param snippet .
5155 void editor_insert_snippet(GeanyEditor *editor, gint pos, const gchar *snippet)
5157 GString *pattern;
5159 pattern = g_string_new(snippet);
5160 snippets_make_replacements(editor, pattern);
5161 editor_insert_text_block(editor, pattern->str, pos, -1, -1, TRUE);
5162 g_string_free(pattern, TRUE);