Colourise only the visible area when highlighting typenames
[geany-mirror.git] / src / editor.c
blob6a22b02b67799143548656c2e0298cc01c34fc07
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 const GPtrArray *tags = NULL;
707 const TMTag *tag;
708 GeanyFiletype *ft = editor->document->file_type;
710 if (ft->id == GEANY_FILETYPES_C || ft->id == GEANY_FILETYPES_CPP)
712 if (pos >= 2 && (match_last_chars(sci, pos, "->") || match_last_chars(sci, pos, "::")))
713 pos--;
714 else if (ft->id == GEANY_FILETYPES_CPP && pos >= 3 && match_last_chars(sci, pos, "->*"))
715 pos-=2;
716 else if (typed != '.')
717 return;
719 else if (typed != '.')
720 return;
722 /* allow for a space between word and operator */
723 if (isspace(sci_get_char_at(sci, pos - 2)))
724 pos--;
725 name = editor_get_word_at_pos(editor, pos - 1, NULL);
726 if (!name)
727 return;
729 tags = tm_workspace_find(name, tm_tag_max_t, NULL, FALSE, ft->lang);
730 g_free(name);
731 if (!tags || tags->len == 0)
732 return;
734 tag = g_ptr_array_index(tags, 0);
735 name = tag->var_type;
736 if (name)
738 TMSourceFile *obj = editor->document->tm_file;
740 tags = tm_workspace_find_scope_members(obj ? obj->tags_array : NULL,
741 name, TRUE, FALSE);
742 if (tags)
743 show_tags_list(editor, tags, 0);
748 static void on_char_added(GeanyEditor *editor, SCNotification *nt)
750 ScintillaObject *sci = editor->sci;
751 gint pos = sci_get_current_position(sci);
753 switch (nt->ch)
755 case '\r':
756 { /* simple indentation (only for CR format) */
757 if (sci_get_eol_mode(sci) == SC_EOL_CR)
758 on_new_line_added(editor);
759 break;
761 case '\n':
762 { /* simple indentation (for CR/LF and LF format) */
763 on_new_line_added(editor);
764 break;
766 case '>':
767 editor_start_auto_complete(editor, pos, FALSE); /* C/C++ ptr-> scope completion */
768 /* fall through */
769 case '/':
770 { /* close xml-tags */
771 handle_xml(editor, pos, nt->ch);
772 break;
774 case '(':
776 auto_close_chars(sci, pos, nt->ch);
777 /* show calltips */
778 editor_show_calltip(editor, --pos);
779 break;
781 case ')':
782 { /* hide calltips */
783 if (SSM(sci, SCI_CALLTIPACTIVE, 0, 0))
785 SSM(sci, SCI_CALLTIPCANCEL, 0, 0);
787 g_free(calltip.text);
788 calltip.text = NULL;
789 calltip.pos = 0;
790 calltip.sci = NULL;
791 calltip.set = FALSE;
792 break;
794 case '{':
795 case '[':
796 case '"':
797 case '\'':
799 auto_close_chars(sci, pos, nt->ch);
800 break;
802 case '}':
803 { /* closing bracket handling */
804 if (editor->auto_indent)
805 close_block(editor, pos - 1);
806 break;
808 /* scope autocompletion */
809 case '.':
810 case ':': /* C/C++ class:: syntax */
811 /* tag autocompletion */
812 default:
813 #if 0
814 if (! editor_start_auto_complete(editor, pos, FALSE))
815 request_reshowing_calltip(nt);
816 #else
817 editor_start_auto_complete(editor, pos, FALSE);
818 #endif
820 check_line_breaking(editor, pos);
824 /* expand() and fold_changed() are copied from SciTE (thanks) to fix #1923350. */
825 static void expand(ScintillaObject *sci, gint *line, gboolean doExpand,
826 gboolean force, gint visLevels, gint level)
828 gint lineMaxSubord = SSM(sci, SCI_GETLASTCHILD, *line, level & SC_FOLDLEVELNUMBERMASK);
829 gint levelLine = level;
830 (*line)++;
831 while (*line <= lineMaxSubord)
833 if (force)
835 if (visLevels > 0)
836 SSM(sci, SCI_SHOWLINES, *line, *line);
837 else
838 SSM(sci, SCI_HIDELINES, *line, *line);
840 else
842 if (doExpand)
843 SSM(sci, SCI_SHOWLINES, *line, *line);
845 if (levelLine == -1)
846 levelLine = SSM(sci, SCI_GETFOLDLEVEL, *line, 0);
847 if (levelLine & SC_FOLDLEVELHEADERFLAG)
849 if (force)
851 if (visLevels > 1)
852 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
853 else
854 SSM(sci, SCI_SETFOLDEXPANDED, *line, 0);
855 expand(sci, line, doExpand, force, visLevels - 1, -1);
857 else
859 if (doExpand)
861 if (!sci_get_fold_expanded(sci, *line))
862 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
863 expand(sci, line, TRUE, force, visLevels - 1, -1);
865 else
867 expand(sci, line, FALSE, force, visLevels - 1, -1);
871 else
873 (*line)++;
879 static void fold_changed(ScintillaObject *sci, gint line, gint levelNow, gint levelPrev)
881 if (levelNow & SC_FOLDLEVELHEADERFLAG)
883 if (! (levelPrev & SC_FOLDLEVELHEADERFLAG))
885 /* Adding a fold point */
886 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
887 if (!SSM(sci, SCI_GETALLLINESVISIBLE, 0, 0))
888 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
891 else if (levelPrev & SC_FOLDLEVELHEADERFLAG)
893 if (! sci_get_fold_expanded(sci, line))
894 { /* Removing the fold from one that has been contracted so should expand
895 * otherwise lines are left invisible with no way to make them visible */
896 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
897 if (!SSM(sci, SCI_GETALLLINESVISIBLE, 0, 0))
898 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
901 if (! (levelNow & SC_FOLDLEVELWHITEFLAG) &&
902 ((levelPrev & SC_FOLDLEVELNUMBERMASK) > (levelNow & SC_FOLDLEVELNUMBERMASK)))
904 if (!SSM(sci, SCI_GETALLLINESVISIBLE, 0, 0)) {
905 /* See if should still be hidden */
906 gint parentLine = sci_get_fold_parent(sci, line);
907 if (parentLine < 0)
909 SSM(sci, SCI_SHOWLINES, line, line);
911 else if (sci_get_fold_expanded(sci, parentLine) &&
912 sci_get_line_is_visible(sci, parentLine))
914 SSM(sci, SCI_SHOWLINES, line, line);
921 static void ensure_range_visible(ScintillaObject *sci, gint posStart, gint posEnd,
922 gboolean enforcePolicy)
924 gint lineStart = sci_get_line_from_position(sci, MIN(posStart, posEnd));
925 gint lineEnd = sci_get_line_from_position(sci, MAX(posStart, posEnd));
926 gint line;
928 for (line = lineStart; line <= lineEnd; line++)
930 SSM(sci, enforcePolicy ? SCI_ENSUREVISIBLEENFORCEPOLICY : SCI_ENSUREVISIBLE, line, 0);
935 static void auto_update_margin_width(GeanyEditor *editor)
937 gint next_linecount = 1;
938 gint linecount = sci_get_line_count(editor->sci);
939 GeanyDocument *doc = editor->document;
941 while (next_linecount <= linecount)
942 next_linecount *= 10;
944 if (editor->document->priv->line_count != next_linecount)
946 doc->priv->line_count = next_linecount;
947 sci_set_line_numbers(editor->sci, TRUE);
952 static void partial_complete(ScintillaObject *sci, const gchar *text)
954 gint pos = sci_get_current_position(sci);
956 sci_insert_text(sci, pos, text);
957 sci_set_current_position(sci, pos + strlen(text), TRUE);
961 /* Complete the next word part from @a entry */
962 static gboolean check_partial_completion(GeanyEditor *editor, const gchar *entry)
964 gchar *stem, *ptr, *text = utils_strdupa(entry);
966 read_current_word(editor, -1, current_word, sizeof current_word, NULL, TRUE);
967 stem = current_word;
968 if (strstr(text, stem) != text)
969 return FALSE; /* shouldn't happen */
970 if (strlen(text) <= strlen(stem))
971 return FALSE;
973 text += strlen(stem); /* skip stem */
974 ptr = strstr(text + 1, "_");
975 if (ptr)
977 ptr[1] = '\0';
978 partial_complete(editor->sci, text);
979 return TRUE;
981 else
983 /* CamelCase */
984 foreach_str(ptr, text + 1)
986 if (!ptr[0])
987 break;
988 if (g_ascii_isupper(*ptr) && g_ascii_islower(ptr[1]))
990 ptr[0] = '\0';
991 partial_complete(editor->sci, text);
992 return TRUE;
996 return FALSE;
1000 /* Callback for the "sci-notify" signal to emit a "editor-notify" signal.
1001 * Plugins can connect to the "editor-notify" signal. */
1002 void editor_sci_notify_cb(G_GNUC_UNUSED GtkWidget *widget, G_GNUC_UNUSED gint scn,
1003 gpointer scnt, gpointer data)
1005 GeanyEditor *editor = data;
1006 gboolean retval;
1008 g_return_if_fail(editor != NULL);
1010 g_signal_emit_by_name(geany_object, "editor-notify", editor, scnt, &retval);
1014 static gboolean on_editor_notify(G_GNUC_UNUSED GObject *object, GeanyEditor *editor,
1015 SCNotification *nt, G_GNUC_UNUSED gpointer data)
1017 ScintillaObject *sci = editor->sci;
1018 GeanyDocument *doc = editor->document;
1020 switch (nt->nmhdr.code)
1022 case SCN_SAVEPOINTLEFT:
1023 document_set_text_changed(doc, TRUE);
1024 break;
1026 case SCN_SAVEPOINTREACHED:
1027 document_set_text_changed(doc, FALSE);
1028 break;
1030 case SCN_MODIFYATTEMPTRO:
1031 utils_beep();
1032 break;
1034 case SCN_MARGINCLICK:
1035 on_margin_click(editor, nt);
1036 break;
1038 case SCN_UPDATEUI:
1039 on_update_ui(editor, nt);
1040 break;
1042 case SCN_PAINTED:
1043 /* Visible lines are only laid out accurately just before painting,
1044 * so we need to only call editor_scroll_to_line here, because the document
1045 * may have line wrapping and folding enabled.
1046 * http://scintilla.sourceforge.net/ScintillaDoc.html#LineWrapping
1047 * This is important e.g. when loading a session and switching pages
1048 * and having the cursor scroll in view. */
1049 /* FIXME: Really we want to do this just before painting, not after it
1050 * as it will cause repainting. */
1051 if (editor->scroll_percent > 0.0F)
1053 editor_scroll_to_line(editor, -1, editor->scroll_percent);
1054 /* disable further scrolling */
1055 editor->scroll_percent = -1.0F;
1057 break;
1059 case SCN_MODIFIED:
1060 if (editor_prefs.show_linenumber_margin && (nt->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT)) && nt->linesAdded)
1062 /* automatically adjust Scintilla's line numbers margin width */
1063 auto_update_margin_width(editor);
1065 if (nt->modificationType & SC_STARTACTION && ! ignore_callback)
1067 /* get notified about undo changes */
1068 document_undo_add(doc, UNDO_SCINTILLA, NULL);
1070 if (editor_prefs.folding && (nt->modificationType & SC_MOD_CHANGEFOLD) != 0)
1072 /* handle special fold cases, e.g. #1923350 */
1073 fold_changed(sci, nt->line, nt->foldLevelNow, nt->foldLevelPrev);
1075 if (nt->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT))
1077 document_update_tag_list_in_idle(doc);
1079 break;
1081 case SCN_CHARADDED:
1082 on_char_added(editor, nt);
1083 break;
1085 case SCN_USERLISTSELECTION:
1086 if (nt->listType == 1)
1088 sci_add_text(sci, nt->text);
1090 break;
1092 case SCN_AUTOCSELECTION:
1093 if (g_str_equal(nt->text, "..."))
1095 sci_cancel(sci);
1096 utils_beep();
1097 break;
1099 /* fall through */
1100 case SCN_AUTOCCANCELLED:
1101 /* now that autocomplete is finishing or was cancelled, reshow calltips
1102 * if they were showing */
1103 request_reshowing_calltip(nt);
1104 break;
1105 case SCN_NEEDSHOWN:
1106 ensure_range_visible(sci, nt->position, nt->position + nt->length, FALSE);
1107 break;
1109 case SCN_URIDROPPED:
1110 if (nt->text != NULL)
1112 document_open_file_list(nt->text, strlen(nt->text));
1114 break;
1116 case SCN_CALLTIPCLICK:
1117 if (nt->position > 0)
1119 switch (nt->position)
1121 case 1: /* up arrow */
1122 if (calltip.tag_index > 0)
1123 calltip.tag_index--;
1124 break;
1126 case 2: calltip.tag_index++; break; /* down arrow */
1128 editor_show_calltip(editor, -1);
1130 break;
1132 case SCN_ZOOM:
1133 /* recalculate line margin width */
1134 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin);
1135 break;
1137 /* we always return FALSE here to let plugins handle the event too */
1138 return FALSE;
1142 /* Note: this is the same as sci_get_tab_width(), but is still useful when you don't have
1143 * a scintilla pointer. */
1144 static gint get_tab_width(const GeanyIndentPrefs *indent_prefs)
1146 if (indent_prefs->type == GEANY_INDENT_TYPE_BOTH)
1147 return indent_prefs->hard_tab_width;
1149 return indent_prefs->width; /* tab width = indent width */
1153 /* Returns a string containing width chars of whitespace, filled with simple space
1154 * characters or with the right number of tab characters, according to the indent prefs.
1155 * (Result is filled with tabs *and* spaces if width isn't a multiple of
1156 * the tab width). */
1157 static gchar *
1158 get_whitespace(const GeanyIndentPrefs *iprefs, gint width)
1160 g_return_val_if_fail(width >= 0, NULL);
1162 if (width == 0)
1163 return g_strdup("");
1165 if (iprefs->type == GEANY_INDENT_TYPE_SPACES)
1167 return g_strnfill(width, ' ');
1169 else
1170 { /* first fill text with tabs and fill the rest with spaces */
1171 const gint tab_width = get_tab_width(iprefs);
1172 gint tabs = width / tab_width;
1173 gint spaces = width % tab_width;
1174 gint len = tabs + spaces;
1175 gchar *str;
1177 str = g_malloc(len + 1);
1179 memset(str, '\t', tabs);
1180 memset(str + tabs, ' ', spaces);
1181 str[len] = '\0';
1182 return str;
1187 static const GeanyIndentPrefs *
1188 get_default_indent_prefs(void)
1190 static GeanyIndentPrefs iprefs;
1192 iprefs = app->project ? *app->project->priv->indentation : *editor_prefs.indentation;
1193 return &iprefs;
1197 /** Gets the indentation prefs for the editor.
1198 * Prefs can be different according to project or document.
1199 * @warning Always get a fresh result instead of keeping a pointer to it if the editor/project
1200 * settings may have changed, or if this function has been called for a different editor.
1201 * @param editor The editor, or @c NULL to get the default indent prefs.
1202 * @return The indent prefs. */
1203 GEANY_API_SYMBOL
1204 const GeanyIndentPrefs *
1205 editor_get_indent_prefs(GeanyEditor *editor)
1207 static GeanyIndentPrefs iprefs;
1208 const GeanyIndentPrefs *dprefs = get_default_indent_prefs();
1210 /* Return the address of the default prefs to allow returning default and editor
1211 * pref pointers without invalidating the contents of either. */
1212 if (editor == NULL)
1213 return dprefs;
1215 iprefs = *dprefs;
1216 iprefs.type = editor->indent_type;
1217 iprefs.width = editor->indent_width;
1219 /* if per-document auto-indent is enabled, but we don't have a global mode set,
1220 * just use basic auto-indenting */
1221 if (editor->auto_indent && iprefs.auto_indent_mode == GEANY_AUTOINDENT_NONE)
1222 iprefs.auto_indent_mode = GEANY_AUTOINDENT_BASIC;
1224 if (!editor->auto_indent)
1225 iprefs.auto_indent_mode = GEANY_AUTOINDENT_NONE;
1227 return &iprefs;
1231 static void on_new_line_added(GeanyEditor *editor)
1233 ScintillaObject *sci = editor->sci;
1234 gint line = sci_get_current_line(sci);
1236 /* simple indentation */
1237 if (editor->auto_indent)
1239 insert_indent_after_line(editor, line - 1);
1242 if (get_project_pref(auto_continue_multiline))
1243 { /* " * " auto completion in multiline C/C++/D/Java comments */
1244 auto_multiline(editor, line);
1247 if (editor_prefs.newline_strip)
1248 { /* strip the trailing spaces on the previous line */
1249 editor_strip_line_trailing_spaces(editor, line - 1);
1254 static gboolean lexer_has_braces(ScintillaObject *sci)
1256 gint lexer = sci_get_lexer(sci);
1258 switch (lexer)
1260 case SCLEX_CPP:
1261 case SCLEX_D:
1262 case SCLEX_HTML: /* for PHP & JS */
1263 case SCLEX_PHPSCRIPT:
1264 case SCLEX_PASCAL: /* for multiline comments? */
1265 case SCLEX_BASH:
1266 case SCLEX_PERL:
1267 case SCLEX_TCL:
1268 case SCLEX_R:
1269 case SCLEX_RUST:
1270 return TRUE;
1271 default:
1272 return FALSE;
1277 /* Read indent chars for the line that pos is on into indent global variable.
1278 * Note: Use sci_get_line_indentation() and get_whitespace()/editor_insert_text_block()
1279 * instead in any new code. */
1280 static void read_indent(GeanyEditor *editor, gint pos)
1282 ScintillaObject *sci = editor->sci;
1283 guint i, len, j = 0;
1284 gint line;
1285 gchar *linebuf;
1287 line = sci_get_line_from_position(sci, pos);
1289 len = sci_get_line_length(sci, line);
1290 linebuf = sci_get_line(sci, line);
1292 for (i = 0; i < len && j <= (sizeof(indent) - 1); i++)
1294 if (linebuf[i] == ' ' || linebuf[i] == '\t') /* simple indentation */
1295 indent[j++] = linebuf[i];
1296 else
1297 break;
1299 indent[j] = '\0';
1300 g_free(linebuf);
1304 static gint get_brace_indent(ScintillaObject *sci, gint line)
1306 gint start = sci_get_position_from_line(sci, line);
1307 gint end = sci_get_line_end_position(sci, line) - 1;
1308 gint lexer = sci_get_lexer(sci);
1309 gint count = 0;
1310 gint pos;
1312 for (pos = end; pos >= start && count < 1; pos--)
1314 if (highlighting_is_code_style(lexer, sci_get_style_at(sci, pos)))
1316 gchar c = sci_get_char_at(sci, pos);
1318 if (c == '{')
1319 count ++;
1320 else if (c == '}')
1321 count --;
1325 return count > 0 ? 1 : 0;
1329 /* gets the last code position on a line
1330 * warning: if there is no code position on the line, returns the start position */
1331 static gint get_sci_line_code_end_position(ScintillaObject *sci, gint line)
1333 gint start = sci_get_position_from_line(sci, line);
1334 gint lexer = sci_get_lexer(sci);
1335 gint pos;
1337 for (pos = sci_get_line_end_position(sci, line) - 1; pos > start; pos--)
1339 gint style = sci_get_style_at(sci, pos);
1341 if (highlighting_is_code_style(lexer, style) && ! isspace(sci_get_char_at(sci, pos)))
1342 break;
1345 return pos;
1349 static gint get_python_indent(ScintillaObject *sci, gint line)
1351 gint last_char = get_sci_line_code_end_position(sci, line);
1353 /* add extra indentation for Python after colon */
1354 if (sci_get_char_at(sci, last_char) == ':' &&
1355 sci_get_style_at(sci, last_char) == SCE_P_OPERATOR)
1357 return 1;
1359 return 0;
1363 static gint get_xml_indent(ScintillaObject *sci, gint line)
1365 gboolean need_close = FALSE;
1366 gint end = get_sci_line_code_end_position(sci, line);
1367 gint pos;
1369 /* don't indent if there's a closing tag to the right of the cursor */
1370 pos = sci_get_current_position(sci);
1371 if (sci_get_char_at(sci, pos) == '<' &&
1372 sci_get_char_at(sci, pos + 1) == '/')
1373 return 0;
1375 if (sci_get_char_at(sci, end) == '>' &&
1376 sci_get_char_at(sci, end - 1) != '/')
1378 gint style = sci_get_style_at(sci, end);
1380 if (style == SCE_H_TAG || style == SCE_H_TAGUNKNOWN)
1382 gint start = sci_get_position_from_line(sci, line);
1383 gchar *line_contents = sci_get_contents_range(sci, start, end + 1);
1384 gchar *opened_tag_name = utils_find_open_xml_tag(line_contents, end + 1 - start);
1386 if (!EMPTY(opened_tag_name))
1388 need_close = TRUE;
1389 if (sci_get_lexer(sci) == SCLEX_HTML && utils_is_short_html_tag(opened_tag_name))
1390 need_close = FALSE;
1392 g_free(line_contents);
1393 g_free(opened_tag_name);
1397 return need_close ? 1 : 0;
1401 static gint get_indent_size_after_line(GeanyEditor *editor, gint line)
1403 ScintillaObject *sci = editor->sci;
1404 gint size;
1405 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1407 g_return_val_if_fail(line >= 0, 0);
1409 size = sci_get_line_indentation(sci, line);
1411 if (iprefs->auto_indent_mode > GEANY_AUTOINDENT_BASIC)
1413 gint additional_indent = 0;
1415 if (lexer_has_braces(sci))
1416 additional_indent = iprefs->width * get_brace_indent(sci, line);
1417 else if (sci_get_lexer(sci) == SCLEX_PYTHON) /* Python/Cython */
1418 additional_indent = iprefs->width * get_python_indent(sci, line);
1420 /* HTML lexer "has braces" because of PHP and JavaScript. If get_brace_indent() did not
1421 * recommend us to insert additional indent, we are probably not in PHP/JavaScript chunk and
1422 * should make the XML-related check */
1423 if (additional_indent == 0 &&
1424 (sci_get_lexer(sci) == SCLEX_HTML ||
1425 sci_get_lexer(sci) == SCLEX_XML) &&
1426 editor->document->file_type->priv->xml_indent_tags)
1428 size += iprefs->width * get_xml_indent(sci, line);
1431 size += additional_indent;
1433 return size;
1437 static void insert_indent_after_line(GeanyEditor *editor, gint line)
1439 ScintillaObject *sci = editor->sci;
1440 gint line_indent = sci_get_line_indentation(sci, line);
1441 gint size = get_indent_size_after_line(editor, line);
1442 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1443 gchar *text;
1445 if (size == 0)
1446 return;
1448 if (iprefs->type == GEANY_INDENT_TYPE_TABS && size == line_indent)
1450 /* support tab indents, space aligns style - copy last line 'indent' exactly */
1451 gint start = sci_get_position_from_line(sci, line);
1452 gint end = sci_get_line_indent_position(sci, line);
1454 text = sci_get_contents_range(sci, start, end);
1456 else
1458 text = get_whitespace(iprefs, size);
1460 sci_add_text(sci, text);
1461 g_free(text);
1465 static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c)
1467 const gchar *closing_char = NULL;
1468 gint end_pos = -1;
1470 if (utils_isbrace(c, 0))
1471 end_pos = sci_find_matching_brace(sci, pos - 1);
1473 switch (c)
1475 case '(':
1476 if ((editor_prefs.autoclose_chars & GEANY_AC_PARENTHESIS) && end_pos == -1)
1477 closing_char = ")";
1478 break;
1479 case '{':
1480 if ((editor_prefs.autoclose_chars & GEANY_AC_CBRACKET) && end_pos == -1)
1481 closing_char = "}";
1482 break;
1483 case '[':
1484 if ((editor_prefs.autoclose_chars & GEANY_AC_SBRACKET) && end_pos == -1)
1485 closing_char = "]";
1486 break;
1487 case '\'':
1488 if (editor_prefs.autoclose_chars & GEANY_AC_SQUOTE)
1489 closing_char = "'";
1490 break;
1491 case '"':
1492 if (editor_prefs.autoclose_chars & GEANY_AC_DQUOTE)
1493 closing_char = "\"";
1494 break;
1497 if (closing_char != NULL)
1499 sci_add_text(sci, closing_char);
1500 sci_set_current_position(sci, pos, TRUE);
1505 /* Finds a corresponding matching brace to the given pos
1506 * (this is taken from Scintilla Editor.cxx,
1507 * fit to work with close_block) */
1508 static gint brace_match(ScintillaObject *sci, gint pos)
1510 gchar chBrace = sci_get_char_at(sci, pos);
1511 gchar chSeek = utils_brace_opposite(chBrace);
1512 gchar chAtPos;
1513 gint direction = -1;
1514 gint styBrace;
1515 gint depth = 1;
1516 gint styAtPos;
1518 /* Hack: we need the style at @p pos but it isn't computed yet, so force styling
1519 * of this very position */
1520 sci_colourise(sci, pos, pos + 1);
1522 styBrace = sci_get_style_at(sci, pos);
1524 if (utils_is_opening_brace(chBrace, editor_prefs.brace_match_ltgt))
1525 direction = 1;
1527 pos += direction;
1528 while ((pos >= 0) && (pos < sci_get_length(sci)))
1530 chAtPos = sci_get_char_at(sci, pos);
1531 styAtPos = sci_get_style_at(sci, pos);
1533 if ((pos > sci_get_end_styled(sci)) || (styAtPos == styBrace))
1535 if (chAtPos == chBrace)
1536 depth++;
1537 if (chAtPos == chSeek)
1538 depth--;
1539 if (depth == 0)
1540 return pos;
1542 pos += direction;
1544 return -1;
1548 /* Called after typing '}'. */
1549 static void close_block(GeanyEditor *editor, gint pos)
1551 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1552 gint x = 0, cnt = 0;
1553 gint line, line_len;
1554 gchar *text, *line_buf;
1555 ScintillaObject *sci;
1556 gint line_indent, last_indent;
1558 if (iprefs->auto_indent_mode < GEANY_AUTOINDENT_CURRENTCHARS)
1559 return;
1560 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
1562 sci = editor->sci;
1564 if (! lexer_has_braces(sci))
1565 return;
1567 line = sci_get_line_from_position(sci, pos);
1568 line_len = sci_get_line_end_position(sci, line) - sci_get_position_from_line(sci, line);
1570 /* check that the line is empty, to not kill text in the line */
1571 line_buf = sci_get_line(sci, line);
1572 line_buf[line_len] = '\0';
1573 while (x < line_len)
1575 if (isspace(line_buf[x]))
1576 cnt++;
1577 x++;
1579 g_free(line_buf);
1581 if ((line_len - 1) != cnt)
1582 return;
1584 if (iprefs->auto_indent_mode == GEANY_AUTOINDENT_MATCHBRACES)
1586 gint start_brace = brace_match(sci, pos);
1588 if (start_brace >= 0)
1590 gint line_start;
1591 gint brace_line = sci_get_line_from_position(sci, start_brace);
1592 gint size = sci_get_line_indentation(sci, brace_line);
1593 gchar *ind = get_whitespace(iprefs, size);
1595 text = g_strconcat(ind, "}", NULL);
1596 line_start = sci_get_position_from_line(sci, line);
1597 sci_set_anchor(sci, line_start);
1598 sci_replace_sel(sci, text);
1599 g_free(text);
1600 g_free(ind);
1601 return;
1603 /* fall through - unmatched brace (possibly because of TCL, PHP lexer bugs) */
1606 /* GEANY_AUTOINDENT_CURRENTCHARS */
1607 line_indent = sci_get_line_indentation(sci, line);
1608 last_indent = sci_get_line_indentation(sci, line - 1);
1610 if (line_indent < last_indent)
1611 return;
1612 line_indent -= iprefs->width;
1613 line_indent = MAX(0, line_indent);
1614 sci_set_line_indentation(sci, line, line_indent);
1618 /* checks whether @p c is an ASCII character (e.g. < 0x80) */
1619 #define IS_ASCII(c) (((unsigned char)(c)) < 0x80)
1622 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1623 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1624 * position can be -1, then the current position is used.
1625 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1626 static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen,
1627 const gchar *wc, gboolean stem)
1629 gint line, line_start, startword, endword;
1630 gchar *chunk;
1631 ScintillaObject *sci;
1633 g_return_if_fail(editor != NULL);
1634 sci = editor->sci;
1636 if (pos == -1)
1637 pos = sci_get_current_position(sci);
1639 line = sci_get_line_from_position(sci, pos);
1640 line_start = sci_get_position_from_line(sci, line);
1641 startword = pos - line_start;
1642 endword = pos - line_start;
1644 word[0] = '\0';
1645 chunk = sci_get_line(sci, line);
1647 if (wc == NULL)
1648 wc = GEANY_WORDCHARS;
1650 /* the checks for "c < 0" are to allow any Unicode character which should make the code
1651 * a little bit more Unicode safe, anyway, this allows also any Unicode punctuation,
1652 * TODO: improve this code */
1653 while (startword > 0 && (strchr(wc, chunk[startword - 1]) || ! IS_ASCII(chunk[startword - 1])))
1654 startword--;
1655 if (!stem)
1657 while (chunk[endword] != 0 && (strchr(wc, chunk[endword]) || ! IS_ASCII(chunk[endword])))
1658 endword++;
1661 if (startword != endword)
1663 chunk[endword] = '\0';
1665 g_strlcpy(word, chunk + startword, wordlen); /* ensure null terminated */
1667 else
1668 g_strlcpy(word, "", wordlen);
1670 g_free(chunk);
1674 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1675 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1676 * position can be -1, then the current position is used.
1677 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1678 void editor_find_current_word(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen,
1679 const gchar *wc)
1681 read_current_word(editor, pos, word, wordlen, wc, FALSE);
1685 /* Same as editor_find_current_word() but uses editor's word boundaries to decide what the word
1686 * is. This should be used e.g. to get the word to search for */
1687 void editor_find_current_word_sciwc(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen)
1689 gint start;
1690 gint end;
1692 g_return_if_fail(editor != NULL);
1694 if (pos == -1)
1695 pos = sci_get_current_position(editor->sci);
1697 start = sci_word_start_position(editor->sci, pos, TRUE);
1698 end = sci_word_end_position(editor->sci, pos, TRUE);
1700 if (start == end) /* caret in whitespaces sequence */
1701 *word = 0;
1702 else
1704 if ((guint)(end - start) >= wordlen)
1705 end = start + (wordlen - 1);
1706 sci_get_text_range(editor->sci, start, end, word);
1712 * Finds the word at the position specified by @a pos. If any word is found, it is returned.
1713 * Otherwise NULL is returned.
1714 * Additional wordchars can be specified to define what to consider as a word.
1716 * @param editor The editor to operate on.
1717 * @param pos The position where the word should be read from.
1718 * May be @c -1 to use the current position.
1719 * @param wordchars The wordchars to separate words. wordchars mean all characters to count
1720 * as part of a word. May be @c NULL to use the default wordchars,
1721 * see @ref GEANY_WORDCHARS.
1723 * @return A newly-allocated string containing the word at the given @a pos or @c NULL.
1724 * Should be freed when no longer needed.
1726 * @since 0.16
1728 GEANY_API_SYMBOL
1729 gchar *editor_get_word_at_pos(GeanyEditor *editor, gint pos, const gchar *wordchars)
1731 static gchar cword[GEANY_MAX_WORD_LENGTH];
1733 g_return_val_if_fail(editor != NULL, FALSE);
1735 read_current_word(editor, pos, cword, sizeof(cword), wordchars, FALSE);
1737 return (*cword == '\0') ? NULL : g_strdup(cword);
1741 /* Read the word up to position @a pos. */
1742 static const gchar *
1743 editor_read_word_stem(GeanyEditor *editor, gint pos, const gchar *wordchars)
1745 static gchar word[GEANY_MAX_WORD_LENGTH];
1747 read_current_word(editor, pos, word, sizeof word, wordchars, TRUE);
1749 return (*word) ? word : NULL;
1753 static gint find_previous_brace(ScintillaObject *sci, gint pos)
1755 gint orig_pos = pos;
1757 while (pos >= 0 && pos > orig_pos - 300)
1759 gchar c = sci_get_char_at(sci, pos);
1760 if (utils_is_opening_brace(c, editor_prefs.brace_match_ltgt))
1761 return pos;
1762 pos--;
1764 return -1;
1768 static gint find_start_bracket(ScintillaObject *sci, gint pos)
1770 gint brackets = 0;
1771 gint orig_pos = pos;
1773 while (pos > 0 && pos > orig_pos - 300)
1775 gchar c = sci_get_char_at(sci, pos);
1777 if (c == ')') brackets++;
1778 else if (c == '(') brackets--;
1779 if (brackets < 0) return pos; /* found start bracket */
1780 pos--;
1782 return -1;
1786 static gboolean append_calltip(GString *str, const TMTag *tag, filetype_id ft_id)
1788 if (! tag->arglist)
1789 return FALSE;
1791 if (ft_id != GEANY_FILETYPES_PASCAL && ft_id != GEANY_FILETYPES_GO)
1792 { /* usual calltips: "retval tagname (arglist)" */
1793 if (tag->var_type)
1795 guint i;
1797 g_string_append(str, tag->var_type);
1798 for (i = 0; i < tag->pointerOrder; i++)
1800 g_string_append_c(str, '*');
1802 g_string_append_c(str, ' ');
1804 if (tag->scope)
1806 const gchar *cosep = symbols_get_context_separator(ft_id);
1808 g_string_append(str, tag->scope);
1809 g_string_append(str, cosep);
1811 g_string_append(str, tag->name);
1812 g_string_append_c(str, ' ');
1813 g_string_append(str, tag->arglist);
1815 else
1816 { /* special case Pascal/Go calltips: "tagname (arglist) : retval"
1817 * (with ':' omitted for Go) */
1818 g_string_append(str, tag->name);
1819 g_string_append_c(str, ' ');
1820 g_string_append(str, tag->arglist);
1822 if (!EMPTY(tag->var_type))
1824 g_string_append(str, ft_id == GEANY_FILETYPES_PASCAL ? " : " : " ");
1825 g_string_append(str, tag->var_type);
1829 return TRUE;
1833 static gchar *find_calltip(const gchar *word, GeanyFiletype *ft)
1835 const GPtrArray *tags;
1836 const TMTagType arg_types = tm_tag_function_t | tm_tag_prototype_t |
1837 tm_tag_method_t | tm_tag_macro_with_arg_t;
1838 TMTagAttrType *attrs = NULL;
1839 TMTag *tag;
1840 GString *str = NULL;
1841 guint i;
1843 g_return_val_if_fail(ft && word && *word, NULL);
1845 /* use all types in case language uses wrong tag type e.g. python "members" instead of "methods" */
1846 tags = tm_workspace_find(word, tm_tag_max_t, attrs, FALSE, ft->lang);
1847 if (tags->len == 0)
1848 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 /* user typed e.g. 'new Classname(' so lookup D constructor Classname::this() */
1856 tags = tm_workspace_find_scoped("this", tag->name,
1857 arg_types, attrs, FALSE, ft->lang, TRUE);
1858 if (tags->len == 0)
1859 return NULL;
1862 /* remove tags with no argument list */
1863 for (i = 0; i < tags->len; i++)
1865 tag = TM_TAG(tags->pdata[i]);
1867 if (! tag->arglist)
1868 tags->pdata[i] = NULL;
1870 tm_tags_prune((GPtrArray *) tags);
1871 if (tags->len == 0)
1872 return NULL;
1873 else
1874 { /* remove duplicate calltips */
1875 TMTagAttrType sort_attr[] = {tm_tag_attr_name_t, tm_tag_attr_scope_t,
1876 tm_tag_attr_arglist_t, 0};
1878 tm_tags_sort((GPtrArray *) tags, sort_attr, TRUE, FALSE);
1881 /* if the current word has changed since last time, start with the first tag match */
1882 if (! utils_str_equal(word, calltip.last_word))
1883 calltip.tag_index = 0;
1884 /* cache the current word for next time */
1885 g_free(calltip.last_word);
1886 calltip.last_word = g_strdup(word);
1887 calltip.tag_index = MIN(calltip.tag_index, tags->len - 1); /* ensure tag_index is in range */
1889 for (i = calltip.tag_index; i < tags->len; i++)
1891 tag = TM_TAG(tags->pdata[i]);
1893 if (str == NULL)
1895 str = g_string_new(NULL);
1896 if (calltip.tag_index > 0)
1897 g_string_prepend(str, "\001 "); /* up arrow */
1898 append_calltip(str, tag, FILETYPE_ID(ft));
1900 else /* add a down arrow */
1902 if (calltip.tag_index > 0) /* already have an up arrow */
1903 g_string_insert_c(str, 1, '\002');
1904 else
1905 g_string_prepend(str, "\002 ");
1906 break;
1909 if (str)
1911 gchar *result = str->str;
1913 g_string_free(str, FALSE);
1914 return result;
1916 return NULL;
1920 /* use pos = -1 to search for the previous unmatched open bracket. */
1921 gboolean editor_show_calltip(GeanyEditor *editor, gint pos)
1923 gint orig_pos = pos; /* the position for the calltip */
1924 gint lexer;
1925 gint style;
1926 gchar word[GEANY_MAX_WORD_LENGTH];
1927 gchar *str;
1928 ScintillaObject *sci;
1930 g_return_val_if_fail(editor != NULL, FALSE);
1931 g_return_val_if_fail(editor->document->file_type != NULL, FALSE);
1933 sci = editor->sci;
1935 lexer = sci_get_lexer(sci);
1937 if (pos == -1)
1939 /* position of '(' is unknown, so go backwards from current position to find it */
1940 pos = sci_get_current_position(sci);
1941 pos--;
1942 orig_pos = pos;
1943 pos = (lexer == SCLEX_LATEX) ? find_previous_brace(sci, pos) :
1944 find_start_bracket(sci, pos);
1945 if (pos == -1)
1946 return FALSE;
1949 /* the style 1 before the brace (which may be highlighted) */
1950 style = sci_get_style_at(sci, pos - 1);
1951 if (! highlighting_is_code_style(lexer, style))
1952 return FALSE;
1954 word[0] = '\0';
1955 editor_find_current_word(editor, pos - 1, word, sizeof word, NULL);
1956 if (word[0] == '\0')
1957 return FALSE;
1959 str = find_calltip(word, editor->document->file_type);
1960 if (str)
1962 g_free(calltip.text); /* free the old calltip */
1963 calltip.text = str;
1964 calltip.pos = orig_pos;
1965 calltip.sci = sci;
1966 calltip.set = TRUE;
1967 utils_wrap_string(calltip.text, -1);
1968 SSM(sci, SCI_CALLTIPSHOW, orig_pos, (sptr_t) calltip.text);
1969 return TRUE;
1971 return FALSE;
1975 gchar *editor_get_calltip_text(GeanyEditor *editor, const TMTag *tag)
1977 GString *str;
1979 g_return_val_if_fail(editor != NULL, NULL);
1981 str = g_string_new(NULL);
1982 if (append_calltip(str, tag, editor->document->file_type->id))
1983 return g_string_free(str, FALSE);
1984 else
1985 return g_string_free(str, TRUE);
1989 /* HTML entities auto completion from html_entities.tags text file */
1990 static gboolean
1991 autocomplete_html(ScintillaObject *sci, const gchar *root, gsize rootlen)
1993 guint i;
1994 gboolean found = FALSE;
1995 GString *words;
1996 const gchar **entities = symbols_get_html_entities();
1998 if (*root != '&' || entities == NULL)
1999 return FALSE;
2001 words = g_string_sized_new(500);
2002 for (i = 0; ; i++)
2004 if (entities[i] == NULL)
2005 break;
2006 else if (entities[i][0] == '#')
2007 continue;
2009 if (! strncmp(entities[i], root, rootlen))
2011 if (words->len)
2012 g_string_append_c(words, '\n');
2014 g_string_append(words, entities[i]);
2015 found = TRUE;
2018 if (found)
2019 show_autocomplete(sci, rootlen, words);
2021 g_string_free(words, TRUE);
2022 return found;
2026 /* Current document & global tags autocompletion */
2027 static gboolean
2028 autocomplete_tags(GeanyEditor *editor, const gchar *root, gsize rootlen)
2030 TMTagAttrType attrs[] = { tm_tag_attr_name_t, 0 };
2031 const GPtrArray *tags;
2032 GeanyDocument *doc;
2034 g_return_val_if_fail(editor, FALSE);
2036 doc = editor->document;
2038 tags = tm_workspace_find(root, tm_tag_max_t, attrs, TRUE, doc->file_type->lang);
2039 if (tags)
2041 show_tags_list(editor, tags, rootlen);
2042 return tags->len > 0;
2044 return FALSE;
2048 static gboolean autocomplete_check_html(GeanyEditor *editor, gint style, gint pos)
2050 GeanyFiletype *ft = editor->document->file_type;
2051 gboolean try = FALSE;
2053 /* use entity completion when style is not JavaScript, ASP, Python, PHP, ...
2054 * (everything after SCE_HJ_START is for embedded scripting languages) */
2055 if (ft->id == GEANY_FILETYPES_HTML && style < SCE_HJ_START)
2056 try = TRUE;
2057 else if (sci_get_lexer(editor->sci) == SCLEX_XML && style < SCE_HJ_START)
2058 try = TRUE;
2059 else if (ft->id == GEANY_FILETYPES_PHP)
2061 /* use entity completion when style is outside of PHP styles */
2062 if (! is_style_php(style))
2063 try = TRUE;
2065 if (try)
2067 gchar root[GEANY_MAX_WORD_LENGTH];
2068 gchar *tmp;
2070 read_current_word(editor, pos, root, sizeof(root), GEANY_WORDCHARS"&", TRUE);
2072 /* Allow something like "&quot;some text&quot;".
2073 * for entity completion we want to have completion for '&' within words. */
2074 tmp = strchr(root, '&');
2075 if (tmp != NULL)
2077 return autocomplete_html(editor->sci, tmp, strlen(tmp));
2080 return FALSE;
2084 /* Algorithm based on based on Scite's StartAutoCompleteWord()
2085 * @returns a sorted list of words matching @p root */
2086 static GSList *get_doc_words(ScintillaObject *sci, gchar *root, gsize rootlen)
2088 gchar *word;
2089 gint len, current, word_end;
2090 gint pos_find, flags;
2091 guint word_length;
2092 gsize nmatches = 0;
2093 GSList *words = NULL;
2094 struct Sci_TextToFind ttf;
2096 len = sci_get_length(sci);
2097 current = sci_get_current_position(sci) - rootlen;
2099 ttf.lpstrText = root;
2100 ttf.chrg.cpMin = 0;
2101 ttf.chrg.cpMax = len;
2102 ttf.chrgText.cpMin = 0;
2103 ttf.chrgText.cpMax = 0;
2104 flags = SCFIND_WORDSTART | SCFIND_MATCHCASE;
2106 /* search the whole document for the word root and collect results */
2107 pos_find = scintilla_send_message(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
2108 while (pos_find >= 0 && pos_find < len)
2110 word_end = pos_find + rootlen;
2111 if (pos_find != current)
2113 word_end = sci_word_end_position(sci, word_end, TRUE);
2115 word_length = word_end - pos_find;
2116 if (word_length > rootlen)
2118 word = sci_get_contents_range(sci, pos_find, word_end);
2119 /* search whether we already have the word in, otherwise add it */
2120 if (g_slist_find_custom(words, word, (GCompareFunc)strcmp) != NULL)
2121 g_free(word);
2122 else
2124 words = g_slist_prepend(words, word);
2125 nmatches++;
2128 if (nmatches == editor_prefs.autocompletion_max_entries)
2129 break;
2132 ttf.chrg.cpMin = word_end;
2133 pos_find = scintilla_send_message(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
2136 return g_slist_sort(words, (GCompareFunc)utils_str_casecmp);
2140 static gboolean autocomplete_doc_word(GeanyEditor *editor, gchar *root, gsize rootlen)
2142 ScintillaObject *sci = editor->sci;
2143 GSList *words, *node;
2144 GString *str;
2145 guint n_words = 0;
2147 words = get_doc_words(sci, root, rootlen);
2148 if (!words)
2150 scintilla_send_message(sci, SCI_AUTOCCANCEL, 0, 0);
2151 return FALSE;
2154 str = g_string_sized_new(rootlen * 2 * 10);
2155 foreach_slist(node, words)
2157 g_string_append(str, node->data);
2158 g_free(node->data);
2159 if (node->next)
2160 g_string_append_c(str, '\n');
2161 n_words++;
2163 if (n_words >= editor_prefs.autocompletion_max_entries)
2164 g_string_append(str, "\n...");
2166 g_slist_free(words);
2168 show_autocomplete(sci, rootlen, str);
2169 g_string_free(str, TRUE);
2170 return TRUE;
2174 gboolean editor_start_auto_complete(GeanyEditor *editor, gint pos, gboolean force)
2176 gint rootlen, lexer, style;
2177 gchar *root;
2178 gchar cword[GEANY_MAX_WORD_LENGTH];
2179 ScintillaObject *sci;
2180 gboolean ret = FALSE;
2181 const gchar *wordchars;
2182 GeanyFiletype *ft;
2184 g_return_val_if_fail(editor != NULL, FALSE);
2186 if (! editor_prefs.auto_complete_symbols && ! force)
2187 return FALSE;
2189 /* If we are at the beginning of the document, we skip autocompletion as we can't determine the
2190 * necessary styling information */
2191 if (G_UNLIKELY(pos < 2))
2192 return FALSE;
2194 sci = editor->sci;
2195 ft = editor->document->file_type;
2197 lexer = sci_get_lexer(sci);
2198 style = sci_get_style_at(sci, pos - 2);
2200 /* don't autocomplete in comments and strings */
2201 if (!force && !highlighting_is_code_style(lexer, style))
2202 return FALSE;
2204 autocomplete_scope(editor);
2205 ret = autocomplete_check_html(editor, style, pos);
2207 if (ft->id == GEANY_FILETYPES_LATEX)
2208 wordchars = GEANY_WORDCHARS"\\"; /* add \ to word chars if we are in a LaTeX file */
2209 else if (ft->id == GEANY_FILETYPES_CSS)
2210 wordchars = GEANY_WORDCHARS"-"; /* add - because they are part of property names */
2211 else
2212 wordchars = GEANY_WORDCHARS;
2214 read_current_word(editor, pos, cword, sizeof(cword), wordchars, TRUE);
2215 root = cword;
2216 rootlen = strlen(root);
2218 if (!ret && rootlen > 0)
2220 if (ft->id == GEANY_FILETYPES_PHP && style == SCE_HPHP_DEFAULT &&
2221 rootlen == 3 && strcmp(root, "php") == 0 && pos >= 5 &&
2222 sci_get_char_at(sci, pos - 5) == '<' &&
2223 sci_get_char_at(sci, pos - 4) == '?')
2225 /* nothing, don't complete PHP open tags */
2227 else
2229 /* force is set when called by keyboard shortcut, otherwise start at the
2230 * editor_prefs.symbolcompletion_min_chars'th char */
2231 if (force || rootlen >= editor_prefs.symbolcompletion_min_chars)
2233 /* complete tags, except if forcing when completion is already visible */
2234 if (!(force && SSM(sci, SCI_AUTOCACTIVE, 0, 0)))
2235 ret = autocomplete_tags(editor, root, rootlen);
2237 /* If forcing and there's nothing else to show, complete from words in document */
2238 if (!ret && (force || editor_prefs.autocomplete_doc_words))
2239 ret = autocomplete_doc_word(editor, root, rootlen);
2243 if (!ret && force)
2244 utils_beep();
2246 return ret;
2250 static const gchar *snippets_find_completion_by_name(const gchar *type, const gchar *name)
2252 gchar *result = NULL;
2253 GHashTable *tmp;
2255 g_return_val_if_fail(type != NULL && name != NULL, NULL);
2257 tmp = g_hash_table_lookup(snippet_hash, type);
2258 if (tmp != NULL)
2260 result = g_hash_table_lookup(tmp, name);
2262 /* whether nothing is set for the current filetype(tmp is NULL) or
2263 * the particular completion for this filetype is not set (result is NULL) */
2264 if (tmp == NULL || result == NULL)
2266 tmp = g_hash_table_lookup(snippet_hash, "Default");
2267 if (tmp != NULL)
2269 result = g_hash_table_lookup(tmp, name);
2272 /* if result is still NULL here, no completion could be found */
2274 /* result is owned by the hash table and will be freed when the table will destroyed */
2275 return result;
2279 static void snippets_replace_specials(gpointer key, gpointer value, gpointer user_data)
2281 gchar *needle;
2282 GString *pattern = user_data;
2284 g_return_if_fail(key != NULL);
2285 g_return_if_fail(value != NULL);
2287 needle = g_strconcat("%", (gchar*) key, "%", NULL);
2289 utils_string_replace_all(pattern, needle, (gchar*) value);
2290 g_free(needle);
2294 static void fix_indentation(GeanyEditor *editor, GString *buf)
2296 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
2297 gchar *whitespace;
2298 GRegex *regex;
2299 gint cflags = G_REGEX_MULTILINE;
2301 /* transform leading tabs into indent widths (in spaces) */
2302 whitespace = g_strnfill(iprefs->width, ' ');
2303 regex = g_regex_new("^ *(\t)", cflags, 0, NULL);
2304 while (utils_string_regex_replace_all(buf, regex, 1, whitespace, TRUE));
2305 g_regex_unref(regex);
2307 /* remaining tabs are for alignment */
2308 if (iprefs->type != GEANY_INDENT_TYPE_TABS)
2309 utils_string_replace_all(buf, "\t", whitespace);
2311 /* use leading tabs */
2312 if (iprefs->type != GEANY_INDENT_TYPE_SPACES)
2314 gchar *str;
2316 /* for tabs+spaces mode we want the real tab width, not indent width */
2317 SETPTR(whitespace, g_strnfill(sci_get_tab_width(editor->sci), ' '));
2318 str = g_strdup_printf("^\t*(%s)", whitespace);
2320 regex = g_regex_new(str, cflags, 0, NULL);
2321 while (utils_string_regex_replace_all(buf, regex, 1, "\t", TRUE));
2322 g_regex_unref(regex);
2323 g_free(str);
2325 g_free(whitespace);
2329 /** Inserts text, replacing \\t tab chars (@c 0x9) and \\n newline chars (@c 0xA)
2330 * accordingly for the document.
2331 * - Leading tabs are replaced with the correct indentation.
2332 * - Non-leading tabs are replaced with spaces (except when using 'Tabs' indent type).
2333 * - Newline chars are replaced with the correct line ending string.
2334 * This is very useful for inserting code without having to handle the indent
2335 * type yourself (Tabs & Spaces mode can be tricky).
2336 * @param editor Editor.
2337 * @param text Intended as e.g. @c "if (foo)\n\tbar();".
2338 * @param insert_pos Document position to insert text at.
2339 * @param cursor_index If >= 0, the index into @a text to place the cursor.
2340 * @param newline_indent_size Indentation size (in spaces) to insert for each newline; use
2341 * -1 to read the indent size from the line with @a insert_pos on it.
2342 * @param replace_newlines Whether to replace newlines. If
2343 * newlines have been replaced already, this should be false, to avoid errors e.g. on Windows.
2344 * @warning Make sure all \\t tab chars in @a text are intended as indent widths or alignment,
2345 * not hard tabs, as those won't be preserved.
2346 * @note This doesn't scroll the cursor in view afterwards. **/
2347 GEANY_API_SYMBOL
2348 void editor_insert_text_block(GeanyEditor *editor, const gchar *text, gint insert_pos,
2349 gint cursor_index, gint newline_indent_size, gboolean replace_newlines)
2351 ScintillaObject *sci = editor->sci;
2352 gint line_start = sci_get_line_from_position(sci, insert_pos);
2353 GString *buf;
2354 const gchar *eol = editor_get_eol_char(editor);
2355 gint idx;
2357 g_return_if_fail(text);
2358 g_return_if_fail(editor != NULL);
2359 g_return_if_fail(insert_pos >= 0);
2361 buf = g_string_new(text);
2363 if (cursor_index >= 0)
2364 g_string_insert(buf, cursor_index, geany_cursor_marker); /* remember cursor pos */
2366 if (newline_indent_size == -1)
2368 /* count indent size up to insert_pos instead of asking sci
2369 * because there may be spaces after it */
2370 gchar *tmp = sci_get_line(sci, line_start);
2372 idx = insert_pos - sci_get_position_from_line(sci, line_start);
2373 tmp[idx] = '\0';
2374 newline_indent_size = count_indent_size(editor, tmp);
2375 g_free(tmp);
2378 /* Add line indents (in spaces) */
2379 if (newline_indent_size > 0)
2381 const gchar *nl = replace_newlines ? "\n" : eol;
2382 gchar *whitespace;
2384 whitespace = g_strnfill(newline_indent_size, ' ');
2385 SETPTR(whitespace, g_strconcat(nl, whitespace, NULL));
2386 utils_string_replace_all(buf, nl, whitespace);
2387 g_free(whitespace);
2390 /* transform line endings */
2391 if (replace_newlines)
2392 utils_string_replace_all(buf, "\n", eol);
2394 fix_indentation(editor, buf);
2396 idx = replace_cursor_markers(editor, buf);
2397 if (idx >= 0)
2399 sci_insert_text(sci, insert_pos, buf->str);
2400 sci_set_current_position(sci, insert_pos + idx, FALSE);
2402 else
2403 sci_insert_text(sci, insert_pos, buf->str);
2405 snippet_cursor_insert_pos = sci_get_current_position(sci);
2407 g_string_free(buf, TRUE);
2411 /* Move the cursor to the next specified cursor position in an inserted snippet.
2412 * Can, and should, be optimized to give better results */
2413 void editor_goto_next_snippet_cursor(GeanyEditor *editor)
2415 ScintillaObject *sci = editor->sci;
2416 gint current_pos = sci_get_current_position(sci);
2418 if (snippet_offsets && !g_queue_is_empty(snippet_offsets))
2420 gint offset;
2422 offset = GPOINTER_TO_INT(g_queue_pop_head(snippet_offsets));
2423 if (current_pos > snippet_cursor_insert_pos)
2424 snippet_cursor_insert_pos = offset + current_pos;
2425 else
2426 snippet_cursor_insert_pos += offset;
2428 sci_set_current_position(sci, snippet_cursor_insert_pos, TRUE);
2430 else
2432 utils_beep();
2437 static void snippets_make_replacements(GeanyEditor *editor, GString *pattern)
2439 GHashTable *specials;
2441 /* replace 'special' completions */
2442 specials = g_hash_table_lookup(snippet_hash, "Special");
2443 if (G_LIKELY(specials != NULL))
2445 g_hash_table_foreach(specials, snippets_replace_specials, pattern);
2448 /* now transform other wildcards */
2449 utils_string_replace_all(pattern, "%newline%", "\n");
2450 utils_string_replace_all(pattern, "%ws%", "\t");
2452 /* replace %cursor% by a very unlikely string marker */
2453 utils_string_replace_all(pattern, "%cursor%", geany_cursor_marker);
2455 /* unescape '%' after all %wildcards% */
2456 templates_replace_valist(pattern, "{pc}", "%", NULL);
2458 /* replace any template {foo} wildcards */
2459 templates_replace_common(pattern, editor->document->file_name, editor->document->file_type, NULL);
2463 static gssize replace_cursor_markers(GeanyEditor *editor, GString *pattern)
2465 gssize cur_index = -1;
2466 gint i;
2467 GList *temp_list = NULL;
2468 gint cursor_steps = 0, old_cursor = 0;
2470 i = 0;
2471 while (1)
2473 cursor_steps = utils_string_find(pattern, cursor_steps, -1, geany_cursor_marker);
2474 if (cursor_steps == -1)
2475 break;
2477 g_string_erase(pattern, cursor_steps, strlen(geany_cursor_marker));
2479 if (i++ > 0)
2481 /* save the relative offset to each cursor position */
2482 temp_list = g_list_prepend(temp_list, GINT_TO_POINTER(cursor_steps - old_cursor));
2484 else
2486 /* first cursor already includes newline positions */
2487 cur_index = cursor_steps;
2489 old_cursor = cursor_steps;
2492 /* put the cursor positions for the most recent
2493 * parsed snippet first, followed by any remaining positions */
2494 i = 0;
2495 if (temp_list)
2497 GList *node;
2499 temp_list = g_list_reverse(temp_list);
2500 foreach_list(node, temp_list)
2501 g_queue_push_nth(snippet_offsets, node->data, i++);
2503 /* limit length of queue */
2504 while (g_queue_get_length(snippet_offsets) > 20)
2505 g_queue_pop_tail(snippet_offsets);
2507 g_list_free(temp_list);
2509 /* if there's no first cursor, skip whole snippet */
2510 if (cur_index < 0)
2511 cur_index = pattern->len;
2513 return cur_index;
2517 static gboolean snippets_complete_constructs(GeanyEditor *editor, gint pos, const gchar *word)
2519 ScintillaObject *sci = editor->sci;
2520 gchar *str;
2521 const gchar *completion;
2522 gint str_len;
2523 gint ft_id = editor->document->file_type->id;
2525 str = g_strdup(word);
2526 g_strstrip(str);
2528 completion = snippets_find_completion_by_name(filetypes[ft_id]->name, str);
2529 if (completion == NULL)
2531 g_free(str);
2532 return FALSE;
2535 /* remove the typed word, it will be added again by the used auto completion
2536 * (not really necessary but this makes the auto completion more flexible,
2537 * e.g. with a completion like hi=hello, so typing "hi<TAB>" will result in "hello") */
2538 str_len = strlen(str);
2539 sci_set_selection_start(sci, pos - str_len);
2540 sci_set_selection_end(sci, pos);
2541 sci_replace_sel(sci, "");
2542 pos -= str_len; /* pos has changed while deleting */
2544 editor_insert_snippet(editor, pos, completion);
2545 sci_scroll_caret(sci);
2547 g_free(str);
2548 return TRUE;
2552 static gboolean at_eol(ScintillaObject *sci, gint pos)
2554 gint line = sci_get_line_from_position(sci, pos);
2555 gchar c;
2557 /* skip any trailing spaces */
2558 while (TRUE)
2560 c = sci_get_char_at(sci, pos);
2561 if (c == ' ' || c == '\t')
2562 pos++;
2563 else
2564 break;
2567 return (pos == sci_get_line_end_position(sci, line));
2571 gboolean editor_complete_snippet(GeanyEditor *editor, gint pos)
2573 gboolean result = FALSE;
2574 const gchar *wc;
2575 const gchar *word;
2576 ScintillaObject *sci;
2578 g_return_val_if_fail(editor != NULL, FALSE);
2580 sci = editor->sci;
2581 if (sci_has_selection(sci))
2582 return FALSE;
2583 /* return if we are editing an existing line (chars on right of cursor) */
2584 if (keybindings_lookup_item(GEANY_KEY_GROUP_EDITOR,
2585 GEANY_KEYS_EDITOR_COMPLETESNIPPET)->key == GDK_space &&
2586 ! editor_prefs.complete_snippets_whilst_editing && ! at_eol(sci, pos))
2587 return FALSE;
2589 wc = snippets_find_completion_by_name("Special", "wordchars");
2590 word = editor_read_word_stem(editor, pos, wc);
2592 /* prevent completion of "for " */
2593 if (!EMPTY(word) &&
2594 ! isspace(sci_get_char_at(sci, pos - 1))) /* pos points to the line end char so use pos -1 */
2596 sci_start_undo_action(sci); /* needed because we insert a space separately from construct */
2597 result = snippets_complete_constructs(editor, pos, word);
2598 sci_end_undo_action(sci);
2599 if (result)
2600 sci_cancel(sci); /* cancel any autocompletion list, etc */
2602 return result;
2606 static void insert_closing_tag(GeanyEditor *editor, gint pos, gchar ch, const gchar *tag_name)
2608 ScintillaObject *sci = editor->sci;
2609 gchar *to_insert = NULL;
2611 if (ch == '/')
2613 const gchar *gt = ">";
2614 /* if there is already a '>' behind the cursor, don't add it */
2615 if (sci_get_char_at(sci, pos) == '>')
2616 gt = "";
2618 to_insert = g_strconcat(tag_name, gt, NULL);
2620 else
2621 to_insert = g_strconcat("</", tag_name, ">", NULL);
2623 sci_start_undo_action(sci);
2624 sci_replace_sel(sci, to_insert);
2625 if (ch == '>')
2626 sci_set_selection(sci, pos, pos);
2627 sci_end_undo_action(sci);
2628 g_free(to_insert);
2633 * (stolen from anjuta and heavily modified)
2634 * This routine will auto complete XML or HTML tags that are still open by closing them
2635 * @param ch The character we are dealing with, currently only works with the '>' character
2636 * @return True if handled, false otherwise
2638 static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch)
2640 ScintillaObject *sci = editor->sci;
2641 gint lexer = sci_get_lexer(sci);
2642 gint min, size, style;
2643 gchar *str_found, sel[512];
2644 gboolean result = FALSE;
2646 /* If the user has turned us off, quit now.
2647 * This may make sense only in certain languages */
2648 if (! editor_prefs.auto_close_xml_tags || (lexer != SCLEX_HTML && lexer != SCLEX_XML))
2649 return FALSE;
2651 /* return if we are inside any embedded script */
2652 style = sci_get_style_at(sci, pos);
2653 if (style > SCE_H_XCCOMMENT && ! highlighting_is_string_style(lexer, style))
2654 return FALSE;
2656 /* if ch is /, check for </, else quit */
2657 if (ch == '/' && sci_get_char_at(sci, pos - 2) != '<')
2658 return FALSE;
2660 /* Grab the last 512 characters or so */
2661 min = pos - (sizeof(sel) - 1);
2662 if (min < 0) min = 0;
2664 if (pos - min < 3)
2665 return FALSE; /* Smallest tag is 3 characters e.g. <p> */
2667 sci_get_text_range(sci, min, pos, sel);
2668 sel[sizeof(sel) - 1] = '\0';
2670 if (ch == '>' && sel[pos - min - 2] == '/')
2671 /* User typed something like "<br/>" */
2672 return FALSE;
2674 size = pos - min;
2675 if (ch == '/')
2676 size -= 2; /* skip </ */
2677 str_found = utils_find_open_xml_tag(sel, size);
2679 if (lexer == SCLEX_HTML && utils_is_short_html_tag(str_found))
2681 /* ignore tag */
2683 else if (!EMPTY(str_found))
2685 insert_closing_tag(editor, pos, ch, str_found);
2686 result = TRUE;
2688 g_free(str_found);
2689 return result;
2693 /* like sci_get_line_indentation(), but for a string. */
2694 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent)
2696 const gchar *ptr;
2697 gsize tab_size = sci_get_tab_width(editor->sci);
2698 gsize count = 0;
2700 g_return_val_if_fail(base_indent, 0);
2702 for (ptr = base_indent; *ptr != 0; ptr++)
2704 switch (*ptr)
2706 case ' ':
2707 count++;
2708 break;
2709 case '\t':
2710 count += tab_size;
2711 break;
2712 default:
2713 return count;
2716 return count;
2720 /* Handles special cases where HTML is embedded in another language or
2721 * another language is embedded in HTML */
2722 static GeanyFiletype *editor_get_filetype_at_line(GeanyEditor *editor, gint line)
2724 gint style, line_start;
2725 GeanyFiletype *current_ft;
2727 g_return_val_if_fail(editor != NULL, NULL);
2728 g_return_val_if_fail(editor->document->file_type != NULL, NULL);
2730 current_ft = editor->document->file_type;
2731 line_start = sci_get_position_from_line(editor->sci, line);
2732 style = sci_get_style_at(editor->sci, line_start);
2734 /* Handle PHP filetype with embedded HTML */
2735 if (current_ft->id == GEANY_FILETYPES_PHP && ! is_style_php(style))
2736 current_ft = filetypes[GEANY_FILETYPES_HTML];
2738 /* Handle languages embedded in HTML */
2739 if (current_ft->id == GEANY_FILETYPES_HTML)
2741 /* Embedded JS */
2742 if (style >= SCE_HJ_DEFAULT && style <= SCE_HJ_REGEX)
2743 current_ft = filetypes[GEANY_FILETYPES_JS];
2744 /* ASP JS */
2745 else if (style >= SCE_HJA_DEFAULT && style <= SCE_HJA_REGEX)
2746 current_ft = filetypes[GEANY_FILETYPES_JS];
2747 /* Embedded VB */
2748 else if (style >= SCE_HB_DEFAULT && style <= SCE_HB_STRINGEOL)
2749 current_ft = filetypes[GEANY_FILETYPES_BASIC];
2750 /* ASP VB */
2751 else if (style >= SCE_HBA_DEFAULT && style <= SCE_HBA_STRINGEOL)
2752 current_ft = filetypes[GEANY_FILETYPES_BASIC];
2753 /* Embedded Python */
2754 else if (style >= SCE_HP_DEFAULT && style <= SCE_HP_IDENTIFIER)
2755 current_ft = filetypes[GEANY_FILETYPES_PYTHON];
2756 /* ASP Python */
2757 else if (style >= SCE_HPA_DEFAULT && style <= SCE_HPA_IDENTIFIER)
2758 current_ft = filetypes[GEANY_FILETYPES_PYTHON];
2759 /* Embedded PHP */
2760 else if ((style >= SCE_HPHP_DEFAULT && style <= SCE_HPHP_OPERATOR) ||
2761 style == SCE_HPHP_COMPLEX_VARIABLE)
2763 current_ft = filetypes[GEANY_FILETYPES_PHP];
2767 /* Ensure the filetype's config is loaded */
2768 filetypes_load_config(current_ft->id, FALSE);
2770 return current_ft;
2774 static void real_comment_multiline(GeanyEditor *editor, gint line_start, gint last_line)
2776 const gchar *eol;
2777 gchar *str_begin, *str_end;
2778 const gchar *co, *cc;
2779 gint line_len;
2780 GeanyFiletype *ft;
2782 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2784 ft = editor_get_filetype_at_line(editor, line_start);
2786 eol = editor_get_eol_char(editor);
2787 if (! filetype_get_comment_open_close(ft, FALSE, &co, &cc))
2788 g_return_if_reached();
2789 str_begin = g_strdup_printf("%s%s", (co != NULL) ? co : "", eol);
2790 str_end = g_strdup_printf("%s%s", (cc != NULL) ? cc : "", eol);
2792 /* insert the comment strings */
2793 sci_insert_text(editor->sci, line_start, str_begin);
2794 line_len = sci_get_position_from_line(editor->sci, last_line + 2);
2795 sci_insert_text(editor->sci, line_len, str_end);
2797 g_free(str_begin);
2798 g_free(str_end);
2802 /* find @p text inside the range of the current style */
2803 static gint find_in_current_style(ScintillaObject *sci, const gchar *text, gboolean backwards)
2805 gint start = sci_get_current_position(sci);
2806 gint end = start;
2807 gint len = sci_get_length(sci);
2808 gint current_style = sci_get_style_at(sci, start);
2809 struct Sci_TextToFind ttf;
2811 while (start > 0 && sci_get_style_at(sci, start - 1) == current_style)
2812 start -= 1;
2813 while (end < len && sci_get_style_at(sci, end + 1) == current_style)
2814 end += 1;
2816 ttf.lpstrText = (gchar*) text;
2817 ttf.chrg.cpMin = backwards ? end + 1 : start;
2818 ttf.chrg.cpMax = backwards ? start : end + 1;
2819 return sci_find_text(sci, 0, &ttf);
2823 static void sci_delete_line(ScintillaObject *sci, gint line)
2825 gint start = sci_get_position_from_line(sci, line);
2826 gint len = sci_get_line_length(sci, line);
2827 SSM(sci, SCI_DELETERANGE, start, len);
2831 static gboolean real_uncomment_multiline(GeanyEditor *editor)
2833 /* find the beginning of the multi line comment */
2834 gint start, end, start_line, end_line;
2835 GeanyFiletype *ft;
2836 const gchar *co, *cc;
2838 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, FALSE);
2840 ft = editor_get_filetype_at_line(editor, sci_get_current_line(editor->sci));
2841 if (! filetype_get_comment_open_close(ft, FALSE, &co, &cc))
2842 g_return_val_if_reached(FALSE);
2844 start = find_in_current_style(editor->sci, co, TRUE);
2845 end = find_in_current_style(editor->sci, cc, FALSE);
2847 if (start < 0 || end < 0 || start > end /* who knows */)
2848 return FALSE;
2850 start_line = sci_get_line_from_position(editor->sci, start);
2851 end_line = sci_get_line_from_position(editor->sci, end);
2853 /* remove comment close chars */
2854 SSM(editor->sci, SCI_DELETERANGE, end, strlen(cc));
2855 if (sci_is_blank_line(editor->sci, end_line))
2856 sci_delete_line(editor->sci, end_line);
2858 /* remove comment open chars (do it last since it would move the end position) */
2859 SSM(editor->sci, SCI_DELETERANGE, start, strlen(co));
2860 if (sci_is_blank_line(editor->sci, start_line))
2861 sci_delete_line(editor->sci, start_line);
2863 return TRUE;
2867 static gint get_multiline_comment_style(GeanyEditor *editor, gint line_start)
2869 gint lexer = sci_get_lexer(editor->sci);
2870 gint style_comment;
2872 /* List only those lexers which support multi line comments */
2873 switch (lexer)
2875 case SCLEX_XML:
2876 case SCLEX_HTML:
2877 case SCLEX_PHPSCRIPT:
2879 if (is_style_php(sci_get_style_at(editor->sci, line_start)))
2880 style_comment = SCE_HPHP_COMMENT;
2881 else
2882 style_comment = SCE_H_COMMENT;
2883 break;
2885 case SCLEX_HASKELL:
2886 case SCLEX_LITERATEHASKELL:
2887 style_comment = SCE_HA_COMMENTBLOCK; break;
2888 case SCLEX_LUA: style_comment = SCE_LUA_COMMENT; break;
2889 case SCLEX_CSS: style_comment = SCE_CSS_COMMENT; break;
2890 case SCLEX_SQL: style_comment = SCE_SQL_COMMENT; break;
2891 case SCLEX_CAML: style_comment = SCE_CAML_COMMENT; break;
2892 case SCLEX_D: style_comment = SCE_D_COMMENT; break;
2893 case SCLEX_PASCAL: style_comment = SCE_PAS_COMMENT; break;
2894 case SCLEX_RUST: style_comment = SCE_RUST_COMMENTBLOCK; break;
2895 default: style_comment = SCE_C_COMMENT;
2898 return style_comment;
2902 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise
2903 * returns the amount of uncommented single comment lines, in case of multi line uncomment
2904 * it returns just 1 */
2905 gint editor_do_uncomment(GeanyEditor *editor, gint line, gboolean toggle)
2907 gint first_line, last_line;
2908 gint x, i, line_start, line_len;
2909 gint sel_start, sel_end;
2910 gint count = 0;
2911 gsize co_len;
2912 gchar sel[256];
2913 const gchar *co, *cc;
2914 gboolean single_line = FALSE;
2915 GeanyFiletype *ft;
2917 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, 0);
2919 if (line < 0)
2920 { /* use selection or current line */
2921 sel_start = sci_get_selection_start(editor->sci);
2922 sel_end = sci_get_selection_end(editor->sci);
2924 first_line = sci_get_line_from_position(editor->sci, sel_start);
2925 /* Find the last line with chars selected (not EOL char) */
2926 last_line = sci_get_line_from_position(editor->sci,
2927 sel_end - editor_get_eol_char_len(editor));
2928 last_line = MAX(first_line, last_line);
2930 else
2932 first_line = last_line = line;
2933 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
2936 ft = editor_get_filetype_at_line(editor, first_line);
2938 if (! filetype_get_comment_open_close(ft, TRUE, &co, &cc))
2939 return 0;
2941 co_len = strlen(co);
2942 if (co_len == 0)
2943 return 0;
2945 sci_start_undo_action(editor->sci);
2947 for (i = first_line; i <= last_line; i++)
2949 gint buf_len;
2951 line_start = sci_get_position_from_line(editor->sci, i);
2952 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
2953 x = 0;
2955 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
2956 if (buf_len <= 0)
2957 continue;
2958 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
2959 sel[buf_len] = '\0';
2961 while (isspace(sel[x])) x++;
2963 /* to skip blank lines */
2964 if (x < line_len && sel[x] != '\0')
2966 /* use single line comment */
2967 if (EMPTY(cc))
2969 single_line = TRUE;
2971 if (toggle)
2973 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
2974 if (strncmp(sel + x, co, co_len) != 0 ||
2975 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) != 0)
2976 continue;
2978 co_len += tm_len;
2980 else
2982 if (strncmp(sel + x, co, co_len) != 0)
2983 continue;
2986 sci_set_selection(editor->sci, line_start + x, line_start + x + co_len);
2987 sci_replace_sel(editor->sci, "");
2988 count++;
2990 /* use multi line comment */
2991 else
2993 gint style_comment;
2995 /* skip lines which are already comments */
2996 style_comment = get_multiline_comment_style(editor, line_start);
2997 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
2999 if (real_uncomment_multiline(editor))
3000 count = 1;
3003 /* break because we are already on the last line */
3004 break;
3008 sci_end_undo_action(editor->sci);
3010 /* restore selection if there is one
3011 * but don't touch the selection if caller is editor_do_comment_toggle */
3012 if (! toggle && sel_start < sel_end)
3014 if (single_line)
3016 sci_set_selection_start(editor->sci, sel_start - co_len);
3017 sci_set_selection_end(editor->sci, sel_end - (count * co_len));
3019 else
3021 gint eol_len = editor_get_eol_char_len(editor);
3022 sci_set_selection_start(editor->sci, sel_start - co_len - eol_len);
3023 sci_set_selection_end(editor->sci, sel_end - co_len - eol_len);
3027 return count;
3031 void editor_do_comment_toggle(GeanyEditor *editor)
3033 gint first_line, last_line;
3034 gint x, i, line_start, line_len, first_line_start, last_line_start;
3035 gint sel_start, sel_end;
3036 gint count_commented = 0, count_uncommented = 0;
3037 gchar sel[256];
3038 const gchar *co, *cc;
3039 gboolean break_loop = FALSE, single_line = FALSE;
3040 gboolean first_line_was_comment = FALSE;
3041 gboolean last_line_was_comment = FALSE;
3042 gsize co_len;
3043 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
3044 GeanyFiletype *ft;
3046 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
3048 sel_start = sci_get_selection_start(editor->sci);
3049 sel_end = sci_get_selection_end(editor->sci);
3051 first_line = sci_get_line_from_position(editor->sci, sel_start);
3052 /* Find the last line with chars selected (not EOL char) */
3053 last_line = sci_get_line_from_position(editor->sci,
3054 sel_end - editor_get_eol_char_len(editor));
3055 last_line = MAX(first_line, last_line);
3057 first_line_start = sci_get_position_from_line(editor->sci, first_line);
3058 last_line_start = sci_get_position_from_line(editor->sci, last_line);
3060 ft = editor_get_filetype_at_line(editor, first_line);
3062 if (! filetype_get_comment_open_close(ft, TRUE, &co, &cc))
3063 return;
3065 co_len = strlen(co);
3066 if (co_len == 0)
3067 return;
3069 sci_start_undo_action(editor->sci);
3071 for (i = first_line; (i <= last_line) && (! break_loop); i++)
3073 gint buf_len;
3075 line_start = sci_get_position_from_line(editor->sci, i);
3076 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
3077 x = 0;
3079 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
3080 if (buf_len < 0)
3081 continue;
3082 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3083 sel[buf_len] = '\0';
3085 while (isspace(sel[x])) x++;
3087 /* use single line comment */
3088 if (EMPTY(cc))
3090 gboolean do_continue = FALSE;
3091 single_line = TRUE;
3093 if (strncmp(sel + x, co, co_len) == 0 &&
3094 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) == 0)
3096 do_continue = TRUE;
3099 if (do_continue && i == first_line)
3100 first_line_was_comment = TRUE;
3101 last_line_was_comment = do_continue;
3103 if (do_continue)
3105 count_uncommented += editor_do_uncomment(editor, i, TRUE);
3106 continue;
3109 /* we are still here, so the above lines were not already comments, so comment it */
3110 count_commented += editor_do_comment(editor, i, FALSE, TRUE, TRUE);
3112 /* use multi line comment */
3113 else
3115 gint style_comment;
3117 /* skip lines which are already comments */
3118 style_comment = get_multiline_comment_style(editor, line_start);
3119 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3121 if (real_uncomment_multiline(editor))
3122 count_uncommented++;
3124 else
3126 real_comment_multiline(editor, line_start, last_line);
3127 count_commented++;
3130 /* break because we are already on the last line */
3131 break_loop = TRUE;
3132 break;
3136 sci_end_undo_action(editor->sci);
3138 co_len += tm_len;
3140 /* restore selection or caret position */
3141 if (single_line)
3143 gint a = (first_line_was_comment) ? - (gint) co_len : (gint) co_len;
3144 gint indent_len;
3146 /* don't modify sel_start when the selection starts within indentation */
3147 read_indent(editor, sel_start);
3148 indent_len = (gint) strlen(indent);
3149 if ((sel_start - first_line_start) <= indent_len)
3150 a = 0;
3151 /* if the selection start was inside the comment mark, adjust the position */
3152 else if (first_line_was_comment &&
3153 sel_start >= (first_line_start + indent_len) &&
3154 sel_start <= (first_line_start + indent_len + (gint) co_len))
3156 a = (first_line_start + indent_len) - sel_start;
3159 if (sel_start < sel_end)
3161 gint b = (count_commented * (gint) co_len) - (count_uncommented * (gint) co_len);
3163 /* same for selection end, but here we add an offset on the offset above */
3164 read_indent(editor, sel_end + b);
3165 indent_len = (gint) strlen(indent);
3166 if ((sel_end - last_line_start) < indent_len)
3167 b += last_line_was_comment ? (gint) co_len : -(gint) co_len;
3168 else if (last_line_was_comment &&
3169 sel_end >= (last_line_start + indent_len) &&
3170 sel_end <= (last_line_start + indent_len + (gint) co_len))
3172 b += (gint) co_len - (sel_end - (last_line_start + indent_len));
3175 sci_set_selection_start(editor->sci, sel_start + a);
3176 sci_set_selection_end(editor->sci, sel_end + b);
3178 else
3179 sci_set_current_position(editor->sci, sel_start + a, TRUE);
3181 else
3183 gint eol_len = editor_get_eol_char_len(editor);
3184 if (count_uncommented > 0)
3186 sci_set_selection_start(editor->sci, sel_start - (gint) co_len + eol_len);
3187 sci_set_selection_end(editor->sci, sel_end - (gint) co_len + eol_len);
3189 else if (count_commented > 0)
3191 sci_set_selection_start(editor->sci, sel_start + (gint) co_len - eol_len);
3192 sci_set_selection_end(editor->sci, sel_end + (gint) co_len - eol_len);
3194 if (sel_start >= sel_end)
3195 sci_scroll_caret(editor->sci);
3200 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise */
3201 gint editor_do_comment(GeanyEditor *editor, gint line, gboolean allow_empty_lines, gboolean toggle,
3202 gboolean single_comment)
3204 gint first_line, last_line;
3205 gint x, i, line_start, line_len;
3206 gint sel_start, sel_end, co_len;
3207 gint count = 0;
3208 gchar sel[256];
3209 const gchar *co, *cc;
3210 gboolean break_loop = FALSE, single_line = FALSE;
3211 GeanyFiletype *ft;
3213 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, 0);
3215 if (line < 0)
3216 { /* use selection or current line */
3217 sel_start = sci_get_selection_start(editor->sci);
3218 sel_end = sci_get_selection_end(editor->sci);
3220 first_line = sci_get_line_from_position(editor->sci, sel_start);
3221 /* Find the last line with chars selected (not EOL char) */
3222 last_line = sci_get_line_from_position(editor->sci,
3223 sel_end - editor_get_eol_char_len(editor));
3224 last_line = MAX(first_line, last_line);
3226 else
3228 first_line = last_line = line;
3229 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
3232 ft = editor_get_filetype_at_line(editor, first_line);
3234 if (! filetype_get_comment_open_close(ft, single_comment, &co, &cc))
3235 return 0;
3237 co_len = strlen(co);
3238 if (co_len == 0)
3239 return 0;
3241 sci_start_undo_action(editor->sci);
3243 for (i = first_line; (i <= last_line) && (! break_loop); i++)
3245 gint buf_len;
3247 line_start = sci_get_position_from_line(editor->sci, i);
3248 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
3249 x = 0;
3251 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
3252 if (buf_len < 0)
3253 continue;
3254 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3255 sel[buf_len] = '\0';
3257 while (isspace(sel[x])) x++;
3259 /* to skip blank lines */
3260 if (allow_empty_lines || (x < line_len && sel[x] != '\0'))
3262 /* use single line comment */
3263 if (EMPTY(cc))
3265 gint start = line_start;
3266 single_line = TRUE;
3268 if (ft->comment_use_indent)
3269 start = line_start + x;
3271 if (toggle)
3273 gchar *text = g_strconcat(co, editor_prefs.comment_toggle_mark, NULL);
3274 sci_insert_text(editor->sci, start, text);
3275 g_free(text);
3277 else
3278 sci_insert_text(editor->sci, start, co);
3279 count++;
3281 /* use multi line comment */
3282 else
3284 gint style_comment;
3286 /* skip lines which are already comments */
3287 style_comment = get_multiline_comment_style(editor, line_start);
3288 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3289 continue;
3291 real_comment_multiline(editor, line_start, last_line);
3292 count = 1;
3294 /* break because we are already on the last line */
3295 break_loop = TRUE;
3296 break;
3300 sci_end_undo_action(editor->sci);
3302 /* restore selection if there is one
3303 * but don't touch the selection if caller is editor_do_comment_toggle */
3304 if (! toggle && sel_start < sel_end)
3306 if (single_line)
3308 sci_set_selection_start(editor->sci, sel_start + co_len);
3309 sci_set_selection_end(editor->sci, sel_end + (count * co_len));
3311 else
3313 gint eol_len = editor_get_eol_char_len(editor);
3314 sci_set_selection_start(editor->sci, sel_start + co_len + eol_len);
3315 sci_set_selection_end(editor->sci, sel_end + co_len + eol_len);
3318 return count;
3322 static gboolean brace_timeout_active = FALSE;
3324 static gboolean delay_match_brace(G_GNUC_UNUSED gpointer user_data)
3326 GeanyDocument *doc = document_get_current();
3327 GeanyEditor *editor;
3328 gint brace_pos = GPOINTER_TO_INT(user_data);
3329 gint end_pos, cur_pos;
3331 brace_timeout_active = FALSE;
3332 if (!doc)
3333 return FALSE;
3335 editor = doc->editor;
3336 cur_pos = sci_get_current_position(editor->sci) - 1;
3338 if (cur_pos != brace_pos)
3340 cur_pos++;
3341 if (cur_pos != brace_pos)
3343 /* we have moved past the original brace_pos, but after the timeout
3344 * we may now be on a new brace, so check again */
3345 editor_highlight_braces(editor, cur_pos);
3346 return FALSE;
3349 if (!utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3351 editor_highlight_braces(editor, cur_pos);
3352 return FALSE;
3354 end_pos = sci_find_matching_brace(editor->sci, brace_pos);
3356 if (end_pos >= 0)
3358 gint col = MIN(sci_get_col_from_position(editor->sci, brace_pos),
3359 sci_get_col_from_position(editor->sci, end_pos));
3360 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, col, 0);
3361 SSM(editor->sci, SCI_BRACEHIGHLIGHT, brace_pos, end_pos);
3363 else
3365 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3366 SSM(editor->sci, SCI_BRACEBADLIGHT, brace_pos, 0);
3368 return FALSE;
3372 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos)
3374 gint brace_pos = cur_pos - 1;
3376 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3377 SSM(editor->sci, SCI_BRACEBADLIGHT, (uptr_t)-1, 0);
3379 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3381 brace_pos++;
3382 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3384 return;
3387 if (!brace_timeout_active)
3389 brace_timeout_active = TRUE;
3390 /* delaying matching makes scrolling faster e.g. holding down arrow keys */
3391 g_timeout_add(100, delay_match_brace, GINT_TO_POINTER(brace_pos));
3396 static gboolean in_block_comment(gint lexer, gint style)
3398 switch (lexer)
3400 case SCLEX_COBOL:
3401 case SCLEX_CPP:
3402 return (style == SCE_C_COMMENT ||
3403 style == SCE_C_COMMENTDOC);
3405 case SCLEX_PASCAL:
3406 return (style == SCE_PAS_COMMENT ||
3407 style == SCE_PAS_COMMENT2);
3409 case SCLEX_D:
3410 return (style == SCE_D_COMMENT ||
3411 style == SCE_D_COMMENTDOC ||
3412 style == SCE_D_COMMENTNESTED);
3414 case SCLEX_HTML:
3415 case SCLEX_PHPSCRIPT:
3416 return (style == SCE_HPHP_COMMENT);
3418 case SCLEX_CSS:
3419 return (style == SCE_CSS_COMMENT);
3421 case SCLEX_RUST:
3422 return (style == SCE_RUST_COMMENTBLOCK ||
3423 style == SCE_RUST_COMMENTBLOCKDOC);
3425 default:
3426 return FALSE;
3431 static gboolean is_comment_char(gchar c, gint lexer)
3433 if ((c == '*' || c == '+') && lexer == SCLEX_D)
3434 return TRUE;
3435 else
3436 if (c == '*')
3437 return TRUE;
3439 return FALSE;
3443 static void auto_multiline(GeanyEditor *editor, gint cur_line)
3445 ScintillaObject *sci = editor->sci;
3446 gint indent_pos, style;
3447 gint lexer = sci_get_lexer(sci);
3449 /* Use the start of the line enter was pressed on, to avoid any doc keyword styles */
3450 indent_pos = sci_get_line_indent_position(sci, cur_line - 1);
3451 style = sci_get_style_at(sci, indent_pos);
3452 if (!in_block_comment(lexer, style))
3453 return;
3455 /* Check whether the comment block continues on this line */
3456 indent_pos = sci_get_line_indent_position(sci, cur_line);
3457 if (sci_get_style_at(sci, indent_pos) == style || indent_pos >= sci_get_length(sci))
3459 gchar *previous_line = sci_get_line(sci, cur_line - 1);
3460 /* the type of comment, '*' (C/C++/Java), '+' and the others (D) */
3461 const gchar *continuation = "*";
3462 const gchar *whitespace = ""; /* to hold whitespace if needed */
3463 gchar *result;
3464 gint len = strlen(previous_line);
3465 gint i;
3467 /* find and stop at end of multi line comment */
3468 i = len - 1;
3469 while (i >= 0 && isspace(previous_line[i])) i--;
3470 if (i >= 1 && is_comment_char(previous_line[i - 1], lexer) && previous_line[i] == '/')
3472 gint indent_len, indent_width;
3474 indent_pos = sci_get_line_indent_position(sci, cur_line);
3475 indent_len = sci_get_col_from_position(sci, indent_pos);
3476 indent_width = editor_get_indent_prefs(editor)->width;
3478 /* if there is one too many spaces, delete the last space,
3479 * to return to the indent used before the multiline comment was started. */
3480 if (indent_len % indent_width == 1)
3481 SSM(sci, SCI_DELETEBACKNOTLINE, 0, 0); /* remove whitespace indent */
3482 g_free(previous_line);
3483 return;
3485 /* check whether we are on the second line of multi line comment */
3486 i = 0;
3487 while (i < len && isspace(previous_line[i])) i++; /* get to start of the line */
3489 if (i + 1 < len &&
3490 previous_line[i] == '/' && is_comment_char(previous_line[i + 1], lexer))
3491 { /* we are on the second line of a multi line comment, so we have to insert white space */
3492 whitespace = " ";
3495 if (style == SCE_D_COMMENTNESTED)
3496 continuation = "+"; /* for nested comments in D */
3498 result = g_strconcat(whitespace, continuation, " ", NULL);
3499 sci_add_text(sci, result);
3500 g_free(result);
3502 g_free(previous_line);
3507 #if 0
3508 static gboolean editor_lexer_is_c_like(gint lexer)
3510 switch (lexer)
3512 case SCLEX_CPP:
3513 case SCLEX_D:
3514 return TRUE;
3516 default:
3517 return FALSE;
3520 #endif
3523 /* inserts a three-line comment at one line above current cursor position */
3524 void editor_insert_multiline_comment(GeanyEditor *editor)
3526 gchar *text;
3527 gint text_len;
3528 gint line;
3529 gint pos;
3530 gboolean have_multiline_comment = FALSE;
3531 GeanyDocument *doc;
3532 const gchar *co, *cc;
3534 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
3536 if (! filetype_get_comment_open_close(editor->document->file_type, FALSE, &co, &cc))
3537 g_return_if_reached();
3538 if (!EMPTY(cc))
3539 have_multiline_comment = TRUE;
3541 sci_start_undo_action(editor->sci);
3543 doc = editor->document;
3545 /* insert three lines one line above of the current position */
3546 line = sci_get_line_from_position(editor->sci, editor_info.click_pos);
3547 pos = sci_get_position_from_line(editor->sci, line);
3549 /* use the indent on the current line but only when comment indentation is used
3550 * and we don't have multi line comment characters */
3551 if (editor->auto_indent &&
3552 ! have_multiline_comment && doc->file_type->comment_use_indent)
3554 read_indent(editor, editor_info.click_pos);
3555 text = g_strdup_printf("%s\n%s\n%s\n", indent, indent, indent);
3556 text_len = strlen(text);
3558 else
3560 text = g_strdup("\n\n\n");
3561 text_len = 3;
3563 sci_insert_text(editor->sci, pos, text);
3564 g_free(text);
3566 /* select the inserted lines for commenting */
3567 sci_set_selection_start(editor->sci, pos);
3568 sci_set_selection_end(editor->sci, pos + text_len);
3570 editor_do_comment(editor, -1, TRUE, FALSE, FALSE);
3572 /* set the current position to the start of the first inserted line */
3573 pos += strlen(co);
3575 /* on multi line comment jump to the next line, otherwise add the length of added indentation */
3576 if (have_multiline_comment)
3577 pos += 1;
3578 else
3579 pos += strlen(indent);
3581 sci_set_current_position(editor->sci, pos, TRUE);
3582 /* reset the selection */
3583 sci_set_anchor(editor->sci, pos);
3585 sci_end_undo_action(editor->sci);
3589 /* Note: If the editor is pending a redraw, set document::scroll_percent instead.
3590 * Scroll the view to make line appear at percent_of_view.
3591 * line can be -1 to use the current position. */
3592 void editor_scroll_to_line(GeanyEditor *editor, gint line, gfloat percent_of_view)
3594 gint los;
3595 GtkWidget *wid;
3597 g_return_if_fail(editor != NULL);
3599 wid = GTK_WIDGET(editor->sci);
3601 if (! gtk_widget_get_window(wid) || ! gdk_window_is_viewable(gtk_widget_get_window(wid)))
3602 return; /* prevent gdk_window_scroll warning */
3604 if (line == -1)
3605 line = sci_get_current_line(editor->sci);
3607 /* sci 'visible line' != doc line number because of folding and line wrapping */
3608 /* calling SCI_VISIBLEFROMDOCLINE for line is more accurate than calling
3609 * SCI_DOCLINEFROMVISIBLE for vis1. */
3610 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0);
3611 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
3612 line = line - los * percent_of_view;
3613 SSM(editor->sci, SCI_SETFIRSTVISIBLELINE, line, 0);
3614 sci_scroll_caret(editor->sci); /* needed for horizontal scrolling */
3618 /* creates and inserts one tab or whitespace of the amount of the tab width */
3619 void editor_insert_alternative_whitespace(GeanyEditor *editor)
3621 gchar *text;
3622 GeanyIndentPrefs iprefs = *editor_get_indent_prefs(editor);
3624 g_return_if_fail(editor != NULL);
3626 switch (iprefs.type)
3628 case GEANY_INDENT_TYPE_TABS:
3629 iprefs.type = GEANY_INDENT_TYPE_SPACES;
3630 break;
3631 case GEANY_INDENT_TYPE_SPACES:
3632 case GEANY_INDENT_TYPE_BOTH: /* most likely we want a tab */
3633 iprefs.type = GEANY_INDENT_TYPE_TABS;
3634 break;
3636 text = get_whitespace(&iprefs, iprefs.width);
3637 sci_add_text(editor->sci, text);
3638 g_free(text);
3642 void editor_select_word(GeanyEditor *editor)
3644 gint pos;
3645 gint start;
3646 gint end;
3648 g_return_if_fail(editor != NULL);
3650 pos = SSM(editor->sci, SCI_GETCURRENTPOS, 0, 0);
3651 start = sci_word_start_position(editor->sci, pos, TRUE);
3652 end = sci_word_end_position(editor->sci, pos, TRUE);
3654 if (start == end) /* caret in whitespaces sequence */
3656 /* look forward but reverse the selection direction,
3657 * so the caret end up stay as near as the original position. */
3658 end = sci_word_end_position(editor->sci, pos, FALSE);
3659 start = sci_word_end_position(editor->sci, end, TRUE);
3660 if (start == end)
3661 return;
3664 sci_set_selection(editor->sci, start, end);
3668 /* extra_line is for selecting the cursor line (or anchor line) at the bottom of a selection,
3669 * when those lines have no selection (cursor at start of line). */
3670 void editor_select_lines(GeanyEditor *editor, gboolean extra_line)
3672 gint start, end, line;
3674 g_return_if_fail(editor != NULL);
3676 start = sci_get_selection_start(editor->sci);
3677 end = sci_get_selection_end(editor->sci);
3679 /* check if whole lines are already selected */
3680 if (! extra_line && start != end &&
3681 sci_get_col_from_position(editor->sci, start) == 0 &&
3682 sci_get_col_from_position(editor->sci, end) == 0)
3683 return;
3685 line = sci_get_line_from_position(editor->sci, start);
3686 start = sci_get_position_from_line(editor->sci, line);
3688 line = sci_get_line_from_position(editor->sci, end);
3689 end = sci_get_position_from_line(editor->sci, line + 1);
3691 sci_set_selection(editor->sci, start, end);
3695 static gboolean sci_is_blank_line(ScintillaObject *sci, gint line)
3697 return sci_get_line_indent_position(sci, line) ==
3698 sci_get_line_end_position(sci, line);
3702 /* Returns first line of paragraph for GTK_DIR_UP, line after paragraph
3703 * ends for GTK_DIR_DOWN or -1 if called on an empty line. */
3704 static gint find_paragraph_stop(GeanyEditor *editor, gint line, gint direction)
3706 gint step;
3707 ScintillaObject *sci = editor->sci;
3709 /* first check current line and return -1 if it is empty to skip creating of a selection */
3710 if (sci_is_blank_line(sci, line))
3711 return -1;
3713 if (direction == GTK_DIR_UP)
3714 step = -1;
3715 else
3716 step = 1;
3718 while (TRUE)
3720 line += step;
3721 if (line == -1)
3723 /* start of document */
3724 line = 0;
3725 break;
3727 if (line == sci_get_line_count(sci))
3728 break;
3730 if (sci_is_blank_line(sci, line))
3732 /* return line paragraph starts on */
3733 if (direction == GTK_DIR_UP)
3734 line++;
3735 break;
3738 return line;
3742 void editor_select_paragraph(GeanyEditor *editor)
3744 gint pos_start, pos_end, line_start, line_found;
3746 g_return_if_fail(editor != NULL);
3748 line_start = sci_get_current_line(editor->sci);
3750 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_UP);
3751 if (line_found == -1)
3752 return;
3754 pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3756 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_DOWN);
3757 pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3759 sci_set_selection(editor->sci, pos_start, pos_end);
3763 /* Returns first line of block for GTK_DIR_UP, line after block
3764 * ends for GTK_DIR_DOWN or -1 if called on an empty line. */
3765 static gint find_block_stop(GeanyEditor *editor, gint line, gint direction)
3767 gint step, ind;
3768 ScintillaObject *sci = editor->sci;
3770 /* first check current line and return -1 if it is empty to skip creating of a selection */
3771 if (sci_is_blank_line(sci, line))
3772 return -1;
3774 if (direction == GTK_DIR_UP)
3775 step = -1;
3776 else
3777 step = 1;
3779 ind = sci_get_line_indentation(sci, line);
3780 while (TRUE)
3782 line += step;
3783 if (line == -1)
3785 /* start of document */
3786 line = 0;
3787 break;
3789 if (line == sci_get_line_count(sci))
3790 break;
3792 if (sci_get_line_indentation(sci, line) != ind ||
3793 sci_is_blank_line(sci, line))
3795 /* return line block starts on */
3796 if (direction == GTK_DIR_UP)
3797 line++;
3798 break;
3801 return line;
3805 void editor_select_indent_block(GeanyEditor *editor)
3807 gint pos_start, pos_end, line_start, line_found;
3809 g_return_if_fail(editor != NULL);
3811 line_start = sci_get_current_line(editor->sci);
3813 line_found = find_block_stop(editor, line_start, GTK_DIR_UP);
3814 if (line_found == -1)
3815 return;
3817 pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3819 line_found = find_block_stop(editor, line_start, GTK_DIR_DOWN);
3820 pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3822 sci_set_selection(editor->sci, pos_start, pos_end);
3826 /* simple indentation to indent the current line with the same indent as the previous one */
3827 static void smart_line_indentation(GeanyEditor *editor, gint first_line, gint last_line)
3829 gint i, sel_start = 0, sel_end = 0;
3831 /* get previous line and use it for read_indent to use that line
3832 * (otherwise it would fail on a line only containing "{" in advanced indentation mode) */
3833 read_indent(editor, sci_get_position_from_line(editor->sci, first_line - 1));
3835 for (i = first_line; i <= last_line; i++)
3837 /* skip the first line or if the indentation of the previous and current line are equal */
3838 if (i == 0 ||
3839 SSM(editor->sci, SCI_GETLINEINDENTATION, i - 1, 0) ==
3840 SSM(editor->sci, SCI_GETLINEINDENTATION, i, 0))
3841 continue;
3843 sel_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
3844 sel_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
3845 if (sel_start < sel_end)
3847 sci_set_selection(editor->sci, sel_start, sel_end);
3848 sci_replace_sel(editor->sci, "");
3850 sci_insert_text(editor->sci, sel_start, indent);
3855 /* simple indentation to indent the current line with the same indent as the previous one */
3856 void editor_smart_line_indentation(GeanyEditor *editor, gint pos)
3858 gint first_line, last_line;
3859 gint first_sel_start, first_sel_end;
3860 ScintillaObject *sci;
3862 g_return_if_fail(editor != NULL);
3864 sci = editor->sci;
3866 first_sel_start = sci_get_selection_start(sci);
3867 first_sel_end = sci_get_selection_end(sci);
3869 first_line = sci_get_line_from_position(sci, first_sel_start);
3870 /* Find the last line with chars selected (not EOL char) */
3871 last_line = sci_get_line_from_position(sci, first_sel_end - editor_get_eol_char_len(editor));
3872 last_line = MAX(first_line, last_line);
3874 if (pos == -1)
3875 pos = first_sel_start;
3877 sci_start_undo_action(sci);
3879 smart_line_indentation(editor, first_line, last_line);
3881 /* set cursor position if there was no selection */
3882 if (first_sel_start == first_sel_end)
3884 gint indent_pos = SSM(sci, SCI_GETLINEINDENTPOSITION, first_line, 0);
3886 /* use indent position as user may wish to change indentation afterwards */
3887 sci_set_current_position(sci, indent_pos, FALSE);
3889 else
3891 /* fully select all the lines affected */
3892 sci_set_selection_start(sci, sci_get_position_from_line(sci, first_line));
3893 sci_set_selection_end(sci, sci_get_position_from_line(sci, last_line + 1));
3896 sci_end_undo_action(sci);
3900 /* increase / decrease current line or selection by one space */
3901 void editor_indentation_by_one_space(GeanyEditor *editor, gint pos, gboolean decrease)
3903 gint i, first_line, last_line, line_start, indentation_end, count = 0;
3904 gint sel_start, sel_end, first_line_offset = 0;
3906 g_return_if_fail(editor != NULL);
3908 sel_start = sci_get_selection_start(editor->sci);
3909 sel_end = sci_get_selection_end(editor->sci);
3911 first_line = sci_get_line_from_position(editor->sci, sel_start);
3912 /* Find the last line with chars selected (not EOL char) */
3913 last_line = sci_get_line_from_position(editor->sci, sel_end - editor_get_eol_char_len(editor));
3914 last_line = MAX(first_line, last_line);
3916 if (pos == -1)
3917 pos = sel_start;
3919 sci_start_undo_action(editor->sci);
3921 for (i = first_line; i <= last_line; i++)
3923 indentation_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
3924 if (decrease)
3926 line_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
3927 /* searching backwards for a space to remove */
3928 while (sci_get_char_at(editor->sci, indentation_end) != ' ' && indentation_end > line_start)
3929 indentation_end--;
3931 if (sci_get_char_at(editor->sci, indentation_end) == ' ')
3933 sci_set_selection(editor->sci, indentation_end, indentation_end + 1);
3934 sci_replace_sel(editor->sci, "");
3935 count--;
3936 if (i == first_line)
3937 first_line_offset = -1;
3940 else
3942 sci_insert_text(editor->sci, indentation_end, " ");
3943 count++;
3944 if (i == first_line)
3945 first_line_offset = 1;
3949 /* set cursor position */
3950 if (sel_start < sel_end)
3952 gint start = sel_start + first_line_offset;
3953 if (first_line_offset < 0)
3954 start = MAX(sel_start + first_line_offset,
3955 SSM(editor->sci, SCI_POSITIONFROMLINE, first_line, 0));
3957 sci_set_selection_start(editor->sci, start);
3958 sci_set_selection_end(editor->sci, sel_end + count);
3960 else
3961 sci_set_current_position(editor->sci, pos + count, FALSE);
3963 sci_end_undo_action(editor->sci);
3967 void editor_finalize(void)
3969 scintilla_release_resources();
3973 /* wordchars: NULL or a string containing characters to match a word.
3974 * Returns: the current selection or the current word.
3976 * Passing NULL as wordchars is NOT the same as passing GEANY_WORDCHARS: NULL means
3977 * using Scintillas's word boundaries. */
3978 gchar *editor_get_default_selection(GeanyEditor *editor, gboolean use_current_word,
3979 const gchar *wordchars)
3981 gchar *s = NULL;
3983 g_return_val_if_fail(editor != NULL, NULL);
3985 if (sci_get_lines_selected(editor->sci) == 1)
3986 s = sci_get_selection_contents(editor->sci);
3987 else if (sci_get_lines_selected(editor->sci) == 0 && use_current_word)
3988 { /* use the word at current cursor position */
3989 gchar word[GEANY_MAX_WORD_LENGTH];
3991 if (wordchars != NULL)
3992 editor_find_current_word(editor, -1, word, sizeof(word), wordchars);
3993 else
3994 editor_find_current_word_sciwc(editor, -1, word, sizeof(word));
3996 if (word[0] != '\0')
3997 s = g_strdup(word);
3999 return s;
4003 /* Note: Usually the line should be made visible (not folded) before calling this.
4004 * Returns: TRUE if line is/will be displayed to the user, or FALSE if it is
4005 * outside the *vertical* view.
4006 * Warning: You may need horizontal scrolling to make the cursor visible - so always call
4007 * sci_scroll_caret() when this returns TRUE. */
4008 gboolean editor_line_in_view(GeanyEditor *editor, gint line)
4010 gint vis1, los;
4012 g_return_val_if_fail(editor != NULL, FALSE);
4014 /* If line is wrapped the result may occur on another virtual line than the first and may be
4015 * still hidden, so increase the line number to check for the next document line */
4016 if (SSM(editor->sci, SCI_WRAPCOUNT, line, 0) > 1)
4017 line++;
4019 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0); /* convert to visible line number */
4020 vis1 = SSM(editor->sci, SCI_GETFIRSTVISIBLELINE, 0, 0);
4021 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
4023 return (line >= vis1 && line < vis1 + los);
4027 /* If the current line is outside the current view window, scroll the line
4028 * so it appears at percent_of_view. */
4029 void editor_display_current_line(GeanyEditor *editor, gfloat percent_of_view)
4031 gint line;
4033 g_return_if_fail(editor != NULL);
4035 line = sci_get_current_line(editor->sci);
4037 /* unfold maybe folded results */
4038 sci_ensure_line_is_visible(editor->sci, line);
4040 /* scroll the line if it's off screen */
4041 if (! editor_line_in_view(editor, line))
4042 editor->scroll_percent = percent_of_view;
4043 else
4044 sci_scroll_caret(editor->sci); /* may need horizontal scrolling */
4049 * Deletes all currently set indicators in the @a editor window.
4050 * Error indicators (red squiggly underlines) and usual line markers are removed.
4052 * @param editor The editor to operate on.
4054 void editor_indicator_clear_errors(GeanyEditor *editor)
4056 editor_indicator_clear(editor, GEANY_INDICATOR_ERROR);
4057 sci_marker_delete_all(editor->sci, 0); /* remove the yellow error line marker */
4062 * Deletes all currently set indicators matching @a indic in the @a editor window.
4064 * @param editor The editor to operate on.
4065 * @param indic The indicator number to clear, this is a value of @ref GeanyIndicator.
4067 * @since 0.16
4069 GEANY_API_SYMBOL
4070 void editor_indicator_clear(GeanyEditor *editor, gint indic)
4072 glong last_pos;
4074 g_return_if_fail(editor != NULL);
4076 last_pos = sci_get_length(editor->sci);
4077 if (last_pos > 0)
4079 sci_indicator_set(editor->sci, indic);
4080 sci_indicator_clear(editor->sci, 0, last_pos);
4086 * Sets an indicator @a indic on @a line.
4087 * Whitespace at the start and the end of the line is not marked.
4089 * @param editor The editor to operate on.
4090 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4091 * @param line The line number which should be marked.
4093 * @since 0.16
4095 GEANY_API_SYMBOL
4096 void editor_indicator_set_on_line(GeanyEditor *editor, gint indic, gint line)
4098 gint start, end;
4099 guint i = 0, len;
4100 gchar *linebuf;
4102 g_return_if_fail(editor != NULL);
4103 g_return_if_fail(line >= 0);
4105 start = sci_get_position_from_line(editor->sci, line);
4106 end = sci_get_position_from_line(editor->sci, line + 1);
4108 /* skip blank lines */
4109 if ((start + 1) == end ||
4110 start > end ||
4111 (sci_get_line_end_position(editor->sci, line) - start) == 0)
4113 return;
4116 len = end - start;
4117 linebuf = sci_get_line(editor->sci, line);
4119 /* don't set the indicator on whitespace */
4120 while (isspace(linebuf[i]))
4121 i++;
4122 while (len > 1 && len > i && isspace(linebuf[len - 1]))
4124 len--;
4125 end--;
4127 g_free(linebuf);
4129 editor_indicator_set_on_range(editor, indic, start + i, end);
4134 * Sets an indicator on the range specified by @a start and @a end.
4135 * No error checking or whitespace removal is performed, this should be done by the calling
4136 * function if necessary.
4138 * @param editor The editor to operate on.
4139 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4140 * @param start The starting position for the marker.
4141 * @param end The ending position for the marker.
4143 * @since 0.16
4145 GEANY_API_SYMBOL
4146 void editor_indicator_set_on_range(GeanyEditor *editor, gint indic, gint start, gint end)
4148 g_return_if_fail(editor != NULL);
4149 if (start >= end)
4150 return;
4152 sci_indicator_set(editor->sci, indic);
4153 sci_indicator_fill(editor->sci, start, end - start);
4157 /* Inserts the given colour (format should be #...), if there is a selection starting with 0x...
4158 * the replacement will also start with 0x... */
4159 void editor_insert_color(GeanyEditor *editor, const gchar *colour)
4161 g_return_if_fail(editor != NULL);
4163 if (sci_has_selection(editor->sci))
4165 gint start = sci_get_selection_start(editor->sci);
4166 const gchar *replacement = colour;
4168 if (sci_get_char_at(editor->sci, start) == '0' &&
4169 sci_get_char_at(editor->sci, start + 1) == 'x')
4171 gint end = sci_get_selection_end(editor->sci);
4173 sci_set_selection_start(editor->sci, start + 2);
4174 /* we need to also re-set the selection end in case the anchor was located before
4175 * the cursor, since set_selection_start() always moves the cursor, not the anchor */
4176 sci_set_selection_end(editor->sci, end);
4177 replacement++; /* skip the leading "0x" */
4179 else if (sci_get_char_at(editor->sci, start - 1) == '#')
4180 { /* double clicking something like #00ffff may only select 00ffff because of wordchars */
4181 replacement++; /* so skip the '#' to only replace the colour value */
4183 sci_replace_sel(editor->sci, replacement);
4185 else
4186 sci_add_text(editor->sci, colour);
4191 * Retrieves the end of line characters mode (LF, CR/LF, CR) in the given editor.
4192 * If @a editor is @c NULL, the default end of line characters are used.
4194 * @param editor The editor to operate on, or @c NULL to query the default value.
4195 * @return The used end of line characters mode.
4197 * @since 0.20
4199 GEANY_API_SYMBOL
4200 gint editor_get_eol_char_mode(GeanyEditor *editor)
4202 gint mode = file_prefs.default_eol_character;
4204 if (editor != NULL)
4205 mode = sci_get_eol_mode(editor->sci);
4207 return mode;
4212 * Retrieves the localized name (for displaying) of the used end of line characters
4213 * (LF, CR/LF, CR) in the given editor.
4214 * If @a editor is @c NULL, the default end of line characters are used.
4216 * @param editor The editor to operate on, or @c NULL to query the default value.
4217 * @return The name of the end of line characters.
4219 * @since 0.19
4221 GEANY_API_SYMBOL
4222 const gchar *editor_get_eol_char_name(GeanyEditor *editor)
4224 gint mode = file_prefs.default_eol_character;
4226 if (editor != NULL)
4227 mode = sci_get_eol_mode(editor->sci);
4229 return utils_get_eol_name(mode);
4234 * Retrieves the length of the used end of line characters (LF, CR/LF, CR) in the given editor.
4235 * If @a editor is @c NULL, the default end of line characters are used.
4236 * The returned value is 1 for CR and LF and 2 for CR/LF.
4238 * @param editor The editor to operate on, or @c NULL to query the default value.
4239 * @return The length of the end of line characters.
4241 * @since 0.19
4243 GEANY_API_SYMBOL
4244 gint editor_get_eol_char_len(GeanyEditor *editor)
4246 gint mode = file_prefs.default_eol_character;
4248 if (editor != NULL)
4249 mode = sci_get_eol_mode(editor->sci);
4251 switch (mode)
4253 case SC_EOL_CRLF: return 2; break;
4254 default: return 1; break;
4260 * Retrieves the used end of line characters (LF, CR/LF, CR) in the given editor.
4261 * If @a editor is @c NULL, the default end of line characters are used.
4262 * The returned value is either "\n", "\r\n" or "\r".
4264 * @param editor The editor to operate on, or @c NULL to query the default value.
4265 * @return The end of line characters.
4267 * @since 0.19
4269 GEANY_API_SYMBOL
4270 const gchar *editor_get_eol_char(GeanyEditor *editor)
4272 gint mode = file_prefs.default_eol_character;
4274 if (editor != NULL)
4275 mode = sci_get_eol_mode(editor->sci);
4277 return utils_get_eol_char(mode);
4281 static void fold_all(GeanyEditor *editor, gboolean want_fold)
4283 gint lines, first, i;
4285 if (editor == NULL || ! editor_prefs.folding)
4286 return;
4288 lines = sci_get_line_count(editor->sci);
4289 first = sci_get_first_visible_line(editor->sci);
4291 for (i = 0; i < lines; i++)
4293 gint level = sci_get_fold_level(editor->sci, i);
4295 if (level & SC_FOLDLEVELHEADERFLAG)
4297 if (sci_get_fold_expanded(editor->sci, i) == want_fold)
4298 sci_toggle_fold(editor->sci, i);
4301 editor_scroll_to_line(editor, first, 0.0F);
4305 void editor_unfold_all(GeanyEditor *editor)
4307 fold_all(editor, FALSE);
4311 void editor_fold_all(GeanyEditor *editor)
4313 fold_all(editor, TRUE);
4317 void editor_replace_tabs(GeanyEditor *editor, gboolean ignore_selection)
4319 gint search_pos, pos_in_line, current_tab_true_length;
4320 gint anchor_pos, caret_pos;
4321 gint tab_len;
4322 gchar *tab_str;
4323 struct Sci_TextToFind ttf;
4325 g_return_if_fail(editor != NULL);
4327 sci_start_undo_action(editor->sci);
4328 tab_len = sci_get_tab_width(editor->sci);
4329 if (sci_has_selection(editor->sci) && !ignore_selection)
4331 ttf.chrg.cpMin = sci_get_selection_start(editor->sci);
4332 ttf.chrg.cpMax = sci_get_selection_end(editor->sci);
4334 else
4336 ttf.chrg.cpMin = 0;
4337 ttf.chrg.cpMax = sci_get_length(editor->sci);
4339 ttf.lpstrText = (gchar*) "\t";
4341 anchor_pos = SSM(editor->sci, SCI_GETANCHOR, 0, 0);
4342 caret_pos = sci_get_current_position(editor->sci);
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 if (anchor_pos > search_pos)
4362 anchor_pos += current_tab_true_length - 1;
4363 if (caret_pos > search_pos)
4364 caret_pos += current_tab_true_length - 1;
4366 sci_set_selection(editor->sci, anchor_pos, caret_pos);
4367 sci_end_undo_action(editor->sci);
4371 /* Replaces all occurrences all spaces of the length of a given tab_width,
4372 * optionally restricting the search to the current selection. */
4373 void editor_replace_spaces(GeanyEditor *editor, gboolean ignore_selection)
4375 gint search_pos;
4376 gint anchor_pos, caret_pos;
4377 static gdouble tab_len_f = -1.0; /* keep the last used value */
4378 gint tab_len;
4379 gchar *text;
4380 struct Sci_TextToFind ttf;
4382 g_return_if_fail(editor != NULL);
4384 if (tab_len_f < 0.0)
4385 tab_len_f = sci_get_tab_width(editor->sci);
4387 if (! dialogs_show_input_numeric(
4388 _("Enter Tab Width"),
4389 _("Enter the amount of spaces which should be replaced by a tab character."),
4390 &tab_len_f, 1, 100, 1))
4392 return;
4394 tab_len = (gint) tab_len_f;
4395 text = g_strnfill(tab_len, ' ');
4397 sci_start_undo_action(editor->sci);
4398 if (sci_has_selection(editor->sci) && !ignore_selection)
4400 ttf.chrg.cpMin = sci_get_selection_start(editor->sci);
4401 ttf.chrg.cpMax = sci_get_selection_end(editor->sci);
4403 else
4405 ttf.chrg.cpMin = 0;
4406 ttf.chrg.cpMax = sci_get_length(editor->sci);
4408 ttf.lpstrText = text;
4410 anchor_pos = SSM(editor->sci, SCI_GETANCHOR, 0, 0);
4411 caret_pos = sci_get_current_position(editor->sci);
4412 while (TRUE)
4414 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4415 if (search_pos == -1)
4416 break;
4417 /* only replace indentation because otherwise we can mess up alignment */
4418 if (search_pos > sci_get_line_indent_position(editor->sci,
4419 sci_get_line_from_position(editor->sci, search_pos)))
4421 ttf.chrg.cpMin = search_pos + tab_len;
4422 continue;
4424 sci_set_target_start(editor->sci, search_pos);
4425 sci_set_target_end(editor->sci, search_pos + tab_len);
4426 sci_replace_target(editor->sci, "\t", FALSE);
4427 ttf.chrg.cpMin = search_pos;
4428 /* update end of range now text has changed */
4429 ttf.chrg.cpMax -= tab_len - 1;
4431 if (anchor_pos > search_pos)
4432 anchor_pos -= tab_len - 1;
4433 if (caret_pos > search_pos)
4434 caret_pos -= tab_len - 1;
4436 sci_set_selection(editor->sci, anchor_pos, caret_pos);
4437 sci_end_undo_action(editor->sci);
4438 g_free(text);
4442 void editor_strip_line_trailing_spaces(GeanyEditor *editor, gint line)
4444 gint line_start = sci_get_position_from_line(editor->sci, line);
4445 gint line_end = sci_get_line_end_position(editor->sci, line);
4446 gint i = line_end - 1;
4447 gchar ch = sci_get_char_at(editor->sci, i);
4449 /* Diff hunks should keep trailing spaces */
4450 if (sci_get_lexer(editor->sci) == SCLEX_DIFF)
4451 return;
4453 while ((i >= line_start) && ((ch == ' ') || (ch == '\t')))
4455 i--;
4456 ch = sci_get_char_at(editor->sci, i);
4458 if (i < (line_end - 1))
4460 sci_set_target_start(editor->sci, i + 1);
4461 sci_set_target_end(editor->sci, line_end);
4462 sci_replace_target(editor->sci, "", FALSE);
4467 void editor_strip_trailing_spaces(GeanyEditor *editor, gboolean ignore_selection)
4469 gint start_line;
4470 gint end_line;
4471 gint line;
4473 if (sci_has_selection(editor->sci) && !ignore_selection)
4475 gint selection_start = sci_get_selection_start(editor->sci);
4476 gint selection_end = sci_get_selection_end(editor->sci);
4478 start_line = sci_get_line_from_position(editor->sci, selection_start);
4479 end_line = sci_get_line_from_position(editor->sci, selection_end);
4481 if (sci_get_col_from_position(editor->sci, selection_end) > 0)
4482 end_line++;
4484 else
4486 start_line = 0;
4487 end_line = sci_get_line_count(editor->sci);
4490 sci_start_undo_action(editor->sci);
4492 for (line = start_line; line < end_line; line++)
4494 editor_strip_line_trailing_spaces(editor, line);
4496 sci_end_undo_action(editor->sci);
4500 void editor_ensure_final_newline(GeanyEditor *editor)
4502 gint max_lines = sci_get_line_count(editor->sci);
4503 gboolean append_newline = (max_lines == 1);
4504 gint end_document = sci_get_position_from_line(editor->sci, max_lines);
4506 if (max_lines > 1)
4508 append_newline = end_document > sci_get_position_from_line(editor->sci, max_lines - 1);
4510 if (append_newline)
4512 const gchar *eol = editor_get_eol_char(editor);
4514 sci_insert_text(editor->sci, end_document, eol);
4519 void editor_set_font(GeanyEditor *editor, const gchar *font)
4521 gint style, size;
4522 gchar *font_name;
4523 PangoFontDescription *pfd;
4525 g_return_if_fail(editor);
4527 pfd = pango_font_description_from_string(font);
4528 size = pango_font_description_get_size(pfd) / PANGO_SCALE;
4529 font_name = g_strdup_printf("!%s", pango_font_description_get_family(pfd));
4530 pango_font_description_free(pfd);
4532 for (style = 0; style <= STYLE_MAX; style++)
4533 sci_set_font(editor->sci, style, font_name, size);
4535 g_free(font_name);
4537 /* zoom to 100% to prevent confusion */
4538 sci_zoom_off(editor->sci);
4542 void editor_set_line_wrapping(GeanyEditor *editor, gboolean wrap)
4544 g_return_if_fail(editor != NULL);
4546 editor->line_wrapping = wrap;
4547 sci_set_lines_wrapped(editor->sci, wrap);
4551 /** Sets the indent type for @a editor.
4552 * @param editor Editor.
4553 * @param type Indent type.
4555 * @since 0.16
4557 GEANY_API_SYMBOL
4558 void editor_set_indent_type(GeanyEditor *editor, GeanyIndentType type)
4560 editor_set_indent(editor, type, editor->indent_width);
4564 void editor_set_indent_width(GeanyEditor *editor, gint width)
4566 editor_set_indent(editor, editor->indent_type, width);
4570 void editor_set_indent(GeanyEditor *editor, GeanyIndentType type, gint width)
4572 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
4573 ScintillaObject *sci = editor->sci;
4574 gboolean use_tabs = type != GEANY_INDENT_TYPE_SPACES;
4576 editor->indent_type = type;
4577 editor->indent_width = width;
4578 sci_set_use_tabs(sci, use_tabs);
4580 if (type == GEANY_INDENT_TYPE_BOTH)
4582 sci_set_tab_width(sci, iprefs->hard_tab_width);
4583 if (iprefs->hard_tab_width != 8)
4585 static gboolean warn = TRUE;
4586 if (warn)
4587 ui_set_statusbar(TRUE, _("Warning: non-standard hard tab width: %d != 8!"),
4588 iprefs->hard_tab_width);
4589 warn = FALSE;
4592 else
4593 sci_set_tab_width(sci, width);
4595 SSM(sci, SCI_SETINDENT, width, 0);
4597 /* remove indent spaces on backspace, if using any spaces to indent */
4598 SSM(sci, SCI_SETBACKSPACEUNINDENTS, type != GEANY_INDENT_TYPE_TABS, 0);
4602 /* Convenience function for editor_goto_pos() to pass in a line number. */
4603 gboolean editor_goto_line(GeanyEditor *editor, gint line_no, gint offset)
4605 gint pos;
4607 g_return_val_if_fail(editor, FALSE);
4608 if (line_no < 0 || line_no >= sci_get_line_count(editor->sci))
4609 return FALSE;
4611 if (offset != 0)
4613 gint current_line = sci_get_current_line(editor->sci);
4614 line_no *= offset;
4615 line_no = current_line + line_no;
4618 pos = sci_get_position_from_line(editor->sci, line_no);
4619 return editor_goto_pos(editor, pos, TRUE);
4623 /** Moves to position @a pos, switching to the document if necessary,
4624 * setting a marker if @a mark is set.
4626 * @param editor Editor.
4627 * @param pos The position.
4628 * @param mark Whether to set a mark on the position.
4629 * @return @c TRUE if action has been performed, otherwise @c FALSE.
4631 * @since 0.20
4633 GEANY_API_SYMBOL
4634 gboolean editor_goto_pos(GeanyEditor *editor, gint pos, gboolean mark)
4636 g_return_val_if_fail(editor, FALSE);
4637 if (G_UNLIKELY(pos < 0))
4638 return FALSE;
4640 if (mark)
4642 gint line = sci_get_line_from_position(editor->sci, pos);
4644 /* mark the tag with the yellow arrow */
4645 sci_marker_delete_all(editor->sci, 0);
4646 sci_set_marker_at_line(editor->sci, line, 0);
4649 sci_goto_pos(editor->sci, pos, TRUE);
4650 editor->scroll_percent = 0.25F;
4652 /* finally switch to the page */
4653 document_show_tab(editor->document);
4654 return TRUE;
4658 static gboolean
4659 on_editor_scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer user_data)
4661 GeanyEditor *editor = user_data;
4663 /* Handle scroll events if Alt is pressed and scroll whole pages instead of a
4664 * few lines only, maybe this could/should be done in Scintilla directly */
4665 if (event->state & GDK_MOD1_MASK)
4667 sci_send_command(editor->sci, (event->direction == GDK_SCROLL_DOWN) ? SCI_PAGEDOWN : SCI_PAGEUP);
4668 return TRUE;
4670 else if (event->state & GDK_SHIFT_MASK)
4672 gint amount = (event->direction == GDK_SCROLL_DOWN) ? 8 : -8;
4674 sci_scroll_columns(editor->sci, amount);
4675 return TRUE;
4678 return FALSE; /* let Scintilla handle all other cases */
4682 static gboolean editor_check_colourise(GeanyEditor *editor)
4684 GeanyDocument *doc = editor->document;
4686 if (!doc->priv->colourise_needed)
4687 return FALSE;
4689 doc->priv->colourise_needed = FALSE;
4691 if (doc->priv->full_colourise)
4693 sci_colourise(editor->sci, 0, -1);
4695 /* now that the current document is colourised, fold points are now accurate,
4696 * so force an update of the current function/tag. */
4697 symbols_get_current_function(NULL, NULL);
4698 ui_update_statusbar(NULL, -1);
4700 else
4702 gint start_line, end_line, start, end;
4704 start_line = SSM(doc->editor->sci, SCI_GETFIRSTVISIBLELINE, 0, 0);
4705 end_line = start_line + SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
4706 start_line = SSM(editor->sci, SCI_DOCLINEFROMVISIBLE, start_line, 0);
4707 end_line = SSM(editor->sci, SCI_DOCLINEFROMVISIBLE, end_line, 0);
4708 start = sci_get_position_from_line(editor->sci, start_line);
4709 end = sci_get_line_end_position(editor->sci, end_line);
4710 sci_colourise(editor->sci, start, end);
4713 return TRUE;
4717 /* We only want to colourise just before drawing, to save startup time and
4718 * prevent unnecessary recolouring other documents after one is saved.
4719 * Really we want a "draw" signal but there doesn't seem to be one (expose is too late,
4720 * and "show" doesn't work). */
4721 static gboolean on_editor_focus_in(GtkWidget *widget, GdkEventFocus *event, gpointer user_data)
4723 GeanyEditor *editor = user_data;
4725 editor_check_colourise(editor);
4726 return FALSE;
4730 static gboolean on_editor_expose_event(GtkWidget *widget, GdkEventExpose *event,
4731 gpointer user_data)
4733 GeanyEditor *editor = user_data;
4735 /* This is just to catch any uncolourised documents being drawn that didn't receive focus
4736 * for some reason, maybe it's not necessary but just in case. */
4737 editor_check_colourise(editor);
4738 return FALSE;
4742 #if GTK_CHECK_VERSION(3, 0, 0)
4743 static gboolean on_editor_draw(GtkWidget *widget, cairo_t *cr, gpointer user_data)
4745 return on_editor_expose_event(widget, NULL, user_data);
4747 #endif
4750 static void setup_sci_keys(ScintillaObject *sci)
4752 /* disable some Scintilla keybindings to be able to redefine them cleanly */
4753 sci_clear_cmdkey(sci, 'A' | (SCMOD_CTRL << 16)); /* select all */
4754 sci_clear_cmdkey(sci, 'D' | (SCMOD_CTRL << 16)); /* duplicate */
4755 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16)); /* line transpose */
4756 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line copy */
4757 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16)); /* line cut */
4758 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line delete */
4759 sci_clear_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line to end delete */
4760 sci_clear_cmdkey(sci, '/' | (SCMOD_CTRL << 16)); /* Previous word part */
4761 sci_clear_cmdkey(sci, '\\' | (SCMOD_CTRL << 16)); /* Next word part */
4762 sci_clear_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16)); /* scroll line up */
4763 sci_clear_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16)); /* scroll line down */
4764 sci_clear_cmdkey(sci, SCK_HOME); /* line start */
4765 sci_clear_cmdkey(sci, SCK_END); /* line end */
4766 sci_clear_cmdkey(sci, SCK_END | (SCMOD_ALT << 16)); /* visual line end */
4768 if (editor_prefs.use_gtk_word_boundaries)
4770 /* use GtkEntry-like word boundaries */
4771 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16), SCI_WORDRIGHTEND);
4772 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_WORDRIGHTENDEXTEND);
4773 sci_assign_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16), SCI_DELWORDRIGHTEND);
4775 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_ALT << 16), SCI_LINESCROLLUP);
4776 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_ALT << 16), SCI_LINESCROLLDOWN);
4777 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16), SCI_PARAUP);
4778 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARAUPEXTEND);
4779 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16), SCI_PARADOWN);
4780 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARADOWNEXTEND);
4782 sci_clear_cmdkey(sci, SCK_BACK | (SCMOD_ALT << 16)); /* clear Alt-Backspace (Undo) */
4786 /* registers a Scintilla image from a named icon from the theme */
4787 static gboolean register_named_icon(ScintillaObject *sci, guint id, const gchar *name)
4789 GError *error = NULL;
4790 GdkPixbuf *pixbuf;
4791 gint n_channels, rowstride, width, height;
4792 gint size;
4794 gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &size, NULL);
4795 pixbuf = gtk_icon_theme_load_icon(gtk_icon_theme_get_default(), name, size, 0, &error);
4796 if (! pixbuf)
4798 g_warning("failed to load icon '%s': %s", name, error->message);
4799 g_error_free(error);
4800 return FALSE;
4803 n_channels = gdk_pixbuf_get_n_channels(pixbuf);
4804 rowstride = gdk_pixbuf_get_rowstride(pixbuf);
4805 width = gdk_pixbuf_get_width(pixbuf);
4806 height = gdk_pixbuf_get_height(pixbuf);
4808 if (gdk_pixbuf_get_bits_per_sample(pixbuf) != 8 ||
4809 ! gdk_pixbuf_get_has_alpha(pixbuf) ||
4810 n_channels != 4 ||
4811 rowstride != width * n_channels)
4813 g_warning("incompatible image data for icon '%s'", name);
4814 g_object_unref(pixbuf);
4815 return FALSE;
4818 SSM(sci, SCI_RGBAIMAGESETWIDTH, width, 0);
4819 SSM(sci, SCI_RGBAIMAGESETHEIGHT, height, 0);
4820 SSM(sci, SCI_REGISTERRGBAIMAGE, id, (sptr_t)gdk_pixbuf_get_pixels(pixbuf));
4822 g_object_unref(pixbuf);
4823 return TRUE;
4827 /* Create new editor widget (scintilla).
4828 * @note The @c "sci-notify" signal is connected separately. */
4829 static ScintillaObject *create_new_sci(GeanyEditor *editor)
4831 ScintillaObject *sci;
4833 sci = SCINTILLA(scintilla_new());
4835 /* Scintilla doesn't support RTL languages properly and is primarily
4836 * intended to be used with LTR source code, so override the
4837 * GTK+ default text direction for the Scintilla widget. */
4838 gtk_widget_set_direction(GTK_WIDGET(sci), GTK_TEXT_DIR_LTR);
4840 gtk_widget_show(GTK_WIDGET(sci));
4842 sci_set_codepage(sci, SC_CP_UTF8);
4843 /*SSM(sci, SCI_SETWRAPSTARTINDENT, 4, 0);*/
4844 /* disable scintilla provided popup menu */
4845 sci_use_popup(sci, FALSE);
4847 setup_sci_keys(sci);
4849 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
4850 sci_set_lines_wrapped(sci, editor->line_wrapping);
4851 sci_set_caret_policy_x(sci, CARET_JUMPS | CARET_EVEN, 0);
4852 /*sci_set_caret_policy_y(sci, CARET_JUMPS | CARET_EVEN, 0);*/
4853 SSM(sci, SCI_AUTOCSETSEPARATOR, '\n', 0);
4854 SSM(sci, SCI_SETSCROLLWIDTHTRACKING, 1, 0);
4856 /* tag autocompletion images */
4857 register_named_icon(sci, 1, "classviewer-var");
4858 register_named_icon(sci, 2, "classviewer-method");
4860 /* necessary for column mode editing, implemented in Scintilla since 2.0 */
4861 SSM(sci, SCI_SETADDITIONALSELECTIONTYPING, 1, 0);
4863 /* virtual space */
4864 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
4866 #ifdef GDK_WINDOWING_QUARTZ
4867 /* "retina" (HiDPI) display support on OS X - requires disabling buffered draw */
4868 SSM(sci, SCI_SETBUFFEREDDRAW, 0, 0);
4869 #endif
4871 /* only connect signals if this is for the document notebook, not split window */
4872 if (editor->sci == NULL)
4874 g_signal_connect(sci, "button-press-event", G_CALLBACK(on_editor_button_press_event), editor);
4875 g_signal_connect(sci, "scroll-event", G_CALLBACK(on_editor_scroll_event), editor);
4876 g_signal_connect(sci, "motion-notify-event", G_CALLBACK(on_motion_event), NULL);
4877 g_signal_connect(sci, "focus-in-event", G_CALLBACK(on_editor_focus_in), editor);
4878 #if GTK_CHECK_VERSION(3, 0, 0)
4879 g_signal_connect(sci, "draw", G_CALLBACK(on_editor_draw), editor);
4880 #else
4881 g_signal_connect(sci, "expose-event", G_CALLBACK(on_editor_expose_event), editor);
4882 #endif
4884 return sci;
4888 /** Creates a new Scintilla @c GtkWidget based on the settings for @a editor.
4889 * @param editor Editor settings.
4890 * @return The new widget.
4892 * @since 0.15
4894 GEANY_API_SYMBOL
4895 ScintillaObject *editor_create_widget(GeanyEditor *editor)
4897 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4898 ScintillaObject *old, *sci;
4899 GeanyIndentType old_indent_type = editor->indent_type;
4900 gint old_indent_width = editor->indent_width;
4902 /* temporarily change editor to use the new sci widget */
4903 old = editor->sci;
4904 sci = create_new_sci(editor);
4905 editor->sci = sci;
4907 editor_set_indent(editor, iprefs->type, iprefs->width);
4908 editor_set_font(editor, interface_prefs.editor_font);
4909 editor_apply_update_prefs(editor);
4911 /* if editor already had a widget, restore it */
4912 if (old)
4914 editor->indent_type = old_indent_type;
4915 editor->indent_width = old_indent_width;
4916 editor->sci = old;
4918 return sci;
4922 GeanyEditor *editor_create(GeanyDocument *doc)
4924 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4925 GeanyEditor *editor = g_new0(GeanyEditor, 1);
4927 editor->document = doc;
4928 doc->editor = editor; /* needed in case some editor functions/callbacks expect it */
4930 editor->auto_indent = (iprefs->auto_indent_mode != GEANY_AUTOINDENT_NONE);
4931 editor->line_wrapping = get_project_pref(line_wrapping);
4932 editor->scroll_percent = -1.0F;
4933 editor->line_breaking = FALSE;
4935 editor->sci = editor_create_widget(editor);
4936 return editor;
4940 /* in case we need to free some fields in future */
4941 void editor_destroy(GeanyEditor *editor)
4943 g_free(editor);
4947 static void on_document_save(GObject *obj, GeanyDocument *doc)
4949 gchar *f = g_build_filename(app->configdir, "snippets.conf", NULL);
4951 if (utils_str_equal(doc->real_path, f))
4953 /* reload snippets */
4954 editor_snippets_free();
4955 editor_snippets_init();
4957 g_free(f);
4961 gboolean editor_complete_word_part(GeanyEditor *editor)
4963 gchar *entry;
4965 g_return_val_if_fail(editor, FALSE);
4967 if (!SSM(editor->sci, SCI_AUTOCACTIVE, 0, 0))
4968 return FALSE;
4970 entry = sci_get_string(editor->sci, SCI_AUTOCGETCURRENTTEXT, 0);
4972 /* if no word part, complete normally */
4973 if (!check_partial_completion(editor, entry))
4974 SSM(editor->sci, SCI_AUTOCCOMPLETE, 0, 0);
4976 g_free(entry);
4977 return TRUE;
4981 void editor_init(void)
4983 static GeanyIndentPrefs indent_prefs;
4984 gchar *f;
4986 memset(&editor_prefs, 0, sizeof(GeanyEditorPrefs));
4987 memset(&indent_prefs, 0, sizeof(GeanyIndentPrefs));
4988 editor_prefs.indentation = &indent_prefs;
4990 /* use g_signal_connect_after() to allow plugins connecting to the signal before the default
4991 * handler (on_editor_notify) is called */
4992 g_signal_connect_after(geany_object, "editor-notify", G_CALLBACK(on_editor_notify), NULL);
4994 f = g_build_filename(app->configdir, "snippets.conf", NULL);
4995 ui_add_config_file_menu_item(f, NULL, NULL);
4996 g_free(f);
4997 g_signal_connect(geany_object, "document-save", G_CALLBACK(on_document_save), NULL);
5001 /* TODO: Should these be user-defined instead of hard-coded? */
5002 void editor_set_indentation_guides(GeanyEditor *editor)
5004 gint mode;
5005 gint lexer;
5007 g_return_if_fail(editor != NULL);
5009 if (! editor_prefs.show_indent_guide)
5011 sci_set_indentation_guides(editor->sci, SC_IV_NONE);
5012 return;
5015 lexer = sci_get_lexer(editor->sci);
5016 switch (lexer)
5018 /* Lines added/removed are prefixed with +/- characters, so
5019 * those lines will not be shown with any indentation guides.
5020 * It can be distracting that only a few of lines in a diff/patch
5021 * file will show the guides. */
5022 case SCLEX_DIFF:
5023 mode = SC_IV_NONE;
5024 break;
5026 /* These languages use indentation for control blocks; the "look forward" method works
5027 * best here */
5028 case SCLEX_PYTHON:
5029 case SCLEX_HASKELL:
5030 case SCLEX_MAKEFILE:
5031 case SCLEX_ASM:
5032 case SCLEX_SQL:
5033 case SCLEX_COBOL:
5034 case SCLEX_PROPERTIES:
5035 case SCLEX_FORTRAN: /* Is this the best option for Fortran? */
5036 case SCLEX_CAML:
5037 mode = SC_IV_LOOKFORWARD;
5038 break;
5040 /* C-like (structured) languages benefit from the "look both" method */
5041 case SCLEX_CPP:
5042 case SCLEX_HTML:
5043 case SCLEX_PHPSCRIPT:
5044 case SCLEX_XML:
5045 case SCLEX_PERL:
5046 case SCLEX_LATEX:
5047 case SCLEX_LUA:
5048 case SCLEX_PASCAL:
5049 case SCLEX_RUBY:
5050 case SCLEX_TCL:
5051 case SCLEX_F77:
5052 case SCLEX_CSS:
5053 case SCLEX_BASH:
5054 case SCLEX_VHDL:
5055 case SCLEX_FREEBASIC:
5056 case SCLEX_D:
5057 case SCLEX_OCTAVE:
5058 case SCLEX_RUST:
5059 mode = SC_IV_LOOKBOTH;
5060 break;
5062 default:
5063 mode = SC_IV_REAL;
5064 break;
5067 sci_set_indentation_guides(editor->sci, mode);
5071 /* Apply non-document prefs that can change in the Preferences dialog */
5072 void editor_apply_update_prefs(GeanyEditor *editor)
5074 ScintillaObject *sci;
5076 g_return_if_fail(editor != NULL);
5078 if (main_status.quitting)
5079 return;
5081 sci = editor->sci;
5083 sci_set_mark_long_lines(sci, editor_get_long_line_type(),
5084 editor_get_long_line_column(), editor_prefs.long_line_color);
5086 /* update indent width, tab width */
5087 editor_set_indent(editor, editor->indent_type, editor->indent_width);
5088 sci_set_tab_indents(sci, editor_prefs.use_tab_to_indent);
5090 sci_assign_cmdkey(sci, SCK_HOME | (SCMOD_SHIFT << 16),
5091 editor_prefs.smart_home_key ? SCI_VCHOMEEXTEND : SCI_HOMEEXTEND);
5092 sci_assign_cmdkey(sci, SCK_HOME | ((SCMOD_SHIFT | SCMOD_ALT) << 16),
5093 editor_prefs.smart_home_key ? SCI_VCHOMERECTEXTEND : SCI_HOMERECTEXTEND);
5095 sci_set_autoc_max_height(sci, editor_prefs.symbolcompletion_max_height);
5096 SSM(sci, SCI_AUTOCSETDROPRESTOFWORD, editor_prefs.completion_drops_rest_of_word, 0);
5098 editor_set_indentation_guides(editor);
5100 sci_set_visible_white_spaces(sci, editor_prefs.show_white_space);
5101 sci_set_visible_eols(sci, editor_prefs.show_line_endings);
5102 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
5103 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin);
5105 sci_set_folding_margin_visible(sci, editor_prefs.folding);
5107 /* virtual space */
5108 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
5110 /* (dis)allow scrolling past end of document */
5111 sci_set_scroll_stop_at_last_line(sci, editor_prefs.scroll_stop_at_last_line);
5113 sci_set_scrollbar_mode(sci, editor_prefs.show_scrollbars);
5117 /* This is for tab-indents, space aligns formatted code. Spaces should be preserved. */
5118 static void change_tab_indentation(GeanyEditor *editor, gint line, gboolean increase)
5120 ScintillaObject *sci = editor->sci;
5121 gint pos = sci_get_position_from_line(sci, line);
5123 if (increase)
5125 sci_insert_text(sci, pos, "\t");
5127 else
5129 if (sci_get_char_at(sci, pos) == '\t')
5131 sci_set_selection(sci, pos, pos + 1);
5132 sci_replace_sel(sci, "");
5134 else /* remove spaces only if no tabs */
5136 gint width = sci_get_line_indentation(sci, line);
5138 width -= editor_get_indent_prefs(editor)->width;
5139 sci_set_line_indentation(sci, line, width);
5145 static void editor_change_line_indent(GeanyEditor *editor, gint line, gboolean increase)
5147 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
5148 ScintillaObject *sci = editor->sci;
5150 if (iprefs->type == GEANY_INDENT_TYPE_TABS)
5151 change_tab_indentation(editor, line, increase);
5152 else
5154 gint width = sci_get_line_indentation(sci, line);
5156 width += increase ? iprefs->width : -iprefs->width;
5157 sci_set_line_indentation(sci, line, width);
5162 void editor_indent(GeanyEditor *editor, gboolean increase)
5164 ScintillaObject *sci = editor->sci;
5165 gint caret_pos, caret_line, caret_offset, caret_indent_pos, caret_line_len;
5166 gint anchor_pos, anchor_line, anchor_offset, anchor_indent_pos, anchor_line_len;
5168 /* backup information needed to restore caret and anchor */
5169 caret_pos = sci_get_current_position(sci);
5170 anchor_pos = SSM(sci, SCI_GETANCHOR, 0, 0);
5171 caret_line = sci_get_line_from_position(sci, caret_pos);
5172 anchor_line = sci_get_line_from_position(sci, anchor_pos);
5173 caret_offset = caret_pos - sci_get_position_from_line(sci, caret_line);
5174 anchor_offset = anchor_pos - sci_get_position_from_line(sci, anchor_line);
5175 caret_indent_pos = sci_get_line_indent_position(sci, caret_line);
5176 anchor_indent_pos = sci_get_line_indent_position(sci, anchor_line);
5177 caret_line_len = sci_get_line_length(sci, caret_line);
5178 anchor_line_len = sci_get_line_length(sci, anchor_line);
5180 if (sci_get_lines_selected(sci) <= 1)
5182 editor_change_line_indent(editor, sci_get_current_line(sci), increase);
5184 else
5186 gint start, end;
5187 gint line, lstart, lend;
5189 editor_select_lines(editor, FALSE);
5190 start = sci_get_selection_start(sci);
5191 end = sci_get_selection_end(sci);
5192 lstart = sci_get_line_from_position(sci, start);
5193 lend = sci_get_line_from_position(sci, end);
5194 if (end == sci_get_length(sci))
5195 lend++; /* for last line with text on it */
5197 sci_start_undo_action(sci);
5198 for (line = lstart; line < lend; line++)
5200 editor_change_line_indent(editor, line, increase);
5202 sci_end_undo_action(sci);
5205 /* restore caret and anchor position */
5206 if (caret_pos >= caret_indent_pos)
5207 caret_offset += sci_get_line_length(sci, caret_line) - caret_line_len;
5208 if (anchor_pos >= anchor_indent_pos)
5209 anchor_offset += sci_get_line_length(sci, anchor_line) - anchor_line_len;
5211 SSM(sci, SCI_SETCURRENTPOS, sci_get_position_from_line(sci, caret_line) + caret_offset, 0);
5212 SSM(sci, SCI_SETANCHOR, sci_get_position_from_line(sci, anchor_line) + anchor_offset, 0);
5216 /** Gets snippet by name.
5218 * If @a editor is passed, returns a snippet specific to the document filetype.
5219 * If @a editor is @c NULL, returns a snippet from the default set.
5221 * @param editor Editor or @c NULL.
5222 * @param snippet_name Snippet name.
5223 * @return snippet or @c NULL if it was not found. Must not be freed.
5225 GEANY_API_SYMBOL
5226 const gchar *editor_find_snippet(GeanyEditor *editor, const gchar *snippet_name)
5228 const gchar *subhash_name = editor ? editor->document->file_type->name : "Default";
5229 GHashTable *subhash = g_hash_table_lookup(snippet_hash, subhash_name);
5231 return subhash ? g_hash_table_lookup(subhash, snippet_name) : NULL;
5235 /** Replaces all special sequences in @a snippet and inserts it at @a pos.
5236 * If you insert at the current position, consider calling @c sci_scroll_caret()
5237 * after this function.
5238 * @param editor .
5239 * @param pos .
5240 * @param snippet .
5242 GEANY_API_SYMBOL
5243 void editor_insert_snippet(GeanyEditor *editor, gint pos, const gchar *snippet)
5245 GString *pattern;
5247 pattern = g_string_new(snippet);
5248 snippets_make_replacements(editor, pattern);
5249 editor_insert_text_block(editor, pattern->str, pos, -1, -1, TRUE);
5250 g_string_free(pattern, TRUE);