Get scope members only from corresponding tag arrays
[geany-mirror.git] / src / editor.c
blob37b189f4ff15ecc5f04174fc34aaed2e12d821a1
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 = keybindings_get_modifiers(event->state);
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 == GEANY_PRIMARY_MOD_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 #define get_project_pref(id)\
408 (app->project ? app->project->priv->id : editor_prefs.id)
410 static const GeanyEditorPrefs *
411 get_default_prefs(void)
413 static GeanyEditorPrefs eprefs;
415 eprefs = editor_prefs;
417 /* project overrides */
418 eprefs.indentation = (GeanyIndentPrefs*)editor_get_indent_prefs(NULL);
419 eprefs.long_line_type = editor_get_long_line_type();
420 eprefs.long_line_column = editor_get_long_line_column();
421 eprefs.line_wrapping = get_project_pref(line_wrapping);
422 eprefs.line_break_column = get_project_pref(line_break_column);
423 eprefs.auto_continue_multiline = get_project_pref(auto_continue_multiline);
424 return &eprefs;
428 /* Gets the prefs for the editor.
429 * Prefs can be different according to project or document.
430 * @warning Always get a fresh result instead of keeping a pointer to it if the editor/project
431 * settings may have changed, or if this function has been called for a different editor.
432 * @param editor The editor, or @c NULL to get the default prefs.
433 * @return The prefs. */
434 const GeanyEditorPrefs *editor_get_prefs(GeanyEditor *editor)
436 static GeanyEditorPrefs eprefs;
437 const GeanyEditorPrefs *dprefs = get_default_prefs();
439 /* Return the address of the default prefs to allow returning default and editor
440 * pref pointers without invalidating the contents of either. */
441 if (editor == NULL)
442 return dprefs;
444 eprefs = *dprefs;
445 eprefs.indentation = (GeanyIndentPrefs*)editor_get_indent_prefs(editor);
446 /* add other editor & document overrides as needed */
447 return &eprefs;
451 void editor_toggle_fold(GeanyEditor *editor, gint line, gint modifiers)
453 ScintillaObject *sci;
454 gint header;
456 g_return_if_fail(editor != NULL);
458 sci = editor->sci;
459 /* When collapsing a fold range whose starting line is offscreen,
460 * scroll the starting line to display at the top of the view.
461 * Otherwise it can be confusing when the document scrolls down to hide
462 * the folded lines. */
463 if ((sci_get_fold_level(sci, line) & SC_FOLDLEVELNUMBERMASK) > SC_FOLDLEVELBASE &&
464 !(sci_get_fold_level(sci, line) & SC_FOLDLEVELHEADERFLAG))
466 gint parent = sci_get_fold_parent(sci, line);
467 gint first = sci_get_first_visible_line(sci);
469 parent = SSM(sci, SCI_VISIBLEFROMDOCLINE, parent, 0);
470 if (first > parent)
471 SSM(sci, SCI_SETFIRSTVISIBLELINE, parent, 0);
474 /* find the fold header of the given line in case the one clicked isn't a fold point */
475 if (sci_get_fold_level(sci, line) & SC_FOLDLEVELHEADERFLAG)
476 header = line;
477 else
478 header = sci_get_fold_parent(sci, line);
480 if ((editor_prefs.unfold_all_children && ! (modifiers & SCMOD_SHIFT)) ||
481 (! editor_prefs.unfold_all_children && (modifiers & SCMOD_SHIFT)))
483 SSM(sci, SCI_FOLDCHILDREN, header, SC_FOLDACTION_TOGGLE);
485 else
487 SSM(sci, SCI_FOLDLINE, header, SC_FOLDACTION_TOGGLE);
492 static void on_margin_click(GeanyEditor *editor, SCNotification *nt)
494 /* left click to marker margin marks the line */
495 if (nt->margin == 1)
497 gint line = sci_get_line_from_position(editor->sci, nt->position);
499 /*sci_marker_delete_all(editor->sci, 1);*/
500 sci_toggle_marker_at_line(editor->sci, line, 1); /* toggle the marker */
502 /* left click on the folding margin to toggle folding state of current line */
503 else if (nt->margin == 2 && editor_prefs.folding)
505 gint line = sci_get_line_from_position(editor->sci, nt->position);
506 editor_toggle_fold(editor, line, nt->modifiers);
511 static void on_update_ui(GeanyEditor *editor, G_GNUC_UNUSED SCNotification *nt)
513 ScintillaObject *sci = editor->sci;
514 gint pos = sci_get_current_position(sci);
516 /* since Scintilla 2.24, SCN_UPDATEUI is also sent on scrolling though we don't need to handle
517 * this and so ignore every SCN_UPDATEUI events except for content and selection changes */
518 if (! (nt->updated & SC_UPDATE_CONTENT) && ! (nt->updated & SC_UPDATE_SELECTION))
519 return;
521 /* undo / redo menu update */
522 ui_update_popup_reundo_items(editor->document);
524 /* brace highlighting */
525 editor_highlight_braces(editor, pos);
527 ui_update_statusbar(editor->document, pos);
529 #if 0
530 /** experimental code for inverting selections */
532 gint i;
533 for (i = SSM(sci, SCI_GETSELECTIONSTART, 0, 0); i < SSM(sci, SCI_GETSELECTIONEND, 0, 0); i++)
535 /* need to get colour from getstyleat(), but how? */
536 SSM(sci, SCI_STYLESETFORE, STYLE_DEFAULT, 0);
537 SSM(sci, SCI_STYLESETBACK, STYLE_DEFAULT, 0);
540 sci_get_style_at(sci, pos);
542 #endif
546 static void check_line_breaking(GeanyEditor *editor, gint pos)
548 ScintillaObject *sci = editor->sci;
549 gint line, lstart, col;
550 gchar c;
552 if (!editor->line_breaking)
553 return;
555 col = sci_get_col_from_position(sci, pos);
557 line = sci_get_current_line(sci);
559 lstart = sci_get_position_from_line(sci, line);
561 /* use column instead of position which might be different with multibyte characters */
562 if (col < get_project_pref(line_break_column))
563 return;
565 /* look for the last space before line_break_column */
566 pos = MIN(pos, lstart + get_project_pref(line_break_column));
568 while (pos > lstart)
570 c = sci_get_char_at(sci, --pos);
571 if (c == GDK_space)
573 gint diff, last_pos, last_col;
575 /* remember the distance between the current column and the last column on the line
576 * (we use column position in case the previous line gets altered, such as removing
577 * trailing spaces or in case it contains multibyte characters) */
578 last_pos = sci_get_line_end_position(sci, line);
579 last_col = sci_get_col_from_position(sci, last_pos);
580 diff = last_col - col;
582 /* break the line after the space */
583 sci_set_current_position(sci, pos + 1, FALSE);
584 sci_cancel(sci); /* don't select from completion list */
585 sci_send_command(sci, SCI_NEWLINE);
586 line++;
588 /* correct cursor position (might not be at line end) */
589 last_pos = sci_get_line_end_position(sci, line);
590 last_col = sci_get_col_from_position(sci, last_pos); /* get last column on line */
591 /* last column - distance is the desired column, then retrieve its document position */
592 pos = sci_get_position_from_col(sci, line, last_col - diff);
593 sci_set_current_position(sci, pos, FALSE);
594 sci_scroll_caret(sci);
595 return;
601 static void show_autocomplete(ScintillaObject *sci, gsize rootlen, GString *words)
603 /* hide autocompletion if only option is already typed */
604 if (rootlen >= words->len ||
605 (words->str[rootlen] == '?' && rootlen >= words->len - 2))
607 sci_send_command(sci, SCI_AUTOCCANCEL);
608 return;
610 /* store whether a calltip is showing, so we can reshow it after autocompletion */
611 calltip.set = (gboolean) SSM(sci, SCI_CALLTIPACTIVE, 0, 0);
612 SSM(sci, SCI_AUTOCSHOW, rootlen, (sptr_t) words->str);
616 static void show_tags_list(GeanyEditor *editor, const GPtrArray *tags, gsize rootlen)
618 ScintillaObject *sci = editor->sci;
620 g_return_if_fail(tags);
622 if (tags->len > 0)
624 GString *words = g_string_sized_new(150);
625 guint j;
627 for (j = 0; j < tags->len; ++j)
629 TMTag *tag = tags->pdata[j];
631 if (j > 0)
632 g_string_append_c(words, '\n');
634 if (j == editor_prefs.autocompletion_max_entries)
636 g_string_append(words, "...");
637 break;
639 g_string_append(words, tag->name);
641 /* for now, tag types don't all follow C, so just look at arglist */
642 if (!EMPTY(tag->arglist))
643 g_string_append(words, "?2");
644 else
645 g_string_append(words, "?1");
647 show_autocomplete(sci, rootlen, words);
648 g_string_free(words, TRUE);
653 /* do not use with long strings */
654 static gboolean match_last_chars(ScintillaObject *sci, gint pos, const gchar *str)
656 gsize len = strlen(str);
657 gchar *buf;
659 g_return_val_if_fail(len < 100, FALSE);
660 g_return_val_if_fail((gint)len <= pos, FALSE);
662 buf = g_alloca(len + 1);
663 sci_get_text_range(sci, pos - len, pos, buf);
664 return strcmp(str, buf) == 0;
668 static gboolean reshow_calltip(gpointer data)
670 GeanyDocument *doc;
672 g_return_val_if_fail(calltip.sci != NULL, FALSE);
674 SSM(calltip.sci, SCI_CALLTIPCANCEL, 0, 0);
675 doc = document_get_current();
677 if (doc && doc->editor->sci == calltip.sci)
679 /* we use the position where the calltip was previously started as SCI_GETCURRENTPOS
680 * may be completely wrong in case the user cancelled the auto completion with the mouse */
681 SSM(calltip.sci, SCI_CALLTIPSHOW, calltip.pos, (sptr_t) calltip.text);
683 return FALSE;
687 static void request_reshowing_calltip(SCNotification *nt)
689 if (calltip.set)
691 /* delay the reshow of the calltip window to make sure it is actually displayed,
692 * without it might be not visible on SCN_AUTOCCANCEL. the priority is set to
693 * low to hopefully make Scintilla's events happen before reshowing since they
694 * seem to re-cancel the calltip on autoc menu hiding too */
695 g_idle_add_full(G_PRIORITY_LOW, reshow_calltip, NULL, NULL);
700 static void autocomplete_scope(GeanyEditor *editor)
702 ScintillaObject *sci = editor->sci;
703 gint pos = sci_get_current_position(editor->sci);
704 gchar typed = sci_get_char_at(sci, pos - 1);
705 gchar *name;
706 GeanyFiletype *ft = editor->document->file_type;
707 GPtrArray *tags;
709 if (ft->id == GEANY_FILETYPES_C || ft->id == GEANY_FILETYPES_CPP)
711 if (pos >= 2 && (match_last_chars(sci, pos, "->") || match_last_chars(sci, pos, "::")))
712 pos--;
713 else if (ft->id == GEANY_FILETYPES_CPP && pos >= 3 && match_last_chars(sci, pos, "->*"))
714 pos-=2;
715 else if (typed != '.')
716 return;
718 else if (typed != '.')
719 return;
721 /* allow for a space between word and operator */
722 if (isspace(sci_get_char_at(sci, pos - 2)))
723 pos--;
724 name = editor_get_word_at_pos(editor, pos - 1, NULL);
725 if (!name)
726 return;
728 tags = tm_workspace_find_scope_members(editor->document->tm_file, name);
729 if (tags)
731 show_tags_list(editor, tags, 0);
732 g_ptr_array_free(tags, TRUE);
735 g_free(name);
739 static void on_char_added(GeanyEditor *editor, SCNotification *nt)
741 ScintillaObject *sci = editor->sci;
742 gint pos = sci_get_current_position(sci);
744 switch (nt->ch)
746 case '\r':
747 { /* simple indentation (only for CR format) */
748 if (sci_get_eol_mode(sci) == SC_EOL_CR)
749 on_new_line_added(editor);
750 break;
752 case '\n':
753 { /* simple indentation (for CR/LF and LF format) */
754 on_new_line_added(editor);
755 break;
757 case '>':
758 editor_start_auto_complete(editor, pos, FALSE); /* C/C++ ptr-> scope completion */
759 /* fall through */
760 case '/':
761 { /* close xml-tags */
762 handle_xml(editor, pos, nt->ch);
763 break;
765 case '(':
767 auto_close_chars(sci, pos, nt->ch);
768 /* show calltips */
769 editor_show_calltip(editor, --pos);
770 break;
772 case ')':
773 { /* hide calltips */
774 if (SSM(sci, SCI_CALLTIPACTIVE, 0, 0))
776 SSM(sci, SCI_CALLTIPCANCEL, 0, 0);
778 g_free(calltip.text);
779 calltip.text = NULL;
780 calltip.pos = 0;
781 calltip.sci = NULL;
782 calltip.set = FALSE;
783 break;
785 case '{':
786 case '[':
787 case '"':
788 case '\'':
790 auto_close_chars(sci, pos, nt->ch);
791 break;
793 case '}':
794 { /* closing bracket handling */
795 if (editor->auto_indent)
796 close_block(editor, pos - 1);
797 break;
799 /* scope autocompletion */
800 case '.':
801 case ':': /* C/C++ class:: syntax */
802 /* tag autocompletion */
803 default:
804 #if 0
805 if (! editor_start_auto_complete(editor, pos, FALSE))
806 request_reshowing_calltip(nt);
807 #else
808 editor_start_auto_complete(editor, pos, FALSE);
809 #endif
811 check_line_breaking(editor, pos);
815 /* expand() and fold_changed() are copied from SciTE (thanks) to fix #1923350. */
816 static void expand(ScintillaObject *sci, gint *line, gboolean doExpand,
817 gboolean force, gint visLevels, gint level)
819 gint lineMaxSubord = SSM(sci, SCI_GETLASTCHILD, *line, level & SC_FOLDLEVELNUMBERMASK);
820 gint levelLine = level;
821 (*line)++;
822 while (*line <= lineMaxSubord)
824 if (force)
826 if (visLevels > 0)
827 SSM(sci, SCI_SHOWLINES, *line, *line);
828 else
829 SSM(sci, SCI_HIDELINES, *line, *line);
831 else
833 if (doExpand)
834 SSM(sci, SCI_SHOWLINES, *line, *line);
836 if (levelLine == -1)
837 levelLine = SSM(sci, SCI_GETFOLDLEVEL, *line, 0);
838 if (levelLine & SC_FOLDLEVELHEADERFLAG)
840 if (force)
842 if (visLevels > 1)
843 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
844 else
845 SSM(sci, SCI_SETFOLDEXPANDED, *line, 0);
846 expand(sci, line, doExpand, force, visLevels - 1, -1);
848 else
850 if (doExpand)
852 if (!sci_get_fold_expanded(sci, *line))
853 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
854 expand(sci, line, TRUE, force, visLevels - 1, -1);
856 else
858 expand(sci, line, FALSE, force, visLevels - 1, -1);
862 else
864 (*line)++;
870 static void fold_changed(ScintillaObject *sci, gint line, gint levelNow, gint levelPrev)
872 if (levelNow & SC_FOLDLEVELHEADERFLAG)
874 if (! (levelPrev & SC_FOLDLEVELHEADERFLAG))
876 /* Adding a fold point */
877 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
878 if (!SSM(sci, SCI_GETALLLINESVISIBLE, 0, 0))
879 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
882 else if (levelPrev & SC_FOLDLEVELHEADERFLAG)
884 if (! sci_get_fold_expanded(sci, line))
885 { /* Removing the fold from one that has been contracted so should expand
886 * otherwise lines are left invisible with no way to make them visible */
887 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
888 if (!SSM(sci, SCI_GETALLLINESVISIBLE, 0, 0))
889 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
892 if (! (levelNow & SC_FOLDLEVELWHITEFLAG) &&
893 ((levelPrev & SC_FOLDLEVELNUMBERMASK) > (levelNow & SC_FOLDLEVELNUMBERMASK)))
895 if (!SSM(sci, SCI_GETALLLINESVISIBLE, 0, 0)) {
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);
912 static void ensure_range_visible(ScintillaObject *sci, gint posStart, gint posEnd,
913 gboolean enforcePolicy)
915 gint lineStart = sci_get_line_from_position(sci, MIN(posStart, posEnd));
916 gint lineEnd = sci_get_line_from_position(sci, MAX(posStart, posEnd));
917 gint line;
919 for (line = lineStart; line <= lineEnd; line++)
921 SSM(sci, enforcePolicy ? SCI_ENSUREVISIBLEENFORCEPOLICY : SCI_ENSUREVISIBLE, line, 0);
926 static void auto_update_margin_width(GeanyEditor *editor)
928 gint next_linecount = 1;
929 gint linecount = sci_get_line_count(editor->sci);
930 GeanyDocument *doc = editor->document;
932 while (next_linecount <= linecount)
933 next_linecount *= 10;
935 if (editor->document->priv->line_count != next_linecount)
937 doc->priv->line_count = next_linecount;
938 sci_set_line_numbers(editor->sci, TRUE);
943 static void partial_complete(ScintillaObject *sci, const gchar *text)
945 gint pos = sci_get_current_position(sci);
947 sci_insert_text(sci, pos, text);
948 sci_set_current_position(sci, pos + strlen(text), TRUE);
952 /* Complete the next word part from @a entry */
953 static gboolean check_partial_completion(GeanyEditor *editor, const gchar *entry)
955 gchar *stem, *ptr, *text = utils_strdupa(entry);
957 read_current_word(editor, -1, current_word, sizeof current_word, NULL, TRUE);
958 stem = current_word;
959 if (strstr(text, stem) != text)
960 return FALSE; /* shouldn't happen */
961 if (strlen(text) <= strlen(stem))
962 return FALSE;
964 text += strlen(stem); /* skip stem */
965 ptr = strstr(text + 1, "_");
966 if (ptr)
968 ptr[1] = '\0';
969 partial_complete(editor->sci, text);
970 return TRUE;
972 else
974 /* CamelCase */
975 foreach_str(ptr, text + 1)
977 if (!ptr[0])
978 break;
979 if (g_ascii_isupper(*ptr) && g_ascii_islower(ptr[1]))
981 ptr[0] = '\0';
982 partial_complete(editor->sci, text);
983 return TRUE;
987 return FALSE;
991 /* Callback for the "sci-notify" signal to emit a "editor-notify" signal.
992 * Plugins can connect to the "editor-notify" signal. */
993 void editor_sci_notify_cb(G_GNUC_UNUSED GtkWidget *widget, G_GNUC_UNUSED gint scn,
994 gpointer scnt, gpointer data)
996 GeanyEditor *editor = data;
997 gboolean retval;
999 g_return_if_fail(editor != NULL);
1001 g_signal_emit_by_name(geany_object, "editor-notify", editor, scnt, &retval);
1005 static gboolean on_editor_notify(G_GNUC_UNUSED GObject *object, GeanyEditor *editor,
1006 SCNotification *nt, G_GNUC_UNUSED gpointer data)
1008 ScintillaObject *sci = editor->sci;
1009 GeanyDocument *doc = editor->document;
1011 switch (nt->nmhdr.code)
1013 case SCN_SAVEPOINTLEFT:
1014 document_set_text_changed(doc, TRUE);
1015 break;
1017 case SCN_SAVEPOINTREACHED:
1018 document_set_text_changed(doc, FALSE);
1019 break;
1021 case SCN_MODIFYATTEMPTRO:
1022 utils_beep();
1023 break;
1025 case SCN_MARGINCLICK:
1026 on_margin_click(editor, nt);
1027 break;
1029 case SCN_UPDATEUI:
1030 on_update_ui(editor, nt);
1031 break;
1033 case SCN_PAINTED:
1034 /* Visible lines are only laid out accurately just before painting,
1035 * so we need to only call editor_scroll_to_line here, because the document
1036 * may have line wrapping and folding enabled.
1037 * http://scintilla.sourceforge.net/ScintillaDoc.html#LineWrapping
1038 * This is important e.g. when loading a session and switching pages
1039 * and having the cursor scroll in view. */
1040 /* FIXME: Really we want to do this just before painting, not after it
1041 * as it will cause repainting. */
1042 if (editor->scroll_percent > 0.0F)
1044 editor_scroll_to_line(editor, -1, editor->scroll_percent);
1045 /* disable further scrolling */
1046 editor->scroll_percent = -1.0F;
1048 break;
1050 case SCN_MODIFIED:
1051 if (editor_prefs.show_linenumber_margin && (nt->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT)) && nt->linesAdded)
1053 /* automatically adjust Scintilla's line numbers margin width */
1054 auto_update_margin_width(editor);
1056 if (nt->modificationType & SC_STARTACTION && ! ignore_callback)
1058 /* get notified about undo changes */
1059 document_undo_add(doc, UNDO_SCINTILLA, NULL);
1061 if (editor_prefs.folding && (nt->modificationType & SC_MOD_CHANGEFOLD) != 0)
1063 /* handle special fold cases, e.g. #1923350 */
1064 fold_changed(sci, nt->line, nt->foldLevelNow, nt->foldLevelPrev);
1066 if (nt->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT))
1068 document_update_tag_list_in_idle(doc);
1070 break;
1072 case SCN_CHARADDED:
1073 on_char_added(editor, nt);
1074 break;
1076 case SCN_USERLISTSELECTION:
1077 if (nt->listType == 1)
1079 sci_add_text(sci, nt->text);
1081 break;
1083 case SCN_AUTOCSELECTION:
1084 if (g_str_equal(nt->text, "..."))
1086 sci_cancel(sci);
1087 utils_beep();
1088 break;
1090 /* fall through */
1091 case SCN_AUTOCCANCELLED:
1092 /* now that autocomplete is finishing or was cancelled, reshow calltips
1093 * if they were showing */
1094 request_reshowing_calltip(nt);
1095 break;
1097 #ifdef GEANY_DEBUG
1098 case SCN_STYLENEEDED:
1099 geany_debug("style");
1100 break;
1101 #endif
1102 case SCN_NEEDSHOWN:
1103 ensure_range_visible(sci, nt->position, nt->position + nt->length, FALSE);
1104 break;
1106 case SCN_URIDROPPED:
1107 if (nt->text != NULL)
1109 document_open_file_list(nt->text, strlen(nt->text));
1111 break;
1113 case SCN_CALLTIPCLICK:
1114 if (nt->position > 0)
1116 switch (nt->position)
1118 case 1: /* up arrow */
1119 if (calltip.tag_index > 0)
1120 calltip.tag_index--;
1121 break;
1123 case 2: calltip.tag_index++; break; /* down arrow */
1125 editor_show_calltip(editor, -1);
1127 break;
1129 case SCN_ZOOM:
1130 /* recalculate line margin width */
1131 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin);
1132 break;
1134 /* we always return FALSE here to let plugins handle the event too */
1135 return FALSE;
1139 /* Note: this is the same as sci_get_tab_width(), but is still useful when you don't have
1140 * a scintilla pointer. */
1141 static gint get_tab_width(const GeanyIndentPrefs *indent_prefs)
1143 if (indent_prefs->type == GEANY_INDENT_TYPE_BOTH)
1144 return indent_prefs->hard_tab_width;
1146 return indent_prefs->width; /* tab width = indent width */
1150 /* Returns a string containing width chars of whitespace, filled with simple space
1151 * characters or with the right number of tab characters, according to the indent prefs.
1152 * (Result is filled with tabs *and* spaces if width isn't a multiple of
1153 * the tab width). */
1154 static gchar *
1155 get_whitespace(const GeanyIndentPrefs *iprefs, gint width)
1157 g_return_val_if_fail(width >= 0, NULL);
1159 if (width == 0)
1160 return g_strdup("");
1162 if (iprefs->type == GEANY_INDENT_TYPE_SPACES)
1164 return g_strnfill(width, ' ');
1166 else
1167 { /* first fill text with tabs and fill the rest with spaces */
1168 const gint tab_width = get_tab_width(iprefs);
1169 gint tabs = width / tab_width;
1170 gint spaces = width % tab_width;
1171 gint len = tabs + spaces;
1172 gchar *str;
1174 str = g_malloc(len + 1);
1176 memset(str, '\t', tabs);
1177 memset(str + tabs, ' ', spaces);
1178 str[len] = '\0';
1179 return str;
1184 static const GeanyIndentPrefs *
1185 get_default_indent_prefs(void)
1187 static GeanyIndentPrefs iprefs;
1189 iprefs = app->project ? *app->project->priv->indentation : *editor_prefs.indentation;
1190 return &iprefs;
1194 /** Gets the indentation prefs for the editor.
1195 * Prefs can be different according to project or document.
1196 * @warning Always get a fresh result instead of keeping a pointer to it if the editor/project
1197 * settings may have changed, or if this function has been called for a different editor.
1198 * @param editor The editor, or @c NULL to get the default indent prefs.
1199 * @return The indent prefs. */
1200 GEANY_API_SYMBOL
1201 const GeanyIndentPrefs *
1202 editor_get_indent_prefs(GeanyEditor *editor)
1204 static GeanyIndentPrefs iprefs;
1205 const GeanyIndentPrefs *dprefs = get_default_indent_prefs();
1207 /* Return the address of the default prefs to allow returning default and editor
1208 * pref pointers without invalidating the contents of either. */
1209 if (editor == NULL)
1210 return dprefs;
1212 iprefs = *dprefs;
1213 iprefs.type = editor->indent_type;
1214 iprefs.width = editor->indent_width;
1216 /* if per-document auto-indent is enabled, but we don't have a global mode set,
1217 * just use basic auto-indenting */
1218 if (editor->auto_indent && iprefs.auto_indent_mode == GEANY_AUTOINDENT_NONE)
1219 iprefs.auto_indent_mode = GEANY_AUTOINDENT_BASIC;
1221 if (!editor->auto_indent)
1222 iprefs.auto_indent_mode = GEANY_AUTOINDENT_NONE;
1224 return &iprefs;
1228 static void on_new_line_added(GeanyEditor *editor)
1230 ScintillaObject *sci = editor->sci;
1231 gint line = sci_get_current_line(sci);
1233 /* simple indentation */
1234 if (editor->auto_indent)
1236 insert_indent_after_line(editor, line - 1);
1239 if (get_project_pref(auto_continue_multiline))
1240 { /* " * " auto completion in multiline C/C++/D/Java comments */
1241 auto_multiline(editor, line);
1244 if (editor_prefs.newline_strip)
1245 { /* strip the trailing spaces on the previous line */
1246 editor_strip_line_trailing_spaces(editor, line - 1);
1251 static gboolean lexer_has_braces(ScintillaObject *sci)
1253 gint lexer = sci_get_lexer(sci);
1255 switch (lexer)
1257 case SCLEX_CPP:
1258 case SCLEX_D:
1259 case SCLEX_HTML: /* for PHP & JS */
1260 case SCLEX_PHPSCRIPT:
1261 case SCLEX_PASCAL: /* for multiline comments? */
1262 case SCLEX_BASH:
1263 case SCLEX_PERL:
1264 case SCLEX_TCL:
1265 case SCLEX_R:
1266 case SCLEX_RUST:
1267 return TRUE;
1268 default:
1269 return FALSE;
1274 /* Read indent chars for the line that pos is on into indent global variable.
1275 * Note: Use sci_get_line_indentation() and get_whitespace()/editor_insert_text_block()
1276 * instead in any new code. */
1277 static void read_indent(GeanyEditor *editor, gint pos)
1279 ScintillaObject *sci = editor->sci;
1280 guint i, len, j = 0;
1281 gint line;
1282 gchar *linebuf;
1284 line = sci_get_line_from_position(sci, pos);
1286 len = sci_get_line_length(sci, line);
1287 linebuf = sci_get_line(sci, line);
1289 for (i = 0; i < len && j <= (sizeof(indent) - 1); i++)
1291 if (linebuf[i] == ' ' || linebuf[i] == '\t') /* simple indentation */
1292 indent[j++] = linebuf[i];
1293 else
1294 break;
1296 indent[j] = '\0';
1297 g_free(linebuf);
1301 static gint get_brace_indent(ScintillaObject *sci, gint line)
1303 gint start = sci_get_position_from_line(sci, line);
1304 gint end = sci_get_line_end_position(sci, line) - 1;
1305 gint lexer = sci_get_lexer(sci);
1306 gint count = 0;
1307 gint pos;
1309 for (pos = end; pos >= start && count < 1; pos--)
1311 if (highlighting_is_code_style(lexer, sci_get_style_at(sci, pos)))
1313 gchar c = sci_get_char_at(sci, pos);
1315 if (c == '{')
1316 count ++;
1317 else if (c == '}')
1318 count --;
1322 return count > 0 ? 1 : 0;
1326 /* gets the last code position on a line
1327 * warning: if there is no code position on the line, returns the start position */
1328 static gint get_sci_line_code_end_position(ScintillaObject *sci, gint line)
1330 gint start = sci_get_position_from_line(sci, line);
1331 gint lexer = sci_get_lexer(sci);
1332 gint pos;
1334 for (pos = sci_get_line_end_position(sci, line) - 1; pos > start; pos--)
1336 gint style = sci_get_style_at(sci, pos);
1338 if (highlighting_is_code_style(lexer, style) && ! isspace(sci_get_char_at(sci, pos)))
1339 break;
1342 return pos;
1346 static gint get_python_indent(ScintillaObject *sci, gint line)
1348 gint last_char = get_sci_line_code_end_position(sci, line);
1350 /* add extra indentation for Python after colon */
1351 if (sci_get_char_at(sci, last_char) == ':' &&
1352 sci_get_style_at(sci, last_char) == SCE_P_OPERATOR)
1354 return 1;
1356 return 0;
1360 static gint get_xml_indent(ScintillaObject *sci, gint line)
1362 gboolean need_close = FALSE;
1363 gint end = get_sci_line_code_end_position(sci, line);
1364 gint pos;
1366 /* don't indent if there's a closing tag to the right of the cursor */
1367 pos = sci_get_current_position(sci);
1368 if (sci_get_char_at(sci, pos) == '<' &&
1369 sci_get_char_at(sci, pos + 1) == '/')
1370 return 0;
1372 if (sci_get_char_at(sci, end) == '>' &&
1373 sci_get_char_at(sci, end - 1) != '/')
1375 gint style = sci_get_style_at(sci, end);
1377 if (style == SCE_H_TAG || style == SCE_H_TAGUNKNOWN)
1379 gint start = sci_get_position_from_line(sci, line);
1380 gchar *line_contents = sci_get_contents_range(sci, start, end + 1);
1381 gchar *opened_tag_name = utils_find_open_xml_tag(line_contents, end + 1 - start);
1383 if (!EMPTY(opened_tag_name))
1385 need_close = TRUE;
1386 if (sci_get_lexer(sci) == SCLEX_HTML && utils_is_short_html_tag(opened_tag_name))
1387 need_close = FALSE;
1389 g_free(line_contents);
1390 g_free(opened_tag_name);
1394 return need_close ? 1 : 0;
1398 static gint get_indent_size_after_line(GeanyEditor *editor, gint line)
1400 ScintillaObject *sci = editor->sci;
1401 gint size;
1402 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1404 g_return_val_if_fail(line >= 0, 0);
1406 size = sci_get_line_indentation(sci, line);
1408 if (iprefs->auto_indent_mode > GEANY_AUTOINDENT_BASIC)
1410 gint additional_indent = 0;
1412 if (lexer_has_braces(sci))
1413 additional_indent = iprefs->width * get_brace_indent(sci, line);
1414 else if (sci_get_lexer(sci) == SCLEX_PYTHON) /* Python/Cython */
1415 additional_indent = iprefs->width * get_python_indent(sci, line);
1417 /* HTML lexer "has braces" because of PHP and JavaScript. If get_brace_indent() did not
1418 * recommend us to insert additional indent, we are probably not in PHP/JavaScript chunk and
1419 * should make the XML-related check */
1420 if (additional_indent == 0 &&
1421 (sci_get_lexer(sci) == SCLEX_HTML ||
1422 sci_get_lexer(sci) == SCLEX_XML) &&
1423 editor->document->file_type->priv->xml_indent_tags)
1425 size += iprefs->width * get_xml_indent(sci, line);
1428 size += additional_indent;
1430 return size;
1434 static void insert_indent_after_line(GeanyEditor *editor, gint line)
1436 ScintillaObject *sci = editor->sci;
1437 gint line_indent = sci_get_line_indentation(sci, line);
1438 gint size = get_indent_size_after_line(editor, line);
1439 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1440 gchar *text;
1442 if (size == 0)
1443 return;
1445 if (iprefs->type == GEANY_INDENT_TYPE_TABS && size == line_indent)
1447 /* support tab indents, space aligns style - copy last line 'indent' exactly */
1448 gint start = sci_get_position_from_line(sci, line);
1449 gint end = sci_get_line_indent_position(sci, line);
1451 text = sci_get_contents_range(sci, start, end);
1453 else
1455 text = get_whitespace(iprefs, size);
1457 sci_add_text(sci, text);
1458 g_free(text);
1462 static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c)
1464 const gchar *closing_char = NULL;
1465 gint end_pos = -1;
1467 if (utils_isbrace(c, 0))
1468 end_pos = sci_find_matching_brace(sci, pos - 1);
1470 switch (c)
1472 case '(':
1473 if ((editor_prefs.autoclose_chars & GEANY_AC_PARENTHESIS) && end_pos == -1)
1474 closing_char = ")";
1475 break;
1476 case '{':
1477 if ((editor_prefs.autoclose_chars & GEANY_AC_CBRACKET) && end_pos == -1)
1478 closing_char = "}";
1479 break;
1480 case '[':
1481 if ((editor_prefs.autoclose_chars & GEANY_AC_SBRACKET) && end_pos == -1)
1482 closing_char = "]";
1483 break;
1484 case '\'':
1485 if (editor_prefs.autoclose_chars & GEANY_AC_SQUOTE)
1486 closing_char = "'";
1487 break;
1488 case '"':
1489 if (editor_prefs.autoclose_chars & GEANY_AC_DQUOTE)
1490 closing_char = "\"";
1491 break;
1494 if (closing_char != NULL)
1496 sci_add_text(sci, closing_char);
1497 sci_set_current_position(sci, pos, TRUE);
1502 /* Finds a corresponding matching brace to the given pos
1503 * (this is taken from Scintilla Editor.cxx,
1504 * fit to work with close_block) */
1505 static gint brace_match(ScintillaObject *sci, gint pos)
1507 gchar chBrace = sci_get_char_at(sci, pos);
1508 gchar chSeek = utils_brace_opposite(chBrace);
1509 gchar chAtPos;
1510 gint direction = -1;
1511 gint styBrace;
1512 gint depth = 1;
1513 gint styAtPos;
1515 /* Hack: we need the style at @p pos but it isn't computed yet, so force styling
1516 * of this very position */
1517 sci_colourise(sci, pos, pos + 1);
1519 styBrace = sci_get_style_at(sci, pos);
1521 if (utils_is_opening_brace(chBrace, editor_prefs.brace_match_ltgt))
1522 direction = 1;
1524 pos += direction;
1525 while ((pos >= 0) && (pos < sci_get_length(sci)))
1527 chAtPos = sci_get_char_at(sci, pos);
1528 styAtPos = sci_get_style_at(sci, pos);
1530 if ((pos > sci_get_end_styled(sci)) || (styAtPos == styBrace))
1532 if (chAtPos == chBrace)
1533 depth++;
1534 if (chAtPos == chSeek)
1535 depth--;
1536 if (depth == 0)
1537 return pos;
1539 pos += direction;
1541 return -1;
1545 /* Called after typing '}'. */
1546 static void close_block(GeanyEditor *editor, gint pos)
1548 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1549 gint x = 0, cnt = 0;
1550 gint line, line_len;
1551 gchar *text, *line_buf;
1552 ScintillaObject *sci;
1553 gint line_indent, last_indent;
1555 if (iprefs->auto_indent_mode < GEANY_AUTOINDENT_CURRENTCHARS)
1556 return;
1557 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
1559 sci = editor->sci;
1561 if (! lexer_has_braces(sci))
1562 return;
1564 line = sci_get_line_from_position(sci, pos);
1565 line_len = sci_get_line_end_position(sci, line) - sci_get_position_from_line(sci, line);
1567 /* check that the line is empty, to not kill text in the line */
1568 line_buf = sci_get_line(sci, line);
1569 line_buf[line_len] = '\0';
1570 while (x < line_len)
1572 if (isspace(line_buf[x]))
1573 cnt++;
1574 x++;
1576 g_free(line_buf);
1578 if ((line_len - 1) != cnt)
1579 return;
1581 if (iprefs->auto_indent_mode == GEANY_AUTOINDENT_MATCHBRACES)
1583 gint start_brace = brace_match(sci, pos);
1585 if (start_brace >= 0)
1587 gint line_start;
1588 gint brace_line = sci_get_line_from_position(sci, start_brace);
1589 gint size = sci_get_line_indentation(sci, brace_line);
1590 gchar *ind = get_whitespace(iprefs, size);
1592 text = g_strconcat(ind, "}", NULL);
1593 line_start = sci_get_position_from_line(sci, line);
1594 sci_set_anchor(sci, line_start);
1595 sci_replace_sel(sci, text);
1596 g_free(text);
1597 g_free(ind);
1598 return;
1600 /* fall through - unmatched brace (possibly because of TCL, PHP lexer bugs) */
1603 /* GEANY_AUTOINDENT_CURRENTCHARS */
1604 line_indent = sci_get_line_indentation(sci, line);
1605 last_indent = sci_get_line_indentation(sci, line - 1);
1607 if (line_indent < last_indent)
1608 return;
1609 line_indent -= iprefs->width;
1610 line_indent = MAX(0, line_indent);
1611 sci_set_line_indentation(sci, line, line_indent);
1615 /* checks whether @p c is an ASCII character (e.g. < 0x80) */
1616 #define IS_ASCII(c) (((unsigned char)(c)) < 0x80)
1619 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1620 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1621 * position can be -1, then the current position is used.
1622 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1623 static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen,
1624 const gchar *wc, gboolean stem)
1626 gint line, line_start, startword, endword;
1627 gchar *chunk;
1628 ScintillaObject *sci;
1630 g_return_if_fail(editor != NULL);
1631 sci = editor->sci;
1633 if (pos == -1)
1634 pos = sci_get_current_position(sci);
1636 line = sci_get_line_from_position(sci, pos);
1637 line_start = sci_get_position_from_line(sci, line);
1638 startword = pos - line_start;
1639 endword = pos - line_start;
1641 word[0] = '\0';
1642 chunk = sci_get_line(sci, line);
1644 if (wc == NULL)
1645 wc = GEANY_WORDCHARS;
1647 /* the checks for "c < 0" are to allow any Unicode character which should make the code
1648 * a little bit more Unicode safe, anyway, this allows also any Unicode punctuation,
1649 * TODO: improve this code */
1650 while (startword > 0 && (strchr(wc, chunk[startword - 1]) || ! IS_ASCII(chunk[startword - 1])))
1651 startword--;
1652 if (!stem)
1654 while (chunk[endword] != 0 && (strchr(wc, chunk[endword]) || ! IS_ASCII(chunk[endword])))
1655 endword++;
1658 if (startword != endword)
1660 chunk[endword] = '\0';
1662 g_strlcpy(word, chunk + startword, wordlen); /* ensure null terminated */
1664 else
1665 g_strlcpy(word, "", wordlen);
1667 g_free(chunk);
1671 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1672 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1673 * position can be -1, then the current position is used.
1674 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1675 void editor_find_current_word(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen,
1676 const gchar *wc)
1678 read_current_word(editor, pos, word, wordlen, wc, FALSE);
1682 /* Same as editor_find_current_word() but uses editor's word boundaries to decide what the word
1683 * is. This should be used e.g. to get the word to search for */
1684 void editor_find_current_word_sciwc(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen)
1686 gint start;
1687 gint end;
1689 g_return_if_fail(editor != NULL);
1691 if (pos == -1)
1692 pos = sci_get_current_position(editor->sci);
1694 start = sci_word_start_position(editor->sci, pos, TRUE);
1695 end = sci_word_end_position(editor->sci, pos, TRUE);
1697 if (start == end) /* caret in whitespaces sequence */
1698 *word = 0;
1699 else
1701 if ((guint)(end - start) >= wordlen)
1702 end = start + (wordlen - 1);
1703 sci_get_text_range(editor->sci, start, end, word);
1709 * Finds the word at the position specified by @a pos. If any word is found, it is returned.
1710 * Otherwise NULL is returned.
1711 * Additional wordchars can be specified to define what to consider as a word.
1713 * @param editor The editor to operate on.
1714 * @param pos The position where the word should be read from.
1715 * May be @c -1 to use the current position.
1716 * @param wordchars The wordchars to separate words. wordchars mean all characters to count
1717 * as part of a word. May be @c NULL to use the default wordchars,
1718 * see @ref GEANY_WORDCHARS.
1720 * @return A newly-allocated string containing the word at the given @a pos or @c NULL.
1721 * Should be freed when no longer needed.
1723 * @since 0.16
1725 GEANY_API_SYMBOL
1726 gchar *editor_get_word_at_pos(GeanyEditor *editor, gint pos, const gchar *wordchars)
1728 static gchar cword[GEANY_MAX_WORD_LENGTH];
1730 g_return_val_if_fail(editor != NULL, FALSE);
1732 read_current_word(editor, pos, cword, sizeof(cword), wordchars, FALSE);
1734 return (*cword == '\0') ? NULL : g_strdup(cword);
1738 /* Read the word up to position @a pos. */
1739 static const gchar *
1740 editor_read_word_stem(GeanyEditor *editor, gint pos, const gchar *wordchars)
1742 static gchar word[GEANY_MAX_WORD_LENGTH];
1744 read_current_word(editor, pos, word, sizeof word, wordchars, TRUE);
1746 return (*word) ? word : NULL;
1750 static gint find_previous_brace(ScintillaObject *sci, gint pos)
1752 gint orig_pos = pos;
1754 while (pos >= 0 && pos > orig_pos - 300)
1756 gchar c = sci_get_char_at(sci, pos);
1757 if (utils_is_opening_brace(c, editor_prefs.brace_match_ltgt))
1758 return pos;
1759 pos--;
1761 return -1;
1765 static gint find_start_bracket(ScintillaObject *sci, gint pos)
1767 gint brackets = 0;
1768 gint orig_pos = pos;
1770 while (pos > 0 && pos > orig_pos - 300)
1772 gchar c = sci_get_char_at(sci, pos);
1774 if (c == ')') brackets++;
1775 else if (c == '(') brackets--;
1776 if (brackets < 0) return pos; /* found start bracket */
1777 pos--;
1779 return -1;
1783 static gboolean append_calltip(GString *str, const TMTag *tag, filetype_id ft_id)
1785 if (! tag->arglist)
1786 return FALSE;
1788 if (ft_id != GEANY_FILETYPES_PASCAL && ft_id != GEANY_FILETYPES_GO)
1789 { /* usual calltips: "retval tagname (arglist)" */
1790 if (tag->var_type)
1792 guint i;
1794 g_string_append(str, tag->var_type);
1795 for (i = 0; i < tag->pointerOrder; i++)
1797 g_string_append_c(str, '*');
1799 g_string_append_c(str, ' ');
1801 if (tag->scope)
1803 const gchar *cosep = symbols_get_context_separator(ft_id);
1805 g_string_append(str, tag->scope);
1806 g_string_append(str, cosep);
1808 g_string_append(str, tag->name);
1809 g_string_append_c(str, ' ');
1810 g_string_append(str, tag->arglist);
1812 else
1813 { /* special case Pascal/Go calltips: "tagname (arglist) : retval"
1814 * (with ':' omitted for Go) */
1815 g_string_append(str, tag->name);
1816 g_string_append_c(str, ' ');
1817 g_string_append(str, tag->arglist);
1819 if (!EMPTY(tag->var_type))
1821 g_string_append(str, ft_id == GEANY_FILETYPES_PASCAL ? " : " : " ");
1822 g_string_append(str, tag->var_type);
1826 return TRUE;
1830 static gchar *find_calltip(const gchar *word, GeanyFiletype *ft)
1832 GPtrArray *tags;
1833 const TMTagType arg_types = tm_tag_function_t | tm_tag_prototype_t |
1834 tm_tag_method_t | tm_tag_macro_with_arg_t;
1835 TMTagAttrType *attrs = NULL;
1836 TMTag *tag;
1837 GString *str = NULL;
1838 guint i;
1840 g_return_val_if_fail(ft && word && *word, NULL);
1842 /* use all types in case language uses wrong tag type e.g. python "members" instead of "methods" */
1843 tags = tm_workspace_find(word, NULL, tm_tag_max_t, attrs, FALSE, ft->lang);
1844 if (tags->len == 0)
1846 g_ptr_array_free(tags, TRUE);
1847 return NULL;
1850 tag = TM_TAG(tags->pdata[0]);
1852 if (ft->id == GEANY_FILETYPES_D &&
1853 (tag->type == tm_tag_class_t || tag->type == tm_tag_struct_t))
1855 g_ptr_array_free(tags, TRUE);
1856 /* user typed e.g. 'new Classname(' so lookup D constructor Classname::this() */
1857 tags = tm_workspace_find("this", tag->name,
1858 arg_types, attrs, FALSE, ft->lang);
1859 if (tags->len == 0)
1861 g_ptr_array_free(tags, TRUE);
1862 return NULL;
1866 /* remove tags with no argument list */
1867 for (i = 0; i < tags->len; i++)
1869 tag = TM_TAG(tags->pdata[i]);
1871 if (! tag->arglist)
1872 tags->pdata[i] = NULL;
1874 tm_tags_prune((GPtrArray *) tags);
1875 if (tags->len == 0)
1877 g_ptr_array_free(tags, TRUE);
1878 return NULL;
1880 else
1881 { /* remove duplicate calltips */
1882 TMTagAttrType sort_attr[] = {tm_tag_attr_name_t, tm_tag_attr_scope_t,
1883 tm_tag_attr_arglist_t, 0};
1885 tm_tags_sort((GPtrArray *) tags, sort_attr, TRUE, FALSE);
1888 /* if the current word has changed since last time, start with the first tag match */
1889 if (! utils_str_equal(word, calltip.last_word))
1890 calltip.tag_index = 0;
1891 /* cache the current word for next time */
1892 g_free(calltip.last_word);
1893 calltip.last_word = g_strdup(word);
1894 calltip.tag_index = MIN(calltip.tag_index, tags->len - 1); /* ensure tag_index is in range */
1896 for (i = calltip.tag_index; i < tags->len; i++)
1898 tag = TM_TAG(tags->pdata[i]);
1900 if (str == NULL)
1902 str = g_string_new(NULL);
1903 if (calltip.tag_index > 0)
1904 g_string_prepend(str, "\001 "); /* up arrow */
1905 append_calltip(str, tag, FILETYPE_ID(ft));
1907 else /* add a down arrow */
1909 if (calltip.tag_index > 0) /* already have an up arrow */
1910 g_string_insert_c(str, 1, '\002');
1911 else
1912 g_string_prepend(str, "\002 ");
1913 break;
1917 g_ptr_array_free(tags, TRUE);
1919 if (str)
1921 gchar *result = str->str;
1923 g_string_free(str, FALSE);
1924 return result;
1926 return NULL;
1930 /* use pos = -1 to search for the previous unmatched open bracket. */
1931 gboolean editor_show_calltip(GeanyEditor *editor, gint pos)
1933 gint orig_pos = pos; /* the position for the calltip */
1934 gint lexer;
1935 gint style;
1936 gchar word[GEANY_MAX_WORD_LENGTH];
1937 gchar *str;
1938 ScintillaObject *sci;
1940 g_return_val_if_fail(editor != NULL, FALSE);
1941 g_return_val_if_fail(editor->document->file_type != NULL, FALSE);
1943 sci = editor->sci;
1945 lexer = sci_get_lexer(sci);
1947 if (pos == -1)
1949 /* position of '(' is unknown, so go backwards from current position to find it */
1950 pos = sci_get_current_position(sci);
1951 pos--;
1952 orig_pos = pos;
1953 pos = (lexer == SCLEX_LATEX) ? find_previous_brace(sci, pos) :
1954 find_start_bracket(sci, pos);
1955 if (pos == -1)
1956 return FALSE;
1959 /* the style 1 before the brace (which may be highlighted) */
1960 style = sci_get_style_at(sci, pos - 1);
1961 if (! highlighting_is_code_style(lexer, style))
1962 return FALSE;
1964 word[0] = '\0';
1965 editor_find_current_word(editor, pos - 1, word, sizeof word, NULL);
1966 if (word[0] == '\0')
1967 return FALSE;
1969 str = find_calltip(word, editor->document->file_type);
1970 if (str)
1972 g_free(calltip.text); /* free the old calltip */
1973 calltip.text = str;
1974 calltip.pos = orig_pos;
1975 calltip.sci = sci;
1976 calltip.set = TRUE;
1977 utils_wrap_string(calltip.text, -1);
1978 SSM(sci, SCI_CALLTIPSHOW, orig_pos, (sptr_t) calltip.text);
1979 return TRUE;
1981 return FALSE;
1985 gchar *editor_get_calltip_text(GeanyEditor *editor, const TMTag *tag)
1987 GString *str;
1989 g_return_val_if_fail(editor != NULL, NULL);
1991 str = g_string_new(NULL);
1992 if (append_calltip(str, tag, editor->document->file_type->id))
1993 return g_string_free(str, FALSE);
1994 else
1995 return g_string_free(str, TRUE);
1999 /* HTML entities auto completion from html_entities.tags text file */
2000 static gboolean
2001 autocomplete_html(ScintillaObject *sci, const gchar *root, gsize rootlen)
2003 guint i;
2004 gboolean found = FALSE;
2005 GString *words;
2006 const gchar **entities = symbols_get_html_entities();
2008 if (*root != '&' || entities == NULL)
2009 return FALSE;
2011 words = g_string_sized_new(500);
2012 for (i = 0; ; i++)
2014 if (entities[i] == NULL)
2015 break;
2016 else if (entities[i][0] == '#')
2017 continue;
2019 if (! strncmp(entities[i], root, rootlen))
2021 if (words->len)
2022 g_string_append_c(words, '\n');
2024 g_string_append(words, entities[i]);
2025 found = TRUE;
2028 if (found)
2029 show_autocomplete(sci, rootlen, words);
2031 g_string_free(words, TRUE);
2032 return found;
2036 /* Current document & global tags autocompletion */
2037 static gboolean
2038 autocomplete_tags(GeanyEditor *editor, const gchar *root, gsize rootlen)
2040 TMTagAttrType attrs[] = { tm_tag_attr_name_t, 0 };
2041 GPtrArray *tags;
2042 GeanyDocument *doc;
2043 gboolean found;
2045 g_return_val_if_fail(editor, FALSE);
2047 doc = editor->document;
2049 tags = tm_workspace_find(root, NULL, tm_tag_max_t, attrs, TRUE, doc->file_type->lang);
2050 found = tags->len > 0;
2051 if (found)
2052 show_tags_list(editor, tags, rootlen);
2053 g_ptr_array_free(tags, TRUE);
2055 return found;
2059 static gboolean autocomplete_check_html(GeanyEditor *editor, gint style, gint pos)
2061 GeanyFiletype *ft = editor->document->file_type;
2062 gboolean try = FALSE;
2064 /* use entity completion when style is not JavaScript, ASP, Python, PHP, ...
2065 * (everything after SCE_HJ_START is for embedded scripting languages) */
2066 if (ft->id == GEANY_FILETYPES_HTML && style < SCE_HJ_START)
2067 try = TRUE;
2068 else if (sci_get_lexer(editor->sci) == SCLEX_XML && style < SCE_HJ_START)
2069 try = TRUE;
2070 else if (ft->id == GEANY_FILETYPES_PHP)
2072 /* use entity completion when style is outside of PHP styles */
2073 if (! is_style_php(style))
2074 try = TRUE;
2076 if (try)
2078 gchar root[GEANY_MAX_WORD_LENGTH];
2079 gchar *tmp;
2081 read_current_word(editor, pos, root, sizeof(root), GEANY_WORDCHARS"&", TRUE);
2083 /* Allow something like "&quot;some text&quot;".
2084 * for entity completion we want to have completion for '&' within words. */
2085 tmp = strchr(root, '&');
2086 if (tmp != NULL)
2088 return autocomplete_html(editor->sci, tmp, strlen(tmp));
2091 return FALSE;
2095 /* Algorithm based on based on Scite's StartAutoCompleteWord()
2096 * @returns a sorted list of words matching @p root */
2097 static GSList *get_doc_words(ScintillaObject *sci, gchar *root, gsize rootlen)
2099 gchar *word;
2100 gint len, current, word_end;
2101 gint pos_find, flags;
2102 guint word_length;
2103 gsize nmatches = 0;
2104 GSList *words = NULL;
2105 struct Sci_TextToFind ttf;
2107 len = sci_get_length(sci);
2108 current = sci_get_current_position(sci) - rootlen;
2110 ttf.lpstrText = root;
2111 ttf.chrg.cpMin = 0;
2112 ttf.chrg.cpMax = len;
2113 ttf.chrgText.cpMin = 0;
2114 ttf.chrgText.cpMax = 0;
2115 flags = SCFIND_WORDSTART | SCFIND_MATCHCASE;
2117 /* search the whole document for the word root and collect results */
2118 pos_find = scintilla_send_message(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
2119 while (pos_find >= 0 && pos_find < len)
2121 word_end = pos_find + rootlen;
2122 if (pos_find != current)
2124 word_end = sci_word_end_position(sci, word_end, TRUE);
2126 word_length = word_end - pos_find;
2127 if (word_length > rootlen)
2129 word = sci_get_contents_range(sci, pos_find, word_end);
2130 /* search whether we already have the word in, otherwise add it */
2131 if (g_slist_find_custom(words, word, (GCompareFunc)strcmp) != NULL)
2132 g_free(word);
2133 else
2135 words = g_slist_prepend(words, word);
2136 nmatches++;
2139 if (nmatches == editor_prefs.autocompletion_max_entries)
2140 break;
2143 ttf.chrg.cpMin = word_end;
2144 pos_find = scintilla_send_message(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
2147 return g_slist_sort(words, (GCompareFunc)utils_str_casecmp);
2151 static gboolean autocomplete_doc_word(GeanyEditor *editor, gchar *root, gsize rootlen)
2153 ScintillaObject *sci = editor->sci;
2154 GSList *words, *node;
2155 GString *str;
2156 guint n_words = 0;
2158 words = get_doc_words(sci, root, rootlen);
2159 if (!words)
2161 scintilla_send_message(sci, SCI_AUTOCCANCEL, 0, 0);
2162 return FALSE;
2165 str = g_string_sized_new(rootlen * 2 * 10);
2166 foreach_slist(node, words)
2168 g_string_append(str, node->data);
2169 g_free(node->data);
2170 if (node->next)
2171 g_string_append_c(str, '\n');
2172 n_words++;
2174 if (n_words >= editor_prefs.autocompletion_max_entries)
2175 g_string_append(str, "\n...");
2177 g_slist_free(words);
2179 show_autocomplete(sci, rootlen, str);
2180 g_string_free(str, TRUE);
2181 return TRUE;
2185 gboolean editor_start_auto_complete(GeanyEditor *editor, gint pos, gboolean force)
2187 gint rootlen, lexer, style;
2188 gchar *root;
2189 gchar cword[GEANY_MAX_WORD_LENGTH];
2190 ScintillaObject *sci;
2191 gboolean ret = FALSE;
2192 const gchar *wordchars;
2193 GeanyFiletype *ft;
2195 g_return_val_if_fail(editor != NULL, FALSE);
2197 if (! editor_prefs.auto_complete_symbols && ! force)
2198 return FALSE;
2200 /* If we are at the beginning of the document, we skip autocompletion as we can't determine the
2201 * necessary styling information */
2202 if (G_UNLIKELY(pos < 2))
2203 return FALSE;
2205 sci = editor->sci;
2206 ft = editor->document->file_type;
2208 lexer = sci_get_lexer(sci);
2209 style = sci_get_style_at(sci, pos - 2);
2211 /* don't autocomplete in comments and strings */
2212 if (!force && !highlighting_is_code_style(lexer, style))
2213 return FALSE;
2215 autocomplete_scope(editor);
2216 ret = autocomplete_check_html(editor, style, pos);
2218 if (ft->id == GEANY_FILETYPES_LATEX)
2219 wordchars = GEANY_WORDCHARS"\\"; /* add \ to word chars if we are in a LaTeX file */
2220 else if (ft->id == GEANY_FILETYPES_CSS)
2221 wordchars = GEANY_WORDCHARS"-"; /* add - because they are part of property names */
2222 else
2223 wordchars = GEANY_WORDCHARS;
2225 read_current_word(editor, pos, cword, sizeof(cword), wordchars, TRUE);
2226 root = cword;
2227 rootlen = strlen(root);
2229 if (!ret && rootlen > 0)
2231 if (ft->id == GEANY_FILETYPES_PHP && style == SCE_HPHP_DEFAULT &&
2232 rootlen == 3 && strcmp(root, "php") == 0 && pos >= 5 &&
2233 sci_get_char_at(sci, pos - 5) == '<' &&
2234 sci_get_char_at(sci, pos - 4) == '?')
2236 /* nothing, don't complete PHP open tags */
2238 else
2240 /* force is set when called by keyboard shortcut, otherwise start at the
2241 * editor_prefs.symbolcompletion_min_chars'th char */
2242 if (force || rootlen >= editor_prefs.symbolcompletion_min_chars)
2244 /* complete tags, except if forcing when completion is already visible */
2245 if (!(force && SSM(sci, SCI_AUTOCACTIVE, 0, 0)))
2246 ret = autocomplete_tags(editor, root, rootlen);
2248 /* If forcing and there's nothing else to show, complete from words in document */
2249 if (!ret && (force || editor_prefs.autocomplete_doc_words))
2250 ret = autocomplete_doc_word(editor, root, rootlen);
2254 if (!ret && force)
2255 utils_beep();
2257 return ret;
2261 static const gchar *snippets_find_completion_by_name(const gchar *type, const gchar *name)
2263 gchar *result = NULL;
2264 GHashTable *tmp;
2266 g_return_val_if_fail(type != NULL && name != NULL, NULL);
2268 tmp = g_hash_table_lookup(snippet_hash, type);
2269 if (tmp != NULL)
2271 result = g_hash_table_lookup(tmp, name);
2273 /* whether nothing is set for the current filetype(tmp is NULL) or
2274 * the particular completion for this filetype is not set (result is NULL) */
2275 if (tmp == NULL || result == NULL)
2277 tmp = g_hash_table_lookup(snippet_hash, "Default");
2278 if (tmp != NULL)
2280 result = g_hash_table_lookup(tmp, name);
2283 /* if result is still NULL here, no completion could be found */
2285 /* result is owned by the hash table and will be freed when the table will destroyed */
2286 return result;
2290 static void snippets_replace_specials(gpointer key, gpointer value, gpointer user_data)
2292 gchar *needle;
2293 GString *pattern = user_data;
2295 g_return_if_fail(key != NULL);
2296 g_return_if_fail(value != NULL);
2298 needle = g_strconcat("%", (gchar*) key, "%", NULL);
2300 utils_string_replace_all(pattern, needle, (gchar*) value);
2301 g_free(needle);
2305 static void fix_indentation(GeanyEditor *editor, GString *buf)
2307 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
2308 gchar *whitespace;
2309 GRegex *regex;
2310 gint cflags = G_REGEX_MULTILINE;
2312 /* transform leading tabs into indent widths (in spaces) */
2313 whitespace = g_strnfill(iprefs->width, ' ');
2314 regex = g_regex_new("^ *(\t)", cflags, 0, NULL);
2315 while (utils_string_regex_replace_all(buf, regex, 1, whitespace, TRUE));
2316 g_regex_unref(regex);
2318 /* remaining tabs are for alignment */
2319 if (iprefs->type != GEANY_INDENT_TYPE_TABS)
2320 utils_string_replace_all(buf, "\t", whitespace);
2322 /* use leading tabs */
2323 if (iprefs->type != GEANY_INDENT_TYPE_SPACES)
2325 gchar *str;
2327 /* for tabs+spaces mode we want the real tab width, not indent width */
2328 SETPTR(whitespace, g_strnfill(sci_get_tab_width(editor->sci), ' '));
2329 str = g_strdup_printf("^\t*(%s)", whitespace);
2331 regex = g_regex_new(str, cflags, 0, NULL);
2332 while (utils_string_regex_replace_all(buf, regex, 1, "\t", TRUE));
2333 g_regex_unref(regex);
2334 g_free(str);
2336 g_free(whitespace);
2340 /** Inserts text, replacing \\t tab chars (@c 0x9) and \\n newline chars (@c 0xA)
2341 * accordingly for the document.
2342 * - Leading tabs are replaced with the correct indentation.
2343 * - Non-leading tabs are replaced with spaces (except when using 'Tabs' indent type).
2344 * - Newline chars are replaced with the correct line ending string.
2345 * This is very useful for inserting code without having to handle the indent
2346 * type yourself (Tabs & Spaces mode can be tricky).
2347 * @param editor Editor.
2348 * @param text Intended as e.g. @c "if (foo)\n\tbar();".
2349 * @param insert_pos Document position to insert text at.
2350 * @param cursor_index If >= 0, the index into @a text to place the cursor.
2351 * @param newline_indent_size Indentation size (in spaces) to insert for each newline; use
2352 * -1 to read the indent size from the line with @a insert_pos on it.
2353 * @param replace_newlines Whether to replace newlines. If
2354 * newlines have been replaced already, this should be false, to avoid errors e.g. on Windows.
2355 * @warning Make sure all \\t tab chars in @a text are intended as indent widths or alignment,
2356 * not hard tabs, as those won't be preserved.
2357 * @note This doesn't scroll the cursor in view afterwards. **/
2358 GEANY_API_SYMBOL
2359 void editor_insert_text_block(GeanyEditor *editor, const gchar *text, gint insert_pos,
2360 gint cursor_index, gint newline_indent_size, gboolean replace_newlines)
2362 ScintillaObject *sci = editor->sci;
2363 gint line_start = sci_get_line_from_position(sci, insert_pos);
2364 GString *buf;
2365 const gchar *eol = editor_get_eol_char(editor);
2366 gint idx;
2368 g_return_if_fail(text);
2369 g_return_if_fail(editor != NULL);
2370 g_return_if_fail(insert_pos >= 0);
2372 buf = g_string_new(text);
2374 if (cursor_index >= 0)
2375 g_string_insert(buf, cursor_index, geany_cursor_marker); /* remember cursor pos */
2377 if (newline_indent_size == -1)
2379 /* count indent size up to insert_pos instead of asking sci
2380 * because there may be spaces after it */
2381 gchar *tmp = sci_get_line(sci, line_start);
2383 idx = insert_pos - sci_get_position_from_line(sci, line_start);
2384 tmp[idx] = '\0';
2385 newline_indent_size = count_indent_size(editor, tmp);
2386 g_free(tmp);
2389 /* Add line indents (in spaces) */
2390 if (newline_indent_size > 0)
2392 const gchar *nl = replace_newlines ? "\n" : eol;
2393 gchar *whitespace;
2395 whitespace = g_strnfill(newline_indent_size, ' ');
2396 SETPTR(whitespace, g_strconcat(nl, whitespace, NULL));
2397 utils_string_replace_all(buf, nl, whitespace);
2398 g_free(whitespace);
2401 /* transform line endings */
2402 if (replace_newlines)
2403 utils_string_replace_all(buf, "\n", eol);
2405 fix_indentation(editor, buf);
2407 idx = replace_cursor_markers(editor, buf);
2408 if (idx >= 0)
2410 sci_insert_text(sci, insert_pos, buf->str);
2411 sci_set_current_position(sci, insert_pos + idx, FALSE);
2413 else
2414 sci_insert_text(sci, insert_pos, buf->str);
2416 snippet_cursor_insert_pos = sci_get_current_position(sci);
2418 g_string_free(buf, TRUE);
2422 /* Move the cursor to the next specified cursor position in an inserted snippet.
2423 * Can, and should, be optimized to give better results */
2424 void editor_goto_next_snippet_cursor(GeanyEditor *editor)
2426 ScintillaObject *sci = editor->sci;
2427 gint current_pos = sci_get_current_position(sci);
2429 if (snippet_offsets && !g_queue_is_empty(snippet_offsets))
2431 gint offset;
2433 offset = GPOINTER_TO_INT(g_queue_pop_head(snippet_offsets));
2434 if (current_pos > snippet_cursor_insert_pos)
2435 snippet_cursor_insert_pos = offset + current_pos;
2436 else
2437 snippet_cursor_insert_pos += offset;
2439 sci_set_current_position(sci, snippet_cursor_insert_pos, TRUE);
2441 else
2443 utils_beep();
2448 static void snippets_make_replacements(GeanyEditor *editor, GString *pattern)
2450 GHashTable *specials;
2452 /* replace 'special' completions */
2453 specials = g_hash_table_lookup(snippet_hash, "Special");
2454 if (G_LIKELY(specials != NULL))
2456 g_hash_table_foreach(specials, snippets_replace_specials, pattern);
2459 /* now transform other wildcards */
2460 utils_string_replace_all(pattern, "%newline%", "\n");
2461 utils_string_replace_all(pattern, "%ws%", "\t");
2463 /* replace %cursor% by a very unlikely string marker */
2464 utils_string_replace_all(pattern, "%cursor%", geany_cursor_marker);
2466 /* unescape '%' after all %wildcards% */
2467 templates_replace_valist(pattern, "{pc}", "%", NULL);
2469 /* replace any template {foo} wildcards */
2470 templates_replace_common(pattern, editor->document->file_name, editor->document->file_type, NULL);
2474 static gssize replace_cursor_markers(GeanyEditor *editor, GString *pattern)
2476 gssize cur_index = -1;
2477 gint i;
2478 GList *temp_list = NULL;
2479 gint cursor_steps = 0, old_cursor = 0;
2481 i = 0;
2482 while (1)
2484 cursor_steps = utils_string_find(pattern, cursor_steps, -1, geany_cursor_marker);
2485 if (cursor_steps == -1)
2486 break;
2488 g_string_erase(pattern, cursor_steps, strlen(geany_cursor_marker));
2490 if (i++ > 0)
2492 /* save the relative offset to each cursor position */
2493 temp_list = g_list_prepend(temp_list, GINT_TO_POINTER(cursor_steps - old_cursor));
2495 else
2497 /* first cursor already includes newline positions */
2498 cur_index = cursor_steps;
2500 old_cursor = cursor_steps;
2503 /* put the cursor positions for the most recent
2504 * parsed snippet first, followed by any remaining positions */
2505 i = 0;
2506 if (temp_list)
2508 GList *node;
2510 temp_list = g_list_reverse(temp_list);
2511 foreach_list(node, temp_list)
2512 g_queue_push_nth(snippet_offsets, node->data, i++);
2514 /* limit length of queue */
2515 while (g_queue_get_length(snippet_offsets) > 20)
2516 g_queue_pop_tail(snippet_offsets);
2518 g_list_free(temp_list);
2520 /* if there's no first cursor, skip whole snippet */
2521 if (cur_index < 0)
2522 cur_index = pattern->len;
2524 return cur_index;
2528 static gboolean snippets_complete_constructs(GeanyEditor *editor, gint pos, const gchar *word)
2530 ScintillaObject *sci = editor->sci;
2531 gchar *str;
2532 const gchar *completion;
2533 gint str_len;
2534 gint ft_id = editor->document->file_type->id;
2536 str = g_strdup(word);
2537 g_strstrip(str);
2539 completion = snippets_find_completion_by_name(filetypes[ft_id]->name, str);
2540 if (completion == NULL)
2542 g_free(str);
2543 return FALSE;
2546 /* remove the typed word, it will be added again by the used auto completion
2547 * (not really necessary but this makes the auto completion more flexible,
2548 * e.g. with a completion like hi=hello, so typing "hi<TAB>" will result in "hello") */
2549 str_len = strlen(str);
2550 sci_set_selection_start(sci, pos - str_len);
2551 sci_set_selection_end(sci, pos);
2552 sci_replace_sel(sci, "");
2553 pos -= str_len; /* pos has changed while deleting */
2555 editor_insert_snippet(editor, pos, completion);
2556 sci_scroll_caret(sci);
2558 g_free(str);
2559 return TRUE;
2563 static gboolean at_eol(ScintillaObject *sci, gint pos)
2565 gint line = sci_get_line_from_position(sci, pos);
2566 gchar c;
2568 /* skip any trailing spaces */
2569 while (TRUE)
2571 c = sci_get_char_at(sci, pos);
2572 if (c == ' ' || c == '\t')
2573 pos++;
2574 else
2575 break;
2578 return (pos == sci_get_line_end_position(sci, line));
2582 gboolean editor_complete_snippet(GeanyEditor *editor, gint pos)
2584 gboolean result = FALSE;
2585 const gchar *wc;
2586 const gchar *word;
2587 ScintillaObject *sci;
2589 g_return_val_if_fail(editor != NULL, FALSE);
2591 sci = editor->sci;
2592 if (sci_has_selection(sci))
2593 return FALSE;
2594 /* return if we are editing an existing line (chars on right of cursor) */
2595 if (keybindings_lookup_item(GEANY_KEY_GROUP_EDITOR,
2596 GEANY_KEYS_EDITOR_COMPLETESNIPPET)->key == GDK_space &&
2597 ! editor_prefs.complete_snippets_whilst_editing && ! at_eol(sci, pos))
2598 return FALSE;
2600 wc = snippets_find_completion_by_name("Special", "wordchars");
2601 word = editor_read_word_stem(editor, pos, wc);
2603 /* prevent completion of "for " */
2604 if (!EMPTY(word) &&
2605 ! isspace(sci_get_char_at(sci, pos - 1))) /* pos points to the line end char so use pos -1 */
2607 sci_start_undo_action(sci); /* needed because we insert a space separately from construct */
2608 result = snippets_complete_constructs(editor, pos, word);
2609 sci_end_undo_action(sci);
2610 if (result)
2611 sci_cancel(sci); /* cancel any autocompletion list, etc */
2613 return result;
2617 static void insert_closing_tag(GeanyEditor *editor, gint pos, gchar ch, const gchar *tag_name)
2619 ScintillaObject *sci = editor->sci;
2620 gchar *to_insert = NULL;
2622 if (ch == '/')
2624 const gchar *gt = ">";
2625 /* if there is already a '>' behind the cursor, don't add it */
2626 if (sci_get_char_at(sci, pos) == '>')
2627 gt = "";
2629 to_insert = g_strconcat(tag_name, gt, NULL);
2631 else
2632 to_insert = g_strconcat("</", tag_name, ">", NULL);
2634 sci_start_undo_action(sci);
2635 sci_replace_sel(sci, to_insert);
2636 if (ch == '>')
2637 sci_set_selection(sci, pos, pos);
2638 sci_end_undo_action(sci);
2639 g_free(to_insert);
2644 * (stolen from anjuta and heavily modified)
2645 * This routine will auto complete XML or HTML tags that are still open by closing them
2646 * @param ch The character we are dealing with, currently only works with the '>' character
2647 * @return True if handled, false otherwise
2649 static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch)
2651 ScintillaObject *sci = editor->sci;
2652 gint lexer = sci_get_lexer(sci);
2653 gint min, size, style;
2654 gchar *str_found, sel[512];
2655 gboolean result = FALSE;
2657 /* If the user has turned us off, quit now.
2658 * This may make sense only in certain languages */
2659 if (! editor_prefs.auto_close_xml_tags || (lexer != SCLEX_HTML && lexer != SCLEX_XML))
2660 return FALSE;
2662 /* return if we are inside any embedded script */
2663 style = sci_get_style_at(sci, pos);
2664 if (style > SCE_H_XCCOMMENT && ! highlighting_is_string_style(lexer, style))
2665 return FALSE;
2667 /* if ch is /, check for </, else quit */
2668 if (ch == '/' && sci_get_char_at(sci, pos - 2) != '<')
2669 return FALSE;
2671 /* Grab the last 512 characters or so */
2672 min = pos - (sizeof(sel) - 1);
2673 if (min < 0) min = 0;
2675 if (pos - min < 3)
2676 return FALSE; /* Smallest tag is 3 characters e.g. <p> */
2678 sci_get_text_range(sci, min, pos, sel);
2679 sel[sizeof(sel) - 1] = '\0';
2681 if (ch == '>' && sel[pos - min - 2] == '/')
2682 /* User typed something like "<br/>" */
2683 return FALSE;
2685 size = pos - min;
2686 if (ch == '/')
2687 size -= 2; /* skip </ */
2688 str_found = utils_find_open_xml_tag(sel, size);
2690 if (lexer == SCLEX_HTML && utils_is_short_html_tag(str_found))
2692 /* ignore tag */
2694 else if (!EMPTY(str_found))
2696 insert_closing_tag(editor, pos, ch, str_found);
2697 result = TRUE;
2699 g_free(str_found);
2700 return result;
2704 /* like sci_get_line_indentation(), but for a string. */
2705 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent)
2707 const gchar *ptr;
2708 gsize tab_size = sci_get_tab_width(editor->sci);
2709 gsize count = 0;
2711 g_return_val_if_fail(base_indent, 0);
2713 for (ptr = base_indent; *ptr != 0; ptr++)
2715 switch (*ptr)
2717 case ' ':
2718 count++;
2719 break;
2720 case '\t':
2721 count += tab_size;
2722 break;
2723 default:
2724 return count;
2727 return count;
2731 /* Handles special cases where HTML is embedded in another language or
2732 * another language is embedded in HTML */
2733 static GeanyFiletype *editor_get_filetype_at_line(GeanyEditor *editor, gint line)
2735 gint style, line_start;
2736 GeanyFiletype *current_ft;
2738 g_return_val_if_fail(editor != NULL, NULL);
2739 g_return_val_if_fail(editor->document->file_type != NULL, NULL);
2741 current_ft = editor->document->file_type;
2742 line_start = sci_get_position_from_line(editor->sci, line);
2743 style = sci_get_style_at(editor->sci, line_start);
2745 /* Handle PHP filetype with embedded HTML */
2746 if (current_ft->id == GEANY_FILETYPES_PHP && ! is_style_php(style))
2747 current_ft = filetypes[GEANY_FILETYPES_HTML];
2749 /* Handle languages embedded in HTML */
2750 if (current_ft->id == GEANY_FILETYPES_HTML)
2752 /* Embedded JS */
2753 if (style >= SCE_HJ_DEFAULT && style <= SCE_HJ_REGEX)
2754 current_ft = filetypes[GEANY_FILETYPES_JS];
2755 /* ASP JS */
2756 else if (style >= SCE_HJA_DEFAULT && style <= SCE_HJA_REGEX)
2757 current_ft = filetypes[GEANY_FILETYPES_JS];
2758 /* Embedded VB */
2759 else if (style >= SCE_HB_DEFAULT && style <= SCE_HB_STRINGEOL)
2760 current_ft = filetypes[GEANY_FILETYPES_BASIC];
2761 /* ASP VB */
2762 else if (style >= SCE_HBA_DEFAULT && style <= SCE_HBA_STRINGEOL)
2763 current_ft = filetypes[GEANY_FILETYPES_BASIC];
2764 /* Embedded Python */
2765 else if (style >= SCE_HP_DEFAULT && style <= SCE_HP_IDENTIFIER)
2766 current_ft = filetypes[GEANY_FILETYPES_PYTHON];
2767 /* ASP Python */
2768 else if (style >= SCE_HPA_DEFAULT && style <= SCE_HPA_IDENTIFIER)
2769 current_ft = filetypes[GEANY_FILETYPES_PYTHON];
2770 /* Embedded PHP */
2771 else if ((style >= SCE_HPHP_DEFAULT && style <= SCE_HPHP_OPERATOR) ||
2772 style == SCE_HPHP_COMPLEX_VARIABLE)
2774 current_ft = filetypes[GEANY_FILETYPES_PHP];
2778 /* Ensure the filetype's config is loaded */
2779 filetypes_load_config(current_ft->id, FALSE);
2781 return current_ft;
2785 static void real_comment_multiline(GeanyEditor *editor, gint line_start, gint last_line)
2787 const gchar *eol;
2788 gchar *str_begin, *str_end;
2789 const gchar *co, *cc;
2790 gint line_len;
2791 GeanyFiletype *ft;
2793 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2795 ft = editor_get_filetype_at_line(editor, line_start);
2797 eol = editor_get_eol_char(editor);
2798 if (! filetype_get_comment_open_close(ft, FALSE, &co, &cc))
2799 g_return_if_reached();
2800 str_begin = g_strdup_printf("%s%s", (co != NULL) ? co : "", eol);
2801 str_end = g_strdup_printf("%s%s", (cc != NULL) ? cc : "", eol);
2803 /* insert the comment strings */
2804 sci_insert_text(editor->sci, line_start, str_begin);
2805 line_len = sci_get_position_from_line(editor->sci, last_line + 2);
2806 sci_insert_text(editor->sci, line_len, str_end);
2808 g_free(str_begin);
2809 g_free(str_end);
2813 /* find @p text inside the range of the current style */
2814 static gint find_in_current_style(ScintillaObject *sci, const gchar *text, gboolean backwards)
2816 gint start = sci_get_current_position(sci);
2817 gint end = start;
2818 gint len = sci_get_length(sci);
2819 gint current_style = sci_get_style_at(sci, start);
2820 struct Sci_TextToFind ttf;
2822 while (start > 0 && sci_get_style_at(sci, start - 1) == current_style)
2823 start -= 1;
2824 while (end < len && sci_get_style_at(sci, end + 1) == current_style)
2825 end += 1;
2827 ttf.lpstrText = (gchar*) text;
2828 ttf.chrg.cpMin = backwards ? end + 1 : start;
2829 ttf.chrg.cpMax = backwards ? start : end + 1;
2830 return sci_find_text(sci, 0, &ttf);
2834 static void sci_delete_line(ScintillaObject *sci, gint line)
2836 gint start = sci_get_position_from_line(sci, line);
2837 gint len = sci_get_line_length(sci, line);
2838 SSM(sci, SCI_DELETERANGE, start, len);
2842 static gboolean real_uncomment_multiline(GeanyEditor *editor)
2844 /* find the beginning of the multi line comment */
2845 gint start, end, start_line, end_line;
2846 GeanyFiletype *ft;
2847 const gchar *co, *cc;
2849 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, FALSE);
2851 ft = editor_get_filetype_at_line(editor, sci_get_current_line(editor->sci));
2852 if (! filetype_get_comment_open_close(ft, FALSE, &co, &cc))
2853 g_return_val_if_reached(FALSE);
2855 start = find_in_current_style(editor->sci, co, TRUE);
2856 end = find_in_current_style(editor->sci, cc, FALSE);
2858 if (start < 0 || end < 0 || start > end /* who knows */)
2859 return FALSE;
2861 start_line = sci_get_line_from_position(editor->sci, start);
2862 end_line = sci_get_line_from_position(editor->sci, end);
2864 /* remove comment close chars */
2865 SSM(editor->sci, SCI_DELETERANGE, end, strlen(cc));
2866 if (sci_is_blank_line(editor->sci, end_line))
2867 sci_delete_line(editor->sci, end_line);
2869 /* remove comment open chars (do it last since it would move the end position) */
2870 SSM(editor->sci, SCI_DELETERANGE, start, strlen(co));
2871 if (sci_is_blank_line(editor->sci, start_line))
2872 sci_delete_line(editor->sci, start_line);
2874 return TRUE;
2878 static gint get_multiline_comment_style(GeanyEditor *editor, gint line_start)
2880 gint lexer = sci_get_lexer(editor->sci);
2881 gint style_comment;
2883 /* List only those lexers which support multi line comments */
2884 switch (lexer)
2886 case SCLEX_XML:
2887 case SCLEX_HTML:
2888 case SCLEX_PHPSCRIPT:
2890 if (is_style_php(sci_get_style_at(editor->sci, line_start)))
2891 style_comment = SCE_HPHP_COMMENT;
2892 else
2893 style_comment = SCE_H_COMMENT;
2894 break;
2896 case SCLEX_HASKELL:
2897 case SCLEX_LITERATEHASKELL:
2898 style_comment = SCE_HA_COMMENTBLOCK; break;
2899 case SCLEX_LUA: style_comment = SCE_LUA_COMMENT; break;
2900 case SCLEX_CSS: style_comment = SCE_CSS_COMMENT; break;
2901 case SCLEX_SQL: style_comment = SCE_SQL_COMMENT; break;
2902 case SCLEX_CAML: style_comment = SCE_CAML_COMMENT; break;
2903 case SCLEX_D: style_comment = SCE_D_COMMENT; break;
2904 case SCLEX_PASCAL: style_comment = SCE_PAS_COMMENT; break;
2905 case SCLEX_RUST: style_comment = SCE_RUST_COMMENTBLOCK; break;
2906 default: style_comment = SCE_C_COMMENT;
2909 return style_comment;
2913 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise
2914 * returns the amount of uncommented single comment lines, in case of multi line uncomment
2915 * it returns just 1 */
2916 gint editor_do_uncomment(GeanyEditor *editor, gint line, gboolean toggle)
2918 gint first_line, last_line;
2919 gint x, i, line_start, line_len;
2920 gint sel_start, sel_end;
2921 gint count = 0;
2922 gsize co_len;
2923 gchar sel[256];
2924 const gchar *co, *cc;
2925 gboolean single_line = FALSE;
2926 GeanyFiletype *ft;
2928 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, 0);
2930 if (line < 0)
2931 { /* use selection or current line */
2932 sel_start = sci_get_selection_start(editor->sci);
2933 sel_end = sci_get_selection_end(editor->sci);
2935 first_line = sci_get_line_from_position(editor->sci, sel_start);
2936 /* Find the last line with chars selected (not EOL char) */
2937 last_line = sci_get_line_from_position(editor->sci,
2938 sel_end - editor_get_eol_char_len(editor));
2939 last_line = MAX(first_line, last_line);
2941 else
2943 first_line = last_line = line;
2944 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
2947 ft = editor_get_filetype_at_line(editor, first_line);
2949 if (! filetype_get_comment_open_close(ft, TRUE, &co, &cc))
2950 return 0;
2952 co_len = strlen(co);
2953 if (co_len == 0)
2954 return 0;
2956 sci_start_undo_action(editor->sci);
2958 for (i = first_line; i <= last_line; i++)
2960 gint buf_len;
2962 line_start = sci_get_position_from_line(editor->sci, i);
2963 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
2964 x = 0;
2966 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
2967 if (buf_len <= 0)
2968 continue;
2969 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
2970 sel[buf_len] = '\0';
2972 while (isspace(sel[x])) x++;
2974 /* to skip blank lines */
2975 if (x < line_len && sel[x] != '\0')
2977 /* use single line comment */
2978 if (EMPTY(cc))
2980 single_line = TRUE;
2982 if (toggle)
2984 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
2985 if (strncmp(sel + x, co, co_len) != 0 ||
2986 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) != 0)
2987 continue;
2989 co_len += tm_len;
2991 else
2993 if (strncmp(sel + x, co, co_len) != 0)
2994 continue;
2997 sci_set_selection(editor->sci, line_start + x, line_start + x + co_len);
2998 sci_replace_sel(editor->sci, "");
2999 count++;
3001 /* use multi line comment */
3002 else
3004 gint style_comment;
3006 /* skip lines which are already comments */
3007 style_comment = get_multiline_comment_style(editor, line_start);
3008 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3010 if (real_uncomment_multiline(editor))
3011 count = 1;
3014 /* break because we are already on the last line */
3015 break;
3019 sci_end_undo_action(editor->sci);
3021 /* restore selection if there is one
3022 * but don't touch the selection if caller is editor_do_comment_toggle */
3023 if (! toggle && sel_start < sel_end)
3025 if (single_line)
3027 sci_set_selection_start(editor->sci, sel_start - co_len);
3028 sci_set_selection_end(editor->sci, sel_end - (count * co_len));
3030 else
3032 gint eol_len = editor_get_eol_char_len(editor);
3033 sci_set_selection_start(editor->sci, sel_start - co_len - eol_len);
3034 sci_set_selection_end(editor->sci, sel_end - co_len - eol_len);
3038 return count;
3042 void editor_do_comment_toggle(GeanyEditor *editor)
3044 gint first_line, last_line;
3045 gint x, i, line_start, line_len, first_line_start, last_line_start;
3046 gint sel_start, sel_end;
3047 gint count_commented = 0, count_uncommented = 0;
3048 gchar sel[256];
3049 const gchar *co, *cc;
3050 gboolean break_loop = FALSE, single_line = FALSE;
3051 gboolean first_line_was_comment = FALSE;
3052 gboolean last_line_was_comment = FALSE;
3053 gsize co_len;
3054 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
3055 GeanyFiletype *ft;
3057 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
3059 sel_start = sci_get_selection_start(editor->sci);
3060 sel_end = sci_get_selection_end(editor->sci);
3062 first_line = sci_get_line_from_position(editor->sci, sel_start);
3063 /* Find the last line with chars selected (not EOL char) */
3064 last_line = sci_get_line_from_position(editor->sci,
3065 sel_end - editor_get_eol_char_len(editor));
3066 last_line = MAX(first_line, last_line);
3068 first_line_start = sci_get_position_from_line(editor->sci, first_line);
3069 last_line_start = sci_get_position_from_line(editor->sci, last_line);
3071 ft = editor_get_filetype_at_line(editor, first_line);
3073 if (! filetype_get_comment_open_close(ft, TRUE, &co, &cc))
3074 return;
3076 co_len = strlen(co);
3077 if (co_len == 0)
3078 return;
3080 sci_start_undo_action(editor->sci);
3082 for (i = first_line; (i <= last_line) && (! break_loop); i++)
3084 gint buf_len;
3086 line_start = sci_get_position_from_line(editor->sci, i);
3087 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
3088 x = 0;
3090 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
3091 if (buf_len < 0)
3092 continue;
3093 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3094 sel[buf_len] = '\0';
3096 while (isspace(sel[x])) x++;
3098 /* use single line comment */
3099 if (EMPTY(cc))
3101 gboolean do_continue = FALSE;
3102 single_line = TRUE;
3104 if (strncmp(sel + x, co, co_len) == 0 &&
3105 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) == 0)
3107 do_continue = TRUE;
3110 if (do_continue && i == first_line)
3111 first_line_was_comment = TRUE;
3112 last_line_was_comment = do_continue;
3114 if (do_continue)
3116 count_uncommented += editor_do_uncomment(editor, i, TRUE);
3117 continue;
3120 /* we are still here, so the above lines were not already comments, so comment it */
3121 count_commented += editor_do_comment(editor, i, FALSE, TRUE, TRUE);
3123 /* use multi line comment */
3124 else
3126 gint style_comment;
3128 /* skip lines which are already comments */
3129 style_comment = get_multiline_comment_style(editor, line_start);
3130 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3132 if (real_uncomment_multiline(editor))
3133 count_uncommented++;
3135 else
3137 real_comment_multiline(editor, line_start, last_line);
3138 count_commented++;
3141 /* break because we are already on the last line */
3142 break_loop = TRUE;
3143 break;
3147 sci_end_undo_action(editor->sci);
3149 co_len += tm_len;
3151 /* restore selection or caret position */
3152 if (single_line)
3154 gint a = (first_line_was_comment) ? - (gint) co_len : (gint) co_len;
3155 gint indent_len;
3157 /* don't modify sel_start when the selection starts within indentation */
3158 read_indent(editor, sel_start);
3159 indent_len = (gint) strlen(indent);
3160 if ((sel_start - first_line_start) <= indent_len)
3161 a = 0;
3162 /* if the selection start was inside the comment mark, adjust the position */
3163 else if (first_line_was_comment &&
3164 sel_start >= (first_line_start + indent_len) &&
3165 sel_start <= (first_line_start + indent_len + (gint) co_len))
3167 a = (first_line_start + indent_len) - sel_start;
3170 if (sel_start < sel_end)
3172 gint b = (count_commented * (gint) co_len) - (count_uncommented * (gint) co_len);
3174 /* same for selection end, but here we add an offset on the offset above */
3175 read_indent(editor, sel_end + b);
3176 indent_len = (gint) strlen(indent);
3177 if ((sel_end - last_line_start) < indent_len)
3178 b += last_line_was_comment ? (gint) co_len : -(gint) co_len;
3179 else if (last_line_was_comment &&
3180 sel_end >= (last_line_start + indent_len) &&
3181 sel_end <= (last_line_start + indent_len + (gint) co_len))
3183 b += (gint) co_len - (sel_end - (last_line_start + indent_len));
3186 sci_set_selection_start(editor->sci, sel_start + a);
3187 sci_set_selection_end(editor->sci, sel_end + b);
3189 else
3190 sci_set_current_position(editor->sci, sel_start + a, TRUE);
3192 else
3194 gint eol_len = editor_get_eol_char_len(editor);
3195 if (count_uncommented > 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 else if (count_commented > 0)
3202 sci_set_selection_start(editor->sci, sel_start + (gint) co_len - eol_len);
3203 sci_set_selection_end(editor->sci, sel_end + (gint) co_len - eol_len);
3205 if (sel_start >= sel_end)
3206 sci_scroll_caret(editor->sci);
3211 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise */
3212 gint editor_do_comment(GeanyEditor *editor, gint line, gboolean allow_empty_lines, gboolean toggle,
3213 gboolean single_comment)
3215 gint first_line, last_line;
3216 gint x, i, line_start, line_len;
3217 gint sel_start, sel_end, co_len;
3218 gint count = 0;
3219 gchar sel[256];
3220 const gchar *co, *cc;
3221 gboolean break_loop = FALSE, single_line = FALSE;
3222 GeanyFiletype *ft;
3224 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, 0);
3226 if (line < 0)
3227 { /* use selection or current line */
3228 sel_start = sci_get_selection_start(editor->sci);
3229 sel_end = sci_get_selection_end(editor->sci);
3231 first_line = sci_get_line_from_position(editor->sci, sel_start);
3232 /* Find the last line with chars selected (not EOL char) */
3233 last_line = sci_get_line_from_position(editor->sci,
3234 sel_end - editor_get_eol_char_len(editor));
3235 last_line = MAX(first_line, last_line);
3237 else
3239 first_line = last_line = line;
3240 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
3243 ft = editor_get_filetype_at_line(editor, first_line);
3245 if (! filetype_get_comment_open_close(ft, single_comment, &co, &cc))
3246 return 0;
3248 co_len = strlen(co);
3249 if (co_len == 0)
3250 return 0;
3252 sci_start_undo_action(editor->sci);
3254 for (i = first_line; (i <= last_line) && (! break_loop); i++)
3256 gint buf_len;
3258 line_start = sci_get_position_from_line(editor->sci, i);
3259 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
3260 x = 0;
3262 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
3263 if (buf_len < 0)
3264 continue;
3265 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3266 sel[buf_len] = '\0';
3268 while (isspace(sel[x])) x++;
3270 /* to skip blank lines */
3271 if (allow_empty_lines || (x < line_len && sel[x] != '\0'))
3273 /* use single line comment */
3274 if (EMPTY(cc))
3276 gint start = line_start;
3277 single_line = TRUE;
3279 if (ft->comment_use_indent)
3280 start = line_start + x;
3282 if (toggle)
3284 gchar *text = g_strconcat(co, editor_prefs.comment_toggle_mark, NULL);
3285 sci_insert_text(editor->sci, start, text);
3286 g_free(text);
3288 else
3289 sci_insert_text(editor->sci, start, co);
3290 count++;
3292 /* use multi line comment */
3293 else
3295 gint style_comment;
3297 /* skip lines which are already comments */
3298 style_comment = get_multiline_comment_style(editor, line_start);
3299 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3300 continue;
3302 real_comment_multiline(editor, line_start, last_line);
3303 count = 1;
3305 /* break because we are already on the last line */
3306 break_loop = TRUE;
3307 break;
3311 sci_end_undo_action(editor->sci);
3313 /* restore selection if there is one
3314 * but don't touch the selection if caller is editor_do_comment_toggle */
3315 if (! toggle && sel_start < sel_end)
3317 if (single_line)
3319 sci_set_selection_start(editor->sci, sel_start + co_len);
3320 sci_set_selection_end(editor->sci, sel_end + (count * co_len));
3322 else
3324 gint eol_len = editor_get_eol_char_len(editor);
3325 sci_set_selection_start(editor->sci, sel_start + co_len + eol_len);
3326 sci_set_selection_end(editor->sci, sel_end + co_len + eol_len);
3329 return count;
3333 static gboolean brace_timeout_active = FALSE;
3335 static gboolean delay_match_brace(G_GNUC_UNUSED gpointer user_data)
3337 GeanyDocument *doc = document_get_current();
3338 GeanyEditor *editor;
3339 gint brace_pos = GPOINTER_TO_INT(user_data);
3340 gint end_pos, cur_pos;
3342 brace_timeout_active = FALSE;
3343 if (!doc)
3344 return FALSE;
3346 editor = doc->editor;
3347 cur_pos = sci_get_current_position(editor->sci) - 1;
3349 if (cur_pos != brace_pos)
3351 cur_pos++;
3352 if (cur_pos != brace_pos)
3354 /* we have moved past the original brace_pos, but after the timeout
3355 * we may now be on a new brace, so check again */
3356 editor_highlight_braces(editor, cur_pos);
3357 return FALSE;
3360 if (!utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3362 editor_highlight_braces(editor, cur_pos);
3363 return FALSE;
3365 end_pos = sci_find_matching_brace(editor->sci, brace_pos);
3367 if (end_pos >= 0)
3369 gint col = MIN(sci_get_col_from_position(editor->sci, brace_pos),
3370 sci_get_col_from_position(editor->sci, end_pos));
3371 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, col, 0);
3372 SSM(editor->sci, SCI_BRACEHIGHLIGHT, brace_pos, end_pos);
3374 else
3376 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3377 SSM(editor->sci, SCI_BRACEBADLIGHT, brace_pos, 0);
3379 return FALSE;
3383 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos)
3385 gint brace_pos = cur_pos - 1;
3387 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3388 SSM(editor->sci, SCI_BRACEBADLIGHT, (uptr_t)-1, 0);
3390 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3392 brace_pos++;
3393 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3395 return;
3398 if (!brace_timeout_active)
3400 brace_timeout_active = TRUE;
3401 /* delaying matching makes scrolling faster e.g. holding down arrow keys */
3402 g_timeout_add(100, delay_match_brace, GINT_TO_POINTER(brace_pos));
3407 static gboolean in_block_comment(gint lexer, gint style)
3409 switch (lexer)
3411 case SCLEX_COBOL:
3412 case SCLEX_CPP:
3413 return (style == SCE_C_COMMENT ||
3414 style == SCE_C_COMMENTDOC);
3416 case SCLEX_PASCAL:
3417 return (style == SCE_PAS_COMMENT ||
3418 style == SCE_PAS_COMMENT2);
3420 case SCLEX_D:
3421 return (style == SCE_D_COMMENT ||
3422 style == SCE_D_COMMENTDOC ||
3423 style == SCE_D_COMMENTNESTED);
3425 case SCLEX_HTML:
3426 case SCLEX_PHPSCRIPT:
3427 return (style == SCE_HPHP_COMMENT);
3429 case SCLEX_CSS:
3430 return (style == SCE_CSS_COMMENT);
3432 case SCLEX_RUST:
3433 return (style == SCE_RUST_COMMENTBLOCK ||
3434 style == SCE_RUST_COMMENTBLOCKDOC);
3436 default:
3437 return FALSE;
3442 static gboolean is_comment_char(gchar c, gint lexer)
3444 if ((c == '*' || c == '+') && lexer == SCLEX_D)
3445 return TRUE;
3446 else
3447 if (c == '*')
3448 return TRUE;
3450 return FALSE;
3454 static void auto_multiline(GeanyEditor *editor, gint cur_line)
3456 ScintillaObject *sci = editor->sci;
3457 gint indent_pos, style;
3458 gint lexer = sci_get_lexer(sci);
3460 /* Use the start of the line enter was pressed on, to avoid any doc keyword styles */
3461 indent_pos = sci_get_line_indent_position(sci, cur_line - 1);
3462 style = sci_get_style_at(sci, indent_pos);
3463 if (!in_block_comment(lexer, style))
3464 return;
3466 /* Check whether the comment block continues on this line */
3467 indent_pos = sci_get_line_indent_position(sci, cur_line);
3468 if (sci_get_style_at(sci, indent_pos) == style || indent_pos >= sci_get_length(sci))
3470 gchar *previous_line = sci_get_line(sci, cur_line - 1);
3471 /* the type of comment, '*' (C/C++/Java), '+' and the others (D) */
3472 const gchar *continuation = "*";
3473 const gchar *whitespace = ""; /* to hold whitespace if needed */
3474 gchar *result;
3475 gint len = strlen(previous_line);
3476 gint i;
3478 /* find and stop at end of multi line comment */
3479 i = len - 1;
3480 while (i >= 0 && isspace(previous_line[i])) i--;
3481 if (i >= 1 && is_comment_char(previous_line[i - 1], lexer) && previous_line[i] == '/')
3483 gint indent_len, indent_width;
3485 indent_pos = sci_get_line_indent_position(sci, cur_line);
3486 indent_len = sci_get_col_from_position(sci, indent_pos);
3487 indent_width = editor_get_indent_prefs(editor)->width;
3489 /* if there is one too many spaces, delete the last space,
3490 * to return to the indent used before the multiline comment was started. */
3491 if (indent_len % indent_width == 1)
3492 SSM(sci, SCI_DELETEBACKNOTLINE, 0, 0); /* remove whitespace indent */
3493 g_free(previous_line);
3494 return;
3496 /* check whether we are on the second line of multi line comment */
3497 i = 0;
3498 while (i < len && isspace(previous_line[i])) i++; /* get to start of the line */
3500 if (i + 1 < len &&
3501 previous_line[i] == '/' && is_comment_char(previous_line[i + 1], lexer))
3502 { /* we are on the second line of a multi line comment, so we have to insert white space */
3503 whitespace = " ";
3506 if (style == SCE_D_COMMENTNESTED)
3507 continuation = "+"; /* for nested comments in D */
3509 result = g_strconcat(whitespace, continuation, " ", NULL);
3510 sci_add_text(sci, result);
3511 g_free(result);
3513 g_free(previous_line);
3518 #if 0
3519 static gboolean editor_lexer_is_c_like(gint lexer)
3521 switch (lexer)
3523 case SCLEX_CPP:
3524 case SCLEX_D:
3525 return TRUE;
3527 default:
3528 return FALSE;
3531 #endif
3534 /* inserts a three-line comment at one line above current cursor position */
3535 void editor_insert_multiline_comment(GeanyEditor *editor)
3537 gchar *text;
3538 gint text_len;
3539 gint line;
3540 gint pos;
3541 gboolean have_multiline_comment = FALSE;
3542 GeanyDocument *doc;
3543 const gchar *co, *cc;
3545 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
3547 if (! filetype_get_comment_open_close(editor->document->file_type, FALSE, &co, &cc))
3548 g_return_if_reached();
3549 if (!EMPTY(cc))
3550 have_multiline_comment = TRUE;
3552 sci_start_undo_action(editor->sci);
3554 doc = editor->document;
3556 /* insert three lines one line above of the current position */
3557 line = sci_get_line_from_position(editor->sci, editor_info.click_pos);
3558 pos = sci_get_position_from_line(editor->sci, line);
3560 /* use the indent on the current line but only when comment indentation is used
3561 * and we don't have multi line comment characters */
3562 if (editor->auto_indent &&
3563 ! have_multiline_comment && doc->file_type->comment_use_indent)
3565 read_indent(editor, editor_info.click_pos);
3566 text = g_strdup_printf("%s\n%s\n%s\n", indent, indent, indent);
3567 text_len = strlen(text);
3569 else
3571 text = g_strdup("\n\n\n");
3572 text_len = 3;
3574 sci_insert_text(editor->sci, pos, text);
3575 g_free(text);
3577 /* select the inserted lines for commenting */
3578 sci_set_selection_start(editor->sci, pos);
3579 sci_set_selection_end(editor->sci, pos + text_len);
3581 editor_do_comment(editor, -1, TRUE, FALSE, FALSE);
3583 /* set the current position to the start of the first inserted line */
3584 pos += strlen(co);
3586 /* on multi line comment jump to the next line, otherwise add the length of added indentation */
3587 if (have_multiline_comment)
3588 pos += 1;
3589 else
3590 pos += strlen(indent);
3592 sci_set_current_position(editor->sci, pos, TRUE);
3593 /* reset the selection */
3594 sci_set_anchor(editor->sci, pos);
3596 sci_end_undo_action(editor->sci);
3600 /* Note: If the editor is pending a redraw, set document::scroll_percent instead.
3601 * Scroll the view to make line appear at percent_of_view.
3602 * line can be -1 to use the current position. */
3603 void editor_scroll_to_line(GeanyEditor *editor, gint line, gfloat percent_of_view)
3605 gint los;
3606 GtkWidget *wid;
3608 g_return_if_fail(editor != NULL);
3610 wid = GTK_WIDGET(editor->sci);
3612 if (! gtk_widget_get_window(wid) || ! gdk_window_is_viewable(gtk_widget_get_window(wid)))
3613 return; /* prevent gdk_window_scroll warning */
3615 if (line == -1)
3616 line = sci_get_current_line(editor->sci);
3618 /* sci 'visible line' != doc line number because of folding and line wrapping */
3619 /* calling SCI_VISIBLEFROMDOCLINE for line is more accurate than calling
3620 * SCI_DOCLINEFROMVISIBLE for vis1. */
3621 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0);
3622 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
3623 line = line - los * percent_of_view;
3624 SSM(editor->sci, SCI_SETFIRSTVISIBLELINE, line, 0);
3625 sci_scroll_caret(editor->sci); /* needed for horizontal scrolling */
3629 /* creates and inserts one tab or whitespace of the amount of the tab width */
3630 void editor_insert_alternative_whitespace(GeanyEditor *editor)
3632 gchar *text;
3633 GeanyIndentPrefs iprefs = *editor_get_indent_prefs(editor);
3635 g_return_if_fail(editor != NULL);
3637 switch (iprefs.type)
3639 case GEANY_INDENT_TYPE_TABS:
3640 iprefs.type = GEANY_INDENT_TYPE_SPACES;
3641 break;
3642 case GEANY_INDENT_TYPE_SPACES:
3643 case GEANY_INDENT_TYPE_BOTH: /* most likely we want a tab */
3644 iprefs.type = GEANY_INDENT_TYPE_TABS;
3645 break;
3647 text = get_whitespace(&iprefs, iprefs.width);
3648 sci_add_text(editor->sci, text);
3649 g_free(text);
3653 void editor_select_word(GeanyEditor *editor)
3655 gint pos;
3656 gint start;
3657 gint end;
3659 g_return_if_fail(editor != NULL);
3661 pos = SSM(editor->sci, SCI_GETCURRENTPOS, 0, 0);
3662 start = sci_word_start_position(editor->sci, pos, TRUE);
3663 end = sci_word_end_position(editor->sci, pos, TRUE);
3665 if (start == end) /* caret in whitespaces sequence */
3667 /* look forward but reverse the selection direction,
3668 * so the caret end up stay as near as the original position. */
3669 end = sci_word_end_position(editor->sci, pos, FALSE);
3670 start = sci_word_end_position(editor->sci, end, TRUE);
3671 if (start == end)
3672 return;
3675 sci_set_selection(editor->sci, start, end);
3679 /* extra_line is for selecting the cursor line (or anchor line) at the bottom of a selection,
3680 * when those lines have no selection (cursor at start of line). */
3681 void editor_select_lines(GeanyEditor *editor, gboolean extra_line)
3683 gint start, end, line;
3685 g_return_if_fail(editor != NULL);
3687 start = sci_get_selection_start(editor->sci);
3688 end = sci_get_selection_end(editor->sci);
3690 /* check if whole lines are already selected */
3691 if (! extra_line && start != end &&
3692 sci_get_col_from_position(editor->sci, start) == 0 &&
3693 sci_get_col_from_position(editor->sci, end) == 0)
3694 return;
3696 line = sci_get_line_from_position(editor->sci, start);
3697 start = sci_get_position_from_line(editor->sci, line);
3699 line = sci_get_line_from_position(editor->sci, end);
3700 end = sci_get_position_from_line(editor->sci, line + 1);
3702 sci_set_selection(editor->sci, start, end);
3706 static gboolean sci_is_blank_line(ScintillaObject *sci, gint line)
3708 return sci_get_line_indent_position(sci, line) ==
3709 sci_get_line_end_position(sci, line);
3713 /* Returns first line of paragraph for GTK_DIR_UP, line after paragraph
3714 * ends for GTK_DIR_DOWN or -1 if called on an empty line. */
3715 static gint find_paragraph_stop(GeanyEditor *editor, gint line, gint direction)
3717 gint step;
3718 ScintillaObject *sci = editor->sci;
3720 /* first check current line and return -1 if it is empty to skip creating of a selection */
3721 if (sci_is_blank_line(sci, line))
3722 return -1;
3724 if (direction == GTK_DIR_UP)
3725 step = -1;
3726 else
3727 step = 1;
3729 while (TRUE)
3731 line += step;
3732 if (line == -1)
3734 /* start of document */
3735 line = 0;
3736 break;
3738 if (line == sci_get_line_count(sci))
3739 break;
3741 if (sci_is_blank_line(sci, line))
3743 /* return line paragraph starts on */
3744 if (direction == GTK_DIR_UP)
3745 line++;
3746 break;
3749 return line;
3753 void editor_select_paragraph(GeanyEditor *editor)
3755 gint pos_start, pos_end, line_start, line_found;
3757 g_return_if_fail(editor != NULL);
3759 line_start = sci_get_current_line(editor->sci);
3761 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_UP);
3762 if (line_found == -1)
3763 return;
3765 pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3767 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_DOWN);
3768 pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3770 sci_set_selection(editor->sci, pos_start, pos_end);
3774 /* Returns first line of block for GTK_DIR_UP, line after block
3775 * ends for GTK_DIR_DOWN or -1 if called on an empty line. */
3776 static gint find_block_stop(GeanyEditor *editor, gint line, gint direction)
3778 gint step, ind;
3779 ScintillaObject *sci = editor->sci;
3781 /* first check current line and return -1 if it is empty to skip creating of a selection */
3782 if (sci_is_blank_line(sci, line))
3783 return -1;
3785 if (direction == GTK_DIR_UP)
3786 step = -1;
3787 else
3788 step = 1;
3790 ind = sci_get_line_indentation(sci, line);
3791 while (TRUE)
3793 line += step;
3794 if (line == -1)
3796 /* start of document */
3797 line = 0;
3798 break;
3800 if (line == sci_get_line_count(sci))
3801 break;
3803 if (sci_get_line_indentation(sci, line) != ind ||
3804 sci_is_blank_line(sci, line))
3806 /* return line block starts on */
3807 if (direction == GTK_DIR_UP)
3808 line++;
3809 break;
3812 return line;
3816 void editor_select_indent_block(GeanyEditor *editor)
3818 gint pos_start, pos_end, line_start, line_found;
3820 g_return_if_fail(editor != NULL);
3822 line_start = sci_get_current_line(editor->sci);
3824 line_found = find_block_stop(editor, line_start, GTK_DIR_UP);
3825 if (line_found == -1)
3826 return;
3828 pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3830 line_found = find_block_stop(editor, line_start, GTK_DIR_DOWN);
3831 pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3833 sci_set_selection(editor->sci, pos_start, pos_end);
3837 /* simple indentation to indent the current line with the same indent as the previous one */
3838 static void smart_line_indentation(GeanyEditor *editor, gint first_line, gint last_line)
3840 gint i, sel_start = 0, sel_end = 0;
3842 /* get previous line and use it for read_indent to use that line
3843 * (otherwise it would fail on a line only containing "{" in advanced indentation mode) */
3844 read_indent(editor, sci_get_position_from_line(editor->sci, first_line - 1));
3846 for (i = first_line; i <= last_line; i++)
3848 /* skip the first line or if the indentation of the previous and current line are equal */
3849 if (i == 0 ||
3850 SSM(editor->sci, SCI_GETLINEINDENTATION, i - 1, 0) ==
3851 SSM(editor->sci, SCI_GETLINEINDENTATION, i, 0))
3852 continue;
3854 sel_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
3855 sel_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
3856 if (sel_start < sel_end)
3858 sci_set_selection(editor->sci, sel_start, sel_end);
3859 sci_replace_sel(editor->sci, "");
3861 sci_insert_text(editor->sci, sel_start, indent);
3866 /* simple indentation to indent the current line with the same indent as the previous one */
3867 void editor_smart_line_indentation(GeanyEditor *editor, gint pos)
3869 gint first_line, last_line;
3870 gint first_sel_start, first_sel_end;
3871 ScintillaObject *sci;
3873 g_return_if_fail(editor != NULL);
3875 sci = editor->sci;
3877 first_sel_start = sci_get_selection_start(sci);
3878 first_sel_end = sci_get_selection_end(sci);
3880 first_line = sci_get_line_from_position(sci, first_sel_start);
3881 /* Find the last line with chars selected (not EOL char) */
3882 last_line = sci_get_line_from_position(sci, first_sel_end - editor_get_eol_char_len(editor));
3883 last_line = MAX(first_line, last_line);
3885 if (pos == -1)
3886 pos = first_sel_start;
3888 sci_start_undo_action(sci);
3890 smart_line_indentation(editor, first_line, last_line);
3892 /* set cursor position if there was no selection */
3893 if (first_sel_start == first_sel_end)
3895 gint indent_pos = SSM(sci, SCI_GETLINEINDENTPOSITION, first_line, 0);
3897 /* use indent position as user may wish to change indentation afterwards */
3898 sci_set_current_position(sci, indent_pos, FALSE);
3900 else
3902 /* fully select all the lines affected */
3903 sci_set_selection_start(sci, sci_get_position_from_line(sci, first_line));
3904 sci_set_selection_end(sci, sci_get_position_from_line(sci, last_line + 1));
3907 sci_end_undo_action(sci);
3911 /* increase / decrease current line or selection by one space */
3912 void editor_indentation_by_one_space(GeanyEditor *editor, gint pos, gboolean decrease)
3914 gint i, first_line, last_line, line_start, indentation_end, count = 0;
3915 gint sel_start, sel_end, first_line_offset = 0;
3917 g_return_if_fail(editor != NULL);
3919 sel_start = sci_get_selection_start(editor->sci);
3920 sel_end = sci_get_selection_end(editor->sci);
3922 first_line = sci_get_line_from_position(editor->sci, sel_start);
3923 /* Find the last line with chars selected (not EOL char) */
3924 last_line = sci_get_line_from_position(editor->sci, sel_end - editor_get_eol_char_len(editor));
3925 last_line = MAX(first_line, last_line);
3927 if (pos == -1)
3928 pos = sel_start;
3930 sci_start_undo_action(editor->sci);
3932 for (i = first_line; i <= last_line; i++)
3934 indentation_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
3935 if (decrease)
3937 line_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
3938 /* searching backwards for a space to remove */
3939 while (sci_get_char_at(editor->sci, indentation_end) != ' ' && indentation_end > line_start)
3940 indentation_end--;
3942 if (sci_get_char_at(editor->sci, indentation_end) == ' ')
3944 sci_set_selection(editor->sci, indentation_end, indentation_end + 1);
3945 sci_replace_sel(editor->sci, "");
3946 count--;
3947 if (i == first_line)
3948 first_line_offset = -1;
3951 else
3953 sci_insert_text(editor->sci, indentation_end, " ");
3954 count++;
3955 if (i == first_line)
3956 first_line_offset = 1;
3960 /* set cursor position */
3961 if (sel_start < sel_end)
3963 gint start = sel_start + first_line_offset;
3964 if (first_line_offset < 0)
3965 start = MAX(sel_start + first_line_offset,
3966 SSM(editor->sci, SCI_POSITIONFROMLINE, first_line, 0));
3968 sci_set_selection_start(editor->sci, start);
3969 sci_set_selection_end(editor->sci, sel_end + count);
3971 else
3972 sci_set_current_position(editor->sci, pos + count, FALSE);
3974 sci_end_undo_action(editor->sci);
3978 void editor_finalize(void)
3980 scintilla_release_resources();
3984 /* wordchars: NULL or a string containing characters to match a word.
3985 * Returns: the current selection or the current word.
3987 * Passing NULL as wordchars is NOT the same as passing GEANY_WORDCHARS: NULL means
3988 * using Scintillas's word boundaries. */
3989 gchar *editor_get_default_selection(GeanyEditor *editor, gboolean use_current_word,
3990 const gchar *wordchars)
3992 gchar *s = NULL;
3994 g_return_val_if_fail(editor != NULL, NULL);
3996 if (sci_get_lines_selected(editor->sci) == 1)
3997 s = sci_get_selection_contents(editor->sci);
3998 else if (sci_get_lines_selected(editor->sci) == 0 && use_current_word)
3999 { /* use the word at current cursor position */
4000 gchar word[GEANY_MAX_WORD_LENGTH];
4002 if (wordchars != NULL)
4003 editor_find_current_word(editor, -1, word, sizeof(word), wordchars);
4004 else
4005 editor_find_current_word_sciwc(editor, -1, word, sizeof(word));
4007 if (word[0] != '\0')
4008 s = g_strdup(word);
4010 return s;
4014 /* Note: Usually the line should be made visible (not folded) before calling this.
4015 * Returns: TRUE if line is/will be displayed to the user, or FALSE if it is
4016 * outside the *vertical* view.
4017 * Warning: You may need horizontal scrolling to make the cursor visible - so always call
4018 * sci_scroll_caret() when this returns TRUE. */
4019 gboolean editor_line_in_view(GeanyEditor *editor, gint line)
4021 gint vis1, los;
4023 g_return_val_if_fail(editor != NULL, FALSE);
4025 /* If line is wrapped the result may occur on another virtual line than the first and may be
4026 * still hidden, so increase the line number to check for the next document line */
4027 if (SSM(editor->sci, SCI_WRAPCOUNT, line, 0) > 1)
4028 line++;
4030 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0); /* convert to visible line number */
4031 vis1 = SSM(editor->sci, SCI_GETFIRSTVISIBLELINE, 0, 0);
4032 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
4034 return (line >= vis1 && line < vis1 + los);
4038 /* If the current line is outside the current view window, scroll the line
4039 * so it appears at percent_of_view. */
4040 void editor_display_current_line(GeanyEditor *editor, gfloat percent_of_view)
4042 gint line;
4044 g_return_if_fail(editor != NULL);
4046 line = sci_get_current_line(editor->sci);
4048 /* unfold maybe folded results */
4049 sci_ensure_line_is_visible(editor->sci, line);
4051 /* scroll the line if it's off screen */
4052 if (! editor_line_in_view(editor, line))
4053 editor->scroll_percent = percent_of_view;
4054 else
4055 sci_scroll_caret(editor->sci); /* may need horizontal scrolling */
4060 * Deletes all currently set indicators in the @a editor window.
4061 * Error indicators (red squiggly underlines) and usual line markers are removed.
4063 * @param editor The editor to operate on.
4065 void editor_indicator_clear_errors(GeanyEditor *editor)
4067 editor_indicator_clear(editor, GEANY_INDICATOR_ERROR);
4068 sci_marker_delete_all(editor->sci, 0); /* remove the yellow error line marker */
4073 * Deletes all currently set indicators matching @a indic in the @a editor window.
4075 * @param editor The editor to operate on.
4076 * @param indic The indicator number to clear, this is a value of @ref GeanyIndicator.
4078 * @since 0.16
4080 GEANY_API_SYMBOL
4081 void editor_indicator_clear(GeanyEditor *editor, gint indic)
4083 glong last_pos;
4085 g_return_if_fail(editor != NULL);
4087 last_pos = sci_get_length(editor->sci);
4088 if (last_pos > 0)
4090 sci_indicator_set(editor->sci, indic);
4091 sci_indicator_clear(editor->sci, 0, last_pos);
4097 * Sets an indicator @a indic on @a line.
4098 * Whitespace at the start and the end of the line is not marked.
4100 * @param editor The editor to operate on.
4101 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4102 * @param line The line number which should be marked.
4104 * @since 0.16
4106 GEANY_API_SYMBOL
4107 void editor_indicator_set_on_line(GeanyEditor *editor, gint indic, gint line)
4109 gint start, end;
4110 guint i = 0, len;
4111 gchar *linebuf;
4113 g_return_if_fail(editor != NULL);
4114 g_return_if_fail(line >= 0);
4116 start = sci_get_position_from_line(editor->sci, line);
4117 end = sci_get_position_from_line(editor->sci, line + 1);
4119 /* skip blank lines */
4120 if ((start + 1) == end ||
4121 start > end ||
4122 (sci_get_line_end_position(editor->sci, line) - start) == 0)
4124 return;
4127 len = end - start;
4128 linebuf = sci_get_line(editor->sci, line);
4130 /* don't set the indicator on whitespace */
4131 while (isspace(linebuf[i]))
4132 i++;
4133 while (len > 1 && len > i && isspace(linebuf[len - 1]))
4135 len--;
4136 end--;
4138 g_free(linebuf);
4140 editor_indicator_set_on_range(editor, indic, start + i, end);
4145 * Sets an indicator on the range specified by @a start and @a end.
4146 * No error checking or whitespace removal is performed, this should be done by the calling
4147 * function if necessary.
4149 * @param editor The editor to operate on.
4150 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4151 * @param start The starting position for the marker.
4152 * @param end The ending position for the marker.
4154 * @since 0.16
4156 GEANY_API_SYMBOL
4157 void editor_indicator_set_on_range(GeanyEditor *editor, gint indic, gint start, gint end)
4159 g_return_if_fail(editor != NULL);
4160 if (start >= end)
4161 return;
4163 sci_indicator_set(editor->sci, indic);
4164 sci_indicator_fill(editor->sci, start, end - start);
4168 /* Inserts the given colour (format should be #...), if there is a selection starting with 0x...
4169 * the replacement will also start with 0x... */
4170 void editor_insert_color(GeanyEditor *editor, const gchar *colour)
4172 g_return_if_fail(editor != NULL);
4174 if (sci_has_selection(editor->sci))
4176 gint start = sci_get_selection_start(editor->sci);
4177 const gchar *replacement = colour;
4179 if (sci_get_char_at(editor->sci, start) == '0' &&
4180 sci_get_char_at(editor->sci, start + 1) == 'x')
4182 gint end = sci_get_selection_end(editor->sci);
4184 sci_set_selection_start(editor->sci, start + 2);
4185 /* we need to also re-set the selection end in case the anchor was located before
4186 * the cursor, since set_selection_start() always moves the cursor, not the anchor */
4187 sci_set_selection_end(editor->sci, end);
4188 replacement++; /* skip the leading "0x" */
4190 else if (sci_get_char_at(editor->sci, start - 1) == '#')
4191 { /* double clicking something like #00ffff may only select 00ffff because of wordchars */
4192 replacement++; /* so skip the '#' to only replace the colour value */
4194 sci_replace_sel(editor->sci, replacement);
4196 else
4197 sci_add_text(editor->sci, colour);
4202 * Retrieves the end of line characters mode (LF, CR/LF, CR) in the given editor.
4203 * If @a editor is @c NULL, the default end of line characters are used.
4205 * @param editor The editor to operate on, or @c NULL to query the default value.
4206 * @return The used end of line characters mode.
4208 * @since 0.20
4210 GEANY_API_SYMBOL
4211 gint editor_get_eol_char_mode(GeanyEditor *editor)
4213 gint mode = file_prefs.default_eol_character;
4215 if (editor != NULL)
4216 mode = sci_get_eol_mode(editor->sci);
4218 return mode;
4223 * Retrieves the localized name (for displaying) of the used end of line characters
4224 * (LF, CR/LF, CR) in the given editor.
4225 * If @a editor is @c NULL, the default end of line characters are used.
4227 * @param editor The editor to operate on, or @c NULL to query the default value.
4228 * @return The name of the end of line characters.
4230 * @since 0.19
4232 GEANY_API_SYMBOL
4233 const gchar *editor_get_eol_char_name(GeanyEditor *editor)
4235 gint mode = file_prefs.default_eol_character;
4237 if (editor != NULL)
4238 mode = sci_get_eol_mode(editor->sci);
4240 return utils_get_eol_name(mode);
4245 * Retrieves the length of the used end of line characters (LF, CR/LF, CR) in the given editor.
4246 * If @a editor is @c NULL, the default end of line characters are used.
4247 * The returned value is 1 for CR and LF and 2 for CR/LF.
4249 * @param editor The editor to operate on, or @c NULL to query the default value.
4250 * @return The length of the end of line characters.
4252 * @since 0.19
4254 GEANY_API_SYMBOL
4255 gint editor_get_eol_char_len(GeanyEditor *editor)
4257 gint mode = file_prefs.default_eol_character;
4259 if (editor != NULL)
4260 mode = sci_get_eol_mode(editor->sci);
4262 switch (mode)
4264 case SC_EOL_CRLF: return 2; break;
4265 default: return 1; break;
4271 * Retrieves the used end of line characters (LF, CR/LF, CR) in the given editor.
4272 * If @a editor is @c NULL, the default end of line characters are used.
4273 * The returned value is either "\n", "\r\n" or "\r".
4275 * @param editor The editor to operate on, or @c NULL to query the default value.
4276 * @return The end of line characters.
4278 * @since 0.19
4280 GEANY_API_SYMBOL
4281 const gchar *editor_get_eol_char(GeanyEditor *editor)
4283 gint mode = file_prefs.default_eol_character;
4285 if (editor != NULL)
4286 mode = sci_get_eol_mode(editor->sci);
4288 return utils_get_eol_char(mode);
4292 static void fold_all(GeanyEditor *editor, gboolean want_fold)
4294 gint lines, first, i;
4296 if (editor == NULL || ! editor_prefs.folding)
4297 return;
4299 lines = sci_get_line_count(editor->sci);
4300 first = sci_get_first_visible_line(editor->sci);
4302 for (i = 0; i < lines; i++)
4304 gint level = sci_get_fold_level(editor->sci, i);
4306 if (level & SC_FOLDLEVELHEADERFLAG)
4308 if (sci_get_fold_expanded(editor->sci, i) == want_fold)
4309 sci_toggle_fold(editor->sci, i);
4312 editor_scroll_to_line(editor, first, 0.0F);
4316 void editor_unfold_all(GeanyEditor *editor)
4318 fold_all(editor, FALSE);
4322 void editor_fold_all(GeanyEditor *editor)
4324 fold_all(editor, TRUE);
4328 void editor_replace_tabs(GeanyEditor *editor)
4330 gint search_pos, pos_in_line, current_tab_true_length;
4331 gint tab_len;
4332 gchar *tab_str;
4333 struct Sci_TextToFind ttf;
4335 g_return_if_fail(editor != NULL);
4337 sci_start_undo_action(editor->sci);
4338 tab_len = sci_get_tab_width(editor->sci);
4339 ttf.chrg.cpMin = 0;
4340 ttf.chrg.cpMax = sci_get_length(editor->sci);
4341 ttf.lpstrText = (gchar*) "\t";
4343 while (TRUE)
4345 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4346 if (search_pos == -1)
4347 break;
4349 pos_in_line = sci_get_col_from_position(editor->sci, search_pos);
4350 current_tab_true_length = tab_len - (pos_in_line % tab_len);
4351 tab_str = g_strnfill(current_tab_true_length, ' ');
4352 sci_set_target_start(editor->sci, search_pos);
4353 sci_set_target_end(editor->sci, search_pos + 1);
4354 sci_replace_target(editor->sci, tab_str, FALSE);
4355 /* next search starts after replacement */
4356 ttf.chrg.cpMin = search_pos + current_tab_true_length - 1;
4357 /* update end of range now text has changed */
4358 ttf.chrg.cpMax += current_tab_true_length - 1;
4359 g_free(tab_str);
4361 sci_end_undo_action(editor->sci);
4365 /* Replaces all occurrences all spaces of the length of a given tab_width. */
4366 void editor_replace_spaces(GeanyEditor *editor)
4368 gint search_pos;
4369 static gdouble tab_len_f = -1.0; /* keep the last used value */
4370 gint tab_len;
4371 gchar *text;
4372 struct Sci_TextToFind ttf;
4374 g_return_if_fail(editor != NULL);
4376 if (tab_len_f < 0.0)
4377 tab_len_f = sci_get_tab_width(editor->sci);
4379 if (! dialogs_show_input_numeric(
4380 _("Enter Tab Width"),
4381 _("Enter the amount of spaces which should be replaced by a tab character."),
4382 &tab_len_f, 1, 100, 1))
4384 return;
4386 tab_len = (gint) tab_len_f;
4387 text = g_strnfill(tab_len, ' ');
4389 sci_start_undo_action(editor->sci);
4390 ttf.chrg.cpMin = 0;
4391 ttf.chrg.cpMax = sci_get_length(editor->sci);
4392 ttf.lpstrText = text;
4394 while (TRUE)
4396 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4397 if (search_pos == -1)
4398 break;
4399 /* only replace indentation because otherwise we can mess up alignment */
4400 if (search_pos > sci_get_line_indent_position(editor->sci,
4401 sci_get_line_from_position(editor->sci, search_pos)))
4403 ttf.chrg.cpMin = search_pos + tab_len;
4404 continue;
4406 sci_set_target_start(editor->sci, search_pos);
4407 sci_set_target_end(editor->sci, search_pos + tab_len);
4408 sci_replace_target(editor->sci, "\t", FALSE);
4409 ttf.chrg.cpMin = search_pos;
4410 /* update end of range now text has changed */
4411 ttf.chrg.cpMax -= tab_len - 1;
4413 sci_end_undo_action(editor->sci);
4414 g_free(text);
4418 void editor_strip_line_trailing_spaces(GeanyEditor *editor, gint line)
4420 gint line_start = sci_get_position_from_line(editor->sci, line);
4421 gint line_end = sci_get_line_end_position(editor->sci, line);
4422 gint i = line_end - 1;
4423 gchar ch = sci_get_char_at(editor->sci, i);
4425 /* Diff hunks should keep trailing spaces */
4426 if (sci_get_lexer(editor->sci) == SCLEX_DIFF)
4427 return;
4429 while ((i >= line_start) && ((ch == ' ') || (ch == '\t')))
4431 i--;
4432 ch = sci_get_char_at(editor->sci, i);
4434 if (i < (line_end - 1))
4436 sci_set_target_start(editor->sci, i + 1);
4437 sci_set_target_end(editor->sci, line_end);
4438 sci_replace_target(editor->sci, "", FALSE);
4443 void editor_strip_trailing_spaces(GeanyEditor *editor)
4445 gint max_lines = sci_get_line_count(editor->sci);
4446 gint line;
4448 sci_start_undo_action(editor->sci);
4450 for (line = 0; line < max_lines; line++)
4452 editor_strip_line_trailing_spaces(editor, line);
4454 sci_end_undo_action(editor->sci);
4458 void editor_ensure_final_newline(GeanyEditor *editor)
4460 gint max_lines = sci_get_line_count(editor->sci);
4461 gboolean append_newline = (max_lines == 1);
4462 gint end_document = sci_get_position_from_line(editor->sci, max_lines);
4464 if (max_lines > 1)
4466 append_newline = end_document > sci_get_position_from_line(editor->sci, max_lines - 1);
4468 if (append_newline)
4470 const gchar *eol = editor_get_eol_char(editor);
4472 sci_insert_text(editor->sci, end_document, eol);
4477 void editor_set_font(GeanyEditor *editor, const gchar *font)
4479 gint style, size;
4480 gchar *font_name;
4481 PangoFontDescription *pfd;
4483 g_return_if_fail(editor);
4485 pfd = pango_font_description_from_string(font);
4486 size = pango_font_description_get_size(pfd) / PANGO_SCALE;
4487 font_name = g_strdup_printf("!%s", pango_font_description_get_family(pfd));
4488 pango_font_description_free(pfd);
4490 for (style = 0; style <= STYLE_MAX; style++)
4491 sci_set_font(editor->sci, style, font_name, size);
4493 g_free(font_name);
4495 /* zoom to 100% to prevent confusion */
4496 sci_zoom_off(editor->sci);
4500 void editor_set_line_wrapping(GeanyEditor *editor, gboolean wrap)
4502 g_return_if_fail(editor != NULL);
4504 editor->line_wrapping = wrap;
4505 sci_set_lines_wrapped(editor->sci, wrap);
4509 /** Sets the indent type for @a editor.
4510 * @param editor Editor.
4511 * @param type Indent type.
4513 * @since 0.16
4515 GEANY_API_SYMBOL
4516 void editor_set_indent_type(GeanyEditor *editor, GeanyIndentType type)
4518 editor_set_indent(editor, type, editor->indent_width);
4522 void editor_set_indent_width(GeanyEditor *editor, gint width)
4524 editor_set_indent(editor, editor->indent_type, width);
4528 void editor_set_indent(GeanyEditor *editor, GeanyIndentType type, gint width)
4530 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
4531 ScintillaObject *sci = editor->sci;
4532 gboolean use_tabs = type != GEANY_INDENT_TYPE_SPACES;
4534 editor->indent_type = type;
4535 editor->indent_width = width;
4536 sci_set_use_tabs(sci, use_tabs);
4538 if (type == GEANY_INDENT_TYPE_BOTH)
4540 sci_set_tab_width(sci, iprefs->hard_tab_width);
4541 if (iprefs->hard_tab_width != 8)
4543 static gboolean warn = TRUE;
4544 if (warn)
4545 ui_set_statusbar(TRUE, _("Warning: non-standard hard tab width: %d != 8!"),
4546 iprefs->hard_tab_width);
4547 warn = FALSE;
4550 else
4551 sci_set_tab_width(sci, width);
4553 SSM(sci, SCI_SETINDENT, width, 0);
4555 /* remove indent spaces on backspace, if using any spaces to indent */
4556 SSM(sci, SCI_SETBACKSPACEUNINDENTS, type != GEANY_INDENT_TYPE_TABS, 0);
4560 /* Convenience function for editor_goto_pos() to pass in a line number. */
4561 gboolean editor_goto_line(GeanyEditor *editor, gint line_no, gint offset)
4563 gint pos;
4565 g_return_val_if_fail(editor, FALSE);
4566 if (line_no < 0 || line_no >= sci_get_line_count(editor->sci))
4567 return FALSE;
4569 if (offset != 0)
4571 gint current_line = sci_get_current_line(editor->sci);
4572 line_no *= offset;
4573 line_no = current_line + line_no;
4576 pos = sci_get_position_from_line(editor->sci, line_no);
4577 return editor_goto_pos(editor, pos, TRUE);
4581 /** Moves to position @a pos, switching to the document if necessary,
4582 * setting a marker if @a mark is set.
4584 * @param editor Editor.
4585 * @param pos The position.
4586 * @param mark Whether to set a mark on the position.
4587 * @return @c TRUE if action has been performed, otherwise @c FALSE.
4589 * @since 0.20
4591 GEANY_API_SYMBOL
4592 gboolean editor_goto_pos(GeanyEditor *editor, gint pos, gboolean mark)
4594 g_return_val_if_fail(editor, FALSE);
4595 if (G_UNLIKELY(pos < 0))
4596 return FALSE;
4598 if (mark)
4600 gint line = sci_get_line_from_position(editor->sci, pos);
4602 /* mark the tag with the yellow arrow */
4603 sci_marker_delete_all(editor->sci, 0);
4604 sci_set_marker_at_line(editor->sci, line, 0);
4607 sci_goto_pos(editor->sci, pos, TRUE);
4608 editor->scroll_percent = 0.25F;
4610 /* finally switch to the page */
4611 document_show_tab(editor->document);
4612 return TRUE;
4616 static gboolean
4617 on_editor_scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer user_data)
4619 GeanyEditor *editor = user_data;
4621 /* Handle scroll events if Alt is pressed and scroll whole pages instead of a
4622 * few lines only, maybe this could/should be done in Scintilla directly */
4623 if (event->state & GDK_MOD1_MASK)
4625 sci_send_command(editor->sci, (event->direction == GDK_SCROLL_DOWN) ? SCI_PAGEDOWN : SCI_PAGEUP);
4626 return TRUE;
4628 else if (event->state & GDK_SHIFT_MASK)
4630 gint amount = (event->direction == GDK_SCROLL_DOWN) ? 8 : -8;
4632 sci_scroll_columns(editor->sci, amount);
4633 return TRUE;
4636 return FALSE; /* let Scintilla handle all other cases */
4640 static gboolean editor_check_colourise(GeanyEditor *editor)
4642 GeanyDocument *doc = editor->document;
4644 if (!doc->priv->colourise_needed)
4645 return FALSE;
4647 doc->priv->colourise_needed = FALSE;
4648 sci_colourise(editor->sci, 0, -1);
4650 /* now that the current document is colourised, fold points are now accurate,
4651 * so force an update of the current function/tag. */
4652 symbols_get_current_function(NULL, NULL);
4653 ui_update_statusbar(NULL, -1);
4655 return TRUE;
4659 /* We only want to colourise just before drawing, to save startup time and
4660 * prevent unnecessary recolouring other documents after one is saved.
4661 * Really we want a "draw" signal but there doesn't seem to be one (expose is too late,
4662 * and "show" doesn't work). */
4663 static gboolean on_editor_focus_in(GtkWidget *widget, GdkEventFocus *event, gpointer user_data)
4665 GeanyEditor *editor = user_data;
4667 editor_check_colourise(editor);
4668 return FALSE;
4672 static gboolean on_editor_expose_event(GtkWidget *widget, GdkEventExpose *event,
4673 gpointer user_data)
4675 GeanyEditor *editor = user_data;
4677 /* This is just to catch any uncolourised documents being drawn that didn't receive focus
4678 * for some reason, maybe it's not necessary but just in case. */
4679 editor_check_colourise(editor);
4680 return FALSE;
4684 #if GTK_CHECK_VERSION(3, 0, 0)
4685 static gboolean on_editor_draw(GtkWidget *widget, cairo_t *cr, gpointer user_data)
4687 return on_editor_expose_event(widget, NULL, user_data);
4689 #endif
4692 static void setup_sci_keys(ScintillaObject *sci)
4694 /* disable some Scintilla keybindings to be able to redefine them cleanly */
4695 sci_clear_cmdkey(sci, 'A' | (SCMOD_CTRL << 16)); /* select all */
4696 sci_clear_cmdkey(sci, 'D' | (SCMOD_CTRL << 16)); /* duplicate */
4697 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16)); /* line transpose */
4698 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line copy */
4699 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16)); /* line cut */
4700 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line delete */
4701 sci_clear_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line to end delete */
4702 sci_clear_cmdkey(sci, '/' | (SCMOD_CTRL << 16)); /* Previous word part */
4703 sci_clear_cmdkey(sci, '\\' | (SCMOD_CTRL << 16)); /* Next word part */
4704 sci_clear_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16)); /* scroll line up */
4705 sci_clear_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16)); /* scroll line down */
4706 sci_clear_cmdkey(sci, SCK_HOME); /* line start */
4707 sci_clear_cmdkey(sci, SCK_END); /* line end */
4708 sci_clear_cmdkey(sci, SCK_END | (SCMOD_ALT << 16)); /* visual line end */
4710 if (editor_prefs.use_gtk_word_boundaries)
4712 /* use GtkEntry-like word boundaries */
4713 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16), SCI_WORDRIGHTEND);
4714 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_WORDRIGHTENDEXTEND);
4715 sci_assign_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16), SCI_DELWORDRIGHTEND);
4717 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_ALT << 16), SCI_LINESCROLLUP);
4718 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_ALT << 16), SCI_LINESCROLLDOWN);
4719 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16), SCI_PARAUP);
4720 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARAUPEXTEND);
4721 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16), SCI_PARADOWN);
4722 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARADOWNEXTEND);
4724 sci_clear_cmdkey(sci, SCK_BACK | (SCMOD_ALT << 16)); /* clear Alt-Backspace (Undo) */
4728 /* registers a Scintilla image from a named icon from the theme */
4729 static gboolean register_named_icon(ScintillaObject *sci, guint id, const gchar *name)
4731 GError *error = NULL;
4732 GdkPixbuf *pixbuf;
4733 gint n_channels, rowstride, width, height;
4734 gint size;
4736 gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &size, NULL);
4737 pixbuf = gtk_icon_theme_load_icon(gtk_icon_theme_get_default(), name, size, 0, &error);
4738 if (! pixbuf)
4740 g_warning("failed to load icon '%s': %s", name, error->message);
4741 g_error_free(error);
4742 return FALSE;
4745 n_channels = gdk_pixbuf_get_n_channels(pixbuf);
4746 rowstride = gdk_pixbuf_get_rowstride(pixbuf);
4747 width = gdk_pixbuf_get_width(pixbuf);
4748 height = gdk_pixbuf_get_height(pixbuf);
4750 if (gdk_pixbuf_get_bits_per_sample(pixbuf) != 8 ||
4751 ! gdk_pixbuf_get_has_alpha(pixbuf) ||
4752 n_channels != 4 ||
4753 rowstride != width * n_channels)
4755 g_warning("incompatible image data for icon '%s'", name);
4756 g_object_unref(pixbuf);
4757 return FALSE;
4760 SSM(sci, SCI_RGBAIMAGESETWIDTH, width, 0);
4761 SSM(sci, SCI_RGBAIMAGESETHEIGHT, height, 0);
4762 SSM(sci, SCI_REGISTERRGBAIMAGE, id, (sptr_t)gdk_pixbuf_get_pixels(pixbuf));
4764 g_object_unref(pixbuf);
4765 return TRUE;
4769 /* Create new editor widget (scintilla).
4770 * @note The @c "sci-notify" signal is connected separately. */
4771 static ScintillaObject *create_new_sci(GeanyEditor *editor)
4773 ScintillaObject *sci;
4775 sci = SCINTILLA(scintilla_new());
4777 /* Scintilla doesn't support RTL languages properly and is primarily
4778 * intended to be used with LTR source code, so override the
4779 * GTK+ default text direction for the Scintilla widget. */
4780 gtk_widget_set_direction(GTK_WIDGET(sci), GTK_TEXT_DIR_LTR);
4782 gtk_widget_show(GTK_WIDGET(sci));
4784 sci_set_codepage(sci, SC_CP_UTF8);
4785 /*SSM(sci, SCI_SETWRAPSTARTINDENT, 4, 0);*/
4786 /* disable scintilla provided popup menu */
4787 sci_use_popup(sci, FALSE);
4789 setup_sci_keys(sci);
4791 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
4792 sci_set_lines_wrapped(sci, editor->line_wrapping);
4793 sci_set_caret_policy_x(sci, CARET_JUMPS | CARET_EVEN, 0);
4794 /*sci_set_caret_policy_y(sci, CARET_JUMPS | CARET_EVEN, 0);*/
4795 SSM(sci, SCI_AUTOCSETSEPARATOR, '\n', 0);
4796 SSM(sci, SCI_SETSCROLLWIDTHTRACKING, 1, 0);
4798 /* tag autocompletion images */
4799 register_named_icon(sci, 1, "classviewer-var");
4800 register_named_icon(sci, 2, "classviewer-method");
4802 /* necessary for column mode editing, implemented in Scintilla since 2.0 */
4803 SSM(sci, SCI_SETADDITIONALSELECTIONTYPING, 1, 0);
4805 /* virtual space */
4806 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
4808 #ifdef GDK_WINDOWING_QUARTZ
4809 /* "retina" (HiDPI) display support on OS X - requires disabling buffered draw */
4810 SSM(sci, SCI_SETBUFFEREDDRAW, 0, 0);
4811 #endif
4813 /* only connect signals if this is for the document notebook, not split window */
4814 if (editor->sci == NULL)
4816 g_signal_connect(sci, "button-press-event", G_CALLBACK(on_editor_button_press_event), editor);
4817 g_signal_connect(sci, "scroll-event", G_CALLBACK(on_editor_scroll_event), editor);
4818 g_signal_connect(sci, "motion-notify-event", G_CALLBACK(on_motion_event), NULL);
4819 g_signal_connect(sci, "focus-in-event", G_CALLBACK(on_editor_focus_in), editor);
4820 #if GTK_CHECK_VERSION(3, 0, 0)
4821 g_signal_connect(sci, "draw", G_CALLBACK(on_editor_draw), editor);
4822 #else
4823 g_signal_connect(sci, "expose-event", G_CALLBACK(on_editor_expose_event), editor);
4824 #endif
4826 return sci;
4830 /** Creates a new Scintilla @c GtkWidget based on the settings for @a editor.
4831 * @param editor Editor settings.
4832 * @return The new widget.
4834 * @since 0.15
4836 GEANY_API_SYMBOL
4837 ScintillaObject *editor_create_widget(GeanyEditor *editor)
4839 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4840 ScintillaObject *old, *sci;
4841 GeanyIndentType old_indent_type = editor->indent_type;
4842 gint old_indent_width = editor->indent_width;
4844 /* temporarily change editor to use the new sci widget */
4845 old = editor->sci;
4846 sci = create_new_sci(editor);
4847 editor->sci = sci;
4849 editor_set_indent(editor, iprefs->type, iprefs->width);
4850 editor_set_font(editor, interface_prefs.editor_font);
4851 editor_apply_update_prefs(editor);
4853 /* if editor already had a widget, restore it */
4854 if (old)
4856 editor->indent_type = old_indent_type;
4857 editor->indent_width = old_indent_width;
4858 editor->sci = old;
4860 return sci;
4864 GeanyEditor *editor_create(GeanyDocument *doc)
4866 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4867 GeanyEditor *editor = g_new0(GeanyEditor, 1);
4869 editor->document = doc;
4870 doc->editor = editor; /* needed in case some editor functions/callbacks expect it */
4872 editor->auto_indent = (iprefs->auto_indent_mode != GEANY_AUTOINDENT_NONE);
4873 editor->line_wrapping = get_project_pref(line_wrapping);
4874 editor->scroll_percent = -1.0F;
4875 editor->line_breaking = FALSE;
4877 editor->sci = editor_create_widget(editor);
4878 return editor;
4882 /* in case we need to free some fields in future */
4883 void editor_destroy(GeanyEditor *editor)
4885 g_free(editor);
4889 static void on_document_save(GObject *obj, GeanyDocument *doc)
4891 gchar *f = g_build_filename(app->configdir, "snippets.conf", NULL);
4893 if (utils_str_equal(doc->real_path, f))
4895 /* reload snippets */
4896 editor_snippets_free();
4897 editor_snippets_init();
4899 g_free(f);
4903 gboolean editor_complete_word_part(GeanyEditor *editor)
4905 gchar *entry;
4907 g_return_val_if_fail(editor, FALSE);
4909 if (!SSM(editor->sci, SCI_AUTOCACTIVE, 0, 0))
4910 return FALSE;
4912 entry = sci_get_string(editor->sci, SCI_AUTOCGETCURRENTTEXT, 0);
4914 /* if no word part, complete normally */
4915 if (!check_partial_completion(editor, entry))
4916 SSM(editor->sci, SCI_AUTOCCOMPLETE, 0, 0);
4918 g_free(entry);
4919 return TRUE;
4923 void editor_init(void)
4925 static GeanyIndentPrefs indent_prefs;
4926 gchar *f;
4928 memset(&editor_prefs, 0, sizeof(GeanyEditorPrefs));
4929 memset(&indent_prefs, 0, sizeof(GeanyIndentPrefs));
4930 editor_prefs.indentation = &indent_prefs;
4932 /* use g_signal_connect_after() to allow plugins connecting to the signal before the default
4933 * handler (on_editor_notify) is called */
4934 g_signal_connect_after(geany_object, "editor-notify", G_CALLBACK(on_editor_notify), NULL);
4936 f = g_build_filename(app->configdir, "snippets.conf", NULL);
4937 ui_add_config_file_menu_item(f, NULL, NULL);
4938 g_free(f);
4939 g_signal_connect(geany_object, "document-save", G_CALLBACK(on_document_save), NULL);
4943 /* TODO: Should these be user-defined instead of hard-coded? */
4944 void editor_set_indentation_guides(GeanyEditor *editor)
4946 gint mode;
4947 gint lexer;
4949 g_return_if_fail(editor != NULL);
4951 if (! editor_prefs.show_indent_guide)
4953 sci_set_indentation_guides(editor->sci, SC_IV_NONE);
4954 return;
4957 lexer = sci_get_lexer(editor->sci);
4958 switch (lexer)
4960 /* Lines added/removed are prefixed with +/- characters, so
4961 * those lines will not be shown with any indentation guides.
4962 * It can be distracting that only a few of lines in a diff/patch
4963 * file will show the guides. */
4964 case SCLEX_DIFF:
4965 mode = SC_IV_NONE;
4966 break;
4968 /* These languages use indentation for control blocks; the "look forward" method works
4969 * best here */
4970 case SCLEX_PYTHON:
4971 case SCLEX_HASKELL:
4972 case SCLEX_MAKEFILE:
4973 case SCLEX_ASM:
4974 case SCLEX_SQL:
4975 case SCLEX_COBOL:
4976 case SCLEX_PROPERTIES:
4977 case SCLEX_FORTRAN: /* Is this the best option for Fortran? */
4978 case SCLEX_CAML:
4979 mode = SC_IV_LOOKFORWARD;
4980 break;
4982 /* C-like (structured) languages benefit from the "look both" method */
4983 case SCLEX_CPP:
4984 case SCLEX_HTML:
4985 case SCLEX_PHPSCRIPT:
4986 case SCLEX_XML:
4987 case SCLEX_PERL:
4988 case SCLEX_LATEX:
4989 case SCLEX_LUA:
4990 case SCLEX_PASCAL:
4991 case SCLEX_RUBY:
4992 case SCLEX_TCL:
4993 case SCLEX_F77:
4994 case SCLEX_CSS:
4995 case SCLEX_BASH:
4996 case SCLEX_VHDL:
4997 case SCLEX_FREEBASIC:
4998 case SCLEX_D:
4999 case SCLEX_OCTAVE:
5000 case SCLEX_RUST:
5001 mode = SC_IV_LOOKBOTH;
5002 break;
5004 default:
5005 mode = SC_IV_REAL;
5006 break;
5009 sci_set_indentation_guides(editor->sci, mode);
5013 /* Apply non-document prefs that can change in the Preferences dialog */
5014 void editor_apply_update_prefs(GeanyEditor *editor)
5016 ScintillaObject *sci;
5018 g_return_if_fail(editor != NULL);
5020 if (main_status.quitting)
5021 return;
5023 sci = editor->sci;
5025 sci_set_mark_long_lines(sci, editor_get_long_line_type(),
5026 editor_get_long_line_column(), editor_prefs.long_line_color);
5028 /* update indent width, tab width */
5029 editor_set_indent(editor, editor->indent_type, editor->indent_width);
5030 sci_set_tab_indents(sci, editor_prefs.use_tab_to_indent);
5032 sci_assign_cmdkey(sci, SCK_HOME | (SCMOD_SHIFT << 16),
5033 editor_prefs.smart_home_key ? SCI_VCHOMEEXTEND : SCI_HOMEEXTEND);
5034 sci_assign_cmdkey(sci, SCK_HOME | ((SCMOD_SHIFT | SCMOD_ALT) << 16),
5035 editor_prefs.smart_home_key ? SCI_VCHOMERECTEXTEND : SCI_HOMERECTEXTEND);
5037 sci_set_autoc_max_height(sci, editor_prefs.symbolcompletion_max_height);
5038 SSM(sci, SCI_AUTOCSETDROPRESTOFWORD, editor_prefs.completion_drops_rest_of_word, 0);
5040 editor_set_indentation_guides(editor);
5042 sci_set_visible_white_spaces(sci, editor_prefs.show_white_space);
5043 sci_set_visible_eols(sci, editor_prefs.show_line_endings);
5044 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
5045 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin);
5047 sci_set_folding_margin_visible(sci, editor_prefs.folding);
5049 /* virtual space */
5050 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
5052 /* (dis)allow scrolling past end of document */
5053 sci_set_scroll_stop_at_last_line(sci, editor_prefs.scroll_stop_at_last_line);
5055 sci_set_scrollbar_mode(sci, editor_prefs.show_scrollbars);
5059 /* This is for tab-indents, space aligns formatted code. Spaces should be preserved. */
5060 static void change_tab_indentation(GeanyEditor *editor, gint line, gboolean increase)
5062 ScintillaObject *sci = editor->sci;
5063 gint pos = sci_get_position_from_line(sci, line);
5065 if (increase)
5067 sci_insert_text(sci, pos, "\t");
5069 else
5071 if (sci_get_char_at(sci, pos) == '\t')
5073 sci_set_selection(sci, pos, pos + 1);
5074 sci_replace_sel(sci, "");
5076 else /* remove spaces only if no tabs */
5078 gint width = sci_get_line_indentation(sci, line);
5080 width -= editor_get_indent_prefs(editor)->width;
5081 sci_set_line_indentation(sci, line, width);
5087 static void editor_change_line_indent(GeanyEditor *editor, gint line, gboolean increase)
5089 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
5090 ScintillaObject *sci = editor->sci;
5092 if (iprefs->type == GEANY_INDENT_TYPE_TABS)
5093 change_tab_indentation(editor, line, increase);
5094 else
5096 gint width = sci_get_line_indentation(sci, line);
5098 width += increase ? iprefs->width : -iprefs->width;
5099 sci_set_line_indentation(sci, line, width);
5104 void editor_indent(GeanyEditor *editor, gboolean increase)
5106 ScintillaObject *sci = editor->sci;
5107 gint caret_pos, caret_line, caret_offset, caret_indent_pos, caret_line_len;
5108 gint anchor_pos, anchor_line, anchor_offset, anchor_indent_pos, anchor_line_len;
5110 /* backup information needed to restore caret and anchor */
5111 caret_pos = sci_get_current_position(sci);
5112 anchor_pos = SSM(sci, SCI_GETANCHOR, 0, 0);
5113 caret_line = sci_get_line_from_position(sci, caret_pos);
5114 anchor_line = sci_get_line_from_position(sci, anchor_pos);
5115 caret_offset = caret_pos - sci_get_position_from_line(sci, caret_line);
5116 anchor_offset = anchor_pos - sci_get_position_from_line(sci, anchor_line);
5117 caret_indent_pos = sci_get_line_indent_position(sci, caret_line);
5118 anchor_indent_pos = sci_get_line_indent_position(sci, anchor_line);
5119 caret_line_len = sci_get_line_length(sci, caret_line);
5120 anchor_line_len = sci_get_line_length(sci, anchor_line);
5122 if (sci_get_lines_selected(sci) <= 1)
5124 editor_change_line_indent(editor, sci_get_current_line(sci), increase);
5126 else
5128 gint start, end;
5129 gint line, lstart, lend;
5131 editor_select_lines(editor, FALSE);
5132 start = sci_get_selection_start(sci);
5133 end = sci_get_selection_end(sci);
5134 lstart = sci_get_line_from_position(sci, start);
5135 lend = sci_get_line_from_position(sci, end);
5136 if (end == sci_get_length(sci))
5137 lend++; /* for last line with text on it */
5139 sci_start_undo_action(sci);
5140 for (line = lstart; line < lend; line++)
5142 editor_change_line_indent(editor, line, increase);
5144 sci_end_undo_action(sci);
5147 /* restore caret and anchor position */
5148 if (caret_pos >= caret_indent_pos)
5149 caret_offset += sci_get_line_length(sci, caret_line) - caret_line_len;
5150 if (anchor_pos >= anchor_indent_pos)
5151 anchor_offset += sci_get_line_length(sci, anchor_line) - anchor_line_len;
5153 SSM(sci, SCI_SETCURRENTPOS, sci_get_position_from_line(sci, caret_line) + caret_offset, 0);
5154 SSM(sci, SCI_SETANCHOR, sci_get_position_from_line(sci, anchor_line) + anchor_offset, 0);
5158 /** Gets snippet by name.
5160 * If @a editor is passed, returns a snippet specific to the document filetype.
5161 * If @a editor is @c NULL, returns a snippet from the default set.
5163 * @param editor Editor or @c NULL.
5164 * @param snippet_name Snippet name.
5165 * @return snippet or @c NULL if it was not found. Must not be freed.
5167 GEANY_API_SYMBOL
5168 const gchar *editor_find_snippet(GeanyEditor *editor, const gchar *snippet_name)
5170 const gchar *subhash_name = editor ? editor->document->file_type->name : "Default";
5171 GHashTable *subhash = g_hash_table_lookup(snippet_hash, subhash_name);
5173 return subhash ? g_hash_table_lookup(subhash, snippet_name) : NULL;
5177 /** Replaces all special sequences in @a snippet and inserts it at @a pos.
5178 * If you insert at the current position, consider calling @c sci_scroll_caret()
5179 * after this function.
5180 * @param editor .
5181 * @param pos .
5182 * @param snippet .
5184 GEANY_API_SYMBOL
5185 void editor_insert_snippet(GeanyEditor *editor, gint pos, const gchar *snippet)
5187 GString *pattern;
5189 pattern = g_string_new(snippet);
5190 snippets_make_replacements(editor, pattern);
5191 editor_insert_text_block(editor, pattern->str, pos, -1, -1, TRUE);
5192 g_string_free(pattern, TRUE);