Fix escaping of infobar text against entity injection from filename
[geany-mirror.git] / src / editor.c
blobe7122062f74a8aef2663349c8235468a95d72853
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 static GHashTable *snippet_hash = NULL;
71 static GtkAccelGroup *snippet_accel_group = NULL;
72 static gboolean autocomplete_scope_shown = FALSE;
74 static const gchar geany_cursor_marker[] = "__GEANY_CURSOR_MARKER__";
76 /* holds word under the mouse or keyboard cursor */
77 static gchar current_word[GEANY_MAX_WORD_LENGTH];
79 /* Initialised in keyfile.c. */
80 GeanyEditorPrefs editor_prefs;
82 EditorInfo editor_info = {current_word, -1};
84 static struct
86 gchar *text;
87 gboolean set;
88 gchar *last_word;
89 guint tag_index;
90 gint pos;
91 ScintillaObject *sci;
92 } calltip = {NULL, FALSE, NULL, 0, 0, NULL};
94 static gchar indent[100];
97 static void on_new_line_added(GeanyEditor *editor);
98 static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch);
99 static void insert_indent_after_line(GeanyEditor *editor, gint line);
100 static void auto_multiline(GeanyEditor *editor, gint pos);
101 static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c);
102 static void close_block(GeanyEditor *editor, gint pos);
103 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos);
104 static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen,
105 const gchar *wc, gboolean stem);
106 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent);
107 static const gchar *snippets_find_completion_by_name(const gchar *type, const gchar *name);
108 static void snippets_make_replacements(GeanyEditor *editor, GString *pattern);
109 static GeanyFiletype *editor_get_filetype_at_line(GeanyEditor *editor, gint line);
110 static gboolean sci_is_blank_line(ScintillaObject *sci, gint line);
113 void editor_snippets_free(void)
115 g_hash_table_destroy(snippet_hash);
116 gtk_window_remove_accel_group(GTK_WINDOW(main_widgets.window), snippet_accel_group);
120 static void snippets_load(GKeyFile *sysconfig, GKeyFile *userconfig)
122 gsize i, j, len = 0, len_keys = 0;
123 gchar **groups_user, **groups_sys;
124 gchar **keys_user, **keys_sys;
125 gchar *value;
126 GHashTable *tmp;
128 /* keys are strings, values are GHashTables, so use g_free and g_hash_table_destroy */
129 snippet_hash =
130 g_hash_table_new_full(g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_hash_table_destroy);
132 /* first read all globally defined auto completions */
133 groups_sys = g_key_file_get_groups(sysconfig, &len);
134 for (i = 0; i < len; i++)
136 if (strcmp(groups_sys[i], "Keybindings") == 0)
137 continue;
138 keys_sys = g_key_file_get_keys(sysconfig, groups_sys[i], &len_keys, NULL);
139 /* create new hash table for the read section (=> filetype) */
140 tmp = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
141 g_hash_table_insert(snippet_hash, g_strdup(groups_sys[i]), tmp);
143 for (j = 0; j < len_keys; j++)
145 g_hash_table_insert(tmp, g_strdup(keys_sys[j]),
146 utils_get_setting_string(sysconfig, groups_sys[i], keys_sys[j], ""));
148 g_strfreev(keys_sys);
150 g_strfreev(groups_sys);
152 /* now read defined completions in user's configuration directory and add / replace them */
153 groups_user = g_key_file_get_groups(userconfig, &len);
154 for (i = 0; i < len; i++)
156 if (strcmp(groups_user[i], "Keybindings") == 0)
157 continue;
158 keys_user = g_key_file_get_keys(userconfig, groups_user[i], &len_keys, NULL);
160 tmp = g_hash_table_lookup(snippet_hash, groups_user[i]);
161 if (tmp == NULL)
162 { /* new key found, create hash table */
163 tmp = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
164 g_hash_table_insert(snippet_hash, g_strdup(groups_user[i]), tmp);
166 for (j = 0; j < len_keys; j++)
168 value = g_hash_table_lookup(tmp, keys_user[j]);
169 if (value == NULL)
170 { /* value = NULL means the key doesn't yet exist, so insert */
171 g_hash_table_insert(tmp, g_strdup(keys_user[j]),
172 utils_get_setting_string(userconfig, groups_user[i], keys_user[j], ""));
174 else
175 { /* old key and value will be freed by destroy function (g_free) */
176 g_hash_table_replace(tmp, g_strdup(keys_user[j]),
177 utils_get_setting_string(userconfig, groups_user[i], keys_user[j], ""));
180 g_strfreev(keys_user);
182 g_strfreev(groups_user);
186 static gboolean on_snippet_keybinding_activate(gchar *key)
188 GeanyDocument *doc = document_get_current();
189 const gchar *s;
191 if (!doc || !gtk_widget_has_focus(GTK_WIDGET(doc->editor->sci)))
192 return FALSE;
194 s = snippets_find_completion_by_name(doc->file_type->name, key);
195 if (!s) /* allow user to specify keybindings for "special" snippets */
197 GHashTable *specials = g_hash_table_lookup(snippet_hash, "Special");
199 if (G_LIKELY(specials != NULL))
200 s = g_hash_table_lookup(specials, key);
202 if (!s)
204 utils_beep();
205 return FALSE;
208 editor_insert_snippet(doc->editor, sci_get_current_position(doc->editor->sci), s);
209 sci_scroll_caret(doc->editor->sci);
211 return TRUE;
215 static void add_kb(GKeyFile *keyfile, const gchar *group, gchar **keys)
217 gsize i;
219 if (!keys)
220 return;
221 for (i = 0; i < g_strv_length(keys); i++)
223 guint key;
224 GdkModifierType mods;
225 gchar *accel_string = g_key_file_get_value(keyfile, group, keys[i], NULL);
227 gtk_accelerator_parse(accel_string, &key, &mods);
228 g_free(accel_string);
230 if (key == 0 && mods == 0)
232 g_warning("Can not parse accelerator \"%s\" from user snippets.conf", accel_string);
233 continue;
235 gtk_accel_group_connect(snippet_accel_group, key, mods, 0,
236 g_cclosure_new_swap((GCallback)on_snippet_keybinding_activate,
237 g_strdup(keys[i]), (GClosureNotify)g_free));
242 static void load_kb(GKeyFile *sysconfig, GKeyFile *userconfig)
244 const gchar kb_group[] = "Keybindings";
245 gchar **keys = g_key_file_get_keys(userconfig, kb_group, NULL, NULL);
246 gchar **ptr;
248 /* remove overridden keys from system keyfile */
249 foreach_strv(ptr, keys)
250 g_key_file_remove_key(sysconfig, kb_group, *ptr, NULL);
252 add_kb(userconfig, kb_group, keys);
253 g_strfreev(keys);
255 keys = g_key_file_get_keys(sysconfig, kb_group, NULL, NULL);
256 add_kb(sysconfig, kb_group, keys);
257 g_strfreev(keys);
261 void editor_snippets_init(void)
263 gchar *sysconfigfile, *userconfigfile;
264 GKeyFile *sysconfig = g_key_file_new();
265 GKeyFile *userconfig = g_key_file_new();
267 sysconfigfile = g_build_filename(app->datadir, "snippets.conf", NULL);
268 userconfigfile = g_build_filename(app->configdir, "snippets.conf", NULL);
270 /* check for old autocomplete.conf files (backwards compatibility) */
271 if (! g_file_test(userconfigfile, G_FILE_TEST_IS_REGULAR))
272 SETPTR(userconfigfile, g_build_filename(app->configdir, "autocomplete.conf", NULL));
274 /* load the actual config files */
275 g_key_file_load_from_file(sysconfig, sysconfigfile, G_KEY_FILE_NONE, NULL);
276 g_key_file_load_from_file(userconfig, userconfigfile, G_KEY_FILE_NONE, NULL);
278 snippets_load(sysconfig, userconfig);
280 /* setup snippet keybindings */
281 snippet_accel_group = gtk_accel_group_new();
282 gtk_window_add_accel_group(GTK_WINDOW(main_widgets.window), snippet_accel_group);
283 load_kb(sysconfig, userconfig);
285 g_free(sysconfigfile);
286 g_free(userconfigfile);
287 g_key_file_free(sysconfig);
288 g_key_file_free(userconfig);
292 static gboolean on_editor_button_press_event(GtkWidget *widget, GdkEventButton *event,
293 gpointer data)
295 GeanyEditor *editor = data;
296 GeanyDocument *doc = editor->document;
298 /* it's very unlikely we got a 'real' click even on 0, 0, so assume it is a
299 * fake event to show the editor menu triggered by a key event where we want to use the
300 * text cursor position. */
301 if (event->x > 0.0 && event->y > 0.0)
302 editor_info.click_pos = sci_get_position_from_xy(editor->sci,
303 (gint)event->x, (gint)event->y, FALSE);
304 else
305 editor_info.click_pos = sci_get_current_position(editor->sci);
307 if (event->button == 1)
309 guint state = keybindings_get_modifiers(event->state);
311 if (event->type == GDK_BUTTON_PRESS && editor_prefs.disable_dnd)
313 gint ss = sci_get_selection_start(editor->sci);
314 sci_set_selection_end(editor->sci, ss);
316 if (event->type == GDK_BUTTON_PRESS && state == GEANY_PRIMARY_MOD_MASK)
318 sci_set_current_position(editor->sci, editor_info.click_pos, FALSE);
320 editor_find_current_word(editor, editor_info.click_pos,
321 current_word, sizeof current_word, NULL);
322 if (*current_word)
323 return symbols_goto_tag(current_word, TRUE);
324 else
325 keybindings_send_command(GEANY_KEY_GROUP_GOTO, GEANY_KEYS_GOTO_MATCHINGBRACE);
326 return TRUE;
328 return document_check_disk_status(doc, FALSE);
331 /* calls the edit popup menu in the editor */
332 if (event->button == 3)
334 gboolean can_goto;
336 /* ensure the editor widget has the focus after this operation */
337 gtk_widget_grab_focus(widget);
339 editor_find_current_word(editor, editor_info.click_pos,
340 current_word, sizeof current_word, NULL);
342 can_goto = sci_has_selection(editor->sci) || current_word[0] != '\0';
343 ui_update_popup_goto_items(can_goto);
344 ui_update_popup_copy_items(doc);
345 ui_update_insert_include_item(doc, 0);
347 g_signal_emit_by_name(geany_object, "update-editor-menu",
348 current_word, editor_info.click_pos, doc);
350 gtk_menu_popup(GTK_MENU(main_widgets.editor_menu),
351 NULL, NULL, NULL, NULL, event->button, event->time);
353 return TRUE;
355 return FALSE;
359 static gboolean is_style_php(gint style)
361 if ((style >= SCE_HPHP_DEFAULT && style <= SCE_HPHP_OPERATOR) ||
362 style == SCE_HPHP_COMPLEX_VARIABLE)
364 return TRUE;
367 return FALSE;
371 static gint editor_get_long_line_type(void)
373 if (app->project)
374 switch (app->project->priv->long_line_behaviour)
376 case 0: /* marker disabled */
377 return 2;
378 case 1: /* use global settings */
379 break;
380 case 2: /* custom (enabled) */
381 return editor_prefs.long_line_type;
384 if (!editor_prefs.long_line_enabled)
385 return 2;
386 else
387 return editor_prefs.long_line_type;
391 static gint editor_get_long_line_column(void)
393 if (app->project && app->project->priv->long_line_behaviour != 1 /* use global settings */)
394 return app->project->priv->long_line_column;
395 else
396 return editor_prefs.long_line_column;
400 #define get_project_pref(id)\
401 (app->project ? app->project->priv->id : editor_prefs.id)
403 static const GeanyEditorPrefs *
404 get_default_prefs(void)
406 static GeanyEditorPrefs eprefs;
408 eprefs = editor_prefs;
410 /* project overrides */
411 eprefs.indentation = (GeanyIndentPrefs*)editor_get_indent_prefs(NULL);
412 eprefs.long_line_type = editor_get_long_line_type();
413 eprefs.long_line_column = editor_get_long_line_column();
414 eprefs.line_wrapping = get_project_pref(line_wrapping);
415 eprefs.line_break_column = get_project_pref(line_break_column);
416 eprefs.auto_continue_multiline = get_project_pref(auto_continue_multiline);
417 return &eprefs;
421 /* Gets the prefs for the editor.
422 * Prefs can be different according to project or document.
423 * @warning Always get a fresh result instead of keeping a pointer to it if the editor/project
424 * settings may have changed, or if this function has been called for a different editor.
425 * @param editor The editor, or @c NULL to get the default prefs.
426 * @return The prefs. */
427 const GeanyEditorPrefs *editor_get_prefs(GeanyEditor *editor)
429 static GeanyEditorPrefs eprefs;
430 const GeanyEditorPrefs *dprefs = get_default_prefs();
432 /* Return the address of the default prefs to allow returning default and editor
433 * pref pointers without invalidating the contents of either. */
434 if (editor == NULL)
435 return dprefs;
437 eprefs = *dprefs;
438 eprefs.indentation = (GeanyIndentPrefs*)editor_get_indent_prefs(editor);
439 /* add other editor & document overrides as needed */
440 return &eprefs;
444 void editor_toggle_fold(GeanyEditor *editor, gint line, gint modifiers)
446 ScintillaObject *sci;
447 gint header;
449 g_return_if_fail(editor != NULL);
451 sci = editor->sci;
452 /* When collapsing a fold range whose starting line is offscreen,
453 * scroll the starting line to display at the top of the view.
454 * Otherwise it can be confusing when the document scrolls down to hide
455 * the folded lines. */
456 if ((sci_get_fold_level(sci, line) & SC_FOLDLEVELNUMBERMASK) > SC_FOLDLEVELBASE &&
457 !(sci_get_fold_level(sci, line) & SC_FOLDLEVELHEADERFLAG))
459 gint parent = sci_get_fold_parent(sci, line);
460 gint first = sci_get_first_visible_line(sci);
462 parent = SSM(sci, SCI_VISIBLEFROMDOCLINE, parent, 0);
463 if (first > parent)
464 SSM(sci, SCI_SETFIRSTVISIBLELINE, parent, 0);
467 /* find the fold header of the given line in case the one clicked isn't a fold point */
468 if (sci_get_fold_level(sci, line) & SC_FOLDLEVELHEADERFLAG)
469 header = line;
470 else
471 header = sci_get_fold_parent(sci, line);
473 if ((editor_prefs.unfold_all_children && ! (modifiers & SCMOD_SHIFT)) ||
474 (! editor_prefs.unfold_all_children && (modifiers & SCMOD_SHIFT)))
476 SSM(sci, SCI_FOLDCHILDREN, header, SC_FOLDACTION_TOGGLE);
478 else
480 SSM(sci, SCI_FOLDLINE, header, SC_FOLDACTION_TOGGLE);
485 static void on_margin_click(GeanyEditor *editor, SCNotification *nt)
487 /* left click to marker margin marks the line */
488 if (nt->margin == 1)
490 gint line = sci_get_line_from_position(editor->sci, nt->position);
492 /*sci_marker_delete_all(editor->sci, 1);*/
493 sci_toggle_marker_at_line(editor->sci, line, 1); /* toggle the marker */
495 /* left click on the folding margin to toggle folding state of current line */
496 else if (nt->margin == 2 && editor_prefs.folding)
498 gint line = sci_get_line_from_position(editor->sci, nt->position);
499 editor_toggle_fold(editor, line, nt->modifiers);
504 static void on_update_ui(GeanyEditor *editor, G_GNUC_UNUSED SCNotification *nt)
506 ScintillaObject *sci = editor->sci;
507 gint pos = sci_get_current_position(sci);
509 /* since Scintilla 2.24, SCN_UPDATEUI is also sent on scrolling though we don't need to handle
510 * this and so ignore every SCN_UPDATEUI events except for content and selection changes */
511 if (! (nt->updated & SC_UPDATE_CONTENT) && ! (nt->updated & SC_UPDATE_SELECTION))
512 return;
514 /* undo / redo menu update */
515 ui_update_popup_reundo_items(editor->document);
517 /* brace highlighting */
518 editor_highlight_braces(editor, pos);
520 ui_update_statusbar(editor->document, pos);
522 #if 0
523 /** experimental code for inverting selections */
525 gint i;
526 for (i = SSM(sci, SCI_GETSELECTIONSTART, 0, 0); i < SSM(sci, SCI_GETSELECTIONEND, 0, 0); i++)
528 /* need to get colour from getstyleat(), but how? */
529 SSM(sci, SCI_STYLESETFORE, STYLE_DEFAULT, 0);
530 SSM(sci, SCI_STYLESETBACK, STYLE_DEFAULT, 0);
533 sci_get_style_at(sci, pos);
535 #endif
539 static void check_line_breaking(GeanyEditor *editor, gint pos)
541 ScintillaObject *sci = editor->sci;
542 gint line, lstart, col;
543 gchar c;
545 if (!editor->line_breaking)
546 return;
548 col = sci_get_col_from_position(sci, pos);
550 line = sci_get_current_line(sci);
552 lstart = sci_get_position_from_line(sci, line);
554 /* use column instead of position which might be different with multibyte characters */
555 if (col < get_project_pref(line_break_column))
556 return;
558 /* look for the last space before line_break_column */
559 pos = sci_get_position_from_col(sci, lstart, get_project_pref(line_break_column));
561 while (pos > lstart)
563 c = sci_get_char_at(sci, --pos);
564 if (c == ' ')
566 gint diff, last_pos, last_col;
568 /* remember the distance between the current column and the last column on the line
569 * (we use column position in case the previous line gets altered, such as removing
570 * trailing spaces or in case it contains multibyte characters) */
571 last_pos = sci_get_line_end_position(sci, line);
572 last_col = sci_get_col_from_position(sci, last_pos);
573 diff = last_col - col;
575 /* break the line after the space */
576 sci_set_current_position(sci, pos + 1, FALSE);
577 sci_cancel(sci); /* don't select from completion list */
578 sci_send_command(sci, SCI_NEWLINE);
579 line++;
581 /* correct cursor position (might not be at line end) */
582 last_pos = sci_get_line_end_position(sci, line);
583 last_col = sci_get_col_from_position(sci, last_pos); /* get last column on line */
584 /* last column - distance is the desired column, then retrieve its document position */
585 pos = sci_get_position_from_col(sci, line, last_col - diff);
586 sci_set_current_position(sci, pos, FALSE);
587 sci_scroll_caret(sci);
588 return;
594 static void show_autocomplete(ScintillaObject *sci, gsize rootlen, GString *words)
596 /* hide autocompletion if only option is already typed */
597 if (rootlen >= words->len ||
598 (words->str[rootlen] == '?' && rootlen >= words->len - 2))
600 sci_send_command(sci, SCI_AUTOCCANCEL);
601 return;
603 /* store whether a calltip is showing, so we can reshow it after autocompletion */
604 calltip.set = (gboolean) SSM(sci, SCI_CALLTIPACTIVE, 0, 0);
605 SSM(sci, SCI_AUTOCSHOW, rootlen, (sptr_t) words->str);
609 static void show_tags_list(GeanyEditor *editor, const GPtrArray *tags, gsize rootlen)
611 ScintillaObject *sci = editor->sci;
613 g_return_if_fail(tags);
615 if (tags->len > 0)
617 GString *words = g_string_sized_new(150);
618 guint j;
620 for (j = 0; j < tags->len; ++j)
622 TMTag *tag = tags->pdata[j];
624 if (j > 0)
625 g_string_append_c(words, '\n');
627 if (j == editor_prefs.autocompletion_max_entries)
629 g_string_append(words, "...");
630 break;
632 g_string_append(words, tag->name);
634 /* for now, tag types don't all follow C, so just look at arglist */
635 if (!EMPTY(tag->arglist))
636 g_string_append(words, "?2");
637 else
638 g_string_append(words, "?1");
640 show_autocomplete(sci, rootlen, words);
641 g_string_free(words, TRUE);
646 /* do not use with long strings */
647 static gboolean match_last_chars(ScintillaObject *sci, gint pos, const gchar *str)
649 gsize len = strlen(str);
650 gchar *buf;
652 g_return_val_if_fail(len < 100, FALSE);
654 if ((gint)len > pos)
655 return FALSE;
657 buf = g_alloca(len + 1);
658 sci_get_text_range(sci, pos - len, pos, buf);
659 return strcmp(str, buf) == 0;
663 static gboolean reshow_calltip(gpointer data)
665 GeanyDocument *doc;
667 g_return_val_if_fail(calltip.sci != NULL, FALSE);
669 SSM(calltip.sci, SCI_CALLTIPCANCEL, 0, 0);
670 doc = document_get_current();
672 if (doc && doc->editor->sci == calltip.sci)
674 /* we use the position where the calltip was previously started as SCI_GETCURRENTPOS
675 * may be completely wrong in case the user cancelled the auto completion with the mouse */
676 SSM(calltip.sci, SCI_CALLTIPSHOW, calltip.pos, (sptr_t) calltip.text);
678 return FALSE;
682 static void request_reshowing_calltip(SCNotification *nt)
684 if (calltip.set)
686 /* delay the reshow of the calltip window to make sure it is actually displayed,
687 * without it might be not visible on SCN_AUTOCCANCEL. the priority is set to
688 * low to hopefully make Scintilla's events happen before reshowing since they
689 * seem to re-cancel the calltip on autoc menu hiding too */
690 g_idle_add_full(G_PRIORITY_LOW, reshow_calltip, NULL, NULL);
695 static gboolean autocomplete_scope(GeanyEditor *editor, const gchar *root, gsize rootlen)
697 ScintillaObject *sci = editor->sci;
698 gint pos = sci_get_current_position(editor->sci);
699 gchar typed = sci_get_char_at(sci, pos - 1);
700 gchar brace_char;
701 gchar *name;
702 GeanyFiletype *ft = editor->document->file_type;
703 GPtrArray *tags;
704 gboolean function = FALSE;
705 gboolean member;
706 gboolean scope_sep_typed = FALSE;
707 gboolean ret = FALSE;
708 const gchar *current_scope;
709 const gchar *context_sep = tm_parser_context_separator(ft->lang);
711 if (autocomplete_scope_shown)
713 /* move at the operator position */
714 pos -= rootlen;
716 /* allow for a space between word and operator */
717 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
718 pos--;
720 if (pos > 0)
721 typed = sci_get_char_at(sci, pos - 1);
724 /* make sure to keep in sync with similar checks below */
725 if (match_last_chars(sci, pos, context_sep))
727 pos -= strlen(context_sep);
728 scope_sep_typed = TRUE;
730 else if (typed == '.')
731 pos -= 1;
732 else if ((ft->id == GEANY_FILETYPES_C || ft->id == GEANY_FILETYPES_CPP) &&
733 match_last_chars(sci, pos, "->"))
734 pos -= 2;
735 else if (ft->id == GEANY_FILETYPES_CPP && match_last_chars(sci, pos, "->*"))
736 pos -= 3;
737 else
738 return FALSE;
740 /* allow for a space between word and operator */
741 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
742 pos--;
744 /* if function or array index, skip to matching brace */
745 brace_char = sci_get_char_at(sci, pos - 1);
746 if (pos > 0 && (brace_char == ')' || brace_char == ']'))
748 gint brace_pos = sci_find_matching_brace(sci, pos - 1);
750 if (brace_pos != -1)
752 pos = brace_pos;
753 function = brace_char == ')';
756 /* allow for a space between opening brace and name */
757 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
758 pos--;
761 name = editor_get_word_at_pos(editor, pos, NULL);
762 if (!name)
763 return FALSE;
765 /* check if invoked on member */
766 pos -= strlen(name);
767 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
768 pos--;
769 /* make sure to keep in sync with similar checks above */
770 member = match_last_chars(sci, pos, ".") || match_last_chars(sci, pos, context_sep) ||
771 match_last_chars(sci, pos, "->") || match_last_chars(sci, pos, "->*");
773 if (symbols_get_current_scope(editor->document, &current_scope) == -1)
774 current_scope = "";
775 tags = tm_workspace_find_scope_members(editor->document->tm_file, name, function,
776 member, current_scope, scope_sep_typed);
777 if (tags)
779 GPtrArray *filtered = g_ptr_array_new();
780 TMTag *tag;
781 guint i;
783 foreach_ptr_array(tag, i, tags)
785 if (g_str_has_prefix(tag->name, root))
786 g_ptr_array_add(filtered, tag);
789 if (filtered->len > 0)
791 show_tags_list(editor, filtered, rootlen);
792 ret = TRUE;
795 g_ptr_array_free(tags, TRUE);
796 g_ptr_array_free(filtered, TRUE);
799 g_free(name);
800 return ret;
804 static void on_char_added(GeanyEditor *editor, SCNotification *nt)
806 ScintillaObject *sci = editor->sci;
807 gint pos = sci_get_current_position(sci);
809 switch (nt->ch)
811 case '\r':
812 { /* simple indentation (only for CR format) */
813 if (sci_get_eol_mode(sci) == SC_EOL_CR)
814 on_new_line_added(editor);
815 break;
817 case '\n':
818 { /* simple indentation (for CR/LF and LF format) */
819 on_new_line_added(editor);
820 break;
822 case '>':
823 editor_start_auto_complete(editor, pos, FALSE); /* C/C++ ptr-> scope completion */
824 /* fall through */
825 case '/':
826 { /* close xml-tags */
827 handle_xml(editor, pos, nt->ch);
828 break;
830 case '(':
832 auto_close_chars(sci, pos, nt->ch);
833 /* show calltips */
834 editor_show_calltip(editor, --pos);
835 break;
837 case ')':
838 { /* hide calltips */
839 if (SSM(sci, SCI_CALLTIPACTIVE, 0, 0))
841 SSM(sci, SCI_CALLTIPCANCEL, 0, 0);
843 g_free(calltip.text);
844 calltip.text = NULL;
845 calltip.pos = 0;
846 calltip.sci = NULL;
847 calltip.set = FALSE;
848 break;
850 case '{':
851 case '[':
852 case '"':
853 case '\'':
855 auto_close_chars(sci, pos, nt->ch);
856 break;
858 case '}':
859 { /* closing bracket handling */
860 if (editor->auto_indent)
861 close_block(editor, pos - 1);
862 break;
864 /* scope autocompletion */
865 case '.':
866 case ':': /* C/C++ class:: syntax */
867 /* tag autocompletion */
868 default:
869 #if 0
870 if (! editor_start_auto_complete(editor, pos, FALSE))
871 request_reshowing_calltip(nt);
872 #else
873 editor_start_auto_complete(editor, pos, FALSE);
874 #endif
876 check_line_breaking(editor, pos);
880 /* expand() and fold_changed() are copied from SciTE (thanks) to fix #1923350. */
881 static void expand(ScintillaObject *sci, gint *line, gboolean doExpand,
882 gboolean force, gint visLevels, gint level)
884 gint lineMaxSubord = SSM(sci, SCI_GETLASTCHILD, *line, level & SC_FOLDLEVELNUMBERMASK);
885 gint levelLine = level;
886 (*line)++;
887 while (*line <= lineMaxSubord)
889 if (force)
891 if (visLevels > 0)
892 SSM(sci, SCI_SHOWLINES, *line, *line);
893 else
894 SSM(sci, SCI_HIDELINES, *line, *line);
896 else
898 if (doExpand)
899 SSM(sci, SCI_SHOWLINES, *line, *line);
901 if (levelLine == -1)
902 levelLine = SSM(sci, SCI_GETFOLDLEVEL, *line, 0);
903 if (levelLine & SC_FOLDLEVELHEADERFLAG)
905 if (force)
907 if (visLevels > 1)
908 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
909 else
910 SSM(sci, SCI_SETFOLDEXPANDED, *line, 0);
911 expand(sci, line, doExpand, force, visLevels - 1, -1);
913 else
915 if (doExpand)
917 if (!sci_get_fold_expanded(sci, *line))
918 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
919 expand(sci, line, TRUE, force, visLevels - 1, -1);
921 else
923 expand(sci, line, FALSE, force, visLevels - 1, -1);
927 else
929 (*line)++;
935 static void fold_changed(ScintillaObject *sci, gint line, gint levelNow, gint levelPrev)
937 if (levelNow & SC_FOLDLEVELHEADERFLAG)
939 if (! (levelPrev & SC_FOLDLEVELHEADERFLAG))
941 /* Adding a fold point */
942 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
943 if (!SSM(sci, SCI_GETALLLINESVISIBLE, 0, 0))
944 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
947 else if (levelPrev & SC_FOLDLEVELHEADERFLAG)
949 if (! sci_get_fold_expanded(sci, line))
950 { /* Removing the fold from one that has been contracted so should expand
951 * otherwise lines are left invisible with no way to make them visible */
952 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
953 if (!SSM(sci, SCI_GETALLLINESVISIBLE, 0, 0))
954 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
957 if (! (levelNow & SC_FOLDLEVELWHITEFLAG) &&
958 ((levelPrev & SC_FOLDLEVELNUMBERMASK) > (levelNow & SC_FOLDLEVELNUMBERMASK)))
960 if (!SSM(sci, SCI_GETALLLINESVISIBLE, 0, 0)) {
961 /* See if should still be hidden */
962 gint parentLine = sci_get_fold_parent(sci, line);
963 if (parentLine < 0)
965 SSM(sci, SCI_SHOWLINES, line, line);
967 else if (sci_get_fold_expanded(sci, parentLine) &&
968 sci_get_line_is_visible(sci, parentLine))
970 SSM(sci, SCI_SHOWLINES, line, line);
977 static void ensure_range_visible(ScintillaObject *sci, gint posStart, gint posEnd,
978 gboolean enforcePolicy)
980 gint lineStart = sci_get_line_from_position(sci, MIN(posStart, posEnd));
981 gint lineEnd = sci_get_line_from_position(sci, MAX(posStart, posEnd));
982 gint line;
984 for (line = lineStart; line <= lineEnd; line++)
986 SSM(sci, enforcePolicy ? SCI_ENSUREVISIBLEENFORCEPOLICY : SCI_ENSUREVISIBLE, line, 0);
991 static void auto_update_margin_width(GeanyEditor *editor)
993 gint next_linecount = 1;
994 gint linecount = sci_get_line_count(editor->sci);
995 GeanyDocument *doc = editor->document;
997 while (next_linecount <= linecount)
998 next_linecount *= 10;
1000 if (editor->document->priv->line_count != next_linecount)
1002 doc->priv->line_count = next_linecount;
1003 sci_set_line_numbers(editor->sci, TRUE);
1008 static void partial_complete(ScintillaObject *sci, const gchar *text)
1010 gint pos = sci_get_current_position(sci);
1012 sci_insert_text(sci, pos, text);
1013 sci_set_current_position(sci, pos + strlen(text), TRUE);
1017 /* Complete the next word part from @a entry */
1018 static gboolean check_partial_completion(GeanyEditor *editor, const gchar *entry)
1020 gchar *stem, *ptr, *text = utils_strdupa(entry);
1022 read_current_word(editor, -1, current_word, sizeof current_word, NULL, TRUE);
1023 stem = current_word;
1024 if (strstr(text, stem) != text)
1025 return FALSE; /* shouldn't happen */
1026 if (strlen(text) <= strlen(stem))
1027 return FALSE;
1029 text += strlen(stem); /* skip stem */
1030 ptr = strstr(text + 1, "_");
1031 if (ptr)
1033 ptr[1] = '\0';
1034 partial_complete(editor->sci, text);
1035 return TRUE;
1037 else
1039 /* CamelCase */
1040 foreach_str(ptr, text + 1)
1042 if (!ptr[0])
1043 break;
1044 if (g_ascii_isupper(*ptr) && g_ascii_islower(ptr[1]))
1046 ptr[0] = '\0';
1047 partial_complete(editor->sci, text);
1048 return TRUE;
1052 return FALSE;
1056 /* Callback for the "sci-notify" signal to emit a "editor-notify" signal.
1057 * Plugins can connect to the "editor-notify" signal. */
1058 void editor_sci_notify_cb(G_GNUC_UNUSED GtkWidget *widget, G_GNUC_UNUSED gint scn,
1059 gpointer scnt, gpointer data)
1061 GeanyEditor *editor = data;
1062 gboolean retval;
1064 g_return_if_fail(editor != NULL);
1066 g_signal_emit_by_name(geany_object, "editor-notify", editor, scnt, &retval);
1070 static gboolean on_editor_notify(G_GNUC_UNUSED GObject *object, GeanyEditor *editor,
1071 SCNotification *nt, G_GNUC_UNUSED gpointer data)
1073 ScintillaObject *sci = editor->sci;
1074 GeanyDocument *doc = editor->document;
1076 switch (nt->nmhdr.code)
1078 case SCN_SAVEPOINTLEFT:
1079 document_set_text_changed(doc, TRUE);
1080 break;
1082 case SCN_SAVEPOINTREACHED:
1083 document_set_text_changed(doc, FALSE);
1084 break;
1086 case SCN_MODIFYATTEMPTRO:
1087 utils_beep();
1088 break;
1090 case SCN_MARGINCLICK:
1091 on_margin_click(editor, nt);
1092 break;
1094 case SCN_UPDATEUI:
1095 on_update_ui(editor, nt);
1096 break;
1098 case SCN_PAINTED:
1099 /* Visible lines are only laid out accurately just before painting,
1100 * so we need to only call editor_scroll_to_line here, because the document
1101 * may have line wrapping and folding enabled.
1102 * http://scintilla.sourceforge.net/ScintillaDoc.html#LineWrapping
1103 * This is important e.g. when loading a session and switching pages
1104 * and having the cursor scroll in view. */
1105 /* FIXME: Really we want to do this just before painting, not after it
1106 * as it will cause repainting. */
1107 if (editor->scroll_percent > 0.0F)
1109 editor_scroll_to_line(editor, -1, editor->scroll_percent);
1110 /* disable further scrolling */
1111 editor->scroll_percent = -1.0F;
1113 break;
1115 case SCN_MODIFIED:
1116 if (editor_prefs.show_linenumber_margin && (nt->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT)) && nt->linesAdded)
1118 /* automatically adjust Scintilla's line numbers margin width */
1119 auto_update_margin_width(editor);
1121 if (nt->modificationType & SC_STARTACTION && ! ignore_callback)
1123 /* get notified about undo changes */
1124 document_undo_add(doc, UNDO_SCINTILLA, NULL);
1126 if (editor_prefs.folding && (nt->modificationType & SC_MOD_CHANGEFOLD) != 0)
1128 /* handle special fold cases, e.g. #1923350 */
1129 fold_changed(sci, nt->line, nt->foldLevelNow, nt->foldLevelPrev);
1131 if (nt->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT))
1133 document_update_tag_list_in_idle(doc);
1135 break;
1137 case SCN_CHARADDED:
1138 on_char_added(editor, nt);
1139 break;
1141 case SCN_USERLISTSELECTION:
1142 if (nt->listType == 1)
1144 sci_add_text(sci, nt->text);
1146 break;
1148 case SCN_AUTOCSELECTION:
1149 if (g_str_equal(nt->text, "..."))
1151 sci_cancel(sci);
1152 utils_beep();
1153 break;
1155 /* fall through */
1156 case SCN_AUTOCCANCELLED:
1157 /* now that autocomplete is finishing or was cancelled, reshow calltips
1158 * if they were showing */
1159 autocomplete_scope_shown = FALSE;
1160 request_reshowing_calltip(nt);
1161 break;
1162 case SCN_NEEDSHOWN:
1163 ensure_range_visible(sci, nt->position, nt->position + nt->length, FALSE);
1164 break;
1166 case SCN_URIDROPPED:
1167 if (nt->text != NULL)
1169 document_open_file_list(nt->text, strlen(nt->text));
1171 break;
1173 case SCN_CALLTIPCLICK:
1174 if (nt->position > 0)
1176 switch (nt->position)
1178 case 1: /* up arrow */
1179 if (calltip.tag_index > 0)
1180 calltip.tag_index--;
1181 break;
1183 case 2: calltip.tag_index++; break; /* down arrow */
1185 editor_show_calltip(editor, -1);
1187 break;
1189 case SCN_ZOOM:
1190 /* recalculate line margin width */
1191 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin);
1192 break;
1194 /* we always return FALSE here to let plugins handle the event too */
1195 return FALSE;
1199 /* Note: this is the same as sci_get_tab_width(), but is still useful when you don't have
1200 * a scintilla pointer. */
1201 static gint get_tab_width(const GeanyIndentPrefs *indent_prefs)
1203 if (indent_prefs->type == GEANY_INDENT_TYPE_BOTH)
1204 return indent_prefs->hard_tab_width;
1206 return indent_prefs->width; /* tab width = indent width */
1210 /* Returns a string containing width chars of whitespace, filled with simple space
1211 * characters or with the right number of tab characters, according to the indent prefs.
1212 * (Result is filled with tabs *and* spaces if width isn't a multiple of
1213 * the tab width). */
1214 static gchar *
1215 get_whitespace(const GeanyIndentPrefs *iprefs, gint width)
1217 g_return_val_if_fail(width >= 0, NULL);
1219 if (width == 0)
1220 return g_strdup("");
1222 if (iprefs->type == GEANY_INDENT_TYPE_SPACES)
1224 return g_strnfill(width, ' ');
1226 else
1227 { /* first fill text with tabs and fill the rest with spaces */
1228 const gint tab_width = get_tab_width(iprefs);
1229 gint tabs = width / tab_width;
1230 gint spaces = width % tab_width;
1231 gint len = tabs + spaces;
1232 gchar *str;
1234 str = g_malloc(len + 1);
1236 memset(str, '\t', tabs);
1237 memset(str + tabs, ' ', spaces);
1238 str[len] = '\0';
1239 return str;
1244 static const GeanyIndentPrefs *
1245 get_default_indent_prefs(void)
1247 static GeanyIndentPrefs iprefs;
1249 iprefs = app->project ? *app->project->priv->indentation : *editor_prefs.indentation;
1250 return &iprefs;
1254 /** Gets the indentation prefs for the editor.
1255 * Prefs can be different according to project or document.
1256 * @warning Always get a fresh result instead of keeping a pointer to it if the editor/project
1257 * settings may have changed, or if this function has been called for a different editor.
1258 * @param editor @nullable The editor, or @c NULL to get the default indent prefs.
1259 * @return The indent prefs. */
1260 GEANY_API_SYMBOL
1261 const GeanyIndentPrefs *
1262 editor_get_indent_prefs(GeanyEditor *editor)
1264 static GeanyIndentPrefs iprefs;
1265 const GeanyIndentPrefs *dprefs = get_default_indent_prefs();
1267 /* Return the address of the default prefs to allow returning default and editor
1268 * pref pointers without invalidating the contents of either. */
1269 if (editor == NULL)
1270 return dprefs;
1272 iprefs = *dprefs;
1273 iprefs.type = editor->indent_type;
1274 iprefs.width = editor->indent_width;
1276 /* if per-document auto-indent is enabled, but we don't have a global mode set,
1277 * just use basic auto-indenting */
1278 if (editor->auto_indent && iprefs.auto_indent_mode == GEANY_AUTOINDENT_NONE)
1279 iprefs.auto_indent_mode = GEANY_AUTOINDENT_BASIC;
1281 if (!editor->auto_indent)
1282 iprefs.auto_indent_mode = GEANY_AUTOINDENT_NONE;
1284 return &iprefs;
1288 static void on_new_line_added(GeanyEditor *editor)
1290 ScintillaObject *sci = editor->sci;
1291 gint line = sci_get_current_line(sci);
1293 /* simple indentation */
1294 if (editor->auto_indent)
1296 insert_indent_after_line(editor, line - 1);
1299 if (get_project_pref(auto_continue_multiline))
1300 { /* " * " auto completion in multiline C/C++/D/Java comments */
1301 auto_multiline(editor, line);
1304 if (editor_prefs.newline_strip)
1305 { /* strip the trailing spaces on the previous line */
1306 editor_strip_line_trailing_spaces(editor, line - 1);
1311 static gboolean lexer_has_braces(ScintillaObject *sci)
1313 gint lexer = sci_get_lexer(sci);
1315 switch (lexer)
1317 case SCLEX_CPP:
1318 case SCLEX_D:
1319 case SCLEX_HTML: /* for PHP & JS */
1320 case SCLEX_PHPSCRIPT:
1321 case SCLEX_PASCAL: /* for multiline comments? */
1322 case SCLEX_BASH:
1323 case SCLEX_PERL:
1324 case SCLEX_TCL:
1325 case SCLEX_R:
1326 case SCLEX_RUST:
1327 return TRUE;
1328 default:
1329 return FALSE;
1334 /* Read indent chars for the line that pos is on into indent global variable.
1335 * Note: Use sci_get_line_indentation() and get_whitespace()/editor_insert_text_block()
1336 * instead in any new code. */
1337 static void read_indent(GeanyEditor *editor, gint pos)
1339 ScintillaObject *sci = editor->sci;
1340 guint i, len, j = 0;
1341 gint line;
1342 gchar *linebuf;
1344 line = sci_get_line_from_position(sci, pos);
1346 len = sci_get_line_length(sci, line);
1347 linebuf = sci_get_line(sci, line);
1349 for (i = 0; i < len && j <= (sizeof(indent) - 1); i++)
1351 if (linebuf[i] == ' ' || linebuf[i] == '\t') /* simple indentation */
1352 indent[j++] = linebuf[i];
1353 else
1354 break;
1356 indent[j] = '\0';
1357 g_free(linebuf);
1361 static gint get_brace_indent(ScintillaObject *sci, gint line)
1363 gint start = sci_get_position_from_line(sci, line);
1364 gint end = sci_get_line_end_position(sci, line) - 1;
1365 gint lexer = sci_get_lexer(sci);
1366 gint count = 0;
1367 gint pos;
1369 for (pos = end; pos >= start && count < 1; pos--)
1371 if (highlighting_is_code_style(lexer, sci_get_style_at(sci, pos)))
1373 gchar c = sci_get_char_at(sci, pos);
1375 if (c == '{')
1376 count ++;
1377 else if (c == '}')
1378 count --;
1382 return count > 0 ? 1 : 0;
1386 /* gets the last code position on a line
1387 * warning: if there is no code position on the line, returns the start position */
1388 static gint get_sci_line_code_end_position(ScintillaObject *sci, gint line)
1390 gint start = sci_get_position_from_line(sci, line);
1391 gint lexer = sci_get_lexer(sci);
1392 gint pos;
1394 for (pos = sci_get_line_end_position(sci, line) - 1; pos > start; pos--)
1396 gint style = sci_get_style_at(sci, pos);
1398 if (highlighting_is_code_style(lexer, style) && ! isspace(sci_get_char_at(sci, pos)))
1399 break;
1402 return pos;
1406 static gint get_python_indent(ScintillaObject *sci, gint line)
1408 gint last_char = get_sci_line_code_end_position(sci, line);
1410 /* add extra indentation for Python after colon */
1411 if (sci_get_char_at(sci, last_char) == ':' &&
1412 sci_get_style_at(sci, last_char) == SCE_P_OPERATOR)
1414 return 1;
1416 return 0;
1420 static gint get_xml_indent(ScintillaObject *sci, gint line)
1422 gboolean need_close = FALSE;
1423 gint end = get_sci_line_code_end_position(sci, line);
1424 gint pos;
1426 /* don't indent if there's a closing tag to the right of the cursor */
1427 pos = sci_get_current_position(sci);
1428 if (sci_get_char_at(sci, pos) == '<' &&
1429 sci_get_char_at(sci, pos + 1) == '/')
1430 return 0;
1432 if (sci_get_char_at(sci, end) == '>' &&
1433 sci_get_char_at(sci, end - 1) != '/')
1435 gint style = sci_get_style_at(sci, end);
1437 if (style == SCE_H_TAG || style == SCE_H_TAGUNKNOWN)
1439 gint start = sci_get_position_from_line(sci, line);
1440 gchar *line_contents = sci_get_contents_range(sci, start, end + 1);
1441 gchar *opened_tag_name = utils_find_open_xml_tag(line_contents, end + 1 - start);
1443 if (!EMPTY(opened_tag_name))
1445 need_close = TRUE;
1446 if (sci_get_lexer(sci) == SCLEX_HTML && utils_is_short_html_tag(opened_tag_name))
1447 need_close = FALSE;
1449 g_free(line_contents);
1450 g_free(opened_tag_name);
1454 return need_close ? 1 : 0;
1458 static gint get_indent_size_after_line(GeanyEditor *editor, gint line)
1460 ScintillaObject *sci = editor->sci;
1461 gint size;
1462 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1464 g_return_val_if_fail(line >= 0, 0);
1466 size = sci_get_line_indentation(sci, line);
1468 if (iprefs->auto_indent_mode > GEANY_AUTOINDENT_BASIC)
1470 gint additional_indent = 0;
1472 if (lexer_has_braces(sci))
1473 additional_indent = iprefs->width * get_brace_indent(sci, line);
1474 else if (sci_get_lexer(sci) == SCLEX_PYTHON) /* Python/Cython */
1475 additional_indent = iprefs->width * get_python_indent(sci, line);
1477 /* HTML lexer "has braces" because of PHP and JavaScript. If get_brace_indent() did not
1478 * recommend us to insert additional indent, we are probably not in PHP/JavaScript chunk and
1479 * should make the XML-related check */
1480 if (additional_indent == 0 &&
1481 (sci_get_lexer(sci) == SCLEX_HTML ||
1482 sci_get_lexer(sci) == SCLEX_XML) &&
1483 editor->document->file_type->priv->xml_indent_tags)
1485 size += iprefs->width * get_xml_indent(sci, line);
1488 size += additional_indent;
1490 return size;
1494 static void insert_indent_after_line(GeanyEditor *editor, gint line)
1496 ScintillaObject *sci = editor->sci;
1497 gint line_indent = sci_get_line_indentation(sci, line);
1498 gint size = get_indent_size_after_line(editor, line);
1499 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1500 gchar *text;
1502 if (size == 0)
1503 return;
1505 if (iprefs->type == GEANY_INDENT_TYPE_TABS && size == line_indent)
1507 /* support tab indents, space aligns style - copy last line 'indent' exactly */
1508 gint start = sci_get_position_from_line(sci, line);
1509 gint end = sci_get_line_indent_position(sci, line);
1511 text = sci_get_contents_range(sci, start, end);
1513 else
1515 text = get_whitespace(iprefs, size);
1517 sci_add_text(sci, text);
1518 g_free(text);
1522 static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c)
1524 const gchar *closing_char = NULL;
1525 gint end_pos = -1;
1527 if (utils_isbrace(c, 0))
1528 end_pos = sci_find_matching_brace(sci, pos - 1);
1530 switch (c)
1532 case '(':
1533 if ((editor_prefs.autoclose_chars & GEANY_AC_PARENTHESIS) && end_pos == -1)
1534 closing_char = ")";
1535 break;
1536 case '{':
1537 if ((editor_prefs.autoclose_chars & GEANY_AC_CBRACKET) && end_pos == -1)
1538 closing_char = "}";
1539 break;
1540 case '[':
1541 if ((editor_prefs.autoclose_chars & GEANY_AC_SBRACKET) && end_pos == -1)
1542 closing_char = "]";
1543 break;
1544 case '\'':
1545 if (editor_prefs.autoclose_chars & GEANY_AC_SQUOTE)
1546 closing_char = "'";
1547 break;
1548 case '"':
1549 if (editor_prefs.autoclose_chars & GEANY_AC_DQUOTE)
1550 closing_char = "\"";
1551 break;
1554 if (closing_char != NULL)
1556 sci_add_text(sci, closing_char);
1557 sci_set_current_position(sci, pos, TRUE);
1562 /* Finds a corresponding matching brace to the given pos
1563 * (this is taken from Scintilla Editor.cxx,
1564 * fit to work with close_block) */
1565 static gint brace_match(ScintillaObject *sci, gint pos)
1567 gchar chBrace = sci_get_char_at(sci, pos);
1568 gchar chSeek = utils_brace_opposite(chBrace);
1569 gchar chAtPos;
1570 gint direction = -1;
1571 gint styBrace;
1572 gint depth = 1;
1573 gint styAtPos;
1575 /* Hack: we need the style at @p pos but it isn't computed yet, so force styling
1576 * of this very position */
1577 sci_colourise(sci, pos, pos + 1);
1579 styBrace = sci_get_style_at(sci, pos);
1581 if (utils_is_opening_brace(chBrace, editor_prefs.brace_match_ltgt))
1582 direction = 1;
1584 pos += direction;
1585 while ((pos >= 0) && (pos < sci_get_length(sci)))
1587 chAtPos = sci_get_char_at(sci, pos);
1588 styAtPos = sci_get_style_at(sci, pos);
1590 if ((pos > sci_get_end_styled(sci)) || (styAtPos == styBrace))
1592 if (chAtPos == chBrace)
1593 depth++;
1594 if (chAtPos == chSeek)
1595 depth--;
1596 if (depth == 0)
1597 return pos;
1599 pos += direction;
1601 return -1;
1605 /* Called after typing '}'. */
1606 static void close_block(GeanyEditor *editor, gint pos)
1608 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1609 gint x = 0, cnt = 0;
1610 gint line, line_len;
1611 gchar *line_buf;
1612 ScintillaObject *sci;
1613 gint line_indent, last_indent;
1615 if (iprefs->auto_indent_mode < GEANY_AUTOINDENT_CURRENTCHARS)
1616 return;
1617 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
1619 sci = editor->sci;
1621 if (! lexer_has_braces(sci))
1622 return;
1624 line = sci_get_line_from_position(sci, pos);
1625 line_len = sci_get_line_end_position(sci, line) - sci_get_position_from_line(sci, line);
1627 /* check that the line is empty, to not kill text in the line */
1628 line_buf = sci_get_line(sci, line);
1629 line_buf[line_len] = '\0';
1630 while (x < line_len)
1632 if (isspace(line_buf[x]))
1633 cnt++;
1634 x++;
1636 g_free(line_buf);
1638 if ((line_len - 1) != cnt)
1639 return;
1641 if (iprefs->auto_indent_mode == GEANY_AUTOINDENT_MATCHBRACES)
1643 gint start_brace = brace_match(sci, pos);
1645 if (start_brace >= 0)
1647 gint line_start;
1648 gint brace_line = sci_get_line_from_position(sci, start_brace);
1649 gint size = sci_get_line_indentation(sci, brace_line);
1650 gchar *ind = get_whitespace(iprefs, size);
1651 gchar *text = g_strconcat(ind, "}", NULL);
1653 line_start = sci_get_position_from_line(sci, line);
1654 sci_set_anchor(sci, line_start);
1655 sci_replace_sel(sci, text);
1656 g_free(text);
1657 g_free(ind);
1658 return;
1660 /* fall through - unmatched brace (possibly because of TCL, PHP lexer bugs) */
1663 /* GEANY_AUTOINDENT_CURRENTCHARS */
1664 line_indent = sci_get_line_indentation(sci, line);
1665 last_indent = sci_get_line_indentation(sci, line - 1);
1667 if (line_indent < last_indent)
1668 return;
1669 line_indent -= iprefs->width;
1670 line_indent = MAX(0, line_indent);
1671 sci_set_line_indentation(sci, line, line_indent);
1675 /* checks whether @p c is an ASCII character (e.g. < 0x80) */
1676 #define IS_ASCII(c) (((unsigned char)(c)) < 0x80)
1679 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1680 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1681 * position can be -1, then the current position is used.
1682 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1683 static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen,
1684 const gchar *wc, gboolean stem)
1686 gint line, line_start, startword, endword;
1687 gchar *chunk;
1688 ScintillaObject *sci;
1690 g_return_if_fail(editor != NULL);
1691 sci = editor->sci;
1693 if (pos == -1)
1694 pos = sci_get_current_position(sci);
1696 line = sci_get_line_from_position(sci, pos);
1697 line_start = sci_get_position_from_line(sci, line);
1698 startword = pos - line_start;
1699 endword = pos - line_start;
1701 word[0] = '\0';
1702 chunk = sci_get_line(sci, line);
1704 if (wc == NULL)
1705 wc = GEANY_WORDCHARS;
1707 /* the checks for "c < 0" are to allow any Unicode character which should make the code
1708 * a little bit more Unicode safe, anyway, this allows also any Unicode punctuation,
1709 * TODO: improve this code */
1710 while (startword > 0 && (strchr(wc, chunk[startword - 1]) || ! IS_ASCII(chunk[startword - 1])))
1711 startword--;
1712 if (!stem)
1714 while (chunk[endword] != 0 && (strchr(wc, chunk[endword]) || ! IS_ASCII(chunk[endword])))
1715 endword++;
1718 if (startword != endword)
1720 chunk[endword] = '\0';
1722 g_strlcpy(word, chunk + startword, wordlen); /* ensure null terminated */
1724 else
1725 g_strlcpy(word, "", wordlen);
1727 g_free(chunk);
1731 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1732 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1733 * position can be -1, then the current position is used.
1734 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1735 void editor_find_current_word(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen,
1736 const gchar *wc)
1738 read_current_word(editor, pos, word, wordlen, wc, FALSE);
1742 /* Same as editor_find_current_word() but uses editor's word boundaries to decide what the word
1743 * is. This should be used e.g. to get the word to search for */
1744 void editor_find_current_word_sciwc(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen)
1746 gint start;
1747 gint end;
1749 g_return_if_fail(editor != NULL);
1751 if (pos == -1)
1752 pos = sci_get_current_position(editor->sci);
1754 start = sci_word_start_position(editor->sci, pos, TRUE);
1755 end = sci_word_end_position(editor->sci, pos, TRUE);
1757 if (start == end) /* caret in whitespaces sequence */
1758 *word = 0;
1759 else
1761 if ((guint)(end - start) >= wordlen)
1762 end = start + (wordlen - 1);
1763 sci_get_text_range(editor->sci, start, end, word);
1769 * Finds the word at the position specified by @a pos. If any word is found, it is returned.
1770 * Otherwise NULL is returned.
1771 * Additional wordchars can be specified to define what to consider as a word.
1773 * @param editor The editor to operate on.
1774 * @param pos The position where the word should be read from.
1775 * May be @c -1 to use the current position.
1776 * @param wordchars The wordchars to separate words. wordchars mean all characters to count
1777 * as part of a word. May be @c NULL to use the default wordchars,
1778 * see @ref GEANY_WORDCHARS.
1780 * @return @nullable A newly-allocated string containing the word at the given @a pos or @c NULL.
1781 * Should be freed when no longer needed.
1783 * @since 0.16
1785 GEANY_API_SYMBOL
1786 gchar *editor_get_word_at_pos(GeanyEditor *editor, gint pos, const gchar *wordchars)
1788 static gchar cword[GEANY_MAX_WORD_LENGTH];
1790 g_return_val_if_fail(editor != NULL, FALSE);
1792 read_current_word(editor, pos, cword, sizeof(cword), wordchars, FALSE);
1794 return (*cword == '\0') ? NULL : g_strdup(cword);
1798 /* Read the word up to position @a pos. */
1799 static const gchar *
1800 editor_read_word_stem(GeanyEditor *editor, gint pos, const gchar *wordchars)
1802 static gchar word[GEANY_MAX_WORD_LENGTH];
1804 read_current_word(editor, pos, word, sizeof word, wordchars, TRUE);
1806 return (*word) ? word : NULL;
1810 static gint find_previous_brace(ScintillaObject *sci, gint pos)
1812 gint orig_pos = pos;
1814 while (pos >= 0 && pos > orig_pos - 300)
1816 gchar c = sci_get_char_at(sci, pos);
1817 if (utils_is_opening_brace(c, editor_prefs.brace_match_ltgt))
1818 return pos;
1819 pos--;
1821 return -1;
1825 static gint find_start_bracket(ScintillaObject *sci, gint pos)
1827 gint brackets = 0;
1828 gint orig_pos = pos;
1830 while (pos > 0 && pos > orig_pos - 300)
1832 gchar c = sci_get_char_at(sci, pos);
1834 if (c == ')') brackets++;
1835 else if (c == '(') brackets--;
1836 if (brackets < 0) return pos; /* found start bracket */
1837 pos--;
1839 return -1;
1843 static gboolean append_calltip(GString *str, const TMTag *tag, GeanyFiletypeID ft_id)
1845 if (! tag->arglist)
1846 return FALSE;
1848 if (ft_id != GEANY_FILETYPES_PASCAL && ft_id != GEANY_FILETYPES_GO)
1849 { /* usual calltips: "retval tagname (arglist)" */
1850 if (tag->var_type)
1852 guint i;
1854 g_string_append(str, tag->var_type);
1855 for (i = 0; i < tag->pointerOrder; i++)
1857 g_string_append_c(str, '*');
1859 g_string_append_c(str, ' ');
1861 if (tag->scope)
1863 const gchar *cosep = symbols_get_context_separator(ft_id);
1865 g_string_append(str, tag->scope);
1866 g_string_append(str, cosep);
1868 g_string_append(str, tag->name);
1869 g_string_append_c(str, ' ');
1870 g_string_append(str, tag->arglist);
1872 else
1873 { /* special case Pascal/Go calltips: "tagname (arglist) : retval"
1874 * (with ':' omitted for Go) */
1875 g_string_append(str, tag->name);
1876 g_string_append_c(str, ' ');
1877 g_string_append(str, tag->arglist);
1879 if (!EMPTY(tag->var_type))
1881 g_string_append(str, ft_id == GEANY_FILETYPES_PASCAL ? " : " : " ");
1882 g_string_append(str, tag->var_type);
1886 return TRUE;
1890 static gchar *find_calltip(const gchar *word, GeanyFiletype *ft)
1892 GPtrArray *tags;
1893 const TMTagType arg_types = tm_tag_function_t | tm_tag_prototype_t |
1894 tm_tag_method_t | tm_tag_macro_with_arg_t;
1895 TMTag *tag;
1896 GString *str = NULL;
1897 guint i;
1899 g_return_val_if_fail(ft && word && *word, NULL);
1901 /* use all types in case language uses wrong tag type e.g. python "members" instead of "methods" */
1902 tags = tm_workspace_find(word, NULL, tm_tag_max_t, NULL, ft->lang);
1903 if (tags->len == 0)
1905 g_ptr_array_free(tags, TRUE);
1906 return NULL;
1909 tag = TM_TAG(tags->pdata[0]);
1911 if (ft->id == GEANY_FILETYPES_D &&
1912 (tag->type == tm_tag_class_t || tag->type == tm_tag_struct_t))
1914 g_ptr_array_free(tags, TRUE);
1915 /* user typed e.g. 'new Classname(' so lookup D constructor Classname::this() */
1916 tags = tm_workspace_find("this", tag->name, arg_types, NULL, ft->lang);
1917 if (tags->len == 0)
1919 g_ptr_array_free(tags, TRUE);
1920 return NULL;
1924 /* remove tags with no argument list */
1925 for (i = 0; i < tags->len; i++)
1927 tag = TM_TAG(tags->pdata[i]);
1929 if (! tag->arglist)
1930 tags->pdata[i] = NULL;
1932 tm_tags_prune((GPtrArray *) tags);
1933 if (tags->len == 0)
1935 g_ptr_array_free(tags, TRUE);
1936 return NULL;
1938 else
1939 { /* remove duplicate calltips */
1940 TMTagAttrType sort_attr[] = {tm_tag_attr_name_t, tm_tag_attr_scope_t,
1941 tm_tag_attr_arglist_t, 0};
1943 tm_tags_sort((GPtrArray *) tags, sort_attr, TRUE, FALSE);
1946 /* if the current word has changed since last time, start with the first tag match */
1947 if (! utils_str_equal(word, calltip.last_word))
1948 calltip.tag_index = 0;
1949 /* cache the current word for next time */
1950 g_free(calltip.last_word);
1951 calltip.last_word = g_strdup(word);
1952 calltip.tag_index = MIN(calltip.tag_index, tags->len - 1); /* ensure tag_index is in range */
1954 for (i = calltip.tag_index; i < tags->len; i++)
1956 tag = TM_TAG(tags->pdata[i]);
1958 if (str == NULL)
1960 str = g_string_new(NULL);
1961 if (calltip.tag_index > 0)
1962 g_string_prepend(str, "\001 "); /* up arrow */
1963 append_calltip(str, tag, FILETYPE_ID(ft));
1965 else /* add a down arrow */
1967 if (calltip.tag_index > 0) /* already have an up arrow */
1968 g_string_insert_c(str, 1, '\002');
1969 else
1970 g_string_prepend(str, "\002 ");
1971 break;
1975 g_ptr_array_free(tags, TRUE);
1977 if (str)
1979 gchar *result = str->str;
1981 g_string_free(str, FALSE);
1982 return result;
1984 return NULL;
1988 /* use pos = -1 to search for the previous unmatched open bracket. */
1989 gboolean editor_show_calltip(GeanyEditor *editor, gint pos)
1991 gint orig_pos = pos; /* the position for the calltip */
1992 gint lexer;
1993 gint style;
1994 gchar word[GEANY_MAX_WORD_LENGTH];
1995 gchar *str;
1996 ScintillaObject *sci;
1998 g_return_val_if_fail(editor != NULL, FALSE);
1999 g_return_val_if_fail(editor->document->file_type != NULL, FALSE);
2001 sci = editor->sci;
2003 lexer = sci_get_lexer(sci);
2005 if (pos == -1)
2007 /* position of '(' is unknown, so go backwards from current position to find it */
2008 pos = sci_get_current_position(sci);
2009 pos--;
2010 orig_pos = pos;
2011 pos = (lexer == SCLEX_LATEX) ? find_previous_brace(sci, pos) :
2012 find_start_bracket(sci, pos);
2013 if (pos == -1)
2014 return FALSE;
2017 /* the style 1 before the brace (which may be highlighted) */
2018 style = sci_get_style_at(sci, pos - 1);
2019 if (! highlighting_is_code_style(lexer, style))
2020 return FALSE;
2022 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
2023 pos--;
2025 /* skip possible generic/template specification, like foo<int>() */
2026 if (sci_get_char_at(sci, pos - 1) == '>')
2028 pos = sci_find_matching_brace(sci, pos - 1);
2029 if (pos == -1)
2030 return FALSE;
2032 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
2033 pos--;
2036 word[0] = '\0';
2037 editor_find_current_word(editor, pos - 1, word, sizeof word, NULL);
2038 if (word[0] == '\0')
2039 return FALSE;
2041 str = find_calltip(word, editor->document->file_type);
2042 if (str)
2044 g_free(calltip.text); /* free the old calltip */
2045 calltip.text = str;
2046 calltip.pos = orig_pos;
2047 calltip.sci = sci;
2048 calltip.set = TRUE;
2049 utils_wrap_string(calltip.text, -1);
2050 SSM(sci, SCI_CALLTIPSHOW, orig_pos, (sptr_t) calltip.text);
2051 return TRUE;
2053 return FALSE;
2057 gchar *editor_get_calltip_text(GeanyEditor *editor, const TMTag *tag)
2059 GString *str;
2061 g_return_val_if_fail(editor != NULL, NULL);
2063 str = g_string_new(NULL);
2064 if (append_calltip(str, tag, editor->document->file_type->id))
2065 return g_string_free(str, FALSE);
2066 else
2067 return g_string_free(str, TRUE);
2071 /* Current document & global tags autocompletion */
2072 static gboolean
2073 autocomplete_tags(GeanyEditor *editor, GeanyFiletype *ft, const gchar *root, gsize rootlen)
2075 GPtrArray *tags;
2076 gboolean found;
2078 g_return_val_if_fail(editor, FALSE);
2080 tags = tm_workspace_find_prefix(root, ft->lang, editor_prefs.autocompletion_max_entries);
2081 found = tags->len > 0;
2082 if (found)
2083 show_tags_list(editor, tags, rootlen);
2084 g_ptr_array_free(tags, TRUE);
2086 return found;
2090 static gboolean autocomplete_check_html(GeanyEditor *editor, gint style, gint pos)
2092 GeanyFiletype *ft = editor->document->file_type;
2093 gboolean try = FALSE;
2095 /* use entity completion when style is not JavaScript, ASP, Python, PHP, ...
2096 * (everything after SCE_HJ_START is for embedded scripting languages) */
2097 if (ft->id == GEANY_FILETYPES_HTML && style < SCE_HJ_START)
2098 try = TRUE;
2099 else if (sci_get_lexer(editor->sci) == SCLEX_XML && style < SCE_HJ_START)
2100 try = TRUE;
2101 else if (ft->id == GEANY_FILETYPES_PHP)
2103 /* use entity completion when style is outside of PHP styles */
2104 if (! is_style_php(style))
2105 try = TRUE;
2107 if (try)
2109 gchar root[GEANY_MAX_WORD_LENGTH];
2110 gchar *tmp;
2112 read_current_word(editor, pos, root, sizeof(root), GEANY_WORDCHARS"&", TRUE);
2114 /* Allow something like "&quot;some text&quot;".
2115 * for entity completion we want to have completion for '&' within words. */
2116 tmp = strchr(root, '&');
2117 if (tmp != NULL)
2119 return autocomplete_tags(editor, filetypes_index(GEANY_FILETYPES_HTML), tmp, strlen(tmp));
2122 return FALSE;
2126 /* Algorithm based on based on Scite's StartAutoCompleteWord()
2127 * @returns a sorted list of words matching @p root */
2128 static GSList *get_doc_words(ScintillaObject *sci, gchar *root, gsize rootlen)
2130 gchar *word;
2131 gint len, current, word_end;
2132 gint pos_find, flags;
2133 guint word_length;
2134 gsize nmatches = 0;
2135 GSList *words = NULL;
2136 struct Sci_TextToFind ttf;
2138 len = sci_get_length(sci);
2139 current = sci_get_current_position(sci) - rootlen;
2141 ttf.lpstrText = root;
2142 ttf.chrg.cpMin = 0;
2143 ttf.chrg.cpMax = len;
2144 ttf.chrgText.cpMin = 0;
2145 ttf.chrgText.cpMax = 0;
2146 flags = SCFIND_WORDSTART | SCFIND_MATCHCASE;
2148 /* search the whole document for the word root and collect results */
2149 pos_find = SSM(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
2150 while (pos_find >= 0 && pos_find < len)
2152 word_end = pos_find + rootlen;
2153 if (pos_find != current)
2155 word_end = sci_word_end_position(sci, word_end, TRUE);
2157 word_length = word_end - pos_find;
2158 if (word_length > rootlen)
2160 word = sci_get_contents_range(sci, pos_find, word_end);
2161 /* search whether we already have the word in, otherwise add it */
2162 if (g_slist_find_custom(words, word, (GCompareFunc)strcmp) != NULL)
2163 g_free(word);
2164 else
2166 words = g_slist_prepend(words, word);
2167 nmatches++;
2170 if (nmatches == editor_prefs.autocompletion_max_entries)
2171 break;
2174 ttf.chrg.cpMin = word_end;
2175 pos_find = SSM(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
2178 return g_slist_sort(words, (GCompareFunc)utils_str_casecmp);
2182 static gboolean autocomplete_doc_word(GeanyEditor *editor, gchar *root, gsize rootlen)
2184 ScintillaObject *sci = editor->sci;
2185 GSList *words, *node;
2186 GString *str;
2187 guint n_words = 0;
2189 words = get_doc_words(sci, root, rootlen);
2190 if (!words)
2192 SSM(sci, SCI_AUTOCCANCEL, 0, 0);
2193 return FALSE;
2196 str = g_string_sized_new(rootlen * 2 * 10);
2197 foreach_slist(node, words)
2199 g_string_append(str, node->data);
2200 g_free(node->data);
2201 if (node->next)
2202 g_string_append_c(str, '\n');
2203 n_words++;
2205 if (n_words >= editor_prefs.autocompletion_max_entries)
2206 g_string_append(str, "\n...");
2208 g_slist_free(words);
2210 show_autocomplete(sci, rootlen, str);
2211 g_string_free(str, TRUE);
2212 return TRUE;
2216 gboolean editor_start_auto_complete(GeanyEditor *editor, gint pos, gboolean force)
2218 gint rootlen, lexer, style;
2219 gchar *root;
2220 gchar cword[GEANY_MAX_WORD_LENGTH];
2221 ScintillaObject *sci;
2222 gboolean ret = FALSE;
2223 const gchar *wordchars;
2224 GeanyFiletype *ft;
2226 g_return_val_if_fail(editor != NULL, FALSE);
2228 if (! editor_prefs.auto_complete_symbols && ! force)
2229 return FALSE;
2231 /* If we are at the beginning of the document, we skip autocompletion as we can't determine the
2232 * necessary styling information */
2233 if (G_UNLIKELY(pos < 2))
2234 return FALSE;
2236 sci = editor->sci;
2237 ft = editor->document->file_type;
2239 lexer = sci_get_lexer(sci);
2240 style = sci_get_style_at(sci, pos - 2);
2242 /* don't autocomplete in comments and strings */
2243 if (!force && !highlighting_is_code_style(lexer, style))
2244 return FALSE;
2246 ret = autocomplete_check_html(editor, style, pos);
2248 if (ft->id == GEANY_FILETYPES_LATEX)
2249 wordchars = GEANY_WORDCHARS"\\"; /* add \ to word chars if we are in a LaTeX file */
2250 else if (ft->id == GEANY_FILETYPES_CSS)
2251 wordchars = GEANY_WORDCHARS"-"; /* add - because they are part of property names */
2252 else
2253 wordchars = GEANY_WORDCHARS;
2255 read_current_word(editor, pos, cword, sizeof(cword), wordchars, TRUE);
2256 root = cword;
2257 rootlen = strlen(root);
2259 if (ret || force)
2261 if (autocomplete_scope_shown)
2263 autocomplete_scope_shown = FALSE;
2264 if (!ret)
2265 sci_send_command(sci, SCI_AUTOCCANCEL);
2268 else
2270 ret = autocomplete_scope(editor, root, rootlen);
2271 if (!ret && autocomplete_scope_shown)
2272 sci_send_command(sci, SCI_AUTOCCANCEL);
2273 autocomplete_scope_shown = ret;
2276 if (!ret && rootlen > 0)
2278 if (ft->id == GEANY_FILETYPES_PHP && style == SCE_HPHP_DEFAULT &&
2279 rootlen == 3 && strcmp(root, "php") == 0 && pos >= 5 &&
2280 sci_get_char_at(sci, pos - 5) == '<' &&
2281 sci_get_char_at(sci, pos - 4) == '?')
2283 /* nothing, don't complete PHP open tags */
2285 else
2287 /* force is set when called by keyboard shortcut, otherwise start at the
2288 * editor_prefs.symbolcompletion_min_chars'th char */
2289 if (force || rootlen >= editor_prefs.symbolcompletion_min_chars)
2291 /* complete tags, except if forcing when completion is already visible */
2292 if (!(force && SSM(sci, SCI_AUTOCACTIVE, 0, 0)))
2293 ret = autocomplete_tags(editor, editor->document->file_type, root, rootlen);
2295 /* If forcing and there's nothing else to show, complete from words in document */
2296 if (!ret && (force || editor_prefs.autocomplete_doc_words))
2297 ret = autocomplete_doc_word(editor, root, rootlen);
2301 if (!ret && force)
2302 utils_beep();
2304 return ret;
2308 static const gchar *snippets_find_completion_by_name(const gchar *type, const gchar *name)
2310 gchar *result = NULL;
2311 GHashTable *tmp;
2313 g_return_val_if_fail(type != NULL && name != NULL, NULL);
2315 tmp = g_hash_table_lookup(snippet_hash, type);
2316 if (tmp != NULL)
2318 result = g_hash_table_lookup(tmp, name);
2320 /* whether nothing is set for the current filetype(tmp is NULL) or
2321 * the particular completion for this filetype is not set (result is NULL) */
2322 if (tmp == NULL || result == NULL)
2324 tmp = g_hash_table_lookup(snippet_hash, "Default");
2325 if (tmp != NULL)
2327 result = g_hash_table_lookup(tmp, name);
2330 /* if result is still NULL here, no completion could be found */
2332 /* result is owned by the hash table and will be freed when the table will destroyed */
2333 return result;
2337 static void snippets_replace_specials(gpointer key, gpointer value, gpointer user_data)
2339 gchar *needle;
2340 GString *pattern = user_data;
2342 g_return_if_fail(key != NULL);
2343 g_return_if_fail(value != NULL);
2345 needle = g_strconcat("%", (gchar*) key, "%", NULL);
2347 utils_string_replace_all(pattern, needle, (gchar*) value);
2348 g_free(needle);
2352 static void fix_indentation(GeanyEditor *editor, GString *buf)
2354 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
2355 gchar *whitespace;
2356 GRegex *regex;
2357 gint cflags = G_REGEX_MULTILINE;
2359 /* transform leading tabs into indent widths (in spaces) */
2360 whitespace = g_strnfill(iprefs->width, ' ');
2361 regex = g_regex_new("^ *(\t)", cflags, 0, NULL);
2362 while (utils_string_regex_replace_all(buf, regex, 1, whitespace, TRUE));
2363 g_regex_unref(regex);
2365 /* remaining tabs are for alignment */
2366 if (iprefs->type != GEANY_INDENT_TYPE_TABS)
2367 utils_string_replace_all(buf, "\t", whitespace);
2369 /* use leading tabs */
2370 if (iprefs->type != GEANY_INDENT_TYPE_SPACES)
2372 gchar *str;
2374 /* for tabs+spaces mode we want the real tab width, not indent width */
2375 SETPTR(whitespace, g_strnfill(sci_get_tab_width(editor->sci), ' '));
2376 str = g_strdup_printf("^\t*(%s)", whitespace);
2378 regex = g_regex_new(str, cflags, 0, NULL);
2379 while (utils_string_regex_replace_all(buf, regex, 1, "\t", TRUE));
2380 g_regex_unref(regex);
2381 g_free(str);
2383 g_free(whitespace);
2387 typedef struct
2389 Sci_Position start, len;
2390 } SelectionRange;
2393 #define CURSOR_PLACEHOLDER "_" /* Would rather use … but not all docs are unicode */
2396 /* Replaces the internal cursor markers with the placeholder suitable for
2397 * display. Except for the first cursor if indicator_for_first is FALSE,
2398 * which is simply deleted.
2400 * Returns insertion points as SelectionRange list, so that the caller
2401 * can use the positions (currently for indicators). */
2402 static GSList *replace_cursor_markers(GeanyEditor *editor, GString *template,
2403 gboolean indicator_for_first)
2405 gint i = 0;
2406 GSList *temp_list = NULL;
2407 gint cursor_steps = 0;
2408 SelectionRange *sel;
2410 while (TRUE)
2412 cursor_steps = utils_string_find(template, cursor_steps, -1, geany_cursor_marker);
2413 if (cursor_steps == -1)
2414 break;
2416 sel = g_new0(SelectionRange, 1);
2417 sel->start = cursor_steps;
2418 g_string_erase(template, cursor_steps, strlen(geany_cursor_marker));
2419 if (i > 0 || indicator_for_first)
2421 g_string_insert(template, cursor_steps, CURSOR_PLACEHOLDER);
2422 sel->len = sizeof(CURSOR_PLACEHOLDER) - 1;
2424 i += 1;
2425 temp_list = g_slist_append(temp_list, sel);
2428 return temp_list;
2432 /** Inserts text, replacing \\t tab chars (@c 0x9) and \\n newline chars (@c 0xA)
2433 * accordingly for the document.
2434 * - Leading tabs are replaced with the correct indentation.
2435 * - Non-leading tabs are replaced with spaces (except when using 'Tabs' indent type).
2436 * - Newline chars are replaced with the correct line ending string.
2437 * This is very useful for inserting code without having to handle the indent
2438 * type yourself (Tabs & Spaces mode can be tricky).
2439 * @param editor Editor.
2440 * @param text Intended as e.g. @c "if (foo)\n\tbar();".
2441 * @param insert_pos Document position to insert text at.
2442 * @param cursor_index If >= 0, the index into @a text to place the cursor.
2443 * @param newline_indent_size Indentation size (in spaces) to insert for each newline; use
2444 * -1 to read the indent size from the line with @a insert_pos on it.
2445 * @param replace_newlines Whether to replace newlines. If
2446 * newlines have been replaced already, this should be false, to avoid errors e.g. on Windows.
2447 * @warning Make sure all \\t tab chars in @a text are intended as indent widths or alignment,
2448 * not hard tabs, as those won't be preserved.
2449 * @note This doesn't scroll the cursor in view afterwards. **/
2450 GEANY_API_SYMBOL
2451 void editor_insert_text_block(GeanyEditor *editor, const gchar *text, gint insert_pos,
2452 gint cursor_index, gint newline_indent_size, gboolean replace_newlines)
2454 ScintillaObject *sci = editor->sci;
2455 gint line_start = sci_get_line_from_position(sci, insert_pos);
2456 GString *buf;
2457 const gchar *eol = editor_get_eol_char(editor);
2458 GSList *jump_locs, *item;
2460 g_return_if_fail(text);
2461 g_return_if_fail(editor != NULL);
2462 g_return_if_fail(insert_pos >= 0);
2464 buf = g_string_new(text);
2466 if (cursor_index >= 0)
2467 g_string_insert(buf, cursor_index, geany_cursor_marker); /* remember cursor pos */
2469 if (newline_indent_size == -1)
2471 /* count indent size up to insert_pos instead of asking sci
2472 * because there may be spaces after it */
2473 gchar *tmp = sci_get_line(sci, line_start);
2474 gint idx;
2476 idx = insert_pos - sci_get_position_from_line(sci, line_start);
2477 tmp[idx] = '\0';
2478 newline_indent_size = count_indent_size(editor, tmp);
2479 g_free(tmp);
2482 /* Add line indents (in spaces) */
2483 if (newline_indent_size > 0)
2485 const gchar *nl = replace_newlines ? "\n" : eol;
2486 gchar *whitespace;
2488 whitespace = g_strnfill(newline_indent_size, ' ');
2489 SETPTR(whitespace, g_strconcat(nl, whitespace, NULL));
2490 utils_string_replace_all(buf, nl, whitespace);
2491 g_free(whitespace);
2494 /* transform line endings */
2495 if (replace_newlines)
2496 utils_string_replace_all(buf, "\n", eol);
2498 fix_indentation(editor, buf);
2500 jump_locs = replace_cursor_markers(editor, buf, cursor_index < 0);
2501 sci_insert_text(sci, insert_pos, buf->str);
2503 foreach_list(item, jump_locs)
2505 SelectionRange *sel = item->data;
2506 gint start = insert_pos + sel->start;
2507 gint end = start + sel->len;
2508 editor_indicator_set_on_range(editor, GEANY_INDICATOR_SNIPPET, start, end);
2509 /* jump to first cursor position initially */
2510 if (item == jump_locs)
2511 sci_set_selection(sci, start, end);
2514 /* Set cursor to the requested index, or by default to after the snippet */
2515 if (cursor_index >= 0)
2516 sci_set_current_position(sci, insert_pos + cursor_index, FALSE);
2517 else if (jump_locs == NULL)
2518 sci_set_current_position(sci, insert_pos + buf->len, FALSE);
2520 g_slist_free_full(jump_locs, g_free);
2521 g_string_free(buf, TRUE);
2525 static gboolean find_next_snippet_indicator(GeanyEditor *editor, SelectionRange *sel)
2527 ScintillaObject *sci = editor->sci;
2528 gint pos = sci_get_current_position(sci);
2530 if (pos == sci_get_length(sci))
2531 return FALSE; /* EOF */
2533 /* Rewind the cursor a bit if we're in the middle (or start) of an indicator,
2534 * and treat that as the next indicator. */
2535 while (SSM(sci, SCI_INDICATORVALUEAT, GEANY_INDICATOR_SNIPPET, pos) && pos > 0)
2536 pos -= 1;
2538 /* Be careful at the beginning of the file */
2539 if (SSM(sci, SCI_INDICATORVALUEAT, GEANY_INDICATOR_SNIPPET, pos))
2540 sel->start = pos;
2541 else
2542 sel->start = SSM(sci, SCI_INDICATOREND, GEANY_INDICATOR_SNIPPET, pos);
2543 sel->len = SSM(sci, SCI_INDICATOREND, GEANY_INDICATOR_SNIPPET, sel->start) - sel->start;
2545 /* 0 if there is no remaining cursor */
2546 return sel->len > 0;
2550 /* Move the cursor to the next specified cursor position in an inserted snippet.
2551 * Can, and should, be optimized to give better results */
2552 gboolean editor_goto_next_snippet_cursor(GeanyEditor *editor)
2554 ScintillaObject *sci = editor->sci;
2555 SelectionRange sel;
2557 if (find_next_snippet_indicator(editor, &sel))
2559 sci_indicator_set(sci, GEANY_INDICATOR_SNIPPET);
2560 sci_set_selection(sci, sel.start, sel.start + sel.len);
2561 return TRUE;
2563 else
2565 return FALSE;
2570 static void snippets_make_replacements(GeanyEditor *editor, GString *pattern)
2572 GHashTable *specials;
2574 /* replace 'special' completions */
2575 specials = g_hash_table_lookup(snippet_hash, "Special");
2576 if (G_LIKELY(specials != NULL))
2578 g_hash_table_foreach(specials, snippets_replace_specials, pattern);
2581 /* now transform other wildcards */
2582 utils_string_replace_all(pattern, "%newline%", "\n");
2583 utils_string_replace_all(pattern, "%ws%", "\t");
2585 /* replace %cursor% by a very unlikely string marker */
2586 utils_string_replace_all(pattern, "%cursor%", geany_cursor_marker);
2588 /* unescape '%' after all %wildcards% */
2589 templates_replace_valist(pattern, "{pc}", "%", NULL);
2591 /* replace any template {foo} wildcards */
2592 templates_replace_common(pattern, editor->document->file_name, editor->document->file_type, NULL);
2596 static gboolean snippets_complete_constructs(GeanyEditor *editor, gint pos, const gchar *word)
2598 ScintillaObject *sci = editor->sci;
2599 gchar *str;
2600 const gchar *completion;
2601 gint str_len;
2602 gint ft_id = editor->document->file_type->id;
2604 str = g_strdup(word);
2605 g_strstrip(str);
2607 completion = snippets_find_completion_by_name(filetypes[ft_id]->name, str);
2608 if (completion == NULL)
2610 g_free(str);
2611 return FALSE;
2614 /* remove the typed word, it will be added again by the used auto completion
2615 * (not really necessary but this makes the auto completion more flexible,
2616 * e.g. with a completion like hi=hello, so typing "hi<TAB>" will result in "hello") */
2617 str_len = strlen(str);
2618 sci_set_selection_start(sci, pos - str_len);
2619 sci_set_selection_end(sci, pos);
2620 sci_replace_sel(sci, "");
2621 pos -= str_len; /* pos has changed while deleting */
2623 editor_insert_snippet(editor, pos, completion);
2624 sci_scroll_caret(sci);
2626 g_free(str);
2627 return TRUE;
2631 static gboolean at_eol(ScintillaObject *sci, gint pos)
2633 gint line = sci_get_line_from_position(sci, pos);
2634 gchar c;
2636 /* skip any trailing spaces */
2637 while (TRUE)
2639 c = sci_get_char_at(sci, pos);
2640 if (c == ' ' || c == '\t')
2641 pos++;
2642 else
2643 break;
2646 return (pos == sci_get_line_end_position(sci, line));
2650 gboolean editor_complete_snippet(GeanyEditor *editor, gint pos)
2652 gboolean result = FALSE;
2653 const gchar *wc;
2654 const gchar *word;
2655 ScintillaObject *sci;
2657 g_return_val_if_fail(editor != NULL, FALSE);
2659 sci = editor->sci;
2660 if (sci_has_selection(sci))
2661 return FALSE;
2662 /* return if we are editing an existing line (chars on right of cursor) */
2663 if (keybindings_lookup_item(GEANY_KEY_GROUP_EDITOR,
2664 GEANY_KEYS_EDITOR_COMPLETESNIPPET)->key == GDK_space &&
2665 ! editor_prefs.complete_snippets_whilst_editing && ! at_eol(sci, pos))
2666 return FALSE;
2668 wc = snippets_find_completion_by_name("Special", "wordchars");
2669 word = editor_read_word_stem(editor, pos, wc);
2671 /* prevent completion of "for " */
2672 if (!EMPTY(word) &&
2673 ! isspace(sci_get_char_at(sci, pos - 1))) /* pos points to the line end char so use pos -1 */
2675 sci_start_undo_action(sci); /* needed because we insert a space separately from construct */
2676 result = snippets_complete_constructs(editor, pos, word);
2677 sci_end_undo_action(sci);
2678 if (result)
2679 sci_cancel(sci); /* cancel any autocompletion list, etc */
2681 return result;
2685 static void insert_closing_tag(GeanyEditor *editor, gint pos, gchar ch, const gchar *tag_name)
2687 ScintillaObject *sci = editor->sci;
2688 gchar *to_insert = NULL;
2690 if (ch == '/')
2692 const gchar *gt = ">";
2693 /* if there is already a '>' behind the cursor, don't add it */
2694 if (sci_get_char_at(sci, pos) == '>')
2695 gt = "";
2697 to_insert = g_strconcat(tag_name, gt, NULL);
2699 else
2700 to_insert = g_strconcat("</", tag_name, ">", NULL);
2702 sci_start_undo_action(sci);
2703 sci_replace_sel(sci, to_insert);
2704 if (ch == '>')
2705 sci_set_selection(sci, pos, pos);
2706 sci_end_undo_action(sci);
2707 g_free(to_insert);
2712 * (stolen from anjuta and heavily modified)
2713 * This routine will auto complete XML or HTML tags that are still open by closing them
2714 * @param ch The character we are dealing with, currently only works with the '>' character
2715 * @return True if handled, false otherwise
2717 static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch)
2719 ScintillaObject *sci = editor->sci;
2720 gint lexer = sci_get_lexer(sci);
2721 gint min, size, style;
2722 gchar *str_found, sel[512];
2723 gboolean result = FALSE;
2725 /* If the user has turned us off, quit now.
2726 * This may make sense only in certain languages */
2727 if (! editor_prefs.auto_close_xml_tags || (lexer != SCLEX_HTML && lexer != SCLEX_XML))
2728 return FALSE;
2730 /* return if we are inside any embedded script */
2731 style = sci_get_style_at(sci, pos);
2732 if (style > SCE_H_XCCOMMENT && ! highlighting_is_string_style(lexer, style))
2733 return FALSE;
2735 /* if ch is /, check for </, else quit */
2736 if (ch == '/' && sci_get_char_at(sci, pos - 2) != '<')
2737 return FALSE;
2739 /* Grab the last 512 characters or so */
2740 min = pos - (sizeof(sel) - 1);
2741 if (min < 0) min = 0;
2743 if (pos - min < 3)
2744 return FALSE; /* Smallest tag is 3 characters e.g. <p> */
2746 sci_get_text_range(sci, min, pos, sel);
2747 sel[sizeof(sel) - 1] = '\0';
2749 if (ch == '>' && sel[pos - min - 2] == '/')
2750 /* User typed something like "<br/>" */
2751 return FALSE;
2753 size = pos - min;
2754 if (ch == '/')
2755 size -= 2; /* skip </ */
2756 str_found = utils_find_open_xml_tag(sel, size);
2758 if (lexer == SCLEX_HTML && utils_is_short_html_tag(str_found))
2760 /* ignore tag */
2762 else if (!EMPTY(str_found))
2764 insert_closing_tag(editor, pos, ch, str_found);
2765 result = TRUE;
2767 g_free(str_found);
2768 return result;
2772 /* like sci_get_line_indentation(), but for a string. */
2773 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent)
2775 const gchar *ptr;
2776 gsize tab_size = sci_get_tab_width(editor->sci);
2777 gsize count = 0;
2779 g_return_val_if_fail(base_indent, 0);
2781 for (ptr = base_indent; *ptr != 0; ptr++)
2783 switch (*ptr)
2785 case ' ':
2786 count++;
2787 break;
2788 case '\t':
2789 count += tab_size;
2790 break;
2791 default:
2792 return count;
2795 return count;
2799 /* Handles special cases where HTML is embedded in another language or
2800 * another language is embedded in HTML */
2801 static GeanyFiletype *editor_get_filetype_at_line(GeanyEditor *editor, gint line)
2803 gint style, line_start;
2804 GeanyFiletype *current_ft;
2806 g_return_val_if_fail(editor != NULL, NULL);
2807 g_return_val_if_fail(editor->document->file_type != NULL, NULL);
2809 current_ft = editor->document->file_type;
2810 line_start = sci_get_position_from_line(editor->sci, line);
2811 style = sci_get_style_at(editor->sci, line_start);
2813 /* Handle PHP filetype with embedded HTML */
2814 if (current_ft->id == GEANY_FILETYPES_PHP && ! is_style_php(style))
2815 current_ft = filetypes[GEANY_FILETYPES_HTML];
2817 /* Handle languages embedded in HTML */
2818 if (current_ft->id == GEANY_FILETYPES_HTML)
2820 /* Embedded JS */
2821 if (style >= SCE_HJ_DEFAULT && style <= SCE_HJ_REGEX)
2822 current_ft = filetypes[GEANY_FILETYPES_JS];
2823 /* ASP JS */
2824 else if (style >= SCE_HJA_DEFAULT && style <= SCE_HJA_REGEX)
2825 current_ft = filetypes[GEANY_FILETYPES_JS];
2826 /* Embedded VB */
2827 else if (style >= SCE_HB_DEFAULT && style <= SCE_HB_STRINGEOL)
2828 current_ft = filetypes[GEANY_FILETYPES_BASIC];
2829 /* ASP VB */
2830 else if (style >= SCE_HBA_DEFAULT && style <= SCE_HBA_STRINGEOL)
2831 current_ft = filetypes[GEANY_FILETYPES_BASIC];
2832 /* Embedded Python */
2833 else if (style >= SCE_HP_DEFAULT && style <= SCE_HP_IDENTIFIER)
2834 current_ft = filetypes[GEANY_FILETYPES_PYTHON];
2835 /* ASP Python */
2836 else if (style >= SCE_HPA_DEFAULT && style <= SCE_HPA_IDENTIFIER)
2837 current_ft = filetypes[GEANY_FILETYPES_PYTHON];
2838 /* Embedded PHP */
2839 else if ((style >= SCE_HPHP_DEFAULT && style <= SCE_HPHP_OPERATOR) ||
2840 style == SCE_HPHP_COMPLEX_VARIABLE)
2842 current_ft = filetypes[GEANY_FILETYPES_PHP];
2846 /* Ensure the filetype's config is loaded */
2847 filetypes_load_config(current_ft->id, FALSE);
2849 return current_ft;
2853 static void real_comment_multiline(GeanyEditor *editor, gint line_start, gint last_line)
2855 const gchar *eol;
2856 gchar *str_begin, *str_end;
2857 const gchar *co, *cc;
2858 gint line_len;
2859 GeanyFiletype *ft;
2861 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2863 ft = editor_get_filetype_at_line(editor, line_start);
2865 eol = editor_get_eol_char(editor);
2866 if (! filetype_get_comment_open_close(ft, FALSE, &co, &cc))
2867 g_return_if_reached();
2868 str_begin = g_strdup_printf("%s%s", (co != NULL) ? co : "", eol);
2869 str_end = g_strdup_printf("%s%s", (cc != NULL) ? cc : "", eol);
2871 /* insert the comment strings */
2872 sci_insert_text(editor->sci, line_start, str_begin);
2873 line_len = sci_get_position_from_line(editor->sci, last_line + 2);
2874 sci_insert_text(editor->sci, line_len, str_end);
2876 g_free(str_begin);
2877 g_free(str_end);
2881 /* find @p text inside the range of the current style */
2882 static gint find_in_current_style(ScintillaObject *sci, const gchar *text, gboolean backwards)
2884 gint start = sci_get_current_position(sci);
2885 gint end = start;
2886 gint len = sci_get_length(sci);
2887 gint current_style = sci_get_style_at(sci, start);
2888 struct Sci_TextToFind ttf;
2890 while (start > 0 && sci_get_style_at(sci, start - 1) == current_style)
2891 start -= 1;
2892 while (end < len && sci_get_style_at(sci, end + 1) == current_style)
2893 end += 1;
2895 ttf.lpstrText = (gchar*) text;
2896 ttf.chrg.cpMin = backwards ? end + 1 : start;
2897 ttf.chrg.cpMax = backwards ? start : end + 1;
2898 return sci_find_text(sci, 0, &ttf);
2902 static void sci_delete_line(ScintillaObject *sci, gint line)
2904 gint start = sci_get_position_from_line(sci, line);
2905 gint len = sci_get_line_length(sci, line);
2906 SSM(sci, SCI_DELETERANGE, start, len);
2910 static gboolean real_uncomment_multiline(GeanyEditor *editor)
2912 /* find the beginning of the multi line comment */
2913 gint start, end, start_line, end_line;
2914 GeanyFiletype *ft;
2915 const gchar *co, *cc;
2917 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, FALSE);
2919 ft = editor_get_filetype_at_line(editor, sci_get_current_line(editor->sci));
2920 if (! filetype_get_comment_open_close(ft, FALSE, &co, &cc))
2921 g_return_val_if_reached(FALSE);
2923 start = find_in_current_style(editor->sci, co, TRUE);
2924 end = find_in_current_style(editor->sci, cc, FALSE);
2926 if (start < 0 || end < 0 || start > end /* who knows */)
2927 return FALSE;
2929 start_line = sci_get_line_from_position(editor->sci, start);
2930 end_line = sci_get_line_from_position(editor->sci, end);
2932 /* remove comment close chars */
2933 SSM(editor->sci, SCI_DELETERANGE, end, strlen(cc));
2934 if (sci_is_blank_line(editor->sci, end_line))
2935 sci_delete_line(editor->sci, end_line);
2937 /* remove comment open chars (do it last since it would move the end position) */
2938 SSM(editor->sci, SCI_DELETERANGE, start, strlen(co));
2939 if (sci_is_blank_line(editor->sci, start_line))
2940 sci_delete_line(editor->sci, start_line);
2942 return TRUE;
2946 static gint get_multiline_comment_style(GeanyEditor *editor, gint line_start)
2948 gint lexer = sci_get_lexer(editor->sci);
2949 gint style_comment;
2951 /* List only those lexers which support multi line comments */
2952 switch (lexer)
2954 case SCLEX_XML:
2955 case SCLEX_HTML:
2956 case SCLEX_PHPSCRIPT:
2958 if (is_style_php(sci_get_style_at(editor->sci, line_start)))
2959 style_comment = SCE_HPHP_COMMENT;
2960 else
2961 style_comment = SCE_H_COMMENT;
2962 break;
2964 case SCLEX_HASKELL:
2965 case SCLEX_LITERATEHASKELL:
2966 style_comment = SCE_HA_COMMENTBLOCK; break;
2967 case SCLEX_LUA: style_comment = SCE_LUA_COMMENT; break;
2968 case SCLEX_CSS: style_comment = SCE_CSS_COMMENT; break;
2969 case SCLEX_SQL: style_comment = SCE_SQL_COMMENT; break;
2970 case SCLEX_CAML: style_comment = SCE_CAML_COMMENT; break;
2971 case SCLEX_D: style_comment = SCE_D_COMMENT; break;
2972 case SCLEX_PASCAL: style_comment = SCE_PAS_COMMENT; break;
2973 case SCLEX_RUST: style_comment = SCE_RUST_COMMENTBLOCK; break;
2974 default: style_comment = SCE_C_COMMENT;
2977 return style_comment;
2981 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise
2982 * returns the amount of uncommented single comment lines, in case of multi line uncomment
2983 * it returns just 1 */
2984 gint editor_do_uncomment(GeanyEditor *editor, gint line, gboolean toggle)
2986 gint first_line, last_line;
2987 gint x, i, line_start, line_len;
2988 gint sel_start, sel_end;
2989 gint count = 0;
2990 gsize co_len;
2991 gchar sel[256];
2992 const gchar *co, *cc;
2993 gboolean single_line = FALSE;
2994 GeanyFiletype *ft;
2996 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, 0);
2998 if (line < 0)
2999 { /* use selection or current line */
3000 sel_start = sci_get_selection_start(editor->sci);
3001 sel_end = sci_get_selection_end(editor->sci);
3003 first_line = sci_get_line_from_position(editor->sci, sel_start);
3004 /* Find the last line with chars selected (not EOL char) */
3005 last_line = sci_get_line_from_position(editor->sci,
3006 sel_end - editor_get_eol_char_len(editor));
3007 last_line = MAX(first_line, last_line);
3009 else
3011 first_line = last_line = line;
3012 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
3015 ft = editor_get_filetype_at_line(editor, first_line);
3017 if (! filetype_get_comment_open_close(ft, TRUE, &co, &cc))
3018 return 0;
3020 co_len = strlen(co);
3021 if (co_len == 0)
3022 return 0;
3024 sci_start_undo_action(editor->sci);
3026 for (i = first_line; i <= last_line; i++)
3028 gint buf_len;
3030 line_start = sci_get_position_from_line(editor->sci, i);
3031 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
3032 x = 0;
3034 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
3035 if (buf_len <= 0)
3036 continue;
3037 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3038 sel[buf_len] = '\0';
3040 while (isspace(sel[x])) x++;
3042 /* to skip blank lines */
3043 if (x < line_len && sel[x] != '\0')
3045 /* use single line comment */
3046 if (EMPTY(cc))
3048 single_line = TRUE;
3050 if (toggle)
3052 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
3053 if (strncmp(sel + x, co, co_len) != 0 ||
3054 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) != 0)
3055 continue;
3057 co_len += tm_len;
3059 else
3061 if (strncmp(sel + x, co, co_len) != 0)
3062 continue;
3065 sci_set_selection(editor->sci, line_start + x, line_start + x + co_len);
3066 sci_replace_sel(editor->sci, "");
3067 count++;
3069 /* use multi line comment */
3070 else
3072 gint style_comment;
3074 /* skip lines which are already comments */
3075 style_comment = get_multiline_comment_style(editor, line_start);
3076 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3078 if (real_uncomment_multiline(editor))
3079 count = 1;
3082 /* break because we are already on the last line */
3083 break;
3087 sci_end_undo_action(editor->sci);
3089 /* restore selection if there is one
3090 * but don't touch the selection if caller is editor_do_comment_toggle */
3091 if (! toggle && sel_start < sel_end)
3093 if (single_line)
3095 sci_set_selection_start(editor->sci, sel_start - co_len);
3096 sci_set_selection_end(editor->sci, sel_end - (count * co_len));
3098 else
3100 gint eol_len = editor_get_eol_char_len(editor);
3101 sci_set_selection_start(editor->sci, sel_start - co_len - eol_len);
3102 sci_set_selection_end(editor->sci, sel_end - co_len - eol_len);
3106 return count;
3110 void editor_do_comment_toggle(GeanyEditor *editor)
3112 gint first_line, last_line;
3113 gint x, i, line_start, line_len, first_line_start, last_line_start;
3114 gint sel_start, sel_end;
3115 gint count_commented = 0, count_uncommented = 0;
3116 gchar sel[256];
3117 const gchar *co, *cc;
3118 gboolean single_line = FALSE;
3119 gboolean first_line_was_comment = FALSE;
3120 gboolean last_line_was_comment = FALSE;
3121 gsize co_len;
3122 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
3123 GeanyFiletype *ft;
3125 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
3127 sel_start = sci_get_selection_start(editor->sci);
3128 sel_end = sci_get_selection_end(editor->sci);
3130 first_line = sci_get_line_from_position(editor->sci, sel_start);
3131 /* Find the last line with chars selected (not EOL char) */
3132 last_line = sci_get_line_from_position(editor->sci,
3133 sel_end - editor_get_eol_char_len(editor));
3134 last_line = MAX(first_line, last_line);
3136 first_line_start = sci_get_position_from_line(editor->sci, first_line);
3137 last_line_start = sci_get_position_from_line(editor->sci, last_line);
3139 ft = editor_get_filetype_at_line(editor, first_line);
3141 if (! filetype_get_comment_open_close(ft, TRUE, &co, &cc))
3142 return;
3144 co_len = strlen(co);
3145 if (co_len == 0)
3146 return;
3148 sci_start_undo_action(editor->sci);
3150 for (i = first_line; i <= last_line; i++)
3152 gint buf_len;
3154 line_start = sci_get_position_from_line(editor->sci, i);
3155 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
3156 x = 0;
3158 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
3159 if (buf_len < 0)
3160 continue;
3161 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3162 sel[buf_len] = '\0';
3164 while (isspace(sel[x])) x++;
3166 /* use single line comment */
3167 if (EMPTY(cc))
3169 gboolean do_continue = FALSE;
3170 single_line = TRUE;
3172 if (strncmp(sel + x, co, co_len) == 0 &&
3173 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) == 0)
3175 do_continue = TRUE;
3178 if (do_continue && i == first_line)
3179 first_line_was_comment = TRUE;
3180 last_line_was_comment = do_continue;
3182 if (do_continue)
3184 count_uncommented += editor_do_uncomment(editor, i, TRUE);
3185 continue;
3188 /* we are still here, so the above lines were not already comments, so comment it */
3189 count_commented += editor_do_comment(editor, i, FALSE, TRUE, TRUE);
3191 /* use multi line comment */
3192 else
3194 gint style_comment;
3196 /* skip lines which are already comments */
3197 style_comment = get_multiline_comment_style(editor, line_start);
3198 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3200 if (real_uncomment_multiline(editor))
3201 count_uncommented++;
3203 else
3205 real_comment_multiline(editor, line_start, last_line);
3206 count_commented++;
3209 /* break because we are already on the last line */
3210 break;
3214 sci_end_undo_action(editor->sci);
3216 co_len += tm_len;
3218 /* restore selection or caret position */
3219 if (single_line)
3221 gint a = (first_line_was_comment) ? - (gint) co_len : (gint) co_len;
3222 gint indent_len;
3224 /* don't modify sel_start when the selection starts within indentation */
3225 read_indent(editor, sel_start);
3226 indent_len = (gint) strlen(indent);
3227 if ((sel_start - first_line_start) <= indent_len)
3228 a = 0;
3229 /* if the selection start was inside the comment mark, adjust the position */
3230 else if (first_line_was_comment &&
3231 sel_start >= (first_line_start + indent_len) &&
3232 sel_start <= (first_line_start + indent_len + (gint) co_len))
3234 a = (first_line_start + indent_len) - sel_start;
3237 if (sel_start < sel_end)
3239 gint b = (count_commented * (gint) co_len) - (count_uncommented * (gint) co_len);
3241 /* same for selection end, but here we add an offset on the offset above */
3242 read_indent(editor, sel_end + b);
3243 indent_len = (gint) strlen(indent);
3244 if ((sel_end - last_line_start) < indent_len)
3245 b += last_line_was_comment ? (gint) co_len : -(gint) co_len;
3246 else if (last_line_was_comment &&
3247 sel_end >= (last_line_start + indent_len) &&
3248 sel_end <= (last_line_start + indent_len + (gint) co_len))
3250 b += (gint) co_len - (sel_end - (last_line_start + indent_len));
3253 sci_set_selection_start(editor->sci, sel_start + a);
3254 sci_set_selection_end(editor->sci, sel_end + b);
3256 else
3257 sci_set_current_position(editor->sci, sel_start + a, TRUE);
3259 else
3261 gint eol_len = editor_get_eol_char_len(editor);
3262 if (count_uncommented > 0)
3264 sci_set_selection_start(editor->sci, sel_start - (gint) co_len + eol_len);
3265 sci_set_selection_end(editor->sci, sel_end - (gint) co_len + eol_len);
3267 else if (count_commented > 0)
3269 sci_set_selection_start(editor->sci, sel_start + (gint) co_len - eol_len);
3270 sci_set_selection_end(editor->sci, sel_end + (gint) co_len - eol_len);
3272 if (sel_start >= sel_end)
3273 sci_scroll_caret(editor->sci);
3278 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise */
3279 gint editor_do_comment(GeanyEditor *editor, gint line, gboolean allow_empty_lines, gboolean toggle,
3280 gboolean single_comment)
3282 gint first_line, last_line;
3283 gint x, i, line_start, line_len;
3284 gint sel_start, sel_end, co_len;
3285 gint count = 0;
3286 gchar sel[256];
3287 const gchar *co, *cc;
3288 gboolean single_line = FALSE;
3289 GeanyFiletype *ft;
3291 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, 0);
3293 if (line < 0)
3294 { /* use selection or current line */
3295 sel_start = sci_get_selection_start(editor->sci);
3296 sel_end = sci_get_selection_end(editor->sci);
3298 first_line = sci_get_line_from_position(editor->sci, sel_start);
3299 /* Find the last line with chars selected (not EOL char) */
3300 last_line = sci_get_line_from_position(editor->sci,
3301 sel_end - editor_get_eol_char_len(editor));
3302 last_line = MAX(first_line, last_line);
3304 else
3306 first_line = last_line = line;
3307 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
3310 ft = editor_get_filetype_at_line(editor, first_line);
3312 if (! filetype_get_comment_open_close(ft, single_comment, &co, &cc))
3313 return 0;
3315 co_len = strlen(co);
3316 if (co_len == 0)
3317 return 0;
3319 sci_start_undo_action(editor->sci);
3321 for (i = first_line; i <= last_line; i++)
3323 gint buf_len;
3325 line_start = sci_get_position_from_line(editor->sci, i);
3326 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
3327 x = 0;
3329 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
3330 if (buf_len < 0)
3331 continue;
3332 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3333 sel[buf_len] = '\0';
3335 while (isspace(sel[x])) x++;
3337 /* to skip blank lines */
3338 if (allow_empty_lines || (x < line_len && sel[x] != '\0'))
3340 /* use single line comment */
3341 if (EMPTY(cc))
3343 gint start = line_start;
3344 single_line = TRUE;
3346 if (ft->comment_use_indent)
3347 start = line_start + x;
3349 if (toggle)
3351 gchar *text = g_strconcat(co, editor_prefs.comment_toggle_mark, NULL);
3352 sci_insert_text(editor->sci, start, text);
3353 g_free(text);
3355 else
3356 sci_insert_text(editor->sci, start, co);
3357 count++;
3359 /* use multi line comment */
3360 else
3362 gint style_comment;
3364 /* skip lines which are already comments */
3365 style_comment = get_multiline_comment_style(editor, line_start);
3366 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3367 continue;
3369 real_comment_multiline(editor, line_start, last_line);
3370 count = 1;
3372 /* break because we are already on the last line */
3373 break;
3377 sci_end_undo_action(editor->sci);
3379 /* restore selection if there is one
3380 * but don't touch the selection if caller is editor_do_comment_toggle */
3381 if (! toggle && sel_start < sel_end)
3383 if (single_line)
3385 sci_set_selection_start(editor->sci, sel_start + co_len);
3386 sci_set_selection_end(editor->sci, sel_end + (count * co_len));
3388 else
3390 gint eol_len = editor_get_eol_char_len(editor);
3391 sci_set_selection_start(editor->sci, sel_start + co_len + eol_len);
3392 sci_set_selection_end(editor->sci, sel_end + co_len + eol_len);
3395 return count;
3399 static gboolean brace_timeout_active = FALSE;
3401 static gboolean delay_match_brace(G_GNUC_UNUSED gpointer user_data)
3403 GeanyDocument *doc = document_get_current();
3404 GeanyEditor *editor;
3405 gint brace_pos = GPOINTER_TO_INT(user_data);
3406 gint end_pos, cur_pos;
3408 brace_timeout_active = FALSE;
3409 if (!doc)
3410 return FALSE;
3412 editor = doc->editor;
3413 cur_pos = sci_get_current_position(editor->sci) - 1;
3415 if (cur_pos != brace_pos)
3417 cur_pos++;
3418 if (cur_pos != brace_pos)
3420 /* we have moved past the original brace_pos, but after the timeout
3421 * we may now be on a new brace, so check again */
3422 editor_highlight_braces(editor, cur_pos);
3423 return FALSE;
3426 if (!utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3428 editor_highlight_braces(editor, cur_pos);
3429 return FALSE;
3431 end_pos = sci_find_matching_brace(editor->sci, brace_pos);
3433 if (end_pos >= 0)
3435 gint col = MIN(sci_get_col_from_position(editor->sci, brace_pos),
3436 sci_get_col_from_position(editor->sci, end_pos));
3437 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, col, 0);
3438 SSM(editor->sci, SCI_BRACEHIGHLIGHT, brace_pos, end_pos);
3440 else
3442 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3443 SSM(editor->sci, SCI_BRACEBADLIGHT, brace_pos, 0);
3445 return FALSE;
3449 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos)
3451 gint brace_pos = cur_pos - 1;
3453 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3454 SSM(editor->sci, SCI_BRACEBADLIGHT, (uptr_t)-1, 0);
3456 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3458 brace_pos++;
3459 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3461 return;
3464 if (!brace_timeout_active)
3466 brace_timeout_active = TRUE;
3467 /* delaying matching makes scrolling faster e.g. holding down arrow keys */
3468 g_timeout_add(100, delay_match_brace, GINT_TO_POINTER(brace_pos));
3473 static gboolean in_block_comment(gint lexer, gint style)
3475 switch (lexer)
3477 case SCLEX_COBOL:
3478 case SCLEX_CPP:
3479 return (style == SCE_C_COMMENT ||
3480 style == SCE_C_COMMENTDOC);
3482 case SCLEX_PASCAL:
3483 return (style == SCE_PAS_COMMENT ||
3484 style == SCE_PAS_COMMENT2);
3486 case SCLEX_D:
3487 return (style == SCE_D_COMMENT ||
3488 style == SCE_D_COMMENTDOC ||
3489 style == SCE_D_COMMENTNESTED);
3491 case SCLEX_HTML:
3492 case SCLEX_PHPSCRIPT:
3493 return (style == SCE_HPHP_COMMENT);
3495 case SCLEX_CSS:
3496 return (style == SCE_CSS_COMMENT);
3498 case SCLEX_RUST:
3499 return (style == SCE_RUST_COMMENTBLOCK ||
3500 style == SCE_RUST_COMMENTBLOCKDOC);
3502 default:
3503 return FALSE;
3508 static gboolean is_comment_char(gchar c, gint lexer)
3510 if ((c == '*' || c == '+') && lexer == SCLEX_D)
3511 return TRUE;
3512 else
3513 if (c == '*')
3514 return TRUE;
3516 return FALSE;
3520 static void auto_multiline(GeanyEditor *editor, gint cur_line)
3522 ScintillaObject *sci = editor->sci;
3523 gint indent_pos, style;
3524 gint lexer = sci_get_lexer(sci);
3526 /* Use the start of the line enter was pressed on, to avoid any doc keyword styles */
3527 indent_pos = sci_get_line_indent_position(sci, cur_line - 1);
3528 style = sci_get_style_at(sci, indent_pos);
3529 if (!in_block_comment(lexer, style))
3530 return;
3532 /* Check whether the comment block continues on this line */
3533 indent_pos = sci_get_line_indent_position(sci, cur_line);
3534 if (sci_get_style_at(sci, indent_pos) == style || indent_pos >= sci_get_length(sci))
3536 gchar *previous_line = sci_get_line(sci, cur_line - 1);
3537 /* the type of comment, '*' (C/C++/Java), '+' and the others (D) */
3538 const gchar *continuation = "*";
3539 const gchar *whitespace = ""; /* to hold whitespace if needed */
3540 gchar *result;
3541 gint len = strlen(previous_line);
3542 gint i;
3544 /* find and stop at end of multi line comment */
3545 i = len - 1;
3546 while (i >= 0 && isspace(previous_line[i])) i--;
3547 if (i >= 1 && is_comment_char(previous_line[i - 1], lexer) && previous_line[i] == '/')
3549 gint indent_len, indent_width;
3551 indent_pos = sci_get_line_indent_position(sci, cur_line);
3552 indent_len = sci_get_col_from_position(sci, indent_pos);
3553 indent_width = editor_get_indent_prefs(editor)->width;
3555 /* if there is one too many spaces, delete the last space,
3556 * to return to the indent used before the multiline comment was started. */
3557 if (indent_len % indent_width == 1)
3558 SSM(sci, SCI_DELETEBACKNOTLINE, 0, 0); /* remove whitespace indent */
3559 g_free(previous_line);
3560 return;
3562 /* check whether we are on the second line of multi line comment */
3563 i = 0;
3564 while (i < len && isspace(previous_line[i])) i++; /* get to start of the line */
3566 if (i + 1 < len &&
3567 previous_line[i] == '/' && is_comment_char(previous_line[i + 1], lexer))
3568 { /* we are on the second line of a multi line comment, so we have to insert white space */
3569 whitespace = " ";
3572 if (style == SCE_D_COMMENTNESTED)
3573 continuation = "+"; /* for nested comments in D */
3575 result = g_strconcat(whitespace, continuation, " ", NULL);
3576 sci_add_text(sci, result);
3577 g_free(result);
3579 g_free(previous_line);
3584 #if 0
3585 static gboolean editor_lexer_is_c_like(gint lexer)
3587 switch (lexer)
3589 case SCLEX_CPP:
3590 case SCLEX_D:
3591 return TRUE;
3593 default:
3594 return FALSE;
3597 #endif
3600 /* inserts a three-line comment at one line above current cursor position */
3601 void editor_insert_multiline_comment(GeanyEditor *editor)
3603 gchar *text;
3604 gint text_len;
3605 gint line;
3606 gint pos;
3607 gboolean have_multiline_comment = FALSE;
3608 GeanyDocument *doc;
3609 const gchar *co, *cc;
3611 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
3613 if (! filetype_get_comment_open_close(editor->document->file_type, FALSE, &co, &cc))
3614 g_return_if_reached();
3615 if (!EMPTY(cc))
3616 have_multiline_comment = TRUE;
3618 sci_start_undo_action(editor->sci);
3620 doc = editor->document;
3622 /* insert three lines one line above of the current position */
3623 line = sci_get_line_from_position(editor->sci, editor_info.click_pos);
3624 pos = sci_get_position_from_line(editor->sci, line);
3626 /* use the indent on the current line but only when comment indentation is used
3627 * and we don't have multi line comment characters */
3628 if (editor->auto_indent &&
3629 ! have_multiline_comment && doc->file_type->comment_use_indent)
3631 read_indent(editor, editor_info.click_pos);
3632 text = g_strdup_printf("%s\n%s\n%s\n", indent, indent, indent);
3633 text_len = strlen(text);
3635 else
3637 text = g_strdup("\n\n\n");
3638 text_len = 3;
3640 sci_insert_text(editor->sci, pos, text);
3641 g_free(text);
3643 /* select the inserted lines for commenting */
3644 sci_set_selection_start(editor->sci, pos);
3645 sci_set_selection_end(editor->sci, pos + text_len);
3647 editor_do_comment(editor, -1, TRUE, FALSE, FALSE);
3649 /* set the current position to the start of the first inserted line */
3650 pos += strlen(co);
3652 /* on multi line comment jump to the next line, otherwise add the length of added indentation */
3653 if (have_multiline_comment)
3654 pos += 1;
3655 else
3656 pos += strlen(indent);
3658 sci_set_current_position(editor->sci, pos, TRUE);
3659 /* reset the selection */
3660 sci_set_anchor(editor->sci, pos);
3662 sci_end_undo_action(editor->sci);
3666 /* Note: If the editor is pending a redraw, set document::scroll_percent instead.
3667 * Scroll the view to make line appear at percent_of_view.
3668 * line can be -1 to use the current position. */
3669 void editor_scroll_to_line(GeanyEditor *editor, gint line, gfloat percent_of_view)
3671 gint los;
3672 GtkWidget *wid;
3674 g_return_if_fail(editor != NULL);
3676 wid = GTK_WIDGET(editor->sci);
3678 if (! gtk_widget_get_window(wid) || ! gdk_window_is_viewable(gtk_widget_get_window(wid)))
3679 return; /* prevent gdk_window_scroll warning */
3681 if (line == -1)
3682 line = sci_get_current_line(editor->sci);
3684 /* sci 'visible line' != doc line number because of folding and line wrapping */
3685 /* calling SCI_VISIBLEFROMDOCLINE for line is more accurate than calling
3686 * SCI_DOCLINEFROMVISIBLE for vis1. */
3687 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0);
3688 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
3689 line = line - los * percent_of_view;
3690 SSM(editor->sci, SCI_SETFIRSTVISIBLELINE, line, 0);
3691 sci_scroll_caret(editor->sci); /* needed for horizontal scrolling */
3695 /* creates and inserts one tab or whitespace of the amount of the tab width */
3696 void editor_insert_alternative_whitespace(GeanyEditor *editor)
3698 gchar *text;
3699 GeanyIndentPrefs iprefs = *editor_get_indent_prefs(editor);
3701 g_return_if_fail(editor != NULL);
3703 switch (iprefs.type)
3705 case GEANY_INDENT_TYPE_TABS:
3706 iprefs.type = GEANY_INDENT_TYPE_SPACES;
3707 break;
3708 case GEANY_INDENT_TYPE_SPACES:
3709 case GEANY_INDENT_TYPE_BOTH: /* most likely we want a tab */
3710 iprefs.type = GEANY_INDENT_TYPE_TABS;
3711 break;
3713 text = get_whitespace(&iprefs, iprefs.width);
3714 sci_add_text(editor->sci, text);
3715 g_free(text);
3719 void editor_select_word(GeanyEditor *editor)
3721 gint pos;
3722 gint start;
3723 gint end;
3725 g_return_if_fail(editor != NULL);
3727 pos = SSM(editor->sci, SCI_GETCURRENTPOS, 0, 0);
3728 start = sci_word_start_position(editor->sci, pos, TRUE);
3729 end = sci_word_end_position(editor->sci, pos, TRUE);
3731 if (start == end) /* caret in whitespaces sequence */
3733 /* look forward but reverse the selection direction,
3734 * so the caret end up stay as near as the original position. */
3735 end = sci_word_end_position(editor->sci, pos, FALSE);
3736 start = sci_word_end_position(editor->sci, end, TRUE);
3737 if (start == end)
3738 return;
3741 sci_set_selection(editor->sci, start, end);
3745 /* extra_line is for selecting the cursor line (or anchor line) at the bottom of a selection,
3746 * when those lines have no selection (cursor at start of line). */
3747 void editor_select_lines(GeanyEditor *editor, gboolean extra_line)
3749 gint start, end, line;
3751 g_return_if_fail(editor != NULL);
3753 start = sci_get_selection_start(editor->sci);
3754 end = sci_get_selection_end(editor->sci);
3756 /* check if whole lines are already selected */
3757 if (! extra_line && start != end &&
3758 sci_get_col_from_position(editor->sci, start) == 0 &&
3759 sci_get_col_from_position(editor->sci, end) == 0)
3760 return;
3762 line = sci_get_line_from_position(editor->sci, start);
3763 start = sci_get_position_from_line(editor->sci, line);
3765 line = sci_get_line_from_position(editor->sci, end);
3766 end = sci_get_position_from_line(editor->sci, line + 1);
3768 sci_set_selection(editor->sci, start, end);
3772 static gboolean sci_is_blank_line(ScintillaObject *sci, gint line)
3774 return sci_get_line_indent_position(sci, line) ==
3775 sci_get_line_end_position(sci, line);
3779 /* Returns first line of paragraph for GTK_DIR_UP, line after paragraph
3780 * ends for GTK_DIR_DOWN or -1 if called on an empty line. */
3781 static gint find_paragraph_stop(GeanyEditor *editor, gint line, gint direction)
3783 gint step;
3784 ScintillaObject *sci = editor->sci;
3786 /* first check current line and return -1 if it is empty to skip creating of a selection */
3787 if (sci_is_blank_line(sci, line))
3788 return -1;
3790 if (direction == GTK_DIR_UP)
3791 step = -1;
3792 else
3793 step = 1;
3795 while (TRUE)
3797 line += step;
3798 if (line == -1)
3800 /* start of document */
3801 line = 0;
3802 break;
3804 if (line == sci_get_line_count(sci))
3805 break;
3807 if (sci_is_blank_line(sci, line))
3809 /* return line paragraph starts on */
3810 if (direction == GTK_DIR_UP)
3811 line++;
3812 break;
3815 return line;
3819 void editor_select_paragraph(GeanyEditor *editor)
3821 gint pos_start, pos_end, line_start, line_found;
3823 g_return_if_fail(editor != NULL);
3825 line_start = sci_get_current_line(editor->sci);
3827 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_UP);
3828 if (line_found == -1)
3829 return;
3831 pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3833 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_DOWN);
3834 pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3836 sci_set_selection(editor->sci, pos_start, pos_end);
3840 /* Returns first line of block for GTK_DIR_UP, line after block
3841 * ends for GTK_DIR_DOWN or -1 if called on an empty line. */
3842 static gint find_block_stop(GeanyEditor *editor, gint line, gint direction)
3844 gint step, ind;
3845 ScintillaObject *sci = editor->sci;
3847 /* first check current line and return -1 if it is empty to skip creating of a selection */
3848 if (sci_is_blank_line(sci, line))
3849 return -1;
3851 if (direction == GTK_DIR_UP)
3852 step = -1;
3853 else
3854 step = 1;
3856 ind = sci_get_line_indentation(sci, line);
3857 while (TRUE)
3859 line += step;
3860 if (line == -1)
3862 /* start of document */
3863 line = 0;
3864 break;
3866 if (line == sci_get_line_count(sci))
3867 break;
3869 if (sci_get_line_indentation(sci, line) != ind ||
3870 sci_is_blank_line(sci, line))
3872 /* return line block starts on */
3873 if (direction == GTK_DIR_UP)
3874 line++;
3875 break;
3878 return line;
3882 void editor_select_indent_block(GeanyEditor *editor)
3884 gint pos_start, pos_end, line_start, line_found;
3886 g_return_if_fail(editor != NULL);
3888 line_start = sci_get_current_line(editor->sci);
3890 line_found = find_block_stop(editor, line_start, GTK_DIR_UP);
3891 if (line_found == -1)
3892 return;
3894 pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3896 line_found = find_block_stop(editor, line_start, GTK_DIR_DOWN);
3897 pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3899 sci_set_selection(editor->sci, pos_start, pos_end);
3903 /* simple indentation to indent the current line with the same indent as the previous one */
3904 static void smart_line_indentation(GeanyEditor *editor, gint first_line, gint last_line)
3906 gint i, sel_start = 0, sel_end = 0;
3908 /* get previous line and use it for read_indent to use that line
3909 * (otherwise it would fail on a line only containing "{" in advanced indentation mode) */
3910 read_indent(editor, sci_get_position_from_line(editor->sci, first_line - 1));
3912 for (i = first_line; i <= last_line; i++)
3914 /* skip the first line or if the indentation of the previous and current line are equal */
3915 if (i == 0 ||
3916 SSM(editor->sci, SCI_GETLINEINDENTATION, i - 1, 0) ==
3917 SSM(editor->sci, SCI_GETLINEINDENTATION, i, 0))
3918 continue;
3920 sel_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
3921 sel_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
3922 if (sel_start < sel_end)
3924 sci_set_selection(editor->sci, sel_start, sel_end);
3925 sci_replace_sel(editor->sci, "");
3927 sci_insert_text(editor->sci, sel_start, indent);
3932 /* simple indentation to indent the current line with the same indent as the previous one */
3933 void editor_smart_line_indentation(GeanyEditor *editor)
3935 gint first_line, last_line;
3936 gint first_sel_start, first_sel_end;
3937 ScintillaObject *sci;
3939 g_return_if_fail(editor != NULL);
3941 sci = editor->sci;
3943 first_sel_start = sci_get_selection_start(sci);
3944 first_sel_end = sci_get_selection_end(sci);
3946 first_line = sci_get_line_from_position(sci, first_sel_start);
3947 /* Find the last line with chars selected (not EOL char) */
3948 last_line = sci_get_line_from_position(sci, first_sel_end - editor_get_eol_char_len(editor));
3949 last_line = MAX(first_line, last_line);
3951 sci_start_undo_action(sci);
3953 smart_line_indentation(editor, first_line, last_line);
3955 /* set cursor position if there was no selection */
3956 if (first_sel_start == first_sel_end)
3958 gint indent_pos = SSM(sci, SCI_GETLINEINDENTPOSITION, first_line, 0);
3960 /* use indent position as user may wish to change indentation afterwards */
3961 sci_set_current_position(sci, indent_pos, FALSE);
3963 else
3965 /* fully select all the lines affected */
3966 sci_set_selection_start(sci, sci_get_position_from_line(sci, first_line));
3967 sci_set_selection_end(sci, sci_get_position_from_line(sci, last_line + 1));
3970 sci_end_undo_action(sci);
3974 /* increase / decrease current line or selection by one space */
3975 void editor_indentation_by_one_space(GeanyEditor *editor, gint pos, gboolean decrease)
3977 gint i, first_line, last_line, line_start, indentation_end, count = 0;
3978 gint sel_start, sel_end, first_line_offset = 0;
3980 g_return_if_fail(editor != NULL);
3982 sel_start = sci_get_selection_start(editor->sci);
3983 sel_end = sci_get_selection_end(editor->sci);
3985 first_line = sci_get_line_from_position(editor->sci, sel_start);
3986 /* Find the last line with chars selected (not EOL char) */
3987 last_line = sci_get_line_from_position(editor->sci, sel_end - editor_get_eol_char_len(editor));
3988 last_line = MAX(first_line, last_line);
3990 if (pos == -1)
3991 pos = sel_start;
3993 sci_start_undo_action(editor->sci);
3995 for (i = first_line; i <= last_line; i++)
3997 indentation_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
3998 if (decrease)
4000 line_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
4001 /* searching backwards for a space to remove */
4002 while (sci_get_char_at(editor->sci, indentation_end) != ' ' && indentation_end > line_start)
4003 indentation_end--;
4005 if (sci_get_char_at(editor->sci, indentation_end) == ' ')
4007 sci_set_selection(editor->sci, indentation_end, indentation_end + 1);
4008 sci_replace_sel(editor->sci, "");
4009 count--;
4010 if (i == first_line)
4011 first_line_offset = -1;
4014 else
4016 sci_insert_text(editor->sci, indentation_end, " ");
4017 count++;
4018 if (i == first_line)
4019 first_line_offset = 1;
4023 /* set cursor position */
4024 if (sel_start < sel_end)
4026 gint start = sel_start + first_line_offset;
4027 if (first_line_offset < 0)
4028 start = MAX(sel_start + first_line_offset,
4029 SSM(editor->sci, SCI_POSITIONFROMLINE, first_line, 0));
4031 sci_set_selection_start(editor->sci, start);
4032 sci_set_selection_end(editor->sci, sel_end + count);
4034 else
4035 sci_set_current_position(editor->sci, pos + count, FALSE);
4037 sci_end_undo_action(editor->sci);
4041 void editor_finalize(void)
4043 scintilla_release_resources();
4047 /* wordchars: NULL or a string containing characters to match a word.
4048 * Returns: the current selection or the current word.
4050 * Passing NULL as wordchars is NOT the same as passing GEANY_WORDCHARS: NULL means
4051 * using Scintillas's word boundaries. */
4052 gchar *editor_get_default_selection(GeanyEditor *editor, gboolean use_current_word,
4053 const gchar *wordchars)
4055 gchar *s = NULL;
4057 g_return_val_if_fail(editor != NULL, NULL);
4059 if (sci_get_lines_selected(editor->sci) == 1)
4060 s = sci_get_selection_contents(editor->sci);
4061 else if (sci_get_lines_selected(editor->sci) == 0 && use_current_word)
4062 { /* use the word at current cursor position */
4063 gchar word[GEANY_MAX_WORD_LENGTH];
4065 if (wordchars != NULL)
4066 editor_find_current_word(editor, -1, word, sizeof(word), wordchars);
4067 else
4068 editor_find_current_word_sciwc(editor, -1, word, sizeof(word));
4070 if (word[0] != '\0')
4071 s = g_strdup(word);
4073 return s;
4077 /* Note: Usually the line should be made visible (not folded) before calling this.
4078 * Returns: TRUE if line is/will be displayed to the user, or FALSE if it is
4079 * outside the *vertical* view.
4080 * Warning: You may need horizontal scrolling to make the cursor visible - so always call
4081 * sci_scroll_caret() when this returns TRUE. */
4082 gboolean editor_line_in_view(GeanyEditor *editor, gint line)
4084 gint vis1, los;
4086 g_return_val_if_fail(editor != NULL, FALSE);
4088 /* If line is wrapped the result may occur on another virtual line than the first and may be
4089 * still hidden, so increase the line number to check for the next document line */
4090 if (SSM(editor->sci, SCI_WRAPCOUNT, line, 0) > 1)
4091 line++;
4093 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0); /* convert to visible line number */
4094 vis1 = SSM(editor->sci, SCI_GETFIRSTVISIBLELINE, 0, 0);
4095 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
4097 return (line >= vis1 && line < vis1 + los);
4101 /* If the current line is outside the current view window, scroll the line
4102 * so it appears at percent_of_view. */
4103 void editor_display_current_line(GeanyEditor *editor, gfloat percent_of_view)
4105 gint line;
4107 g_return_if_fail(editor != NULL);
4109 line = sci_get_current_line(editor->sci);
4111 /* unfold maybe folded results */
4112 sci_ensure_line_is_visible(editor->sci, line);
4114 /* scroll the line if it's off screen */
4115 if (! editor_line_in_view(editor, line))
4116 editor->scroll_percent = percent_of_view;
4117 else
4118 sci_scroll_caret(editor->sci); /* may need horizontal scrolling */
4123 * Deletes all currently set indicators in the @a editor window.
4124 * Error indicators (red squiggly underlines) and usual line markers are removed.
4126 * @param editor The editor to operate on.
4128 void editor_indicator_clear_errors(GeanyEditor *editor)
4130 editor_indicator_clear(editor, GEANY_INDICATOR_ERROR);
4131 sci_marker_delete_all(editor->sci, 0); /* remove the yellow error line marker */
4136 * Deletes all currently set indicators matching @a indic in the @a editor window.
4138 * @param editor The editor to operate on.
4139 * @param indic The indicator number to clear, this is a value of @ref GeanyIndicator.
4141 * @since 0.16
4143 GEANY_API_SYMBOL
4144 void editor_indicator_clear(GeanyEditor *editor, gint indic)
4146 glong last_pos;
4148 g_return_if_fail(editor != NULL);
4150 last_pos = sci_get_length(editor->sci);
4151 if (last_pos > 0)
4153 sci_indicator_set(editor->sci, indic);
4154 sci_indicator_clear(editor->sci, 0, last_pos);
4160 * Sets an indicator @a indic on @a line.
4161 * Whitespace at the start and the end of the line is not marked.
4163 * @param editor The editor to operate on.
4164 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4165 * @param line The line number which should be marked.
4167 * @since 0.16
4169 GEANY_API_SYMBOL
4170 void editor_indicator_set_on_line(GeanyEditor *editor, gint indic, gint line)
4172 gint start, end;
4173 guint i = 0, len;
4174 gchar *linebuf;
4176 g_return_if_fail(editor != NULL);
4177 g_return_if_fail(line >= 0);
4179 start = sci_get_position_from_line(editor->sci, line);
4180 end = sci_get_position_from_line(editor->sci, line + 1);
4182 /* skip blank lines */
4183 if ((start + 1) == end ||
4184 start > end ||
4185 (sci_get_line_end_position(editor->sci, line) - start) == 0)
4187 return;
4190 len = end - start;
4191 linebuf = sci_get_line(editor->sci, line);
4193 /* don't set the indicator on whitespace */
4194 while (isspace(linebuf[i]))
4195 i++;
4196 while (len > 1 && len > i && isspace(linebuf[len - 1]))
4198 len--;
4199 end--;
4201 g_free(linebuf);
4203 editor_indicator_set_on_range(editor, indic, start + i, end);
4208 * Sets an indicator on the range specified by @a start and @a end.
4209 * No error checking or whitespace removal is performed, this should be done by the calling
4210 * function if necessary.
4212 * @param editor The editor to operate on.
4213 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4214 * @param start The starting position for the marker.
4215 * @param end The ending position for the marker.
4217 * @since 0.16
4219 GEANY_API_SYMBOL
4220 void editor_indicator_set_on_range(GeanyEditor *editor, gint indic, gint start, gint end)
4222 g_return_if_fail(editor != NULL);
4223 if (start >= end)
4224 return;
4226 sci_indicator_set(editor->sci, indic);
4227 sci_indicator_fill(editor->sci, start, end - start);
4231 /* Inserts the given colour (format should be #...), if there is a selection starting with 0x...
4232 * the replacement will also start with 0x... */
4233 void editor_insert_color(GeanyEditor *editor, const gchar *colour)
4235 g_return_if_fail(editor != NULL);
4237 if (sci_has_selection(editor->sci))
4239 gint start = sci_get_selection_start(editor->sci);
4240 const gchar *replacement = colour;
4242 if (sci_get_char_at(editor->sci, start) == '0' &&
4243 sci_get_char_at(editor->sci, start + 1) == 'x')
4245 gint end = sci_get_selection_end(editor->sci);
4247 sci_set_selection_start(editor->sci, start + 2);
4248 /* we need to also re-set the selection end in case the anchor was located before
4249 * the cursor, since set_selection_start() always moves the cursor, not the anchor */
4250 sci_set_selection_end(editor->sci, end);
4251 replacement++; /* skip the leading "0x" */
4253 else if (sci_get_char_at(editor->sci, start - 1) == '#')
4254 { /* double clicking something like #00ffff may only select 00ffff because of wordchars */
4255 replacement++; /* so skip the '#' to only replace the colour value */
4257 sci_replace_sel(editor->sci, replacement);
4259 else
4260 sci_add_text(editor->sci, colour);
4265 * Retrieves the end of line characters mode (LF, CR/LF, CR) in the given editor.
4266 * If @a editor is @c NULL, the default end of line characters are used.
4268 * @param editor @nullable The editor to operate on, or @c NULL to query the default value.
4269 * @return The used end of line characters mode.
4271 * @since 0.20
4273 GEANY_API_SYMBOL
4274 gint editor_get_eol_char_mode(GeanyEditor *editor)
4276 gint mode = file_prefs.default_eol_character;
4278 if (editor != NULL)
4279 mode = sci_get_eol_mode(editor->sci);
4281 return mode;
4286 * Retrieves the localized name (for displaying) of the used end of line characters
4287 * (LF, CR/LF, CR) in the given editor.
4288 * If @a editor is @c NULL, the default end of line characters are used.
4290 * @param editor @nullable The editor to operate on, or @c NULL to query the default value.
4291 * @return The name of the end of line characters.
4293 * @since 0.19
4295 GEANY_API_SYMBOL
4296 const gchar *editor_get_eol_char_name(GeanyEditor *editor)
4298 gint mode = file_prefs.default_eol_character;
4300 if (editor != NULL)
4301 mode = sci_get_eol_mode(editor->sci);
4303 return utils_get_eol_name(mode);
4308 * Retrieves the length of the used end of line characters (LF, CR/LF, CR) in the given editor.
4309 * If @a editor is @c NULL, the default end of line characters are used.
4310 * The returned value is 1 for CR and LF and 2 for CR/LF.
4312 * @param editor @nullable The editor to operate on, or @c NULL to query the default value.
4313 * @return The length of the end of line characters.
4315 * @since 0.19
4317 GEANY_API_SYMBOL
4318 gint editor_get_eol_char_len(GeanyEditor *editor)
4320 gint mode = file_prefs.default_eol_character;
4322 if (editor != NULL)
4323 mode = sci_get_eol_mode(editor->sci);
4325 switch (mode)
4327 case SC_EOL_CRLF: return 2; break;
4328 default: return 1; break;
4334 * Retrieves the used end of line characters (LF, CR/LF, CR) in the given editor.
4335 * If @a editor is @c NULL, the default end of line characters are used.
4336 * The returned value is either "\n", "\r\n" or "\r".
4338 * @param editor @nullable The editor to operate on, or @c NULL to query the default value.
4339 * @return The end of line characters.
4341 * @since 0.19
4343 GEANY_API_SYMBOL
4344 const gchar *editor_get_eol_char(GeanyEditor *editor)
4346 gint mode = file_prefs.default_eol_character;
4348 if (editor != NULL)
4349 mode = sci_get_eol_mode(editor->sci);
4351 return utils_get_eol_char(mode);
4355 static void fold_all(GeanyEditor *editor, gboolean want_fold)
4357 gint lines, first, i;
4359 if (editor == NULL || ! editor_prefs.folding)
4360 return;
4362 lines = sci_get_line_count(editor->sci);
4363 first = sci_get_first_visible_line(editor->sci);
4365 for (i = 0; i < lines; i++)
4367 gint level = sci_get_fold_level(editor->sci, i);
4369 if (level & SC_FOLDLEVELHEADERFLAG)
4371 if (sci_get_fold_expanded(editor->sci, i) == want_fold)
4372 sci_toggle_fold(editor->sci, i);
4375 editor_scroll_to_line(editor, first, 0.0F);
4379 void editor_unfold_all(GeanyEditor *editor)
4381 fold_all(editor, FALSE);
4385 void editor_fold_all(GeanyEditor *editor)
4387 fold_all(editor, TRUE);
4391 void editor_replace_tabs(GeanyEditor *editor, gboolean ignore_selection)
4393 gint anchor_pos, caret_pos;
4394 struct Sci_TextToFind ttf;
4396 g_return_if_fail(editor != NULL);
4398 sci_start_undo_action(editor->sci);
4399 if (sci_has_selection(editor->sci) && !ignore_selection)
4401 ttf.chrg.cpMin = sci_get_selection_start(editor->sci);
4402 ttf.chrg.cpMax = sci_get_selection_end(editor->sci);
4404 else
4406 ttf.chrg.cpMin = 0;
4407 ttf.chrg.cpMax = sci_get_length(editor->sci);
4409 ttf.lpstrText = (gchar*) "\t";
4411 anchor_pos = SSM(editor->sci, SCI_GETANCHOR, 0, 0);
4412 caret_pos = sci_get_current_position(editor->sci);
4413 while (TRUE)
4415 gint search_pos, pos_in_line, current_tab_true_length;
4416 gint tab_len;
4417 gchar *tab_str;
4419 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4420 if (search_pos == -1)
4421 break;
4423 tab_len = sci_get_tab_width(editor->sci);
4424 pos_in_line = sci_get_col_from_position(editor->sci, search_pos);
4425 current_tab_true_length = tab_len - (pos_in_line % tab_len);
4426 tab_str = g_strnfill(current_tab_true_length, ' ');
4427 sci_set_target_start(editor->sci, search_pos);
4428 sci_set_target_end(editor->sci, search_pos + 1);
4429 sci_replace_target(editor->sci, tab_str, FALSE);
4430 /* next search starts after replacement */
4431 ttf.chrg.cpMin = search_pos + current_tab_true_length - 1;
4432 /* update end of range now text has changed */
4433 ttf.chrg.cpMax += current_tab_true_length - 1;
4434 g_free(tab_str);
4436 if (anchor_pos > search_pos)
4437 anchor_pos += current_tab_true_length - 1;
4438 if (caret_pos > search_pos)
4439 caret_pos += current_tab_true_length - 1;
4441 sci_set_selection(editor->sci, anchor_pos, caret_pos);
4442 sci_end_undo_action(editor->sci);
4446 /* Replaces all occurrences all spaces of the length of a given tab_width,
4447 * optionally restricting the search to the current selection. */
4448 void editor_replace_spaces(GeanyEditor *editor, gboolean ignore_selection)
4450 gint search_pos;
4451 gint anchor_pos, caret_pos;
4452 static gdouble tab_len_f = -1.0; /* keep the last used value */
4453 gint tab_len;
4454 gchar *text;
4455 struct Sci_TextToFind ttf;
4457 g_return_if_fail(editor != NULL);
4459 if (tab_len_f < 0.0)
4460 tab_len_f = sci_get_tab_width(editor->sci);
4462 if (! dialogs_show_input_numeric(
4463 _("Enter Tab Width"),
4464 _("Enter the amount of spaces which should be replaced by a tab character."),
4465 &tab_len_f, 1, 100, 1))
4467 return;
4469 tab_len = (gint) tab_len_f;
4470 text = g_strnfill(tab_len, ' ');
4472 sci_start_undo_action(editor->sci);
4473 if (sci_has_selection(editor->sci) && !ignore_selection)
4475 ttf.chrg.cpMin = sci_get_selection_start(editor->sci);
4476 ttf.chrg.cpMax = sci_get_selection_end(editor->sci);
4478 else
4480 ttf.chrg.cpMin = 0;
4481 ttf.chrg.cpMax = sci_get_length(editor->sci);
4483 ttf.lpstrText = text;
4485 anchor_pos = SSM(editor->sci, SCI_GETANCHOR, 0, 0);
4486 caret_pos = sci_get_current_position(editor->sci);
4487 while (TRUE)
4489 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4490 if (search_pos == -1)
4491 break;
4492 /* only replace indentation because otherwise we can mess up alignment */
4493 if (search_pos > sci_get_line_indent_position(editor->sci,
4494 sci_get_line_from_position(editor->sci, search_pos)))
4496 ttf.chrg.cpMin = search_pos + tab_len;
4497 continue;
4499 sci_set_target_start(editor->sci, search_pos);
4500 sci_set_target_end(editor->sci, search_pos + tab_len);
4501 sci_replace_target(editor->sci, "\t", FALSE);
4502 ttf.chrg.cpMin = search_pos;
4503 /* update end of range now text has changed */
4504 ttf.chrg.cpMax -= tab_len - 1;
4506 if (anchor_pos > search_pos)
4507 anchor_pos -= tab_len - 1;
4508 if (caret_pos > search_pos)
4509 caret_pos -= tab_len - 1;
4511 sci_set_selection(editor->sci, anchor_pos, caret_pos);
4512 sci_end_undo_action(editor->sci);
4513 g_free(text);
4517 void editor_strip_line_trailing_spaces(GeanyEditor *editor, gint line)
4519 gint line_start = sci_get_position_from_line(editor->sci, line);
4520 gint line_end = sci_get_line_end_position(editor->sci, line);
4521 gint i = line_end - 1;
4522 gchar ch = sci_get_char_at(editor->sci, i);
4524 /* Diff hunks should keep trailing spaces */
4525 if (sci_get_lexer(editor->sci) == SCLEX_DIFF)
4526 return;
4528 while ((i >= line_start) && ((ch == ' ') || (ch == '\t')))
4530 i--;
4531 ch = sci_get_char_at(editor->sci, i);
4533 if (i < (line_end - 1))
4535 sci_set_target_start(editor->sci, i + 1);
4536 sci_set_target_end(editor->sci, line_end);
4537 sci_replace_target(editor->sci, "", FALSE);
4542 void editor_strip_trailing_spaces(GeanyEditor *editor, gboolean ignore_selection)
4544 gint start_line;
4545 gint end_line;
4546 gint line;
4548 if (sci_has_selection(editor->sci) && !ignore_selection)
4550 gint selection_start = sci_get_selection_start(editor->sci);
4551 gint selection_end = sci_get_selection_end(editor->sci);
4553 start_line = sci_get_line_from_position(editor->sci, selection_start);
4554 end_line = sci_get_line_from_position(editor->sci, selection_end);
4556 if (sci_get_col_from_position(editor->sci, selection_end) > 0)
4557 end_line++;
4559 else
4561 start_line = 0;
4562 end_line = sci_get_line_count(editor->sci);
4565 sci_start_undo_action(editor->sci);
4567 for (line = start_line; line < end_line; line++)
4569 editor_strip_line_trailing_spaces(editor, line);
4571 sci_end_undo_action(editor->sci);
4575 void editor_ensure_final_newline(GeanyEditor *editor)
4577 gint max_lines = sci_get_line_count(editor->sci);
4578 gboolean append_newline = (max_lines == 1);
4579 gint end_document = sci_get_position_from_line(editor->sci, max_lines);
4581 if (max_lines > 1)
4583 append_newline = end_document > sci_get_position_from_line(editor->sci, max_lines - 1);
4585 if (append_newline)
4587 const gchar *eol = editor_get_eol_char(editor);
4589 sci_insert_text(editor->sci, end_document, eol);
4594 void editor_set_font(GeanyEditor *editor, const gchar *font)
4596 gint style, size;
4597 gchar *font_name;
4598 PangoFontDescription *pfd;
4600 g_return_if_fail(editor);
4602 pfd = pango_font_description_from_string(font);
4603 size = pango_font_description_get_size(pfd) / PANGO_SCALE;
4604 font_name = g_strdup_printf("!%s", pango_font_description_get_family(pfd));
4605 pango_font_description_free(pfd);
4607 for (style = 0; style <= STYLE_MAX; style++)
4608 sci_set_font(editor->sci, style, font_name, size);
4610 g_free(font_name);
4612 /* zoom to 100% to prevent confusion */
4613 sci_zoom_off(editor->sci);
4617 void editor_set_line_wrapping(GeanyEditor *editor, gboolean wrap)
4619 g_return_if_fail(editor != NULL);
4621 editor->line_wrapping = wrap;
4622 sci_set_lines_wrapped(editor->sci, wrap);
4626 /** Sets the indent type for @a editor.
4627 * @param editor Editor.
4628 * @param type Indent type.
4630 * @since 0.16
4632 GEANY_API_SYMBOL
4633 void editor_set_indent_type(GeanyEditor *editor, GeanyIndentType type)
4635 editor_set_indent(editor, type, editor->indent_width);
4639 /** Sets the indent width for @a editor.
4640 * @param editor Editor.
4641 * @param width New indent width.
4643 * @since 1.27 (API 227)
4645 GEANY_API_SYMBOL
4646 void editor_set_indent_width(GeanyEditor *editor, gint width)
4648 editor_set_indent(editor, editor->indent_type, width);
4652 void editor_set_indent(GeanyEditor *editor, GeanyIndentType type, gint width)
4654 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
4655 ScintillaObject *sci = editor->sci;
4656 gboolean use_tabs = type != GEANY_INDENT_TYPE_SPACES;
4658 editor->indent_type = type;
4659 editor->indent_width = width;
4660 sci_set_use_tabs(sci, use_tabs);
4662 if (type == GEANY_INDENT_TYPE_BOTH)
4664 sci_set_tab_width(sci, iprefs->hard_tab_width);
4665 if (iprefs->hard_tab_width != 8)
4667 static gboolean warn = TRUE;
4668 if (warn)
4669 ui_set_statusbar(TRUE, _("Warning: non-standard hard tab width: %d != 8!"),
4670 iprefs->hard_tab_width);
4671 warn = FALSE;
4674 else
4675 sci_set_tab_width(sci, width);
4677 SSM(sci, SCI_SETINDENT, width, 0);
4679 /* remove indent spaces on backspace, if using any spaces to indent */
4680 SSM(sci, SCI_SETBACKSPACEUNINDENTS, type != GEANY_INDENT_TYPE_TABS, 0);
4684 /* Convenience function for editor_goto_pos() to pass in a line number. */
4685 gboolean editor_goto_line(GeanyEditor *editor, gint line_no, gint offset)
4687 gint pos;
4689 g_return_val_if_fail(editor, FALSE);
4690 if (line_no < 0 || line_no >= sci_get_line_count(editor->sci))
4691 return FALSE;
4693 if (offset != 0)
4695 gint current_line = sci_get_current_line(editor->sci);
4696 line_no *= offset;
4697 line_no = current_line + line_no;
4700 pos = sci_get_position_from_line(editor->sci, line_no);
4701 return editor_goto_pos(editor, pos, TRUE);
4705 /** Moves to position @a pos, switching to the document if necessary,
4706 * setting a marker if @a mark is set.
4708 * @param editor Editor.
4709 * @param pos The position.
4710 * @param mark Whether to set a mark on the position.
4711 * @return @c TRUE if action has been performed, otherwise @c FALSE.
4713 * @since 0.20
4715 GEANY_API_SYMBOL
4716 gboolean editor_goto_pos(GeanyEditor *editor, gint pos, gboolean mark)
4718 g_return_val_if_fail(editor, FALSE);
4719 if (G_UNLIKELY(pos < 0))
4720 return FALSE;
4722 if (mark)
4724 gint line = sci_get_line_from_position(editor->sci, pos);
4726 /* mark the tag with the yellow arrow */
4727 sci_marker_delete_all(editor->sci, 0);
4728 sci_set_marker_at_line(editor->sci, line, 0);
4731 sci_goto_pos(editor->sci, pos, TRUE);
4732 editor->scroll_percent = 0.25F;
4734 /* finally switch to the page */
4735 document_show_tab(editor->document);
4736 return TRUE;
4740 static gboolean
4741 on_editor_scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer user_data)
4743 GeanyEditor *editor = user_data;
4745 /* we only handle up and down, leave the rest to Scintilla */
4746 if (event->direction != GDK_SCROLL_UP && event->direction != GDK_SCROLL_DOWN)
4747 return FALSE;
4749 /* Handle scroll events if Alt is pressed and scroll whole pages instead of a
4750 * few lines only, maybe this could/should be done in Scintilla directly */
4751 if (event->state & GDK_MOD1_MASK)
4753 sci_send_command(editor->sci, (event->direction == GDK_SCROLL_DOWN) ? SCI_PAGEDOWN : SCI_PAGEUP);
4754 return TRUE;
4756 else if (event->state & GDK_SHIFT_MASK)
4758 gint amount = (event->direction == GDK_SCROLL_DOWN) ? 8 : -8;
4760 sci_scroll_columns(editor->sci, amount);
4761 return TRUE;
4764 return FALSE; /* let Scintilla handle all other cases */
4768 static gboolean editor_check_colourise(GeanyEditor *editor)
4770 GeanyDocument *doc = editor->document;
4772 if (!doc->priv->colourise_needed)
4773 return FALSE;
4775 doc->priv->colourise_needed = FALSE;
4776 sci_colourise(editor->sci, 0, -1);
4778 /* now that the current document is colourised, fold points are now accurate,
4779 * so force an update of the current function/tag. */
4780 symbols_get_current_function(NULL, NULL);
4781 ui_update_statusbar(NULL, -1);
4783 return TRUE;
4787 /* We only want to colourise just before drawing, to save startup time and
4788 * prevent unnecessary recolouring other documents after one is saved.
4789 * Really we want a "draw" signal but there doesn't seem to be one (expose is too late,
4790 * and "show" doesn't work). */
4791 static gboolean on_editor_focus_in(GtkWidget *widget, GdkEventFocus *event, gpointer user_data)
4793 GeanyEditor *editor = user_data;
4795 editor_check_colourise(editor);
4796 return FALSE;
4800 static gboolean on_editor_expose_event(GtkWidget *widget, GdkEventExpose *event,
4801 gpointer user_data)
4803 GeanyEditor *editor = user_data;
4805 /* This is just to catch any uncolourised documents being drawn that didn't receive focus
4806 * for some reason, maybe it's not necessary but just in case. */
4807 editor_check_colourise(editor);
4808 return FALSE;
4812 #if GTK_CHECK_VERSION(3, 0, 0)
4813 static gboolean on_editor_draw(GtkWidget *widget, cairo_t *cr, gpointer user_data)
4815 return on_editor_expose_event(widget, NULL, user_data);
4817 #endif
4820 static void setup_sci_keys(ScintillaObject *sci)
4822 /* disable some Scintilla keybindings to be able to redefine them cleanly */
4823 sci_clear_cmdkey(sci, 'A' | (SCMOD_CTRL << 16)); /* select all */
4824 sci_clear_cmdkey(sci, 'D' | (SCMOD_CTRL << 16)); /* duplicate */
4825 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16)); /* line transpose */
4826 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line copy */
4827 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16)); /* line cut */
4828 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line delete */
4829 sci_clear_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line to end delete */
4830 sci_clear_cmdkey(sci, SCK_BACK | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line to beginning delete */
4831 sci_clear_cmdkey(sci, '/' | (SCMOD_CTRL << 16)); /* Previous word part */
4832 sci_clear_cmdkey(sci, '\\' | (SCMOD_CTRL << 16)); /* Next word part */
4833 sci_clear_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16)); /* scroll line up */
4834 sci_clear_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16)); /* scroll line down */
4835 sci_clear_cmdkey(sci, SCK_HOME); /* line start */
4836 sci_clear_cmdkey(sci, SCK_END); /* line end */
4837 sci_clear_cmdkey(sci, SCK_END | (SCMOD_ALT << 16)); /* visual line end */
4839 if (editor_prefs.use_gtk_word_boundaries)
4841 /* use GtkEntry-like word boundaries */
4842 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16), SCI_WORDRIGHTEND);
4843 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_WORDRIGHTENDEXTEND);
4844 sci_assign_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16), SCI_DELWORDRIGHTEND);
4846 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_ALT << 16), SCI_LINESCROLLUP);
4847 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_ALT << 16), SCI_LINESCROLLDOWN);
4848 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16), SCI_PARAUP);
4849 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARAUPEXTEND);
4850 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16), SCI_PARADOWN);
4851 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARADOWNEXTEND);
4853 sci_clear_cmdkey(sci, SCK_BACK | (SCMOD_ALT << 16)); /* clear Alt-Backspace (Undo) */
4857 /* registers a Scintilla image from a named icon from the theme */
4858 static gboolean register_named_icon(ScintillaObject *sci, guint id, const gchar *name)
4860 GError *error = NULL;
4861 GdkPixbuf *pixbuf;
4862 gint n_channels, rowstride, width, height;
4863 gint size;
4865 gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &size, NULL);
4866 pixbuf = gtk_icon_theme_load_icon(gtk_icon_theme_get_default(), name, size, 0, &error);
4867 if (! pixbuf)
4869 g_warning("failed to load icon '%s': %s", name, error->message);
4870 g_error_free(error);
4871 return FALSE;
4874 n_channels = gdk_pixbuf_get_n_channels(pixbuf);
4875 rowstride = gdk_pixbuf_get_rowstride(pixbuf);
4876 width = gdk_pixbuf_get_width(pixbuf);
4877 height = gdk_pixbuf_get_height(pixbuf);
4879 if (gdk_pixbuf_get_bits_per_sample(pixbuf) != 8 ||
4880 ! gdk_pixbuf_get_has_alpha(pixbuf) ||
4881 n_channels != 4 ||
4882 rowstride != width * n_channels)
4884 g_warning("incompatible image data for icon '%s'", name);
4885 g_object_unref(pixbuf);
4886 return FALSE;
4889 SSM(sci, SCI_RGBAIMAGESETWIDTH, width, 0);
4890 SSM(sci, SCI_RGBAIMAGESETHEIGHT, height, 0);
4891 SSM(sci, SCI_REGISTERRGBAIMAGE, id, (sptr_t)gdk_pixbuf_get_pixels(pixbuf));
4893 g_object_unref(pixbuf);
4894 return TRUE;
4898 /* Create new editor widget (scintilla).
4899 * @note The @c "sci-notify" signal is connected separately. */
4900 static ScintillaObject *create_new_sci(GeanyEditor *editor)
4902 ScintillaObject *sci;
4904 sci = SCINTILLA(scintilla_new());
4906 /* Scintilla doesn't support RTL languages properly and is primarily
4907 * intended to be used with LTR source code, so override the
4908 * GTK+ default text direction for the Scintilla widget. */
4909 gtk_widget_set_direction(GTK_WIDGET(sci), GTK_TEXT_DIR_LTR);
4911 gtk_widget_show(GTK_WIDGET(sci));
4913 sci_set_codepage(sci, SC_CP_UTF8);
4914 /*SSM(sci, SCI_SETWRAPSTARTINDENT, 4, 0);*/
4915 /* disable scintilla provided popup menu */
4916 sci_use_popup(sci, FALSE);
4918 setup_sci_keys(sci);
4920 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
4921 sci_set_lines_wrapped(sci, editor->line_wrapping);
4922 sci_set_caret_policy_x(sci, CARET_JUMPS | CARET_EVEN, 0);
4923 /* Y policy is set in editor_apply_update_prefs() */
4924 SSM(sci, SCI_AUTOCSETSEPARATOR, '\n', 0);
4925 SSM(sci, SCI_SETSCROLLWIDTHTRACKING, 1, 0);
4927 /* tag autocompletion images */
4928 register_named_icon(sci, 1, "classviewer-var");
4929 register_named_icon(sci, 2, "classviewer-method");
4931 /* necessary for column mode editing, implemented in Scintilla since 2.0 */
4932 SSM(sci, SCI_SETADDITIONALSELECTIONTYPING, 1, 0);
4934 /* rectangular selection modifier for creating rectangular selections with the mouse */
4935 SSM(sci, SCI_SETRECTANGULARSELECTIONMODIFIER, SCMOD_CTRL, 0);
4937 /* virtual space */
4938 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
4940 /* input method editor's candidate window behaviour */
4941 SSM(sci, SCI_SETIMEINTERACTION, editor_prefs.ime_interaction, 0);
4943 #ifdef GDK_WINDOWING_QUARTZ
4944 # if ! GTK_CHECK_VERSION(3,16,0)
4945 /* "retina" (HiDPI) display support on OS X - requires disabling buffered draw
4946 * on older GTK versions */
4947 SSM(sci, SCI_SETBUFFEREDDRAW, 0, 0);
4948 # endif
4949 #endif
4951 /* only connect signals if this is for the document notebook, not split window */
4952 if (editor->sci == NULL)
4954 g_signal_connect(sci, "button-press-event", G_CALLBACK(on_editor_button_press_event), editor);
4955 g_signal_connect(sci, "scroll-event", G_CALLBACK(on_editor_scroll_event), editor);
4956 g_signal_connect(sci, "motion-notify-event", G_CALLBACK(on_motion_event), NULL);
4957 g_signal_connect(sci, "focus-in-event", G_CALLBACK(on_editor_focus_in), editor);
4958 #if GTK_CHECK_VERSION(3, 0, 0)
4959 g_signal_connect(sci, "draw", G_CALLBACK(on_editor_draw), editor);
4960 #else
4961 g_signal_connect(sci, "expose-event", G_CALLBACK(on_editor_expose_event), editor);
4962 #endif
4964 return sci;
4968 /** Creates a new Scintilla @c GtkWidget based on the settings for @a editor.
4969 * @param editor Editor settings.
4970 * @return @transfer{floating} The new widget.
4972 * @since 0.15
4974 GEANY_API_SYMBOL
4975 ScintillaObject *editor_create_widget(GeanyEditor *editor)
4977 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4978 ScintillaObject *old, *sci;
4979 GeanyIndentType old_indent_type = editor->indent_type;
4980 gint old_indent_width = editor->indent_width;
4982 /* temporarily change editor to use the new sci widget */
4983 old = editor->sci;
4984 sci = create_new_sci(editor);
4985 editor->sci = sci;
4987 editor_set_indent(editor, iprefs->type, iprefs->width);
4988 editor_set_font(editor, interface_prefs.editor_font);
4989 editor_apply_update_prefs(editor);
4991 /* if editor already had a widget, restore it */
4992 if (old)
4994 editor->indent_type = old_indent_type;
4995 editor->indent_width = old_indent_width;
4996 editor->sci = old;
4998 return sci;
5002 GeanyEditor *editor_create(GeanyDocument *doc)
5004 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
5005 GeanyEditor *editor = g_new0(GeanyEditor, 1);
5007 editor->document = doc;
5008 doc->editor = editor; /* needed in case some editor functions/callbacks expect it */
5010 editor->auto_indent = (iprefs->auto_indent_mode != GEANY_AUTOINDENT_NONE);
5011 editor->line_wrapping = get_project_pref(line_wrapping);
5012 editor->scroll_percent = -1.0F;
5013 editor->line_breaking = FALSE;
5015 editor->sci = editor_create_widget(editor);
5016 return editor;
5020 /* in case we need to free some fields in future */
5021 void editor_destroy(GeanyEditor *editor)
5023 g_free(editor);
5027 static void on_document_save(GObject *obj, GeanyDocument *doc)
5029 gchar *f = g_build_filename(app->configdir, "snippets.conf", NULL);
5031 if (utils_str_equal(doc->real_path, f))
5033 /* reload snippets */
5034 editor_snippets_free();
5035 editor_snippets_init();
5037 g_free(f);
5041 gboolean editor_complete_word_part(GeanyEditor *editor)
5043 gchar *entry;
5045 g_return_val_if_fail(editor, FALSE);
5047 if (!SSM(editor->sci, SCI_AUTOCACTIVE, 0, 0))
5048 return FALSE;
5050 entry = sci_get_string(editor->sci, SCI_AUTOCGETCURRENTTEXT, 0);
5052 /* if no word part, complete normally */
5053 if (!check_partial_completion(editor, entry))
5054 SSM(editor->sci, SCI_AUTOCCOMPLETE, 0, 0);
5056 g_free(entry);
5057 return TRUE;
5061 void editor_init(void)
5063 static GeanyIndentPrefs indent_prefs;
5064 gchar *f;
5066 memset(&editor_prefs, 0, sizeof(GeanyEditorPrefs));
5067 memset(&indent_prefs, 0, sizeof(GeanyIndentPrefs));
5068 editor_prefs.indentation = &indent_prefs;
5070 /* use g_signal_connect_after() to allow plugins connecting to the signal before the default
5071 * handler (on_editor_notify) is called */
5072 g_signal_connect_after(geany_object, "editor-notify", G_CALLBACK(on_editor_notify), NULL);
5074 f = g_build_filename(app->configdir, "snippets.conf", NULL);
5075 ui_add_config_file_menu_item(f, NULL, NULL);
5076 g_free(f);
5077 g_signal_connect(geany_object, "document-save", G_CALLBACK(on_document_save), NULL);
5081 /* TODO: Should these be user-defined instead of hard-coded? */
5082 void editor_set_indentation_guides(GeanyEditor *editor)
5084 gint mode;
5085 gint lexer;
5087 g_return_if_fail(editor != NULL);
5089 if (! editor_prefs.show_indent_guide)
5091 sci_set_indentation_guides(editor->sci, SC_IV_NONE);
5092 return;
5095 lexer = sci_get_lexer(editor->sci);
5096 switch (lexer)
5098 /* Lines added/removed are prefixed with +/- characters, so
5099 * those lines will not be shown with any indentation guides.
5100 * It can be distracting that only a few of lines in a diff/patch
5101 * file will show the guides. */
5102 case SCLEX_DIFF:
5103 mode = SC_IV_NONE;
5104 break;
5106 /* These languages use indentation for control blocks; the "look forward" method works
5107 * best here */
5108 case SCLEX_PYTHON:
5109 case SCLEX_HASKELL:
5110 case SCLEX_MAKEFILE:
5111 case SCLEX_ASM:
5112 case SCLEX_SQL:
5113 case SCLEX_COBOL:
5114 case SCLEX_PROPERTIES:
5115 case SCLEX_FORTRAN: /* Is this the best option for Fortran? */
5116 case SCLEX_CAML:
5117 mode = SC_IV_LOOKFORWARD;
5118 break;
5120 /* C-like (structured) languages benefit from the "look both" method */
5121 case SCLEX_CPP:
5122 case SCLEX_HTML:
5123 case SCLEX_PHPSCRIPT:
5124 case SCLEX_XML:
5125 case SCLEX_PERL:
5126 case SCLEX_LATEX:
5127 case SCLEX_LUA:
5128 case SCLEX_PASCAL:
5129 case SCLEX_RUBY:
5130 case SCLEX_TCL:
5131 case SCLEX_F77:
5132 case SCLEX_CSS:
5133 case SCLEX_BASH:
5134 case SCLEX_VHDL:
5135 case SCLEX_FREEBASIC:
5136 case SCLEX_D:
5137 case SCLEX_OCTAVE:
5138 case SCLEX_RUST:
5139 mode = SC_IV_LOOKBOTH;
5140 break;
5142 default:
5143 mode = SC_IV_REAL;
5144 break;
5147 sci_set_indentation_guides(editor->sci, mode);
5151 /* Apply non-document prefs that can change in the Preferences dialog */
5152 void editor_apply_update_prefs(GeanyEditor *editor)
5154 ScintillaObject *sci;
5155 int caret_y_policy;
5157 g_return_if_fail(editor != NULL);
5159 if (main_status.quitting)
5160 return;
5162 sci = editor->sci;
5164 sci_set_mark_long_lines(sci, editor_get_long_line_type(),
5165 editor_get_long_line_column(), editor_prefs.long_line_color);
5167 /* update indent width, tab width */
5168 editor_set_indent(editor, editor->indent_type, editor->indent_width);
5169 sci_set_tab_indents(sci, editor_prefs.use_tab_to_indent);
5171 sci_assign_cmdkey(sci, SCK_HOME | (SCMOD_SHIFT << 16),
5172 editor_prefs.smart_home_key ? SCI_VCHOMEEXTEND : SCI_HOMEEXTEND);
5173 sci_assign_cmdkey(sci, SCK_HOME | ((SCMOD_SHIFT | SCMOD_ALT) << 16),
5174 editor_prefs.smart_home_key ? SCI_VCHOMERECTEXTEND : SCI_HOMERECTEXTEND);
5176 sci_set_autoc_max_height(sci, editor_prefs.symbolcompletion_max_height);
5177 SSM(sci, SCI_AUTOCSETDROPRESTOFWORD, editor_prefs.completion_drops_rest_of_word, 0);
5179 editor_set_indentation_guides(editor);
5181 sci_set_visible_white_spaces(sci, editor_prefs.show_white_space);
5182 sci_set_visible_eols(sci, editor_prefs.show_line_endings);
5183 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
5184 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin);
5186 sci_set_folding_margin_visible(sci, editor_prefs.folding);
5188 /* virtual space */
5189 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
5191 /* caret Y policy */
5192 caret_y_policy = CARET_EVEN;
5193 if (editor_prefs.scroll_lines_around_cursor > 0)
5194 caret_y_policy |= CARET_SLOP | CARET_STRICT;
5195 sci_set_caret_policy_y(sci, caret_y_policy, editor_prefs.scroll_lines_around_cursor);
5197 /* (dis)allow scrolling past end of document */
5198 sci_set_scroll_stop_at_last_line(sci, editor_prefs.scroll_stop_at_last_line);
5200 sci_set_scrollbar_mode(sci, editor_prefs.show_scrollbars);
5204 /* This is for tab-indents, space aligns formatted code. Spaces should be preserved. */
5205 static void change_tab_indentation(GeanyEditor *editor, gint line, gboolean increase)
5207 ScintillaObject *sci = editor->sci;
5208 gint pos = sci_get_position_from_line(sci, line);
5210 if (increase)
5212 sci_insert_text(sci, pos, "\t");
5214 else
5216 if (sci_get_char_at(sci, pos) == '\t')
5218 sci_set_selection(sci, pos, pos + 1);
5219 sci_replace_sel(sci, "");
5221 else /* remove spaces only if no tabs */
5223 gint width = sci_get_line_indentation(sci, line);
5225 width -= editor_get_indent_prefs(editor)->width;
5226 sci_set_line_indentation(sci, line, width);
5232 static void editor_change_line_indent(GeanyEditor *editor, gint line, gboolean increase)
5234 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
5235 ScintillaObject *sci = editor->sci;
5237 if (iprefs->type == GEANY_INDENT_TYPE_TABS)
5238 change_tab_indentation(editor, line, increase);
5239 else
5241 gint width = sci_get_line_indentation(sci, line);
5243 width += increase ? iprefs->width : -iprefs->width;
5244 sci_set_line_indentation(sci, line, width);
5249 void editor_indent(GeanyEditor *editor, gboolean increase)
5251 ScintillaObject *sci = editor->sci;
5252 gint caret_pos, caret_line, caret_offset, caret_indent_pos, caret_line_len;
5253 gint anchor_pos, anchor_line, anchor_offset, anchor_indent_pos, anchor_line_len;
5255 /* backup information needed to restore caret and anchor */
5256 caret_pos = sci_get_current_position(sci);
5257 anchor_pos = SSM(sci, SCI_GETANCHOR, 0, 0);
5258 caret_line = sci_get_line_from_position(sci, caret_pos);
5259 anchor_line = sci_get_line_from_position(sci, anchor_pos);
5260 caret_offset = caret_pos - sci_get_position_from_line(sci, caret_line);
5261 anchor_offset = anchor_pos - sci_get_position_from_line(sci, anchor_line);
5262 caret_indent_pos = sci_get_line_indent_position(sci, caret_line);
5263 anchor_indent_pos = sci_get_line_indent_position(sci, anchor_line);
5264 caret_line_len = sci_get_line_length(sci, caret_line);
5265 anchor_line_len = sci_get_line_length(sci, anchor_line);
5267 if (sci_get_lines_selected(sci) <= 1)
5269 editor_change_line_indent(editor, sci_get_current_line(sci), increase);
5271 else
5273 gint start, end;
5274 gint line, lstart, lend;
5276 editor_select_lines(editor, FALSE);
5277 start = sci_get_selection_start(sci);
5278 end = sci_get_selection_end(sci);
5279 lstart = sci_get_line_from_position(sci, start);
5280 lend = sci_get_line_from_position(sci, end);
5281 if (end == sci_get_length(sci))
5282 lend++; /* for last line with text on it */
5284 sci_start_undo_action(sci);
5285 for (line = lstart; line < lend; line++)
5287 editor_change_line_indent(editor, line, increase);
5289 sci_end_undo_action(sci);
5292 /* restore caret and anchor position */
5293 if (caret_pos >= caret_indent_pos)
5294 caret_offset += sci_get_line_length(sci, caret_line) - caret_line_len;
5295 if (anchor_pos >= anchor_indent_pos)
5296 anchor_offset += sci_get_line_length(sci, anchor_line) - anchor_line_len;
5298 SSM(sci, SCI_SETCURRENTPOS, sci_get_position_from_line(sci, caret_line) + caret_offset, 0);
5299 SSM(sci, SCI_SETANCHOR, sci_get_position_from_line(sci, anchor_line) + anchor_offset, 0);
5303 /** Gets snippet by name.
5305 * If @a editor is passed, returns a snippet specific to the document filetype.
5306 * If @a editor is @c NULL, returns a snippet from the default set.
5308 * @param editor @nullable Editor or @c NULL.
5309 * @param snippet_name Snippet name.
5310 * @return @nullable snippet or @c NULL if it was not found. Must not be freed.
5312 GEANY_API_SYMBOL
5313 const gchar *editor_find_snippet(GeanyEditor *editor, const gchar *snippet_name)
5315 const gchar *subhash_name = editor ? editor->document->file_type->name : "Default";
5316 GHashTable *subhash = g_hash_table_lookup(snippet_hash, subhash_name);
5318 return subhash ? g_hash_table_lookup(subhash, snippet_name) : NULL;
5322 /** Replaces all special sequences in @a snippet and inserts it at @a pos.
5323 * If you insert at the current position, consider calling @c sci_scroll_caret()
5324 * after this function.
5325 * @param editor .
5326 * @param pos .
5327 * @param snippet .
5329 GEANY_API_SYMBOL
5330 void editor_insert_snippet(GeanyEditor *editor, gint pos, const gchar *snippet)
5332 GString *pattern;
5334 pattern = g_string_new(snippet);
5335 snippets_make_replacements(editor, pattern);
5336 editor_insert_text_block(editor, pattern->str, pos, -1, -1, TRUE);
5337 g_string_free(pattern, TRUE);
5340 static void *copy_(void *src) { return src; }
5341 static void free_(void *doc) { }
5343 /** @gironly
5344 * Gets the GType of GeanyEditor
5346 * @return the GeanyEditor type */
5347 GEANY_API_SYMBOL
5348 GType editor_get_type (void);
5350 G_DEFINE_BOXED_TYPE(GeanyEditor, editor, copy_, free_);