Update displayed copyright years
[geany-mirror.git] / src / editor.c
blob595cd5439603c13b8e65b5b8901405e78f34eb43
1 /*
2 * editor.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005-2012 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2012 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com>
6 * Copyright 2009-2012 Frank Lanitz <frank(at)frank(dot)uvena(dot)de>
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 /**
24 * @file editor.h
25 * Editor-related functions for @ref GeanyEditor.
26 * Geany uses the Scintilla editing widget, and this file is mostly built around
27 * Scintilla's functionality.
28 * @see sciwrappers.h.
30 /* Callbacks for the Scintilla widget (ScintillaObject).
31 * Most important is the sci-notify callback, handled in on_editor_notification().
32 * This includes auto-indentation, comments, auto-completion, calltips, etc.
33 * Also some general Scintilla-related functions.
36 #ifdef HAVE_CONFIG_H
37 # include "config.h"
38 #endif
40 #include "editor.h"
42 #include "app.h"
43 #include "callbacks.h"
44 #include "dialogs.h"
45 #include "documentprivate.h"
46 #include "filetypesprivate.h"
47 #include "geanyobject.h"
48 #include "highlighting.h"
49 #include "keybindings.h"
50 #include "main.h"
51 #include "prefs.h"
52 #include "projectprivate.h"
53 #include "sciwrappers.h"
54 #include "support.h"
55 #include "symbols.h"
56 #include "templates.h"
57 #include "ui_utils.h"
58 #include "utils.h"
60 #include "SciLexer.h"
62 #include "gtkcompat.h"
64 #include <ctype.h>
65 #include <string.h>
67 #include <gdk/gdkkeysyms.h>
70 /* Note: use sciwrappers.h instead where possible.
71 * Do not use SSM in files unrelated to scintilla. */
72 #define SSM(s, m, w, l) scintilla_send_message(s, m, w, l)
74 static GHashTable *snippet_hash = NULL;
75 static GQueue *snippet_offsets = NULL;
76 static gint snippet_cursor_insert_pos;
77 static GtkAccelGroup *snippet_accel_group = NULL;
78 static gboolean autocomplete_scope_shown = FALSE;
80 static const gchar geany_cursor_marker[] = "__GEANY_CURSOR_MARKER__";
82 /* holds word under the mouse or keyboard cursor */
83 static gchar current_word[GEANY_MAX_WORD_LENGTH];
85 /* Initialised in keyfile.c. */
86 GeanyEditorPrefs editor_prefs;
88 EditorInfo editor_info = {current_word, -1};
90 static struct
92 gchar *text;
93 gboolean set;
94 gchar *last_word;
95 guint tag_index;
96 gint pos;
97 ScintillaObject *sci;
98 } calltip = {NULL, FALSE, NULL, 0, 0, NULL};
100 static gchar indent[100];
103 static void on_new_line_added(GeanyEditor *editor);
104 static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch);
105 static void insert_indent_after_line(GeanyEditor *editor, gint line);
106 static void auto_multiline(GeanyEditor *editor, gint pos);
107 static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c);
108 static void close_block(GeanyEditor *editor, gint pos);
109 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos);
110 static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen,
111 const gchar *wc, gboolean stem);
112 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent);
113 static const gchar *snippets_find_completion_by_name(const gchar *type, const gchar *name);
114 static void snippets_make_replacements(GeanyEditor *editor, GString *pattern);
115 static gssize replace_cursor_markers(GeanyEditor *editor, GString *pattern);
116 static GeanyFiletype *editor_get_filetype_at_line(GeanyEditor *editor, gint line);
117 static gboolean sci_is_blank_line(ScintillaObject *sci, gint line);
120 void editor_snippets_free(void)
122 g_hash_table_destroy(snippet_hash);
123 g_queue_free(snippet_offsets);
124 gtk_window_remove_accel_group(GTK_WINDOW(main_widgets.window), snippet_accel_group);
128 static void snippets_load(GKeyFile *sysconfig, GKeyFile *userconfig)
130 gsize i, j, len = 0, len_keys = 0;
131 gchar **groups_user, **groups_sys;
132 gchar **keys_user, **keys_sys;
133 gchar *value;
134 GHashTable *tmp;
136 /* keys are strings, values are GHashTables, so use g_free and g_hash_table_destroy */
137 snippet_hash =
138 g_hash_table_new_full(g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_hash_table_destroy);
140 /* first read all globally defined auto completions */
141 groups_sys = g_key_file_get_groups(sysconfig, &len);
142 for (i = 0; i < len; i++)
144 if (strcmp(groups_sys[i], "Keybindings") == 0)
145 continue;
146 keys_sys = g_key_file_get_keys(sysconfig, groups_sys[i], &len_keys, NULL);
147 /* create new hash table for the read section (=> filetype) */
148 tmp = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
149 g_hash_table_insert(snippet_hash, g_strdup(groups_sys[i]), tmp);
151 for (j = 0; j < len_keys; j++)
153 g_hash_table_insert(tmp, g_strdup(keys_sys[j]),
154 utils_get_setting_string(sysconfig, groups_sys[i], keys_sys[j], ""));
156 g_strfreev(keys_sys);
158 g_strfreev(groups_sys);
160 /* now read defined completions in user's configuration directory and add / replace them */
161 groups_user = g_key_file_get_groups(userconfig, &len);
162 for (i = 0; i < len; i++)
164 if (strcmp(groups_user[i], "Keybindings") == 0)
165 continue;
166 keys_user = g_key_file_get_keys(userconfig, groups_user[i], &len_keys, NULL);
168 tmp = g_hash_table_lookup(snippet_hash, groups_user[i]);
169 if (tmp == NULL)
170 { /* new key found, create hash table */
171 tmp = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
172 g_hash_table_insert(snippet_hash, g_strdup(groups_user[i]), tmp);
174 for (j = 0; j < len_keys; j++)
176 value = g_hash_table_lookup(tmp, keys_user[j]);
177 if (value == NULL)
178 { /* value = NULL means the key doesn't yet exist, so insert */
179 g_hash_table_insert(tmp, g_strdup(keys_user[j]),
180 utils_get_setting_string(userconfig, groups_user[i], keys_user[j], ""));
182 else
183 { /* old key and value will be freed by destroy function (g_free) */
184 g_hash_table_replace(tmp, g_strdup(keys_user[j]),
185 utils_get_setting_string(userconfig, groups_user[i], keys_user[j], ""));
188 g_strfreev(keys_user);
190 g_strfreev(groups_user);
194 static void on_snippet_keybinding_activate(gchar *key)
196 GeanyDocument *doc = document_get_current();
197 const gchar *s;
198 GHashTable *specials;
200 if (!doc || !gtk_widget_has_focus(GTK_WIDGET(doc->editor->sci)))
201 return;
203 s = snippets_find_completion_by_name(doc->file_type->name, key);
204 if (!s) /* allow user to specify keybindings for "special" snippets */
206 specials = g_hash_table_lookup(snippet_hash, "Special");
207 if (G_LIKELY(specials != NULL))
208 s = g_hash_table_lookup(specials, key);
210 if (!s)
212 utils_beep();
213 return;
216 editor_insert_snippet(doc->editor, sci_get_current_position(doc->editor->sci), s);
217 sci_scroll_caret(doc->editor->sci);
221 static void add_kb(GKeyFile *keyfile, const gchar *group, gchar **keys)
223 gsize i;
225 if (!keys)
226 return;
227 for (i = 0; i < g_strv_length(keys); i++)
229 guint key;
230 GdkModifierType mods;
231 gchar *accel_string = g_key_file_get_value(keyfile, group, keys[i], NULL);
233 gtk_accelerator_parse(accel_string, &key, &mods);
234 g_free(accel_string);
236 if (key == 0 && mods == 0)
238 g_warning("Can not parse accelerator \"%s\" from user snippets.conf", accel_string);
239 continue;
241 gtk_accel_group_connect(snippet_accel_group, key, mods, 0,
242 g_cclosure_new_swap((GCallback)on_snippet_keybinding_activate,
243 g_strdup(keys[i]), (GClosureNotify)g_free));
248 static void load_kb(GKeyFile *sysconfig, GKeyFile *userconfig)
250 const gchar kb_group[] = "Keybindings";
251 gchar **keys = g_key_file_get_keys(userconfig, kb_group, NULL, NULL);
252 gchar **ptr;
254 /* remove overridden keys from system keyfile */
255 foreach_strv(ptr, keys)
256 g_key_file_remove_key(sysconfig, kb_group, *ptr, NULL);
258 add_kb(userconfig, kb_group, keys);
259 g_strfreev(keys);
261 keys = g_key_file_get_keys(sysconfig, kb_group, NULL, NULL);
262 add_kb(sysconfig, kb_group, keys);
263 g_strfreev(keys);
267 void editor_snippets_init(void)
269 gchar *sysconfigfile, *userconfigfile;
270 GKeyFile *sysconfig = g_key_file_new();
271 GKeyFile *userconfig = g_key_file_new();
273 snippet_offsets = g_queue_new();
275 sysconfigfile = g_build_filename(app->datadir, "snippets.conf", NULL);
276 userconfigfile = g_build_filename(app->configdir, "snippets.conf", NULL);
278 /* check for old autocomplete.conf files (backwards compatibility) */
279 if (! g_file_test(userconfigfile, G_FILE_TEST_IS_REGULAR))
280 SETPTR(userconfigfile, g_build_filename(app->configdir, "autocomplete.conf", NULL));
282 /* load the actual config files */
283 g_key_file_load_from_file(sysconfig, sysconfigfile, G_KEY_FILE_NONE, NULL);
284 g_key_file_load_from_file(userconfig, userconfigfile, G_KEY_FILE_NONE, NULL);
286 snippets_load(sysconfig, userconfig);
288 /* setup snippet keybindings */
289 snippet_accel_group = gtk_accel_group_new();
290 gtk_window_add_accel_group(GTK_WINDOW(main_widgets.window), snippet_accel_group);
291 load_kb(sysconfig, userconfig);
293 g_free(sysconfigfile);
294 g_free(userconfigfile);
295 g_key_file_free(sysconfig);
296 g_key_file_free(userconfig);
300 static gboolean on_editor_button_press_event(GtkWidget *widget, GdkEventButton *event,
301 gpointer data)
303 GeanyEditor *editor = data;
304 GeanyDocument *doc = editor->document;
306 /* it's very unlikely we got a 'real' click even on 0, 0, so assume it is a
307 * fake event to show the editor menu triggered by a key event where we want to use the
308 * text cursor position. */
309 if (event->x > 0.0 && event->y > 0.0)
310 editor_info.click_pos = sci_get_position_from_xy(editor->sci,
311 (gint)event->x, (gint)event->y, FALSE);
312 else
313 editor_info.click_pos = sci_get_current_position(editor->sci);
315 if (event->button == 1)
317 guint state = keybindings_get_modifiers(event->state);
319 if (event->type == GDK_BUTTON_PRESS && editor_prefs.disable_dnd)
321 gint ss = sci_get_selection_start(editor->sci);
322 sci_set_selection_end(editor->sci, ss);
324 if (event->type == GDK_BUTTON_PRESS && state == GEANY_PRIMARY_MOD_MASK)
326 sci_set_current_position(editor->sci, editor_info.click_pos, FALSE);
328 editor_find_current_word(editor, editor_info.click_pos,
329 current_word, sizeof current_word, NULL);
330 if (*current_word)
331 return symbols_goto_tag(current_word, TRUE);
332 else
333 keybindings_send_command(GEANY_KEY_GROUP_GOTO, GEANY_KEYS_GOTO_MATCHINGBRACE);
334 return TRUE;
336 return document_check_disk_status(doc, FALSE);
339 /* calls the edit popup menu in the editor */
340 if (event->button == 3)
342 gboolean can_goto;
344 /* ensure the editor widget has the focus after this operation */
345 gtk_widget_grab_focus(widget);
347 editor_find_current_word(editor, editor_info.click_pos,
348 current_word, sizeof current_word, NULL);
350 can_goto = sci_has_selection(editor->sci) || current_word[0] != '\0';
351 ui_update_popup_goto_items(can_goto);
352 ui_update_popup_copy_items(doc);
353 ui_update_insert_include_item(doc, 0);
355 g_signal_emit_by_name(geany_object, "update-editor-menu",
356 current_word, editor_info.click_pos, doc);
358 gtk_menu_popup(GTK_MENU(main_widgets.editor_menu),
359 NULL, NULL, NULL, NULL, event->button, event->time);
361 return TRUE;
363 return FALSE;
367 static gboolean is_style_php(gint style)
369 if ((style >= SCE_HPHP_DEFAULT && style <= SCE_HPHP_OPERATOR) ||
370 style == SCE_HPHP_COMPLEX_VARIABLE)
372 return TRUE;
375 return FALSE;
379 static gint editor_get_long_line_type(void)
381 if (app->project)
382 switch (app->project->priv->long_line_behaviour)
384 case 0: /* marker disabled */
385 return 2;
386 case 1: /* use global settings */
387 break;
388 case 2: /* custom (enabled) */
389 return editor_prefs.long_line_type;
392 if (!editor_prefs.long_line_enabled)
393 return 2;
394 else
395 return editor_prefs.long_line_type;
399 static gint editor_get_long_line_column(void)
401 if (app->project && app->project->priv->long_line_behaviour != 1 /* use global settings */)
402 return app->project->priv->long_line_column;
403 else
404 return editor_prefs.long_line_column;
408 #define get_project_pref(id)\
409 (app->project ? app->project->priv->id : editor_prefs.id)
411 static const GeanyEditorPrefs *
412 get_default_prefs(void)
414 static GeanyEditorPrefs eprefs;
416 eprefs = editor_prefs;
418 /* project overrides */
419 eprefs.indentation = (GeanyIndentPrefs*)editor_get_indent_prefs(NULL);
420 eprefs.long_line_type = editor_get_long_line_type();
421 eprefs.long_line_column = editor_get_long_line_column();
422 eprefs.line_wrapping = get_project_pref(line_wrapping);
423 eprefs.line_break_column = get_project_pref(line_break_column);
424 eprefs.auto_continue_multiline = get_project_pref(auto_continue_multiline);
425 return &eprefs;
429 /* Gets the prefs for the editor.
430 * Prefs can be different according to project or document.
431 * @warning Always get a fresh result instead of keeping a pointer to it if the editor/project
432 * settings may have changed, or if this function has been called for a different editor.
433 * @param editor The editor, or @c NULL to get the default prefs.
434 * @return The prefs. */
435 const GeanyEditorPrefs *editor_get_prefs(GeanyEditor *editor)
437 static GeanyEditorPrefs eprefs;
438 const GeanyEditorPrefs *dprefs = get_default_prefs();
440 /* Return the address of the default prefs to allow returning default and editor
441 * pref pointers without invalidating the contents of either. */
442 if (editor == NULL)
443 return dprefs;
445 eprefs = *dprefs;
446 eprefs.indentation = (GeanyIndentPrefs*)editor_get_indent_prefs(editor);
447 /* add other editor & document overrides as needed */
448 return &eprefs;
452 void editor_toggle_fold(GeanyEditor *editor, gint line, gint modifiers)
454 ScintillaObject *sci;
455 gint header;
457 g_return_if_fail(editor != NULL);
459 sci = editor->sci;
460 /* When collapsing a fold range whose starting line is offscreen,
461 * scroll the starting line to display at the top of the view.
462 * Otherwise it can be confusing when the document scrolls down to hide
463 * the folded lines. */
464 if ((sci_get_fold_level(sci, line) & SC_FOLDLEVELNUMBERMASK) > SC_FOLDLEVELBASE &&
465 !(sci_get_fold_level(sci, line) & SC_FOLDLEVELHEADERFLAG))
467 gint parent = sci_get_fold_parent(sci, line);
468 gint first = sci_get_first_visible_line(sci);
470 parent = SSM(sci, SCI_VISIBLEFROMDOCLINE, parent, 0);
471 if (first > parent)
472 SSM(sci, SCI_SETFIRSTVISIBLELINE, parent, 0);
475 /* find the fold header of the given line in case the one clicked isn't a fold point */
476 if (sci_get_fold_level(sci, line) & SC_FOLDLEVELHEADERFLAG)
477 header = line;
478 else
479 header = sci_get_fold_parent(sci, line);
481 if ((editor_prefs.unfold_all_children && ! (modifiers & SCMOD_SHIFT)) ||
482 (! editor_prefs.unfold_all_children && (modifiers & SCMOD_SHIFT)))
484 SSM(sci, SCI_FOLDCHILDREN, header, SC_FOLDACTION_TOGGLE);
486 else
488 SSM(sci, SCI_FOLDLINE, header, SC_FOLDACTION_TOGGLE);
493 static void on_margin_click(GeanyEditor *editor, SCNotification *nt)
495 /* left click to marker margin marks the line */
496 if (nt->margin == 1)
498 gint line = sci_get_line_from_position(editor->sci, nt->position);
500 /*sci_marker_delete_all(editor->sci, 1);*/
501 sci_toggle_marker_at_line(editor->sci, line, 1); /* toggle the marker */
503 /* left click on the folding margin to toggle folding state of current line */
504 else if (nt->margin == 2 && editor_prefs.folding)
506 gint line = sci_get_line_from_position(editor->sci, nt->position);
507 editor_toggle_fold(editor, line, nt->modifiers);
512 static void on_update_ui(GeanyEditor *editor, G_GNUC_UNUSED SCNotification *nt)
514 ScintillaObject *sci = editor->sci;
515 gint pos = sci_get_current_position(sci);
517 /* since Scintilla 2.24, SCN_UPDATEUI is also sent on scrolling though we don't need to handle
518 * this and so ignore every SCN_UPDATEUI events except for content and selection changes */
519 if (! (nt->updated & SC_UPDATE_CONTENT) && ! (nt->updated & SC_UPDATE_SELECTION))
520 return;
522 /* undo / redo menu update */
523 ui_update_popup_reundo_items(editor->document);
525 /* brace highlighting */
526 editor_highlight_braces(editor, pos);
528 ui_update_statusbar(editor->document, pos);
530 #if 0
531 /** experimental code for inverting selections */
533 gint i;
534 for (i = SSM(sci, SCI_GETSELECTIONSTART, 0, 0); i < SSM(sci, SCI_GETSELECTIONEND, 0, 0); i++)
536 /* need to get colour from getstyleat(), but how? */
537 SSM(sci, SCI_STYLESETFORE, STYLE_DEFAULT, 0);
538 SSM(sci, SCI_STYLESETBACK, STYLE_DEFAULT, 0);
541 sci_get_style_at(sci, pos);
543 #endif
547 static void check_line_breaking(GeanyEditor *editor, gint pos)
549 ScintillaObject *sci = editor->sci;
550 gint line, lstart, col;
551 gchar c;
553 if (!editor->line_breaking)
554 return;
556 col = sci_get_col_from_position(sci, pos);
558 line = sci_get_current_line(sci);
560 lstart = sci_get_position_from_line(sci, line);
562 /* use column instead of position which might be different with multibyte characters */
563 if (col < get_project_pref(line_break_column))
564 return;
566 /* look for the last space before line_break_column */
567 pos = MIN(pos, lstart + get_project_pref(line_break_column));
569 while (pos > lstart)
571 c = sci_get_char_at(sci, --pos);
572 if (c == GDK_space)
574 gint diff, last_pos, last_col;
576 /* remember the distance between the current column and the last column on the line
577 * (we use column position in case the previous line gets altered, such as removing
578 * trailing spaces or in case it contains multibyte characters) */
579 last_pos = sci_get_line_end_position(sci, line);
580 last_col = sci_get_col_from_position(sci, last_pos);
581 diff = last_col - col;
583 /* break the line after the space */
584 sci_set_current_position(sci, pos + 1, FALSE);
585 sci_cancel(sci); /* don't select from completion list */
586 sci_send_command(sci, SCI_NEWLINE);
587 line++;
589 /* correct cursor position (might not be at line end) */
590 last_pos = sci_get_line_end_position(sci, line);
591 last_col = sci_get_col_from_position(sci, last_pos); /* get last column on line */
592 /* last column - distance is the desired column, then retrieve its document position */
593 pos = sci_get_position_from_col(sci, line, last_col - diff);
594 sci_set_current_position(sci, pos, FALSE);
595 sci_scroll_caret(sci);
596 return;
602 static void show_autocomplete(ScintillaObject *sci, gsize rootlen, GString *words)
604 /* hide autocompletion if only option is already typed */
605 if (rootlen >= words->len ||
606 (words->str[rootlen] == '?' && rootlen >= words->len - 2))
608 sci_send_command(sci, SCI_AUTOCCANCEL);
609 return;
611 /* store whether a calltip is showing, so we can reshow it after autocompletion */
612 calltip.set = (gboolean) SSM(sci, SCI_CALLTIPACTIVE, 0, 0);
613 SSM(sci, SCI_AUTOCSHOW, rootlen, (sptr_t) words->str);
617 static void show_tags_list(GeanyEditor *editor, const GPtrArray *tags, gsize rootlen)
619 ScintillaObject *sci = editor->sci;
621 g_return_if_fail(tags);
623 if (tags->len > 0)
625 GString *words = g_string_sized_new(150);
626 guint j;
628 for (j = 0; j < tags->len; ++j)
630 TMTag *tag = tags->pdata[j];
632 if (j > 0)
633 g_string_append_c(words, '\n');
635 if (j == editor_prefs.autocompletion_max_entries)
637 g_string_append(words, "...");
638 break;
640 g_string_append(words, tag->name);
642 /* for now, tag types don't all follow C, so just look at arglist */
643 if (!EMPTY(tag->arglist))
644 g_string_append(words, "?2");
645 else
646 g_string_append(words, "?1");
648 show_autocomplete(sci, rootlen, words);
649 g_string_free(words, TRUE);
654 /* do not use with long strings */
655 static gboolean match_last_chars(ScintillaObject *sci, gint pos, const gchar *str)
657 gsize len = strlen(str);
658 gchar *buf;
660 g_return_val_if_fail(len < 100, FALSE);
662 if ((gint)len > pos)
663 return FALSE;
665 buf = g_alloca(len + 1);
666 sci_get_text_range(sci, pos - len, pos, buf);
667 return strcmp(str, buf) == 0;
671 static gboolean reshow_calltip(gpointer data)
673 GeanyDocument *doc;
675 g_return_val_if_fail(calltip.sci != NULL, FALSE);
677 SSM(calltip.sci, SCI_CALLTIPCANCEL, 0, 0);
678 doc = document_get_current();
680 if (doc && doc->editor->sci == calltip.sci)
682 /* we use the position where the calltip was previously started as SCI_GETCURRENTPOS
683 * may be completely wrong in case the user cancelled the auto completion with the mouse */
684 SSM(calltip.sci, SCI_CALLTIPSHOW, calltip.pos, (sptr_t) calltip.text);
686 return FALSE;
690 static void request_reshowing_calltip(SCNotification *nt)
692 if (calltip.set)
694 /* delay the reshow of the calltip window to make sure it is actually displayed,
695 * without it might be not visible on SCN_AUTOCCANCEL. the priority is set to
696 * low to hopefully make Scintilla's events happen before reshowing since they
697 * seem to re-cancel the calltip on autoc menu hiding too */
698 g_idle_add_full(G_PRIORITY_LOW, reshow_calltip, NULL, NULL);
703 static gboolean autocomplete_scope(GeanyEditor *editor, const gchar *root, gsize rootlen)
705 ScintillaObject *sci = editor->sci;
706 gint pos = sci_get_current_position(editor->sci);
707 gchar typed = sci_get_char_at(sci, pos - 1);
708 gchar brace_char;
709 gchar *name;
710 GeanyFiletype *ft = editor->document->file_type;
711 GPtrArray *tags;
712 gboolean function = FALSE;
713 gboolean member;
714 gboolean scope_sep_typed = FALSE;
715 gboolean ret = FALSE;
716 const gchar *current_scope;
717 const gchar *context_sep = tm_tag_context_separator(ft->lang);
719 if (autocomplete_scope_shown)
721 /* move at the operator position */
722 pos -= rootlen;
724 /* allow for a space between word and operator */
725 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
726 pos--;
728 if (pos > 0)
729 typed = sci_get_char_at(sci, pos - 1);
732 /* make sure to keep in sync with similar checks below */
733 if (match_last_chars(sci, pos, context_sep))
735 pos -= strlen(context_sep);
736 scope_sep_typed = TRUE;
738 else if (typed == '.')
739 pos -= 1;
740 else if ((ft->id == GEANY_FILETYPES_C || ft->id == GEANY_FILETYPES_CPP) &&
741 match_last_chars(sci, pos, "->"))
742 pos -= 2;
743 else if (ft->id == GEANY_FILETYPES_CPP && match_last_chars(sci, pos, "->*"))
744 pos -= 3;
745 else
746 return FALSE;
748 /* allow for a space between word and operator */
749 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
750 pos--;
752 /* if function or array index, skip to matching brace */
753 brace_char = sci_get_char_at(sci, pos - 1);
754 if (pos > 0 && (brace_char == ')' || brace_char == ']'))
756 gint brace_pos = sci_find_matching_brace(sci, pos - 1);
758 if (brace_pos != -1)
760 pos = brace_pos;
761 function = brace_char == ')';
764 /* allow for a space between opening brace and name */
765 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
766 pos--;
769 name = editor_get_word_at_pos(editor, pos, NULL);
770 if (!name)
771 return FALSE;
773 /* check if invoked on member */
774 pos -= strlen(name);
775 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
776 pos--;
777 /* make sure to keep in sync with similar checks above */
778 member = match_last_chars(sci, pos, ".") || match_last_chars(sci, pos, context_sep) ||
779 match_last_chars(sci, pos, "->") || match_last_chars(sci, pos, "->*");
781 if (symbols_get_current_scope(editor->document, &current_scope) == -1)
782 current_scope = "";
783 tags = tm_workspace_find_scope_members(editor->document->tm_file, name, function,
784 member, current_scope, scope_sep_typed);
785 if (tags)
787 GPtrArray *filtered = g_ptr_array_new();
788 TMTag *tag;
789 guint i;
791 foreach_ptr_array(tag, i, tags)
793 if (g_str_has_prefix(tag->name, root))
794 g_ptr_array_add(filtered, tag);
797 if (filtered->len > 0)
799 show_tags_list(editor, filtered, rootlen);
800 ret = TRUE;
803 g_ptr_array_free(tags, TRUE);
804 g_ptr_array_free(filtered, TRUE);
807 g_free(name);
808 return ret;
812 static void on_char_added(GeanyEditor *editor, SCNotification *nt)
814 ScintillaObject *sci = editor->sci;
815 gint pos = sci_get_current_position(sci);
817 switch (nt->ch)
819 case '\r':
820 { /* simple indentation (only for CR format) */
821 if (sci_get_eol_mode(sci) == SC_EOL_CR)
822 on_new_line_added(editor);
823 break;
825 case '\n':
826 { /* simple indentation (for CR/LF and LF format) */
827 on_new_line_added(editor);
828 break;
830 case '>':
831 editor_start_auto_complete(editor, pos, FALSE); /* C/C++ ptr-> scope completion */
832 /* fall through */
833 case '/':
834 { /* close xml-tags */
835 handle_xml(editor, pos, nt->ch);
836 break;
838 case '(':
840 auto_close_chars(sci, pos, nt->ch);
841 /* show calltips */
842 editor_show_calltip(editor, --pos);
843 break;
845 case ')':
846 { /* hide calltips */
847 if (SSM(sci, SCI_CALLTIPACTIVE, 0, 0))
849 SSM(sci, SCI_CALLTIPCANCEL, 0, 0);
851 g_free(calltip.text);
852 calltip.text = NULL;
853 calltip.pos = 0;
854 calltip.sci = NULL;
855 calltip.set = FALSE;
856 break;
858 case '{':
859 case '[':
860 case '"':
861 case '\'':
863 auto_close_chars(sci, pos, nt->ch);
864 break;
866 case '}':
867 { /* closing bracket handling */
868 if (editor->auto_indent)
869 close_block(editor, pos - 1);
870 break;
872 /* scope autocompletion */
873 case '.':
874 case ':': /* C/C++ class:: syntax */
875 /* tag autocompletion */
876 default:
877 #if 0
878 if (! editor_start_auto_complete(editor, pos, FALSE))
879 request_reshowing_calltip(nt);
880 #else
881 editor_start_auto_complete(editor, pos, FALSE);
882 #endif
884 check_line_breaking(editor, pos);
888 /* expand() and fold_changed() are copied from SciTE (thanks) to fix #1923350. */
889 static void expand(ScintillaObject *sci, gint *line, gboolean doExpand,
890 gboolean force, gint visLevels, gint level)
892 gint lineMaxSubord = SSM(sci, SCI_GETLASTCHILD, *line, level & SC_FOLDLEVELNUMBERMASK);
893 gint levelLine = level;
894 (*line)++;
895 while (*line <= lineMaxSubord)
897 if (force)
899 if (visLevels > 0)
900 SSM(sci, SCI_SHOWLINES, *line, *line);
901 else
902 SSM(sci, SCI_HIDELINES, *line, *line);
904 else
906 if (doExpand)
907 SSM(sci, SCI_SHOWLINES, *line, *line);
909 if (levelLine == -1)
910 levelLine = SSM(sci, SCI_GETFOLDLEVEL, *line, 0);
911 if (levelLine & SC_FOLDLEVELHEADERFLAG)
913 if (force)
915 if (visLevels > 1)
916 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
917 else
918 SSM(sci, SCI_SETFOLDEXPANDED, *line, 0);
919 expand(sci, line, doExpand, force, visLevels - 1, -1);
921 else
923 if (doExpand)
925 if (!sci_get_fold_expanded(sci, *line))
926 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
927 expand(sci, line, TRUE, force, visLevels - 1, -1);
929 else
931 expand(sci, line, FALSE, force, visLevels - 1, -1);
935 else
937 (*line)++;
943 static void fold_changed(ScintillaObject *sci, gint line, gint levelNow, gint levelPrev)
945 if (levelNow & SC_FOLDLEVELHEADERFLAG)
947 if (! (levelPrev & SC_FOLDLEVELHEADERFLAG))
949 /* Adding a fold point */
950 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
951 if (!SSM(sci, SCI_GETALLLINESVISIBLE, 0, 0))
952 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
955 else if (levelPrev & SC_FOLDLEVELHEADERFLAG)
957 if (! sci_get_fold_expanded(sci, line))
958 { /* Removing the fold from one that has been contracted so should expand
959 * otherwise lines are left invisible with no way to make them visible */
960 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
961 if (!SSM(sci, SCI_GETALLLINESVISIBLE, 0, 0))
962 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
965 if (! (levelNow & SC_FOLDLEVELWHITEFLAG) &&
966 ((levelPrev & SC_FOLDLEVELNUMBERMASK) > (levelNow & SC_FOLDLEVELNUMBERMASK)))
968 if (!SSM(sci, SCI_GETALLLINESVISIBLE, 0, 0)) {
969 /* See if should still be hidden */
970 gint parentLine = sci_get_fold_parent(sci, line);
971 if (parentLine < 0)
973 SSM(sci, SCI_SHOWLINES, line, line);
975 else if (sci_get_fold_expanded(sci, parentLine) &&
976 sci_get_line_is_visible(sci, parentLine))
978 SSM(sci, SCI_SHOWLINES, line, line);
985 static void ensure_range_visible(ScintillaObject *sci, gint posStart, gint posEnd,
986 gboolean enforcePolicy)
988 gint lineStart = sci_get_line_from_position(sci, MIN(posStart, posEnd));
989 gint lineEnd = sci_get_line_from_position(sci, MAX(posStart, posEnd));
990 gint line;
992 for (line = lineStart; line <= lineEnd; line++)
994 SSM(sci, enforcePolicy ? SCI_ENSUREVISIBLEENFORCEPOLICY : SCI_ENSUREVISIBLE, line, 0);
999 static void auto_update_margin_width(GeanyEditor *editor)
1001 gint next_linecount = 1;
1002 gint linecount = sci_get_line_count(editor->sci);
1003 GeanyDocument *doc = editor->document;
1005 while (next_linecount <= linecount)
1006 next_linecount *= 10;
1008 if (editor->document->priv->line_count != next_linecount)
1010 doc->priv->line_count = next_linecount;
1011 sci_set_line_numbers(editor->sci, TRUE);
1016 static void partial_complete(ScintillaObject *sci, const gchar *text)
1018 gint pos = sci_get_current_position(sci);
1020 sci_insert_text(sci, pos, text);
1021 sci_set_current_position(sci, pos + strlen(text), TRUE);
1025 /* Complete the next word part from @a entry */
1026 static gboolean check_partial_completion(GeanyEditor *editor, const gchar *entry)
1028 gchar *stem, *ptr, *text = utils_strdupa(entry);
1030 read_current_word(editor, -1, current_word, sizeof current_word, NULL, TRUE);
1031 stem = current_word;
1032 if (strstr(text, stem) != text)
1033 return FALSE; /* shouldn't happen */
1034 if (strlen(text) <= strlen(stem))
1035 return FALSE;
1037 text += strlen(stem); /* skip stem */
1038 ptr = strstr(text + 1, "_");
1039 if (ptr)
1041 ptr[1] = '\0';
1042 partial_complete(editor->sci, text);
1043 return TRUE;
1045 else
1047 /* CamelCase */
1048 foreach_str(ptr, text + 1)
1050 if (!ptr[0])
1051 break;
1052 if (g_ascii_isupper(*ptr) && g_ascii_islower(ptr[1]))
1054 ptr[0] = '\0';
1055 partial_complete(editor->sci, text);
1056 return TRUE;
1060 return FALSE;
1064 /* Callback for the "sci-notify" signal to emit a "editor-notify" signal.
1065 * Plugins can connect to the "editor-notify" signal. */
1066 void editor_sci_notify_cb(G_GNUC_UNUSED GtkWidget *widget, G_GNUC_UNUSED gint scn,
1067 gpointer scnt, gpointer data)
1069 GeanyEditor *editor = data;
1070 gboolean retval;
1072 g_return_if_fail(editor != NULL);
1074 g_signal_emit_by_name(geany_object, "editor-notify", editor, scnt, &retval);
1078 static gboolean on_editor_notify(G_GNUC_UNUSED GObject *object, GeanyEditor *editor,
1079 SCNotification *nt, G_GNUC_UNUSED gpointer data)
1081 ScintillaObject *sci = editor->sci;
1082 GeanyDocument *doc = editor->document;
1084 switch (nt->nmhdr.code)
1086 case SCN_SAVEPOINTLEFT:
1087 document_set_text_changed(doc, TRUE);
1088 break;
1090 case SCN_SAVEPOINTREACHED:
1091 document_set_text_changed(doc, FALSE);
1092 break;
1094 case SCN_MODIFYATTEMPTRO:
1095 utils_beep();
1096 break;
1098 case SCN_MARGINCLICK:
1099 on_margin_click(editor, nt);
1100 break;
1102 case SCN_UPDATEUI:
1103 on_update_ui(editor, nt);
1104 break;
1106 case SCN_PAINTED:
1107 /* Visible lines are only laid out accurately just before painting,
1108 * so we need to only call editor_scroll_to_line here, because the document
1109 * may have line wrapping and folding enabled.
1110 * http://scintilla.sourceforge.net/ScintillaDoc.html#LineWrapping
1111 * This is important e.g. when loading a session and switching pages
1112 * and having the cursor scroll in view. */
1113 /* FIXME: Really we want to do this just before painting, not after it
1114 * as it will cause repainting. */
1115 if (editor->scroll_percent > 0.0F)
1117 editor_scroll_to_line(editor, -1, editor->scroll_percent);
1118 /* disable further scrolling */
1119 editor->scroll_percent = -1.0F;
1121 break;
1123 case SCN_MODIFIED:
1124 if (editor_prefs.show_linenumber_margin && (nt->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT)) && nt->linesAdded)
1126 /* automatically adjust Scintilla's line numbers margin width */
1127 auto_update_margin_width(editor);
1129 if (nt->modificationType & SC_STARTACTION && ! ignore_callback)
1131 /* get notified about undo changes */
1132 document_undo_add(doc, UNDO_SCINTILLA, NULL);
1134 if (editor_prefs.folding && (nt->modificationType & SC_MOD_CHANGEFOLD) != 0)
1136 /* handle special fold cases, e.g. #1923350 */
1137 fold_changed(sci, nt->line, nt->foldLevelNow, nt->foldLevelPrev);
1139 if (nt->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT))
1141 document_update_tag_list_in_idle(doc);
1143 break;
1145 case SCN_CHARADDED:
1146 on_char_added(editor, nt);
1147 break;
1149 case SCN_USERLISTSELECTION:
1150 if (nt->listType == 1)
1152 sci_add_text(sci, nt->text);
1154 break;
1156 case SCN_AUTOCSELECTION:
1157 if (g_str_equal(nt->text, "..."))
1159 sci_cancel(sci);
1160 utils_beep();
1161 break;
1163 /* fall through */
1164 case SCN_AUTOCCANCELLED:
1165 /* now that autocomplete is finishing or was cancelled, reshow calltips
1166 * if they were showing */
1167 autocomplete_scope_shown = FALSE;
1168 request_reshowing_calltip(nt);
1169 break;
1170 case SCN_NEEDSHOWN:
1171 ensure_range_visible(sci, nt->position, nt->position + nt->length, FALSE);
1172 break;
1174 case SCN_URIDROPPED:
1175 if (nt->text != NULL)
1177 document_open_file_list(nt->text, strlen(nt->text));
1179 break;
1181 case SCN_CALLTIPCLICK:
1182 if (nt->position > 0)
1184 switch (nt->position)
1186 case 1: /* up arrow */
1187 if (calltip.tag_index > 0)
1188 calltip.tag_index--;
1189 break;
1191 case 2: calltip.tag_index++; break; /* down arrow */
1193 editor_show_calltip(editor, -1);
1195 break;
1197 case SCN_ZOOM:
1198 /* recalculate line margin width */
1199 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin);
1200 break;
1202 /* we always return FALSE here to let plugins handle the event too */
1203 return FALSE;
1207 /* Note: this is the same as sci_get_tab_width(), but is still useful when you don't have
1208 * a scintilla pointer. */
1209 static gint get_tab_width(const GeanyIndentPrefs *indent_prefs)
1211 if (indent_prefs->type == GEANY_INDENT_TYPE_BOTH)
1212 return indent_prefs->hard_tab_width;
1214 return indent_prefs->width; /* tab width = indent width */
1218 /* Returns a string containing width chars of whitespace, filled with simple space
1219 * characters or with the right number of tab characters, according to the indent prefs.
1220 * (Result is filled with tabs *and* spaces if width isn't a multiple of
1221 * the tab width). */
1222 static gchar *
1223 get_whitespace(const GeanyIndentPrefs *iprefs, gint width)
1225 g_return_val_if_fail(width >= 0, NULL);
1227 if (width == 0)
1228 return g_strdup("");
1230 if (iprefs->type == GEANY_INDENT_TYPE_SPACES)
1232 return g_strnfill(width, ' ');
1234 else
1235 { /* first fill text with tabs and fill the rest with spaces */
1236 const gint tab_width = get_tab_width(iprefs);
1237 gint tabs = width / tab_width;
1238 gint spaces = width % tab_width;
1239 gint len = tabs + spaces;
1240 gchar *str;
1242 str = g_malloc(len + 1);
1244 memset(str, '\t', tabs);
1245 memset(str + tabs, ' ', spaces);
1246 str[len] = '\0';
1247 return str;
1252 static const GeanyIndentPrefs *
1253 get_default_indent_prefs(void)
1255 static GeanyIndentPrefs iprefs;
1257 iprefs = app->project ? *app->project->priv->indentation : *editor_prefs.indentation;
1258 return &iprefs;
1262 /** Gets the indentation prefs for the editor.
1263 * Prefs can be different according to project or document.
1264 * @warning Always get a fresh result instead of keeping a pointer to it if the editor/project
1265 * settings may have changed, or if this function has been called for a different editor.
1266 * @param editor @nullable The editor, or @c NULL to get the default indent prefs.
1267 * @return The indent prefs. */
1268 GEANY_API_SYMBOL
1269 const GeanyIndentPrefs *
1270 editor_get_indent_prefs(GeanyEditor *editor)
1272 static GeanyIndentPrefs iprefs;
1273 const GeanyIndentPrefs *dprefs = get_default_indent_prefs();
1275 /* Return the address of the default prefs to allow returning default and editor
1276 * pref pointers without invalidating the contents of either. */
1277 if (editor == NULL)
1278 return dprefs;
1280 iprefs = *dprefs;
1281 iprefs.type = editor->indent_type;
1282 iprefs.width = editor->indent_width;
1284 /* if per-document auto-indent is enabled, but we don't have a global mode set,
1285 * just use basic auto-indenting */
1286 if (editor->auto_indent && iprefs.auto_indent_mode == GEANY_AUTOINDENT_NONE)
1287 iprefs.auto_indent_mode = GEANY_AUTOINDENT_BASIC;
1289 if (!editor->auto_indent)
1290 iprefs.auto_indent_mode = GEANY_AUTOINDENT_NONE;
1292 return &iprefs;
1296 static void on_new_line_added(GeanyEditor *editor)
1298 ScintillaObject *sci = editor->sci;
1299 gint line = sci_get_current_line(sci);
1301 /* simple indentation */
1302 if (editor->auto_indent)
1304 insert_indent_after_line(editor, line - 1);
1307 if (get_project_pref(auto_continue_multiline))
1308 { /* " * " auto completion in multiline C/C++/D/Java comments */
1309 auto_multiline(editor, line);
1312 if (editor_prefs.newline_strip)
1313 { /* strip the trailing spaces on the previous line */
1314 editor_strip_line_trailing_spaces(editor, line - 1);
1319 static gboolean lexer_has_braces(ScintillaObject *sci)
1321 gint lexer = sci_get_lexer(sci);
1323 switch (lexer)
1325 case SCLEX_CPP:
1326 case SCLEX_D:
1327 case SCLEX_HTML: /* for PHP & JS */
1328 case SCLEX_PHPSCRIPT:
1329 case SCLEX_PASCAL: /* for multiline comments? */
1330 case SCLEX_BASH:
1331 case SCLEX_PERL:
1332 case SCLEX_TCL:
1333 case SCLEX_R:
1334 case SCLEX_RUST:
1335 return TRUE;
1336 default:
1337 return FALSE;
1342 /* Read indent chars for the line that pos is on into indent global variable.
1343 * Note: Use sci_get_line_indentation() and get_whitespace()/editor_insert_text_block()
1344 * instead in any new code. */
1345 static void read_indent(GeanyEditor *editor, gint pos)
1347 ScintillaObject *sci = editor->sci;
1348 guint i, len, j = 0;
1349 gint line;
1350 gchar *linebuf;
1352 line = sci_get_line_from_position(sci, pos);
1354 len = sci_get_line_length(sci, line);
1355 linebuf = sci_get_line(sci, line);
1357 for (i = 0; i < len && j <= (sizeof(indent) - 1); i++)
1359 if (linebuf[i] == ' ' || linebuf[i] == '\t') /* simple indentation */
1360 indent[j++] = linebuf[i];
1361 else
1362 break;
1364 indent[j] = '\0';
1365 g_free(linebuf);
1369 static gint get_brace_indent(ScintillaObject *sci, gint line)
1371 gint start = sci_get_position_from_line(sci, line);
1372 gint end = sci_get_line_end_position(sci, line) - 1;
1373 gint lexer = sci_get_lexer(sci);
1374 gint count = 0;
1375 gint pos;
1377 for (pos = end; pos >= start && count < 1; pos--)
1379 if (highlighting_is_code_style(lexer, sci_get_style_at(sci, pos)))
1381 gchar c = sci_get_char_at(sci, pos);
1383 if (c == '{')
1384 count ++;
1385 else if (c == '}')
1386 count --;
1390 return count > 0 ? 1 : 0;
1394 /* gets the last code position on a line
1395 * warning: if there is no code position on the line, returns the start position */
1396 static gint get_sci_line_code_end_position(ScintillaObject *sci, gint line)
1398 gint start = sci_get_position_from_line(sci, line);
1399 gint lexer = sci_get_lexer(sci);
1400 gint pos;
1402 for (pos = sci_get_line_end_position(sci, line) - 1; pos > start; pos--)
1404 gint style = sci_get_style_at(sci, pos);
1406 if (highlighting_is_code_style(lexer, style) && ! isspace(sci_get_char_at(sci, pos)))
1407 break;
1410 return pos;
1414 static gint get_python_indent(ScintillaObject *sci, gint line)
1416 gint last_char = get_sci_line_code_end_position(sci, line);
1418 /* add extra indentation for Python after colon */
1419 if (sci_get_char_at(sci, last_char) == ':' &&
1420 sci_get_style_at(sci, last_char) == SCE_P_OPERATOR)
1422 return 1;
1424 return 0;
1428 static gint get_xml_indent(ScintillaObject *sci, gint line)
1430 gboolean need_close = FALSE;
1431 gint end = get_sci_line_code_end_position(sci, line);
1432 gint pos;
1434 /* don't indent if there's a closing tag to the right of the cursor */
1435 pos = sci_get_current_position(sci);
1436 if (sci_get_char_at(sci, pos) == '<' &&
1437 sci_get_char_at(sci, pos + 1) == '/')
1438 return 0;
1440 if (sci_get_char_at(sci, end) == '>' &&
1441 sci_get_char_at(sci, end - 1) != '/')
1443 gint style = sci_get_style_at(sci, end);
1445 if (style == SCE_H_TAG || style == SCE_H_TAGUNKNOWN)
1447 gint start = sci_get_position_from_line(sci, line);
1448 gchar *line_contents = sci_get_contents_range(sci, start, end + 1);
1449 gchar *opened_tag_name = utils_find_open_xml_tag(line_contents, end + 1 - start);
1451 if (!EMPTY(opened_tag_name))
1453 need_close = TRUE;
1454 if (sci_get_lexer(sci) == SCLEX_HTML && utils_is_short_html_tag(opened_tag_name))
1455 need_close = FALSE;
1457 g_free(line_contents);
1458 g_free(opened_tag_name);
1462 return need_close ? 1 : 0;
1466 static gint get_indent_size_after_line(GeanyEditor *editor, gint line)
1468 ScintillaObject *sci = editor->sci;
1469 gint size;
1470 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1472 g_return_val_if_fail(line >= 0, 0);
1474 size = sci_get_line_indentation(sci, line);
1476 if (iprefs->auto_indent_mode > GEANY_AUTOINDENT_BASIC)
1478 gint additional_indent = 0;
1480 if (lexer_has_braces(sci))
1481 additional_indent = iprefs->width * get_brace_indent(sci, line);
1482 else if (sci_get_lexer(sci) == SCLEX_PYTHON) /* Python/Cython */
1483 additional_indent = iprefs->width * get_python_indent(sci, line);
1485 /* HTML lexer "has braces" because of PHP and JavaScript. If get_brace_indent() did not
1486 * recommend us to insert additional indent, we are probably not in PHP/JavaScript chunk and
1487 * should make the XML-related check */
1488 if (additional_indent == 0 &&
1489 (sci_get_lexer(sci) == SCLEX_HTML ||
1490 sci_get_lexer(sci) == SCLEX_XML) &&
1491 editor->document->file_type->priv->xml_indent_tags)
1493 size += iprefs->width * get_xml_indent(sci, line);
1496 size += additional_indent;
1498 return size;
1502 static void insert_indent_after_line(GeanyEditor *editor, gint line)
1504 ScintillaObject *sci = editor->sci;
1505 gint line_indent = sci_get_line_indentation(sci, line);
1506 gint size = get_indent_size_after_line(editor, line);
1507 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1508 gchar *text;
1510 if (size == 0)
1511 return;
1513 if (iprefs->type == GEANY_INDENT_TYPE_TABS && size == line_indent)
1515 /* support tab indents, space aligns style - copy last line 'indent' exactly */
1516 gint start = sci_get_position_from_line(sci, line);
1517 gint end = sci_get_line_indent_position(sci, line);
1519 text = sci_get_contents_range(sci, start, end);
1521 else
1523 text = get_whitespace(iprefs, size);
1525 sci_add_text(sci, text);
1526 g_free(text);
1530 static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c)
1532 const gchar *closing_char = NULL;
1533 gint end_pos = -1;
1535 if (utils_isbrace(c, 0))
1536 end_pos = sci_find_matching_brace(sci, pos - 1);
1538 switch (c)
1540 case '(':
1541 if ((editor_prefs.autoclose_chars & GEANY_AC_PARENTHESIS) && end_pos == -1)
1542 closing_char = ")";
1543 break;
1544 case '{':
1545 if ((editor_prefs.autoclose_chars & GEANY_AC_CBRACKET) && end_pos == -1)
1546 closing_char = "}";
1547 break;
1548 case '[':
1549 if ((editor_prefs.autoclose_chars & GEANY_AC_SBRACKET) && end_pos == -1)
1550 closing_char = "]";
1551 break;
1552 case '\'':
1553 if (editor_prefs.autoclose_chars & GEANY_AC_SQUOTE)
1554 closing_char = "'";
1555 break;
1556 case '"':
1557 if (editor_prefs.autoclose_chars & GEANY_AC_DQUOTE)
1558 closing_char = "\"";
1559 break;
1562 if (closing_char != NULL)
1564 sci_add_text(sci, closing_char);
1565 sci_set_current_position(sci, pos, TRUE);
1570 /* Finds a corresponding matching brace to the given pos
1571 * (this is taken from Scintilla Editor.cxx,
1572 * fit to work with close_block) */
1573 static gint brace_match(ScintillaObject *sci, gint pos)
1575 gchar chBrace = sci_get_char_at(sci, pos);
1576 gchar chSeek = utils_brace_opposite(chBrace);
1577 gchar chAtPos;
1578 gint direction = -1;
1579 gint styBrace;
1580 gint depth = 1;
1581 gint styAtPos;
1583 /* Hack: we need the style at @p pos but it isn't computed yet, so force styling
1584 * of this very position */
1585 sci_colourise(sci, pos, pos + 1);
1587 styBrace = sci_get_style_at(sci, pos);
1589 if (utils_is_opening_brace(chBrace, editor_prefs.brace_match_ltgt))
1590 direction = 1;
1592 pos += direction;
1593 while ((pos >= 0) && (pos < sci_get_length(sci)))
1595 chAtPos = sci_get_char_at(sci, pos);
1596 styAtPos = sci_get_style_at(sci, pos);
1598 if ((pos > sci_get_end_styled(sci)) || (styAtPos == styBrace))
1600 if (chAtPos == chBrace)
1601 depth++;
1602 if (chAtPos == chSeek)
1603 depth--;
1604 if (depth == 0)
1605 return pos;
1607 pos += direction;
1609 return -1;
1613 /* Called after typing '}'. */
1614 static void close_block(GeanyEditor *editor, gint pos)
1616 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1617 gint x = 0, cnt = 0;
1618 gint line, line_len;
1619 gchar *text, *line_buf;
1620 ScintillaObject *sci;
1621 gint line_indent, last_indent;
1623 if (iprefs->auto_indent_mode < GEANY_AUTOINDENT_CURRENTCHARS)
1624 return;
1625 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
1627 sci = editor->sci;
1629 if (! lexer_has_braces(sci))
1630 return;
1632 line = sci_get_line_from_position(sci, pos);
1633 line_len = sci_get_line_end_position(sci, line) - sci_get_position_from_line(sci, line);
1635 /* check that the line is empty, to not kill text in the line */
1636 line_buf = sci_get_line(sci, line);
1637 line_buf[line_len] = '\0';
1638 while (x < line_len)
1640 if (isspace(line_buf[x]))
1641 cnt++;
1642 x++;
1644 g_free(line_buf);
1646 if ((line_len - 1) != cnt)
1647 return;
1649 if (iprefs->auto_indent_mode == GEANY_AUTOINDENT_MATCHBRACES)
1651 gint start_brace = brace_match(sci, pos);
1653 if (start_brace >= 0)
1655 gint line_start;
1656 gint brace_line = sci_get_line_from_position(sci, start_brace);
1657 gint size = sci_get_line_indentation(sci, brace_line);
1658 gchar *ind = get_whitespace(iprefs, size);
1660 text = g_strconcat(ind, "}", NULL);
1661 line_start = sci_get_position_from_line(sci, line);
1662 sci_set_anchor(sci, line_start);
1663 sci_replace_sel(sci, text);
1664 g_free(text);
1665 g_free(ind);
1666 return;
1668 /* fall through - unmatched brace (possibly because of TCL, PHP lexer bugs) */
1671 /* GEANY_AUTOINDENT_CURRENTCHARS */
1672 line_indent = sci_get_line_indentation(sci, line);
1673 last_indent = sci_get_line_indentation(sci, line - 1);
1675 if (line_indent < last_indent)
1676 return;
1677 line_indent -= iprefs->width;
1678 line_indent = MAX(0, line_indent);
1679 sci_set_line_indentation(sci, line, line_indent);
1683 /* checks whether @p c is an ASCII character (e.g. < 0x80) */
1684 #define IS_ASCII(c) (((unsigned char)(c)) < 0x80)
1687 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1688 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1689 * position can be -1, then the current position is used.
1690 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1691 static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen,
1692 const gchar *wc, gboolean stem)
1694 gint line, line_start, startword, endword;
1695 gchar *chunk;
1696 ScintillaObject *sci;
1698 g_return_if_fail(editor != NULL);
1699 sci = editor->sci;
1701 if (pos == -1)
1702 pos = sci_get_current_position(sci);
1704 line = sci_get_line_from_position(sci, pos);
1705 line_start = sci_get_position_from_line(sci, line);
1706 startword = pos - line_start;
1707 endword = pos - line_start;
1709 word[0] = '\0';
1710 chunk = sci_get_line(sci, line);
1712 if (wc == NULL)
1713 wc = GEANY_WORDCHARS;
1715 /* the checks for "c < 0" are to allow any Unicode character which should make the code
1716 * a little bit more Unicode safe, anyway, this allows also any Unicode punctuation,
1717 * TODO: improve this code */
1718 while (startword > 0 && (strchr(wc, chunk[startword - 1]) || ! IS_ASCII(chunk[startword - 1])))
1719 startword--;
1720 if (!stem)
1722 while (chunk[endword] != 0 && (strchr(wc, chunk[endword]) || ! IS_ASCII(chunk[endword])))
1723 endword++;
1726 if (startword != endword)
1728 chunk[endword] = '\0';
1730 g_strlcpy(word, chunk + startword, wordlen); /* ensure null terminated */
1732 else
1733 g_strlcpy(word, "", wordlen);
1735 g_free(chunk);
1739 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1740 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1741 * position can be -1, then the current position is used.
1742 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1743 void editor_find_current_word(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen,
1744 const gchar *wc)
1746 read_current_word(editor, pos, word, wordlen, wc, FALSE);
1750 /* Same as editor_find_current_word() but uses editor's word boundaries to decide what the word
1751 * is. This should be used e.g. to get the word to search for */
1752 void editor_find_current_word_sciwc(GeanyEditor *editor, gint pos, gchar *word, gsize wordlen)
1754 gint start;
1755 gint end;
1757 g_return_if_fail(editor != NULL);
1759 if (pos == -1)
1760 pos = sci_get_current_position(editor->sci);
1762 start = sci_word_start_position(editor->sci, pos, TRUE);
1763 end = sci_word_end_position(editor->sci, pos, TRUE);
1765 if (start == end) /* caret in whitespaces sequence */
1766 *word = 0;
1767 else
1769 if ((guint)(end - start) >= wordlen)
1770 end = start + (wordlen - 1);
1771 sci_get_text_range(editor->sci, start, end, word);
1777 * Finds the word at the position specified by @a pos. If any word is found, it is returned.
1778 * Otherwise NULL is returned.
1779 * Additional wordchars can be specified to define what to consider as a word.
1781 * @param editor The editor to operate on.
1782 * @param pos The position where the word should be read from.
1783 * May be @c -1 to use the current position.
1784 * @param wordchars The wordchars to separate words. wordchars mean all characters to count
1785 * as part of a word. May be @c NULL to use the default wordchars,
1786 * see @ref GEANY_WORDCHARS.
1788 * @return @nullable A newly-allocated string containing the word at the given @a pos or @c NULL.
1789 * Should be freed when no longer needed.
1791 * @since 0.16
1793 GEANY_API_SYMBOL
1794 gchar *editor_get_word_at_pos(GeanyEditor *editor, gint pos, const gchar *wordchars)
1796 static gchar cword[GEANY_MAX_WORD_LENGTH];
1798 g_return_val_if_fail(editor != NULL, FALSE);
1800 read_current_word(editor, pos, cword, sizeof(cword), wordchars, FALSE);
1802 return (*cword == '\0') ? NULL : g_strdup(cword);
1806 /* Read the word up to position @a pos. */
1807 static const gchar *
1808 editor_read_word_stem(GeanyEditor *editor, gint pos, const gchar *wordchars)
1810 static gchar word[GEANY_MAX_WORD_LENGTH];
1812 read_current_word(editor, pos, word, sizeof word, wordchars, TRUE);
1814 return (*word) ? word : NULL;
1818 static gint find_previous_brace(ScintillaObject *sci, gint pos)
1820 gint orig_pos = pos;
1822 while (pos >= 0 && pos > orig_pos - 300)
1824 gchar c = sci_get_char_at(sci, pos);
1825 if (utils_is_opening_brace(c, editor_prefs.brace_match_ltgt))
1826 return pos;
1827 pos--;
1829 return -1;
1833 static gint find_start_bracket(ScintillaObject *sci, gint pos)
1835 gint brackets = 0;
1836 gint orig_pos = pos;
1838 while (pos > 0 && pos > orig_pos - 300)
1840 gchar c = sci_get_char_at(sci, pos);
1842 if (c == ')') brackets++;
1843 else if (c == '(') brackets--;
1844 if (brackets < 0) return pos; /* found start bracket */
1845 pos--;
1847 return -1;
1851 static gboolean append_calltip(GString *str, const TMTag *tag, GeanyFiletypeID ft_id)
1853 if (! tag->arglist)
1854 return FALSE;
1856 if (ft_id != GEANY_FILETYPES_PASCAL && ft_id != GEANY_FILETYPES_GO)
1857 { /* usual calltips: "retval tagname (arglist)" */
1858 if (tag->var_type)
1860 guint i;
1862 g_string_append(str, tag->var_type);
1863 for (i = 0; i < tag->pointerOrder; i++)
1865 g_string_append_c(str, '*');
1867 g_string_append_c(str, ' ');
1869 if (tag->scope)
1871 const gchar *cosep = symbols_get_context_separator(ft_id);
1873 g_string_append(str, tag->scope);
1874 g_string_append(str, cosep);
1876 g_string_append(str, tag->name);
1877 g_string_append_c(str, ' ');
1878 g_string_append(str, tag->arglist);
1880 else
1881 { /* special case Pascal/Go calltips: "tagname (arglist) : retval"
1882 * (with ':' omitted for Go) */
1883 g_string_append(str, tag->name);
1884 g_string_append_c(str, ' ');
1885 g_string_append(str, tag->arglist);
1887 if (!EMPTY(tag->var_type))
1889 g_string_append(str, ft_id == GEANY_FILETYPES_PASCAL ? " : " : " ");
1890 g_string_append(str, tag->var_type);
1894 return TRUE;
1898 static gchar *find_calltip(const gchar *word, GeanyFiletype *ft)
1900 GPtrArray *tags;
1901 const TMTagType arg_types = tm_tag_function_t | tm_tag_prototype_t |
1902 tm_tag_method_t | tm_tag_macro_with_arg_t;
1903 TMTag *tag;
1904 GString *str = NULL;
1905 guint i;
1907 g_return_val_if_fail(ft && word && *word, NULL);
1909 /* use all types in case language uses wrong tag type e.g. python "members" instead of "methods" */
1910 tags = tm_workspace_find(word, NULL, tm_tag_max_t, NULL, ft->lang);
1911 if (tags->len == 0)
1913 g_ptr_array_free(tags, TRUE);
1914 return NULL;
1917 tag = TM_TAG(tags->pdata[0]);
1919 if (ft->id == GEANY_FILETYPES_D &&
1920 (tag->type == tm_tag_class_t || tag->type == tm_tag_struct_t))
1922 g_ptr_array_free(tags, TRUE);
1923 /* user typed e.g. 'new Classname(' so lookup D constructor Classname::this() */
1924 tags = tm_workspace_find("this", tag->name, arg_types, NULL, ft->lang);
1925 if (tags->len == 0)
1927 g_ptr_array_free(tags, TRUE);
1928 return NULL;
1932 /* remove tags with no argument list */
1933 for (i = 0; i < tags->len; i++)
1935 tag = TM_TAG(tags->pdata[i]);
1937 if (! tag->arglist)
1938 tags->pdata[i] = NULL;
1940 tm_tags_prune((GPtrArray *) tags);
1941 if (tags->len == 0)
1943 g_ptr_array_free(tags, TRUE);
1944 return NULL;
1946 else
1947 { /* remove duplicate calltips */
1948 TMTagAttrType sort_attr[] = {tm_tag_attr_name_t, tm_tag_attr_scope_t,
1949 tm_tag_attr_arglist_t, 0};
1951 tm_tags_sort((GPtrArray *) tags, sort_attr, TRUE, FALSE);
1954 /* if the current word has changed since last time, start with the first tag match */
1955 if (! utils_str_equal(word, calltip.last_word))
1956 calltip.tag_index = 0;
1957 /* cache the current word for next time */
1958 g_free(calltip.last_word);
1959 calltip.last_word = g_strdup(word);
1960 calltip.tag_index = MIN(calltip.tag_index, tags->len - 1); /* ensure tag_index is in range */
1962 for (i = calltip.tag_index; i < tags->len; i++)
1964 tag = TM_TAG(tags->pdata[i]);
1966 if (str == NULL)
1968 str = g_string_new(NULL);
1969 if (calltip.tag_index > 0)
1970 g_string_prepend(str, "\001 "); /* up arrow */
1971 append_calltip(str, tag, FILETYPE_ID(ft));
1973 else /* add a down arrow */
1975 if (calltip.tag_index > 0) /* already have an up arrow */
1976 g_string_insert_c(str, 1, '\002');
1977 else
1978 g_string_prepend(str, "\002 ");
1979 break;
1983 g_ptr_array_free(tags, TRUE);
1985 if (str)
1987 gchar *result = str->str;
1989 g_string_free(str, FALSE);
1990 return result;
1992 return NULL;
1996 /* use pos = -1 to search for the previous unmatched open bracket. */
1997 gboolean editor_show_calltip(GeanyEditor *editor, gint pos)
1999 gint orig_pos = pos; /* the position for the calltip */
2000 gint lexer;
2001 gint style;
2002 gchar word[GEANY_MAX_WORD_LENGTH];
2003 gchar *str;
2004 ScintillaObject *sci;
2006 g_return_val_if_fail(editor != NULL, FALSE);
2007 g_return_val_if_fail(editor->document->file_type != NULL, FALSE);
2009 sci = editor->sci;
2011 lexer = sci_get_lexer(sci);
2013 if (pos == -1)
2015 /* position of '(' is unknown, so go backwards from current position to find it */
2016 pos = sci_get_current_position(sci);
2017 pos--;
2018 orig_pos = pos;
2019 pos = (lexer == SCLEX_LATEX) ? find_previous_brace(sci, pos) :
2020 find_start_bracket(sci, pos);
2021 if (pos == -1)
2022 return FALSE;
2025 /* the style 1 before the brace (which may be highlighted) */
2026 style = sci_get_style_at(sci, pos - 1);
2027 if (! highlighting_is_code_style(lexer, style))
2028 return FALSE;
2030 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
2031 pos--;
2033 /* skip possible generic/template specification, like foo<int>() */
2034 if (sci_get_char_at(sci, pos - 1) == '>')
2036 pos = sci_find_matching_brace(sci, pos - 1);
2037 if (pos == -1)
2038 return FALSE;
2040 while (pos > 0 && isspace(sci_get_char_at(sci, pos - 1)))
2041 pos--;
2044 word[0] = '\0';
2045 editor_find_current_word(editor, pos - 1, word, sizeof word, NULL);
2046 if (word[0] == '\0')
2047 return FALSE;
2049 str = find_calltip(word, editor->document->file_type);
2050 if (str)
2052 g_free(calltip.text); /* free the old calltip */
2053 calltip.text = str;
2054 calltip.pos = orig_pos;
2055 calltip.sci = sci;
2056 calltip.set = TRUE;
2057 utils_wrap_string(calltip.text, -1);
2058 SSM(sci, SCI_CALLTIPSHOW, orig_pos, (sptr_t) calltip.text);
2059 return TRUE;
2061 return FALSE;
2065 gchar *editor_get_calltip_text(GeanyEditor *editor, const TMTag *tag)
2067 GString *str;
2069 g_return_val_if_fail(editor != NULL, NULL);
2071 str = g_string_new(NULL);
2072 if (append_calltip(str, tag, editor->document->file_type->id))
2073 return g_string_free(str, FALSE);
2074 else
2075 return g_string_free(str, TRUE);
2079 /* HTML entities auto completion from html_entities.tags text file */
2080 static gboolean
2081 autocomplete_html(ScintillaObject *sci, const gchar *root, gsize rootlen)
2083 guint i;
2084 gboolean found = FALSE;
2085 GString *words;
2086 const gchar **entities = symbols_get_html_entities();
2088 if (*root != '&' || entities == NULL)
2089 return FALSE;
2091 words = g_string_sized_new(500);
2092 for (i = 0; ; i++)
2094 if (entities[i] == NULL)
2095 break;
2096 else if (entities[i][0] == '#')
2097 continue;
2099 if (! strncmp(entities[i], root, rootlen))
2101 if (words->len)
2102 g_string_append_c(words, '\n');
2104 g_string_append(words, entities[i]);
2105 found = TRUE;
2108 if (found)
2109 show_autocomplete(sci, rootlen, words);
2111 g_string_free(words, TRUE);
2112 return found;
2116 /* Current document & global tags autocompletion */
2117 static gboolean
2118 autocomplete_tags(GeanyEditor *editor, const gchar *root, gsize rootlen)
2120 GPtrArray *tags;
2121 GeanyDocument *doc;
2122 gboolean found;
2124 g_return_val_if_fail(editor, FALSE);
2126 doc = editor->document;
2128 tags = tm_workspace_find_prefix(root, doc->file_type->lang, editor_prefs.autocompletion_max_entries);
2129 found = tags->len > 0;
2130 if (found)
2131 show_tags_list(editor, tags, rootlen);
2132 g_ptr_array_free(tags, TRUE);
2134 return found;
2138 static gboolean autocomplete_check_html(GeanyEditor *editor, gint style, gint pos)
2140 GeanyFiletype *ft = editor->document->file_type;
2141 gboolean try = FALSE;
2143 /* use entity completion when style is not JavaScript, ASP, Python, PHP, ...
2144 * (everything after SCE_HJ_START is for embedded scripting languages) */
2145 if (ft->id == GEANY_FILETYPES_HTML && style < SCE_HJ_START)
2146 try = TRUE;
2147 else if (sci_get_lexer(editor->sci) == SCLEX_XML && style < SCE_HJ_START)
2148 try = TRUE;
2149 else if (ft->id == GEANY_FILETYPES_PHP)
2151 /* use entity completion when style is outside of PHP styles */
2152 if (! is_style_php(style))
2153 try = TRUE;
2155 if (try)
2157 gchar root[GEANY_MAX_WORD_LENGTH];
2158 gchar *tmp;
2160 read_current_word(editor, pos, root, sizeof(root), GEANY_WORDCHARS"&", TRUE);
2162 /* Allow something like "&quot;some text&quot;".
2163 * for entity completion we want to have completion for '&' within words. */
2164 tmp = strchr(root, '&');
2165 if (tmp != NULL)
2167 return autocomplete_html(editor->sci, tmp, strlen(tmp));
2170 return FALSE;
2174 /* Algorithm based on based on Scite's StartAutoCompleteWord()
2175 * @returns a sorted list of words matching @p root */
2176 static GSList *get_doc_words(ScintillaObject *sci, gchar *root, gsize rootlen)
2178 gchar *word;
2179 gint len, current, word_end;
2180 gint pos_find, flags;
2181 guint word_length;
2182 gsize nmatches = 0;
2183 GSList *words = NULL;
2184 struct Sci_TextToFind ttf;
2186 len = sci_get_length(sci);
2187 current = sci_get_current_position(sci) - rootlen;
2189 ttf.lpstrText = root;
2190 ttf.chrg.cpMin = 0;
2191 ttf.chrg.cpMax = len;
2192 ttf.chrgText.cpMin = 0;
2193 ttf.chrgText.cpMax = 0;
2194 flags = SCFIND_WORDSTART | SCFIND_MATCHCASE;
2196 /* search the whole document for the word root and collect results */
2197 pos_find = scintilla_send_message(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
2198 while (pos_find >= 0 && pos_find < len)
2200 word_end = pos_find + rootlen;
2201 if (pos_find != current)
2203 word_end = sci_word_end_position(sci, word_end, TRUE);
2205 word_length = word_end - pos_find;
2206 if (word_length > rootlen)
2208 word = sci_get_contents_range(sci, pos_find, word_end);
2209 /* search whether we already have the word in, otherwise add it */
2210 if (g_slist_find_custom(words, word, (GCompareFunc)strcmp) != NULL)
2211 g_free(word);
2212 else
2214 words = g_slist_prepend(words, word);
2215 nmatches++;
2218 if (nmatches == editor_prefs.autocompletion_max_entries)
2219 break;
2222 ttf.chrg.cpMin = word_end;
2223 pos_find = scintilla_send_message(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
2226 return g_slist_sort(words, (GCompareFunc)utils_str_casecmp);
2230 static gboolean autocomplete_doc_word(GeanyEditor *editor, gchar *root, gsize rootlen)
2232 ScintillaObject *sci = editor->sci;
2233 GSList *words, *node;
2234 GString *str;
2235 guint n_words = 0;
2237 words = get_doc_words(sci, root, rootlen);
2238 if (!words)
2240 scintilla_send_message(sci, SCI_AUTOCCANCEL, 0, 0);
2241 return FALSE;
2244 str = g_string_sized_new(rootlen * 2 * 10);
2245 foreach_slist(node, words)
2247 g_string_append(str, node->data);
2248 g_free(node->data);
2249 if (node->next)
2250 g_string_append_c(str, '\n');
2251 n_words++;
2253 if (n_words >= editor_prefs.autocompletion_max_entries)
2254 g_string_append(str, "\n...");
2256 g_slist_free(words);
2258 show_autocomplete(sci, rootlen, str);
2259 g_string_free(str, TRUE);
2260 return TRUE;
2264 gboolean editor_start_auto_complete(GeanyEditor *editor, gint pos, gboolean force)
2266 gint rootlen, lexer, style;
2267 gchar *root;
2268 gchar cword[GEANY_MAX_WORD_LENGTH];
2269 ScintillaObject *sci;
2270 gboolean ret = FALSE;
2271 const gchar *wordchars;
2272 GeanyFiletype *ft;
2274 g_return_val_if_fail(editor != NULL, FALSE);
2276 if (! editor_prefs.auto_complete_symbols && ! force)
2277 return FALSE;
2279 /* If we are at the beginning of the document, we skip autocompletion as we can't determine the
2280 * necessary styling information */
2281 if (G_UNLIKELY(pos < 2))
2282 return FALSE;
2284 sci = editor->sci;
2285 ft = editor->document->file_type;
2287 lexer = sci_get_lexer(sci);
2288 style = sci_get_style_at(sci, pos - 2);
2290 /* don't autocomplete in comments and strings */
2291 if (!force && !highlighting_is_code_style(lexer, style))
2292 return FALSE;
2294 ret = autocomplete_check_html(editor, style, pos);
2296 if (ft->id == GEANY_FILETYPES_LATEX)
2297 wordchars = GEANY_WORDCHARS"\\"; /* add \ to word chars if we are in a LaTeX file */
2298 else if (ft->id == GEANY_FILETYPES_CSS)
2299 wordchars = GEANY_WORDCHARS"-"; /* add - because they are part of property names */
2300 else
2301 wordchars = GEANY_WORDCHARS;
2303 read_current_word(editor, pos, cword, sizeof(cword), wordchars, TRUE);
2304 root = cword;
2305 rootlen = strlen(root);
2307 if (ret || force)
2309 if (autocomplete_scope_shown)
2311 autocomplete_scope_shown = FALSE;
2312 if (!ret)
2313 sci_send_command(sci, SCI_AUTOCCANCEL);
2316 else
2318 ret = autocomplete_scope(editor, root, rootlen);
2319 if (!ret && autocomplete_scope_shown)
2320 sci_send_command(sci, SCI_AUTOCCANCEL);
2321 autocomplete_scope_shown = ret;
2324 if (!ret && rootlen > 0)
2326 if (ft->id == GEANY_FILETYPES_PHP && style == SCE_HPHP_DEFAULT &&
2327 rootlen == 3 && strcmp(root, "php") == 0 && pos >= 5 &&
2328 sci_get_char_at(sci, pos - 5) == '<' &&
2329 sci_get_char_at(sci, pos - 4) == '?')
2331 /* nothing, don't complete PHP open tags */
2333 else
2335 /* force is set when called by keyboard shortcut, otherwise start at the
2336 * editor_prefs.symbolcompletion_min_chars'th char */
2337 if (force || rootlen >= editor_prefs.symbolcompletion_min_chars)
2339 /* complete tags, except if forcing when completion is already visible */
2340 if (!(force && SSM(sci, SCI_AUTOCACTIVE, 0, 0)))
2341 ret = autocomplete_tags(editor, root, rootlen);
2343 /* If forcing and there's nothing else to show, complete from words in document */
2344 if (!ret && (force || editor_prefs.autocomplete_doc_words))
2345 ret = autocomplete_doc_word(editor, root, rootlen);
2349 if (!ret && force)
2350 utils_beep();
2352 return ret;
2356 static const gchar *snippets_find_completion_by_name(const gchar *type, const gchar *name)
2358 gchar *result = NULL;
2359 GHashTable *tmp;
2361 g_return_val_if_fail(type != NULL && name != NULL, NULL);
2363 tmp = g_hash_table_lookup(snippet_hash, type);
2364 if (tmp != NULL)
2366 result = g_hash_table_lookup(tmp, name);
2368 /* whether nothing is set for the current filetype(tmp is NULL) or
2369 * the particular completion for this filetype is not set (result is NULL) */
2370 if (tmp == NULL || result == NULL)
2372 tmp = g_hash_table_lookup(snippet_hash, "Default");
2373 if (tmp != NULL)
2375 result = g_hash_table_lookup(tmp, name);
2378 /* if result is still NULL here, no completion could be found */
2380 /* result is owned by the hash table and will be freed when the table will destroyed */
2381 return result;
2385 static void snippets_replace_specials(gpointer key, gpointer value, gpointer user_data)
2387 gchar *needle;
2388 GString *pattern = user_data;
2390 g_return_if_fail(key != NULL);
2391 g_return_if_fail(value != NULL);
2393 needle = g_strconcat("%", (gchar*) key, "%", NULL);
2395 utils_string_replace_all(pattern, needle, (gchar*) value);
2396 g_free(needle);
2400 static void fix_indentation(GeanyEditor *editor, GString *buf)
2402 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
2403 gchar *whitespace;
2404 GRegex *regex;
2405 gint cflags = G_REGEX_MULTILINE;
2407 /* transform leading tabs into indent widths (in spaces) */
2408 whitespace = g_strnfill(iprefs->width, ' ');
2409 regex = g_regex_new("^ *(\t)", cflags, 0, NULL);
2410 while (utils_string_regex_replace_all(buf, regex, 1, whitespace, TRUE));
2411 g_regex_unref(regex);
2413 /* remaining tabs are for alignment */
2414 if (iprefs->type != GEANY_INDENT_TYPE_TABS)
2415 utils_string_replace_all(buf, "\t", whitespace);
2417 /* use leading tabs */
2418 if (iprefs->type != GEANY_INDENT_TYPE_SPACES)
2420 gchar *str;
2422 /* for tabs+spaces mode we want the real tab width, not indent width */
2423 SETPTR(whitespace, g_strnfill(sci_get_tab_width(editor->sci), ' '));
2424 str = g_strdup_printf("^\t*(%s)", whitespace);
2426 regex = g_regex_new(str, cflags, 0, NULL);
2427 while (utils_string_regex_replace_all(buf, regex, 1, "\t", TRUE));
2428 g_regex_unref(regex);
2429 g_free(str);
2431 g_free(whitespace);
2435 /** Inserts text, replacing \\t tab chars (@c 0x9) and \\n newline chars (@c 0xA)
2436 * accordingly for the document.
2437 * - Leading tabs are replaced with the correct indentation.
2438 * - Non-leading tabs are replaced with spaces (except when using 'Tabs' indent type).
2439 * - Newline chars are replaced with the correct line ending string.
2440 * This is very useful for inserting code without having to handle the indent
2441 * type yourself (Tabs & Spaces mode can be tricky).
2442 * @param editor Editor.
2443 * @param text Intended as e.g. @c "if (foo)\n\tbar();".
2444 * @param insert_pos Document position to insert text at.
2445 * @param cursor_index If >= 0, the index into @a text to place the cursor.
2446 * @param newline_indent_size Indentation size (in spaces) to insert for each newline; use
2447 * -1 to read the indent size from the line with @a insert_pos on it.
2448 * @param replace_newlines Whether to replace newlines. If
2449 * newlines have been replaced already, this should be false, to avoid errors e.g. on Windows.
2450 * @warning Make sure all \\t tab chars in @a text are intended as indent widths or alignment,
2451 * not hard tabs, as those won't be preserved.
2452 * @note This doesn't scroll the cursor in view afterwards. **/
2453 GEANY_API_SYMBOL
2454 void editor_insert_text_block(GeanyEditor *editor, const gchar *text, gint insert_pos,
2455 gint cursor_index, gint newline_indent_size, gboolean replace_newlines)
2457 ScintillaObject *sci = editor->sci;
2458 gint line_start = sci_get_line_from_position(sci, insert_pos);
2459 GString *buf;
2460 const gchar *eol = editor_get_eol_char(editor);
2461 gint idx;
2463 g_return_if_fail(text);
2464 g_return_if_fail(editor != NULL);
2465 g_return_if_fail(insert_pos >= 0);
2467 buf = g_string_new(text);
2469 if (cursor_index >= 0)
2470 g_string_insert(buf, cursor_index, geany_cursor_marker); /* remember cursor pos */
2472 if (newline_indent_size == -1)
2474 /* count indent size up to insert_pos instead of asking sci
2475 * because there may be spaces after it */
2476 gchar *tmp = sci_get_line(sci, line_start);
2478 idx = insert_pos - sci_get_position_from_line(sci, line_start);
2479 tmp[idx] = '\0';
2480 newline_indent_size = count_indent_size(editor, tmp);
2481 g_free(tmp);
2484 /* Add line indents (in spaces) */
2485 if (newline_indent_size > 0)
2487 const gchar *nl = replace_newlines ? "\n" : eol;
2488 gchar *whitespace;
2490 whitespace = g_strnfill(newline_indent_size, ' ');
2491 SETPTR(whitespace, g_strconcat(nl, whitespace, NULL));
2492 utils_string_replace_all(buf, nl, whitespace);
2493 g_free(whitespace);
2496 /* transform line endings */
2497 if (replace_newlines)
2498 utils_string_replace_all(buf, "\n", eol);
2500 fix_indentation(editor, buf);
2502 idx = replace_cursor_markers(editor, buf);
2503 if (idx >= 0)
2505 sci_insert_text(sci, insert_pos, buf->str);
2506 sci_set_current_position(sci, insert_pos + idx, FALSE);
2508 else
2509 sci_insert_text(sci, insert_pos, buf->str);
2511 snippet_cursor_insert_pos = sci_get_current_position(sci);
2513 g_string_free(buf, TRUE);
2517 /* Move the cursor to the next specified cursor position in an inserted snippet.
2518 * Can, and should, be optimized to give better results */
2519 void editor_goto_next_snippet_cursor(GeanyEditor *editor)
2521 ScintillaObject *sci = editor->sci;
2522 gint current_pos = sci_get_current_position(sci);
2524 if (snippet_offsets && !g_queue_is_empty(snippet_offsets))
2526 gint offset;
2528 offset = GPOINTER_TO_INT(g_queue_pop_head(snippet_offsets));
2529 if (current_pos > snippet_cursor_insert_pos)
2530 snippet_cursor_insert_pos = offset + current_pos;
2531 else
2532 snippet_cursor_insert_pos += offset;
2534 sci_set_current_position(sci, snippet_cursor_insert_pos, TRUE);
2536 else
2538 utils_beep();
2543 static void snippets_make_replacements(GeanyEditor *editor, GString *pattern)
2545 GHashTable *specials;
2547 /* replace 'special' completions */
2548 specials = g_hash_table_lookup(snippet_hash, "Special");
2549 if (G_LIKELY(specials != NULL))
2551 g_hash_table_foreach(specials, snippets_replace_specials, pattern);
2554 /* now transform other wildcards */
2555 utils_string_replace_all(pattern, "%newline%", "\n");
2556 utils_string_replace_all(pattern, "%ws%", "\t");
2558 /* replace %cursor% by a very unlikely string marker */
2559 utils_string_replace_all(pattern, "%cursor%", geany_cursor_marker);
2561 /* unescape '%' after all %wildcards% */
2562 templates_replace_valist(pattern, "{pc}", "%", NULL);
2564 /* replace any template {foo} wildcards */
2565 templates_replace_common(pattern, editor->document->file_name, editor->document->file_type, NULL);
2569 static gssize replace_cursor_markers(GeanyEditor *editor, GString *pattern)
2571 gssize cur_index = -1;
2572 gint i;
2573 GList *temp_list = NULL;
2574 gint cursor_steps = 0, old_cursor = 0;
2576 i = 0;
2577 while (1)
2579 cursor_steps = utils_string_find(pattern, cursor_steps, -1, geany_cursor_marker);
2580 if (cursor_steps == -1)
2581 break;
2583 g_string_erase(pattern, cursor_steps, strlen(geany_cursor_marker));
2585 if (i++ > 0)
2587 /* save the relative offset to each cursor position */
2588 temp_list = g_list_prepend(temp_list, GINT_TO_POINTER(cursor_steps - old_cursor));
2590 else
2592 /* first cursor already includes newline positions */
2593 cur_index = cursor_steps;
2595 old_cursor = cursor_steps;
2598 /* put the cursor positions for the most recent
2599 * parsed snippet first, followed by any remaining positions */
2600 i = 0;
2601 if (temp_list)
2603 GList *node;
2605 temp_list = g_list_reverse(temp_list);
2606 foreach_list(node, temp_list)
2607 g_queue_push_nth(snippet_offsets, node->data, i++);
2609 /* limit length of queue */
2610 while (g_queue_get_length(snippet_offsets) > 20)
2611 g_queue_pop_tail(snippet_offsets);
2613 g_list_free(temp_list);
2615 /* if there's no first cursor, skip whole snippet */
2616 if (cur_index < 0)
2617 cur_index = pattern->len;
2619 return cur_index;
2623 static gboolean snippets_complete_constructs(GeanyEditor *editor, gint pos, const gchar *word)
2625 ScintillaObject *sci = editor->sci;
2626 gchar *str;
2627 const gchar *completion;
2628 gint str_len;
2629 gint ft_id = editor->document->file_type->id;
2631 str = g_strdup(word);
2632 g_strstrip(str);
2634 completion = snippets_find_completion_by_name(filetypes[ft_id]->name, str);
2635 if (completion == NULL)
2637 g_free(str);
2638 return FALSE;
2641 /* remove the typed word, it will be added again by the used auto completion
2642 * (not really necessary but this makes the auto completion more flexible,
2643 * e.g. with a completion like hi=hello, so typing "hi<TAB>" will result in "hello") */
2644 str_len = strlen(str);
2645 sci_set_selection_start(sci, pos - str_len);
2646 sci_set_selection_end(sci, pos);
2647 sci_replace_sel(sci, "");
2648 pos -= str_len; /* pos has changed while deleting */
2650 editor_insert_snippet(editor, pos, completion);
2651 sci_scroll_caret(sci);
2653 g_free(str);
2654 return TRUE;
2658 static gboolean at_eol(ScintillaObject *sci, gint pos)
2660 gint line = sci_get_line_from_position(sci, pos);
2661 gchar c;
2663 /* skip any trailing spaces */
2664 while (TRUE)
2666 c = sci_get_char_at(sci, pos);
2667 if (c == ' ' || c == '\t')
2668 pos++;
2669 else
2670 break;
2673 return (pos == sci_get_line_end_position(sci, line));
2677 gboolean editor_complete_snippet(GeanyEditor *editor, gint pos)
2679 gboolean result = FALSE;
2680 const gchar *wc;
2681 const gchar *word;
2682 ScintillaObject *sci;
2684 g_return_val_if_fail(editor != NULL, FALSE);
2686 sci = editor->sci;
2687 if (sci_has_selection(sci))
2688 return FALSE;
2689 /* return if we are editing an existing line (chars on right of cursor) */
2690 if (keybindings_lookup_item(GEANY_KEY_GROUP_EDITOR,
2691 GEANY_KEYS_EDITOR_COMPLETESNIPPET)->key == GDK_space &&
2692 ! editor_prefs.complete_snippets_whilst_editing && ! at_eol(sci, pos))
2693 return FALSE;
2695 wc = snippets_find_completion_by_name("Special", "wordchars");
2696 word = editor_read_word_stem(editor, pos, wc);
2698 /* prevent completion of "for " */
2699 if (!EMPTY(word) &&
2700 ! isspace(sci_get_char_at(sci, pos - 1))) /* pos points to the line end char so use pos -1 */
2702 sci_start_undo_action(sci); /* needed because we insert a space separately from construct */
2703 result = snippets_complete_constructs(editor, pos, word);
2704 sci_end_undo_action(sci);
2705 if (result)
2706 sci_cancel(sci); /* cancel any autocompletion list, etc */
2708 return result;
2712 static void insert_closing_tag(GeanyEditor *editor, gint pos, gchar ch, const gchar *tag_name)
2714 ScintillaObject *sci = editor->sci;
2715 gchar *to_insert = NULL;
2717 if (ch == '/')
2719 const gchar *gt = ">";
2720 /* if there is already a '>' behind the cursor, don't add it */
2721 if (sci_get_char_at(sci, pos) == '>')
2722 gt = "";
2724 to_insert = g_strconcat(tag_name, gt, NULL);
2726 else
2727 to_insert = g_strconcat("</", tag_name, ">", NULL);
2729 sci_start_undo_action(sci);
2730 sci_replace_sel(sci, to_insert);
2731 if (ch == '>')
2732 sci_set_selection(sci, pos, pos);
2733 sci_end_undo_action(sci);
2734 g_free(to_insert);
2739 * (stolen from anjuta and heavily modified)
2740 * This routine will auto complete XML or HTML tags that are still open by closing them
2741 * @param ch The character we are dealing with, currently only works with the '>' character
2742 * @return True if handled, false otherwise
2744 static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch)
2746 ScintillaObject *sci = editor->sci;
2747 gint lexer = sci_get_lexer(sci);
2748 gint min, size, style;
2749 gchar *str_found, sel[512];
2750 gboolean result = FALSE;
2752 /* If the user has turned us off, quit now.
2753 * This may make sense only in certain languages */
2754 if (! editor_prefs.auto_close_xml_tags || (lexer != SCLEX_HTML && lexer != SCLEX_XML))
2755 return FALSE;
2757 /* return if we are inside any embedded script */
2758 style = sci_get_style_at(sci, pos);
2759 if (style > SCE_H_XCCOMMENT && ! highlighting_is_string_style(lexer, style))
2760 return FALSE;
2762 /* if ch is /, check for </, else quit */
2763 if (ch == '/' && sci_get_char_at(sci, pos - 2) != '<')
2764 return FALSE;
2766 /* Grab the last 512 characters or so */
2767 min = pos - (sizeof(sel) - 1);
2768 if (min < 0) min = 0;
2770 if (pos - min < 3)
2771 return FALSE; /* Smallest tag is 3 characters e.g. <p> */
2773 sci_get_text_range(sci, min, pos, sel);
2774 sel[sizeof(sel) - 1] = '\0';
2776 if (ch == '>' && sel[pos - min - 2] == '/')
2777 /* User typed something like "<br/>" */
2778 return FALSE;
2780 size = pos - min;
2781 if (ch == '/')
2782 size -= 2; /* skip </ */
2783 str_found = utils_find_open_xml_tag(sel, size);
2785 if (lexer == SCLEX_HTML && utils_is_short_html_tag(str_found))
2787 /* ignore tag */
2789 else if (!EMPTY(str_found))
2791 insert_closing_tag(editor, pos, ch, str_found);
2792 result = TRUE;
2794 g_free(str_found);
2795 return result;
2799 /* like sci_get_line_indentation(), but for a string. */
2800 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent)
2802 const gchar *ptr;
2803 gsize tab_size = sci_get_tab_width(editor->sci);
2804 gsize count = 0;
2806 g_return_val_if_fail(base_indent, 0);
2808 for (ptr = base_indent; *ptr != 0; ptr++)
2810 switch (*ptr)
2812 case ' ':
2813 count++;
2814 break;
2815 case '\t':
2816 count += tab_size;
2817 break;
2818 default:
2819 return count;
2822 return count;
2826 /* Handles special cases where HTML is embedded in another language or
2827 * another language is embedded in HTML */
2828 static GeanyFiletype *editor_get_filetype_at_line(GeanyEditor *editor, gint line)
2830 gint style, line_start;
2831 GeanyFiletype *current_ft;
2833 g_return_val_if_fail(editor != NULL, NULL);
2834 g_return_val_if_fail(editor->document->file_type != NULL, NULL);
2836 current_ft = editor->document->file_type;
2837 line_start = sci_get_position_from_line(editor->sci, line);
2838 style = sci_get_style_at(editor->sci, line_start);
2840 /* Handle PHP filetype with embedded HTML */
2841 if (current_ft->id == GEANY_FILETYPES_PHP && ! is_style_php(style))
2842 current_ft = filetypes[GEANY_FILETYPES_HTML];
2844 /* Handle languages embedded in HTML */
2845 if (current_ft->id == GEANY_FILETYPES_HTML)
2847 /* Embedded JS */
2848 if (style >= SCE_HJ_DEFAULT && style <= SCE_HJ_REGEX)
2849 current_ft = filetypes[GEANY_FILETYPES_JS];
2850 /* ASP JS */
2851 else if (style >= SCE_HJA_DEFAULT && style <= SCE_HJA_REGEX)
2852 current_ft = filetypes[GEANY_FILETYPES_JS];
2853 /* Embedded VB */
2854 else if (style >= SCE_HB_DEFAULT && style <= SCE_HB_STRINGEOL)
2855 current_ft = filetypes[GEANY_FILETYPES_BASIC];
2856 /* ASP VB */
2857 else if (style >= SCE_HBA_DEFAULT && style <= SCE_HBA_STRINGEOL)
2858 current_ft = filetypes[GEANY_FILETYPES_BASIC];
2859 /* Embedded Python */
2860 else if (style >= SCE_HP_DEFAULT && style <= SCE_HP_IDENTIFIER)
2861 current_ft = filetypes[GEANY_FILETYPES_PYTHON];
2862 /* ASP Python */
2863 else if (style >= SCE_HPA_DEFAULT && style <= SCE_HPA_IDENTIFIER)
2864 current_ft = filetypes[GEANY_FILETYPES_PYTHON];
2865 /* Embedded PHP */
2866 else if ((style >= SCE_HPHP_DEFAULT && style <= SCE_HPHP_OPERATOR) ||
2867 style == SCE_HPHP_COMPLEX_VARIABLE)
2869 current_ft = filetypes[GEANY_FILETYPES_PHP];
2873 /* Ensure the filetype's config is loaded */
2874 filetypes_load_config(current_ft->id, FALSE);
2876 return current_ft;
2880 static void real_comment_multiline(GeanyEditor *editor, gint line_start, gint last_line)
2882 const gchar *eol;
2883 gchar *str_begin, *str_end;
2884 const gchar *co, *cc;
2885 gint line_len;
2886 GeanyFiletype *ft;
2888 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2890 ft = editor_get_filetype_at_line(editor, line_start);
2892 eol = editor_get_eol_char(editor);
2893 if (! filetype_get_comment_open_close(ft, FALSE, &co, &cc))
2894 g_return_if_reached();
2895 str_begin = g_strdup_printf("%s%s", (co != NULL) ? co : "", eol);
2896 str_end = g_strdup_printf("%s%s", (cc != NULL) ? cc : "", eol);
2898 /* insert the comment strings */
2899 sci_insert_text(editor->sci, line_start, str_begin);
2900 line_len = sci_get_position_from_line(editor->sci, last_line + 2);
2901 sci_insert_text(editor->sci, line_len, str_end);
2903 g_free(str_begin);
2904 g_free(str_end);
2908 /* find @p text inside the range of the current style */
2909 static gint find_in_current_style(ScintillaObject *sci, const gchar *text, gboolean backwards)
2911 gint start = sci_get_current_position(sci);
2912 gint end = start;
2913 gint len = sci_get_length(sci);
2914 gint current_style = sci_get_style_at(sci, start);
2915 struct Sci_TextToFind ttf;
2917 while (start > 0 && sci_get_style_at(sci, start - 1) == current_style)
2918 start -= 1;
2919 while (end < len && sci_get_style_at(sci, end + 1) == current_style)
2920 end += 1;
2922 ttf.lpstrText = (gchar*) text;
2923 ttf.chrg.cpMin = backwards ? end + 1 : start;
2924 ttf.chrg.cpMax = backwards ? start : end + 1;
2925 return sci_find_text(sci, 0, &ttf);
2929 static void sci_delete_line(ScintillaObject *sci, gint line)
2931 gint start = sci_get_position_from_line(sci, line);
2932 gint len = sci_get_line_length(sci, line);
2933 SSM(sci, SCI_DELETERANGE, start, len);
2937 static gboolean real_uncomment_multiline(GeanyEditor *editor)
2939 /* find the beginning of the multi line comment */
2940 gint start, end, start_line, end_line;
2941 GeanyFiletype *ft;
2942 const gchar *co, *cc;
2944 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, FALSE);
2946 ft = editor_get_filetype_at_line(editor, sci_get_current_line(editor->sci));
2947 if (! filetype_get_comment_open_close(ft, FALSE, &co, &cc))
2948 g_return_val_if_reached(FALSE);
2950 start = find_in_current_style(editor->sci, co, TRUE);
2951 end = find_in_current_style(editor->sci, cc, FALSE);
2953 if (start < 0 || end < 0 || start > end /* who knows */)
2954 return FALSE;
2956 start_line = sci_get_line_from_position(editor->sci, start);
2957 end_line = sci_get_line_from_position(editor->sci, end);
2959 /* remove comment close chars */
2960 SSM(editor->sci, SCI_DELETERANGE, end, strlen(cc));
2961 if (sci_is_blank_line(editor->sci, end_line))
2962 sci_delete_line(editor->sci, end_line);
2964 /* remove comment open chars (do it last since it would move the end position) */
2965 SSM(editor->sci, SCI_DELETERANGE, start, strlen(co));
2966 if (sci_is_blank_line(editor->sci, start_line))
2967 sci_delete_line(editor->sci, start_line);
2969 return TRUE;
2973 static gint get_multiline_comment_style(GeanyEditor *editor, gint line_start)
2975 gint lexer = sci_get_lexer(editor->sci);
2976 gint style_comment;
2978 /* List only those lexers which support multi line comments */
2979 switch (lexer)
2981 case SCLEX_XML:
2982 case SCLEX_HTML:
2983 case SCLEX_PHPSCRIPT:
2985 if (is_style_php(sci_get_style_at(editor->sci, line_start)))
2986 style_comment = SCE_HPHP_COMMENT;
2987 else
2988 style_comment = SCE_H_COMMENT;
2989 break;
2991 case SCLEX_HASKELL:
2992 case SCLEX_LITERATEHASKELL:
2993 style_comment = SCE_HA_COMMENTBLOCK; break;
2994 case SCLEX_LUA: style_comment = SCE_LUA_COMMENT; break;
2995 case SCLEX_CSS: style_comment = SCE_CSS_COMMENT; break;
2996 case SCLEX_SQL: style_comment = SCE_SQL_COMMENT; break;
2997 case SCLEX_CAML: style_comment = SCE_CAML_COMMENT; break;
2998 case SCLEX_D: style_comment = SCE_D_COMMENT; break;
2999 case SCLEX_PASCAL: style_comment = SCE_PAS_COMMENT; break;
3000 case SCLEX_RUST: style_comment = SCE_RUST_COMMENTBLOCK; break;
3001 default: style_comment = SCE_C_COMMENT;
3004 return style_comment;
3008 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise
3009 * returns the amount of uncommented single comment lines, in case of multi line uncomment
3010 * it returns just 1 */
3011 gint editor_do_uncomment(GeanyEditor *editor, gint line, gboolean toggle)
3013 gint first_line, last_line;
3014 gint x, i, line_start, line_len;
3015 gint sel_start, sel_end;
3016 gint count = 0;
3017 gsize co_len;
3018 gchar sel[256];
3019 const gchar *co, *cc;
3020 gboolean single_line = FALSE;
3021 GeanyFiletype *ft;
3023 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, 0);
3025 if (line < 0)
3026 { /* use selection or current line */
3027 sel_start = sci_get_selection_start(editor->sci);
3028 sel_end = sci_get_selection_end(editor->sci);
3030 first_line = sci_get_line_from_position(editor->sci, sel_start);
3031 /* Find the last line with chars selected (not EOL char) */
3032 last_line = sci_get_line_from_position(editor->sci,
3033 sel_end - editor_get_eol_char_len(editor));
3034 last_line = MAX(first_line, last_line);
3036 else
3038 first_line = last_line = line;
3039 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
3042 ft = editor_get_filetype_at_line(editor, first_line);
3044 if (! filetype_get_comment_open_close(ft, TRUE, &co, &cc))
3045 return 0;
3047 co_len = strlen(co);
3048 if (co_len == 0)
3049 return 0;
3051 sci_start_undo_action(editor->sci);
3053 for (i = first_line; i <= last_line; i++)
3055 gint buf_len;
3057 line_start = sci_get_position_from_line(editor->sci, i);
3058 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
3059 x = 0;
3061 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
3062 if (buf_len <= 0)
3063 continue;
3064 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3065 sel[buf_len] = '\0';
3067 while (isspace(sel[x])) x++;
3069 /* to skip blank lines */
3070 if (x < line_len && sel[x] != '\0')
3072 /* use single line comment */
3073 if (EMPTY(cc))
3075 single_line = TRUE;
3077 if (toggle)
3079 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
3080 if (strncmp(sel + x, co, co_len) != 0 ||
3081 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) != 0)
3082 continue;
3084 co_len += tm_len;
3086 else
3088 if (strncmp(sel + x, co, co_len) != 0)
3089 continue;
3092 sci_set_selection(editor->sci, line_start + x, line_start + x + co_len);
3093 sci_replace_sel(editor->sci, "");
3094 count++;
3096 /* use multi line comment */
3097 else
3099 gint style_comment;
3101 /* skip lines which are already comments */
3102 style_comment = get_multiline_comment_style(editor, line_start);
3103 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3105 if (real_uncomment_multiline(editor))
3106 count = 1;
3109 /* break because we are already on the last line */
3110 break;
3114 sci_end_undo_action(editor->sci);
3116 /* restore selection if there is one
3117 * but don't touch the selection if caller is editor_do_comment_toggle */
3118 if (! toggle && sel_start < sel_end)
3120 if (single_line)
3122 sci_set_selection_start(editor->sci, sel_start - co_len);
3123 sci_set_selection_end(editor->sci, sel_end - (count * co_len));
3125 else
3127 gint eol_len = editor_get_eol_char_len(editor);
3128 sci_set_selection_start(editor->sci, sel_start - co_len - eol_len);
3129 sci_set_selection_end(editor->sci, sel_end - co_len - eol_len);
3133 return count;
3137 void editor_do_comment_toggle(GeanyEditor *editor)
3139 gint first_line, last_line;
3140 gint x, i, line_start, line_len, first_line_start, last_line_start;
3141 gint sel_start, sel_end;
3142 gint count_commented = 0, count_uncommented = 0;
3143 gchar sel[256];
3144 const gchar *co, *cc;
3145 gboolean break_loop = FALSE, single_line = FALSE;
3146 gboolean first_line_was_comment = FALSE;
3147 gboolean last_line_was_comment = FALSE;
3148 gsize co_len;
3149 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
3150 GeanyFiletype *ft;
3152 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
3154 sel_start = sci_get_selection_start(editor->sci);
3155 sel_end = sci_get_selection_end(editor->sci);
3157 first_line = sci_get_line_from_position(editor->sci, sel_start);
3158 /* Find the last line with chars selected (not EOL char) */
3159 last_line = sci_get_line_from_position(editor->sci,
3160 sel_end - editor_get_eol_char_len(editor));
3161 last_line = MAX(first_line, last_line);
3163 first_line_start = sci_get_position_from_line(editor->sci, first_line);
3164 last_line_start = sci_get_position_from_line(editor->sci, last_line);
3166 ft = editor_get_filetype_at_line(editor, first_line);
3168 if (! filetype_get_comment_open_close(ft, TRUE, &co, &cc))
3169 return;
3171 co_len = strlen(co);
3172 if (co_len == 0)
3173 return;
3175 sci_start_undo_action(editor->sci);
3177 for (i = first_line; (i <= last_line) && (! break_loop); i++)
3179 gint buf_len;
3181 line_start = sci_get_position_from_line(editor->sci, i);
3182 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
3183 x = 0;
3185 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
3186 if (buf_len < 0)
3187 continue;
3188 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3189 sel[buf_len] = '\0';
3191 while (isspace(sel[x])) x++;
3193 /* use single line comment */
3194 if (EMPTY(cc))
3196 gboolean do_continue = FALSE;
3197 single_line = TRUE;
3199 if (strncmp(sel + x, co, co_len) == 0 &&
3200 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) == 0)
3202 do_continue = TRUE;
3205 if (do_continue && i == first_line)
3206 first_line_was_comment = TRUE;
3207 last_line_was_comment = do_continue;
3209 if (do_continue)
3211 count_uncommented += editor_do_uncomment(editor, i, TRUE);
3212 continue;
3215 /* we are still here, so the above lines were not already comments, so comment it */
3216 count_commented += editor_do_comment(editor, i, FALSE, TRUE, TRUE);
3218 /* use multi line comment */
3219 else
3221 gint style_comment;
3223 /* skip lines which are already comments */
3224 style_comment = get_multiline_comment_style(editor, line_start);
3225 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3227 if (real_uncomment_multiline(editor))
3228 count_uncommented++;
3230 else
3232 real_comment_multiline(editor, line_start, last_line);
3233 count_commented++;
3236 /* break because we are already on the last line */
3237 break_loop = TRUE;
3238 break;
3242 sci_end_undo_action(editor->sci);
3244 co_len += tm_len;
3246 /* restore selection or caret position */
3247 if (single_line)
3249 gint a = (first_line_was_comment) ? - (gint) co_len : (gint) co_len;
3250 gint indent_len;
3252 /* don't modify sel_start when the selection starts within indentation */
3253 read_indent(editor, sel_start);
3254 indent_len = (gint) strlen(indent);
3255 if ((sel_start - first_line_start) <= indent_len)
3256 a = 0;
3257 /* if the selection start was inside the comment mark, adjust the position */
3258 else if (first_line_was_comment &&
3259 sel_start >= (first_line_start + indent_len) &&
3260 sel_start <= (first_line_start + indent_len + (gint) co_len))
3262 a = (first_line_start + indent_len) - sel_start;
3265 if (sel_start < sel_end)
3267 gint b = (count_commented * (gint) co_len) - (count_uncommented * (gint) co_len);
3269 /* same for selection end, but here we add an offset on the offset above */
3270 read_indent(editor, sel_end + b);
3271 indent_len = (gint) strlen(indent);
3272 if ((sel_end - last_line_start) < indent_len)
3273 b += last_line_was_comment ? (gint) co_len : -(gint) co_len;
3274 else if (last_line_was_comment &&
3275 sel_end >= (last_line_start + indent_len) &&
3276 sel_end <= (last_line_start + indent_len + (gint) co_len))
3278 b += (gint) co_len - (sel_end - (last_line_start + indent_len));
3281 sci_set_selection_start(editor->sci, sel_start + a);
3282 sci_set_selection_end(editor->sci, sel_end + b);
3284 else
3285 sci_set_current_position(editor->sci, sel_start + a, TRUE);
3287 else
3289 gint eol_len = editor_get_eol_char_len(editor);
3290 if (count_uncommented > 0)
3292 sci_set_selection_start(editor->sci, sel_start - (gint) co_len + eol_len);
3293 sci_set_selection_end(editor->sci, sel_end - (gint) co_len + eol_len);
3295 else if (count_commented > 0)
3297 sci_set_selection_start(editor->sci, sel_start + (gint) co_len - eol_len);
3298 sci_set_selection_end(editor->sci, sel_end + (gint) co_len - eol_len);
3300 if (sel_start >= sel_end)
3301 sci_scroll_caret(editor->sci);
3306 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise */
3307 gint editor_do_comment(GeanyEditor *editor, gint line, gboolean allow_empty_lines, gboolean toggle,
3308 gboolean single_comment)
3310 gint first_line, last_line;
3311 gint x, i, line_start, line_len;
3312 gint sel_start, sel_end, co_len;
3313 gint count = 0;
3314 gchar sel[256];
3315 const gchar *co, *cc;
3316 gboolean break_loop = FALSE, single_line = FALSE;
3317 GeanyFiletype *ft;
3319 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, 0);
3321 if (line < 0)
3322 { /* use selection or current line */
3323 sel_start = sci_get_selection_start(editor->sci);
3324 sel_end = sci_get_selection_end(editor->sci);
3326 first_line = sci_get_line_from_position(editor->sci, sel_start);
3327 /* Find the last line with chars selected (not EOL char) */
3328 last_line = sci_get_line_from_position(editor->sci,
3329 sel_end - editor_get_eol_char_len(editor));
3330 last_line = MAX(first_line, last_line);
3332 else
3334 first_line = last_line = line;
3335 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
3338 ft = editor_get_filetype_at_line(editor, first_line);
3340 if (! filetype_get_comment_open_close(ft, single_comment, &co, &cc))
3341 return 0;
3343 co_len = strlen(co);
3344 if (co_len == 0)
3345 return 0;
3347 sci_start_undo_action(editor->sci);
3349 for (i = first_line; (i <= last_line) && (! break_loop); i++)
3351 gint buf_len;
3353 line_start = sci_get_position_from_line(editor->sci, i);
3354 line_len = sci_get_line_end_position(editor->sci, i) - line_start;
3355 x = 0;
3357 buf_len = MIN((gint)sizeof(sel) - 1, line_len);
3358 if (buf_len < 0)
3359 continue;
3360 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3361 sel[buf_len] = '\0';
3363 while (isspace(sel[x])) x++;
3365 /* to skip blank lines */
3366 if (allow_empty_lines || (x < line_len && sel[x] != '\0'))
3368 /* use single line comment */
3369 if (EMPTY(cc))
3371 gint start = line_start;
3372 single_line = TRUE;
3374 if (ft->comment_use_indent)
3375 start = line_start + x;
3377 if (toggle)
3379 gchar *text = g_strconcat(co, editor_prefs.comment_toggle_mark, NULL);
3380 sci_insert_text(editor->sci, start, text);
3381 g_free(text);
3383 else
3384 sci_insert_text(editor->sci, start, co);
3385 count++;
3387 /* use multi line comment */
3388 else
3390 gint style_comment;
3392 /* skip lines which are already comments */
3393 style_comment = get_multiline_comment_style(editor, line_start);
3394 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3395 continue;
3397 real_comment_multiline(editor, line_start, last_line);
3398 count = 1;
3400 /* break because we are already on the last line */
3401 break_loop = TRUE;
3402 break;
3406 sci_end_undo_action(editor->sci);
3408 /* restore selection if there is one
3409 * but don't touch the selection if caller is editor_do_comment_toggle */
3410 if (! toggle && sel_start < sel_end)
3412 if (single_line)
3414 sci_set_selection_start(editor->sci, sel_start + co_len);
3415 sci_set_selection_end(editor->sci, sel_end + (count * co_len));
3417 else
3419 gint eol_len = editor_get_eol_char_len(editor);
3420 sci_set_selection_start(editor->sci, sel_start + co_len + eol_len);
3421 sci_set_selection_end(editor->sci, sel_end + co_len + eol_len);
3424 return count;
3428 static gboolean brace_timeout_active = FALSE;
3430 static gboolean delay_match_brace(G_GNUC_UNUSED gpointer user_data)
3432 GeanyDocument *doc = document_get_current();
3433 GeanyEditor *editor;
3434 gint brace_pos = GPOINTER_TO_INT(user_data);
3435 gint end_pos, cur_pos;
3437 brace_timeout_active = FALSE;
3438 if (!doc)
3439 return FALSE;
3441 editor = doc->editor;
3442 cur_pos = sci_get_current_position(editor->sci) - 1;
3444 if (cur_pos != brace_pos)
3446 cur_pos++;
3447 if (cur_pos != brace_pos)
3449 /* we have moved past the original brace_pos, but after the timeout
3450 * we may now be on a new brace, so check again */
3451 editor_highlight_braces(editor, cur_pos);
3452 return FALSE;
3455 if (!utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3457 editor_highlight_braces(editor, cur_pos);
3458 return FALSE;
3460 end_pos = sci_find_matching_brace(editor->sci, brace_pos);
3462 if (end_pos >= 0)
3464 gint col = MIN(sci_get_col_from_position(editor->sci, brace_pos),
3465 sci_get_col_from_position(editor->sci, end_pos));
3466 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, col, 0);
3467 SSM(editor->sci, SCI_BRACEHIGHLIGHT, brace_pos, end_pos);
3469 else
3471 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3472 SSM(editor->sci, SCI_BRACEBADLIGHT, brace_pos, 0);
3474 return FALSE;
3478 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos)
3480 gint brace_pos = cur_pos - 1;
3482 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3483 SSM(editor->sci, SCI_BRACEBADLIGHT, (uptr_t)-1, 0);
3485 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3487 brace_pos++;
3488 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3490 return;
3493 if (!brace_timeout_active)
3495 brace_timeout_active = TRUE;
3496 /* delaying matching makes scrolling faster e.g. holding down arrow keys */
3497 g_timeout_add(100, delay_match_brace, GINT_TO_POINTER(brace_pos));
3502 static gboolean in_block_comment(gint lexer, gint style)
3504 switch (lexer)
3506 case SCLEX_COBOL:
3507 case SCLEX_CPP:
3508 return (style == SCE_C_COMMENT ||
3509 style == SCE_C_COMMENTDOC);
3511 case SCLEX_PASCAL:
3512 return (style == SCE_PAS_COMMENT ||
3513 style == SCE_PAS_COMMENT2);
3515 case SCLEX_D:
3516 return (style == SCE_D_COMMENT ||
3517 style == SCE_D_COMMENTDOC ||
3518 style == SCE_D_COMMENTNESTED);
3520 case SCLEX_HTML:
3521 case SCLEX_PHPSCRIPT:
3522 return (style == SCE_HPHP_COMMENT);
3524 case SCLEX_CSS:
3525 return (style == SCE_CSS_COMMENT);
3527 case SCLEX_RUST:
3528 return (style == SCE_RUST_COMMENTBLOCK ||
3529 style == SCE_RUST_COMMENTBLOCKDOC);
3531 default:
3532 return FALSE;
3537 static gboolean is_comment_char(gchar c, gint lexer)
3539 if ((c == '*' || c == '+') && lexer == SCLEX_D)
3540 return TRUE;
3541 else
3542 if (c == '*')
3543 return TRUE;
3545 return FALSE;
3549 static void auto_multiline(GeanyEditor *editor, gint cur_line)
3551 ScintillaObject *sci = editor->sci;
3552 gint indent_pos, style;
3553 gint lexer = sci_get_lexer(sci);
3555 /* Use the start of the line enter was pressed on, to avoid any doc keyword styles */
3556 indent_pos = sci_get_line_indent_position(sci, cur_line - 1);
3557 style = sci_get_style_at(sci, indent_pos);
3558 if (!in_block_comment(lexer, style))
3559 return;
3561 /* Check whether the comment block continues on this line */
3562 indent_pos = sci_get_line_indent_position(sci, cur_line);
3563 if (sci_get_style_at(sci, indent_pos) == style || indent_pos >= sci_get_length(sci))
3565 gchar *previous_line = sci_get_line(sci, cur_line - 1);
3566 /* the type of comment, '*' (C/C++/Java), '+' and the others (D) */
3567 const gchar *continuation = "*";
3568 const gchar *whitespace = ""; /* to hold whitespace if needed */
3569 gchar *result;
3570 gint len = strlen(previous_line);
3571 gint i;
3573 /* find and stop at end of multi line comment */
3574 i = len - 1;
3575 while (i >= 0 && isspace(previous_line[i])) i--;
3576 if (i >= 1 && is_comment_char(previous_line[i - 1], lexer) && previous_line[i] == '/')
3578 gint indent_len, indent_width;
3580 indent_pos = sci_get_line_indent_position(sci, cur_line);
3581 indent_len = sci_get_col_from_position(sci, indent_pos);
3582 indent_width = editor_get_indent_prefs(editor)->width;
3584 /* if there is one too many spaces, delete the last space,
3585 * to return to the indent used before the multiline comment was started. */
3586 if (indent_len % indent_width == 1)
3587 SSM(sci, SCI_DELETEBACKNOTLINE, 0, 0); /* remove whitespace indent */
3588 g_free(previous_line);
3589 return;
3591 /* check whether we are on the second line of multi line comment */
3592 i = 0;
3593 while (i < len && isspace(previous_line[i])) i++; /* get to start of the line */
3595 if (i + 1 < len &&
3596 previous_line[i] == '/' && is_comment_char(previous_line[i + 1], lexer))
3597 { /* we are on the second line of a multi line comment, so we have to insert white space */
3598 whitespace = " ";
3601 if (style == SCE_D_COMMENTNESTED)
3602 continuation = "+"; /* for nested comments in D */
3604 result = g_strconcat(whitespace, continuation, " ", NULL);
3605 sci_add_text(sci, result);
3606 g_free(result);
3608 g_free(previous_line);
3613 #if 0
3614 static gboolean editor_lexer_is_c_like(gint lexer)
3616 switch (lexer)
3618 case SCLEX_CPP:
3619 case SCLEX_D:
3620 return TRUE;
3622 default:
3623 return FALSE;
3626 #endif
3629 /* inserts a three-line comment at one line above current cursor position */
3630 void editor_insert_multiline_comment(GeanyEditor *editor)
3632 gchar *text;
3633 gint text_len;
3634 gint line;
3635 gint pos;
3636 gboolean have_multiline_comment = FALSE;
3637 GeanyDocument *doc;
3638 const gchar *co, *cc;
3640 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
3642 if (! filetype_get_comment_open_close(editor->document->file_type, FALSE, &co, &cc))
3643 g_return_if_reached();
3644 if (!EMPTY(cc))
3645 have_multiline_comment = TRUE;
3647 sci_start_undo_action(editor->sci);
3649 doc = editor->document;
3651 /* insert three lines one line above of the current position */
3652 line = sci_get_line_from_position(editor->sci, editor_info.click_pos);
3653 pos = sci_get_position_from_line(editor->sci, line);
3655 /* use the indent on the current line but only when comment indentation is used
3656 * and we don't have multi line comment characters */
3657 if (editor->auto_indent &&
3658 ! have_multiline_comment && doc->file_type->comment_use_indent)
3660 read_indent(editor, editor_info.click_pos);
3661 text = g_strdup_printf("%s\n%s\n%s\n", indent, indent, indent);
3662 text_len = strlen(text);
3664 else
3666 text = g_strdup("\n\n\n");
3667 text_len = 3;
3669 sci_insert_text(editor->sci, pos, text);
3670 g_free(text);
3672 /* select the inserted lines for commenting */
3673 sci_set_selection_start(editor->sci, pos);
3674 sci_set_selection_end(editor->sci, pos + text_len);
3676 editor_do_comment(editor, -1, TRUE, FALSE, FALSE);
3678 /* set the current position to the start of the first inserted line */
3679 pos += strlen(co);
3681 /* on multi line comment jump to the next line, otherwise add the length of added indentation */
3682 if (have_multiline_comment)
3683 pos += 1;
3684 else
3685 pos += strlen(indent);
3687 sci_set_current_position(editor->sci, pos, TRUE);
3688 /* reset the selection */
3689 sci_set_anchor(editor->sci, pos);
3691 sci_end_undo_action(editor->sci);
3695 /* Note: If the editor is pending a redraw, set document::scroll_percent instead.
3696 * Scroll the view to make line appear at percent_of_view.
3697 * line can be -1 to use the current position. */
3698 void editor_scroll_to_line(GeanyEditor *editor, gint line, gfloat percent_of_view)
3700 gint los;
3701 GtkWidget *wid;
3703 g_return_if_fail(editor != NULL);
3705 wid = GTK_WIDGET(editor->sci);
3707 if (! gtk_widget_get_window(wid) || ! gdk_window_is_viewable(gtk_widget_get_window(wid)))
3708 return; /* prevent gdk_window_scroll warning */
3710 if (line == -1)
3711 line = sci_get_current_line(editor->sci);
3713 /* sci 'visible line' != doc line number because of folding and line wrapping */
3714 /* calling SCI_VISIBLEFROMDOCLINE for line is more accurate than calling
3715 * SCI_DOCLINEFROMVISIBLE for vis1. */
3716 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0);
3717 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
3718 line = line - los * percent_of_view;
3719 SSM(editor->sci, SCI_SETFIRSTVISIBLELINE, line, 0);
3720 sci_scroll_caret(editor->sci); /* needed for horizontal scrolling */
3724 /* creates and inserts one tab or whitespace of the amount of the tab width */
3725 void editor_insert_alternative_whitespace(GeanyEditor *editor)
3727 gchar *text;
3728 GeanyIndentPrefs iprefs = *editor_get_indent_prefs(editor);
3730 g_return_if_fail(editor != NULL);
3732 switch (iprefs.type)
3734 case GEANY_INDENT_TYPE_TABS:
3735 iprefs.type = GEANY_INDENT_TYPE_SPACES;
3736 break;
3737 case GEANY_INDENT_TYPE_SPACES:
3738 case GEANY_INDENT_TYPE_BOTH: /* most likely we want a tab */
3739 iprefs.type = GEANY_INDENT_TYPE_TABS;
3740 break;
3742 text = get_whitespace(&iprefs, iprefs.width);
3743 sci_add_text(editor->sci, text);
3744 g_free(text);
3748 void editor_select_word(GeanyEditor *editor)
3750 gint pos;
3751 gint start;
3752 gint end;
3754 g_return_if_fail(editor != NULL);
3756 pos = SSM(editor->sci, SCI_GETCURRENTPOS, 0, 0);
3757 start = sci_word_start_position(editor->sci, pos, TRUE);
3758 end = sci_word_end_position(editor->sci, pos, TRUE);
3760 if (start == end) /* caret in whitespaces sequence */
3762 /* look forward but reverse the selection direction,
3763 * so the caret end up stay as near as the original position. */
3764 end = sci_word_end_position(editor->sci, pos, FALSE);
3765 start = sci_word_end_position(editor->sci, end, TRUE);
3766 if (start == end)
3767 return;
3770 sci_set_selection(editor->sci, start, end);
3774 /* extra_line is for selecting the cursor line (or anchor line) at the bottom of a selection,
3775 * when those lines have no selection (cursor at start of line). */
3776 void editor_select_lines(GeanyEditor *editor, gboolean extra_line)
3778 gint start, end, line;
3780 g_return_if_fail(editor != NULL);
3782 start = sci_get_selection_start(editor->sci);
3783 end = sci_get_selection_end(editor->sci);
3785 /* check if whole lines are already selected */
3786 if (! extra_line && start != end &&
3787 sci_get_col_from_position(editor->sci, start) == 0 &&
3788 sci_get_col_from_position(editor->sci, end) == 0)
3789 return;
3791 line = sci_get_line_from_position(editor->sci, start);
3792 start = sci_get_position_from_line(editor->sci, line);
3794 line = sci_get_line_from_position(editor->sci, end);
3795 end = sci_get_position_from_line(editor->sci, line + 1);
3797 sci_set_selection(editor->sci, start, end);
3801 static gboolean sci_is_blank_line(ScintillaObject *sci, gint line)
3803 return sci_get_line_indent_position(sci, line) ==
3804 sci_get_line_end_position(sci, line);
3808 /* Returns first line of paragraph for GTK_DIR_UP, line after paragraph
3809 * ends for GTK_DIR_DOWN or -1 if called on an empty line. */
3810 static gint find_paragraph_stop(GeanyEditor *editor, gint line, gint direction)
3812 gint step;
3813 ScintillaObject *sci = editor->sci;
3815 /* first check current line and return -1 if it is empty to skip creating of a selection */
3816 if (sci_is_blank_line(sci, line))
3817 return -1;
3819 if (direction == GTK_DIR_UP)
3820 step = -1;
3821 else
3822 step = 1;
3824 while (TRUE)
3826 line += step;
3827 if (line == -1)
3829 /* start of document */
3830 line = 0;
3831 break;
3833 if (line == sci_get_line_count(sci))
3834 break;
3836 if (sci_is_blank_line(sci, line))
3838 /* return line paragraph starts on */
3839 if (direction == GTK_DIR_UP)
3840 line++;
3841 break;
3844 return line;
3848 void editor_select_paragraph(GeanyEditor *editor)
3850 gint pos_start, pos_end, line_start, line_found;
3852 g_return_if_fail(editor != NULL);
3854 line_start = sci_get_current_line(editor->sci);
3856 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_UP);
3857 if (line_found == -1)
3858 return;
3860 pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3862 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_DOWN);
3863 pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3865 sci_set_selection(editor->sci, pos_start, pos_end);
3869 /* Returns first line of block for GTK_DIR_UP, line after block
3870 * ends for GTK_DIR_DOWN or -1 if called on an empty line. */
3871 static gint find_block_stop(GeanyEditor *editor, gint line, gint direction)
3873 gint step, ind;
3874 ScintillaObject *sci = editor->sci;
3876 /* first check current line and return -1 if it is empty to skip creating of a selection */
3877 if (sci_is_blank_line(sci, line))
3878 return -1;
3880 if (direction == GTK_DIR_UP)
3881 step = -1;
3882 else
3883 step = 1;
3885 ind = sci_get_line_indentation(sci, line);
3886 while (TRUE)
3888 line += step;
3889 if (line == -1)
3891 /* start of document */
3892 line = 0;
3893 break;
3895 if (line == sci_get_line_count(sci))
3896 break;
3898 if (sci_get_line_indentation(sci, line) != ind ||
3899 sci_is_blank_line(sci, line))
3901 /* return line block starts on */
3902 if (direction == GTK_DIR_UP)
3903 line++;
3904 break;
3907 return line;
3911 void editor_select_indent_block(GeanyEditor *editor)
3913 gint pos_start, pos_end, line_start, line_found;
3915 g_return_if_fail(editor != NULL);
3917 line_start = sci_get_current_line(editor->sci);
3919 line_found = find_block_stop(editor, line_start, GTK_DIR_UP);
3920 if (line_found == -1)
3921 return;
3923 pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3925 line_found = find_block_stop(editor, line_start, GTK_DIR_DOWN);
3926 pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3928 sci_set_selection(editor->sci, pos_start, pos_end);
3932 /* simple indentation to indent the current line with the same indent as the previous one */
3933 static void smart_line_indentation(GeanyEditor *editor, gint first_line, gint last_line)
3935 gint i, sel_start = 0, sel_end = 0;
3937 /* get previous line and use it for read_indent to use that line
3938 * (otherwise it would fail on a line only containing "{" in advanced indentation mode) */
3939 read_indent(editor, sci_get_position_from_line(editor->sci, first_line - 1));
3941 for (i = first_line; i <= last_line; i++)
3943 /* skip the first line or if the indentation of the previous and current line are equal */
3944 if (i == 0 ||
3945 SSM(editor->sci, SCI_GETLINEINDENTATION, i - 1, 0) ==
3946 SSM(editor->sci, SCI_GETLINEINDENTATION, i, 0))
3947 continue;
3949 sel_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
3950 sel_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
3951 if (sel_start < sel_end)
3953 sci_set_selection(editor->sci, sel_start, sel_end);
3954 sci_replace_sel(editor->sci, "");
3956 sci_insert_text(editor->sci, sel_start, indent);
3961 /* simple indentation to indent the current line with the same indent as the previous one */
3962 void editor_smart_line_indentation(GeanyEditor *editor, gint pos)
3964 gint first_line, last_line;
3965 gint first_sel_start, first_sel_end;
3966 ScintillaObject *sci;
3968 g_return_if_fail(editor != NULL);
3970 sci = editor->sci;
3972 first_sel_start = sci_get_selection_start(sci);
3973 first_sel_end = sci_get_selection_end(sci);
3975 first_line = sci_get_line_from_position(sci, first_sel_start);
3976 /* Find the last line with chars selected (not EOL char) */
3977 last_line = sci_get_line_from_position(sci, first_sel_end - editor_get_eol_char_len(editor));
3978 last_line = MAX(first_line, last_line);
3980 if (pos == -1)
3981 pos = first_sel_start;
3983 sci_start_undo_action(sci);
3985 smart_line_indentation(editor, first_line, last_line);
3987 /* set cursor position if there was no selection */
3988 if (first_sel_start == first_sel_end)
3990 gint indent_pos = SSM(sci, SCI_GETLINEINDENTPOSITION, first_line, 0);
3992 /* use indent position as user may wish to change indentation afterwards */
3993 sci_set_current_position(sci, indent_pos, FALSE);
3995 else
3997 /* fully select all the lines affected */
3998 sci_set_selection_start(sci, sci_get_position_from_line(sci, first_line));
3999 sci_set_selection_end(sci, sci_get_position_from_line(sci, last_line + 1));
4002 sci_end_undo_action(sci);
4006 /* increase / decrease current line or selection by one space */
4007 void editor_indentation_by_one_space(GeanyEditor *editor, gint pos, gboolean decrease)
4009 gint i, first_line, last_line, line_start, indentation_end, count = 0;
4010 gint sel_start, sel_end, first_line_offset = 0;
4012 g_return_if_fail(editor != NULL);
4014 sel_start = sci_get_selection_start(editor->sci);
4015 sel_end = sci_get_selection_end(editor->sci);
4017 first_line = sci_get_line_from_position(editor->sci, sel_start);
4018 /* Find the last line with chars selected (not EOL char) */
4019 last_line = sci_get_line_from_position(editor->sci, sel_end - editor_get_eol_char_len(editor));
4020 last_line = MAX(first_line, last_line);
4022 if (pos == -1)
4023 pos = sel_start;
4025 sci_start_undo_action(editor->sci);
4027 for (i = first_line; i <= last_line; i++)
4029 indentation_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
4030 if (decrease)
4032 line_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
4033 /* searching backwards for a space to remove */
4034 while (sci_get_char_at(editor->sci, indentation_end) != ' ' && indentation_end > line_start)
4035 indentation_end--;
4037 if (sci_get_char_at(editor->sci, indentation_end) == ' ')
4039 sci_set_selection(editor->sci, indentation_end, indentation_end + 1);
4040 sci_replace_sel(editor->sci, "");
4041 count--;
4042 if (i == first_line)
4043 first_line_offset = -1;
4046 else
4048 sci_insert_text(editor->sci, indentation_end, " ");
4049 count++;
4050 if (i == first_line)
4051 first_line_offset = 1;
4055 /* set cursor position */
4056 if (sel_start < sel_end)
4058 gint start = sel_start + first_line_offset;
4059 if (first_line_offset < 0)
4060 start = MAX(sel_start + first_line_offset,
4061 SSM(editor->sci, SCI_POSITIONFROMLINE, first_line, 0));
4063 sci_set_selection_start(editor->sci, start);
4064 sci_set_selection_end(editor->sci, sel_end + count);
4066 else
4067 sci_set_current_position(editor->sci, pos + count, FALSE);
4069 sci_end_undo_action(editor->sci);
4073 void editor_finalize(void)
4075 scintilla_release_resources();
4079 /* wordchars: NULL or a string containing characters to match a word.
4080 * Returns: the current selection or the current word.
4082 * Passing NULL as wordchars is NOT the same as passing GEANY_WORDCHARS: NULL means
4083 * using Scintillas's word boundaries. */
4084 gchar *editor_get_default_selection(GeanyEditor *editor, gboolean use_current_word,
4085 const gchar *wordchars)
4087 gchar *s = NULL;
4089 g_return_val_if_fail(editor != NULL, NULL);
4091 if (sci_get_lines_selected(editor->sci) == 1)
4092 s = sci_get_selection_contents(editor->sci);
4093 else if (sci_get_lines_selected(editor->sci) == 0 && use_current_word)
4094 { /* use the word at current cursor position */
4095 gchar word[GEANY_MAX_WORD_LENGTH];
4097 if (wordchars != NULL)
4098 editor_find_current_word(editor, -1, word, sizeof(word), wordchars);
4099 else
4100 editor_find_current_word_sciwc(editor, -1, word, sizeof(word));
4102 if (word[0] != '\0')
4103 s = g_strdup(word);
4105 return s;
4109 /* Note: Usually the line should be made visible (not folded) before calling this.
4110 * Returns: TRUE if line is/will be displayed to the user, or FALSE if it is
4111 * outside the *vertical* view.
4112 * Warning: You may need horizontal scrolling to make the cursor visible - so always call
4113 * sci_scroll_caret() when this returns TRUE. */
4114 gboolean editor_line_in_view(GeanyEditor *editor, gint line)
4116 gint vis1, los;
4118 g_return_val_if_fail(editor != NULL, FALSE);
4120 /* If line is wrapped the result may occur on another virtual line than the first and may be
4121 * still hidden, so increase the line number to check for the next document line */
4122 if (SSM(editor->sci, SCI_WRAPCOUNT, line, 0) > 1)
4123 line++;
4125 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0); /* convert to visible line number */
4126 vis1 = SSM(editor->sci, SCI_GETFIRSTVISIBLELINE, 0, 0);
4127 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
4129 return (line >= vis1 && line < vis1 + los);
4133 /* If the current line is outside the current view window, scroll the line
4134 * so it appears at percent_of_view. */
4135 void editor_display_current_line(GeanyEditor *editor, gfloat percent_of_view)
4137 gint line;
4139 g_return_if_fail(editor != NULL);
4141 line = sci_get_current_line(editor->sci);
4143 /* unfold maybe folded results */
4144 sci_ensure_line_is_visible(editor->sci, line);
4146 /* scroll the line if it's off screen */
4147 if (! editor_line_in_view(editor, line))
4148 editor->scroll_percent = percent_of_view;
4149 else
4150 sci_scroll_caret(editor->sci); /* may need horizontal scrolling */
4155 * Deletes all currently set indicators in the @a editor window.
4156 * Error indicators (red squiggly underlines) and usual line markers are removed.
4158 * @param editor The editor to operate on.
4160 void editor_indicator_clear_errors(GeanyEditor *editor)
4162 editor_indicator_clear(editor, GEANY_INDICATOR_ERROR);
4163 sci_marker_delete_all(editor->sci, 0); /* remove the yellow error line marker */
4168 * Deletes all currently set indicators matching @a indic in the @a editor window.
4170 * @param editor The editor to operate on.
4171 * @param indic The indicator number to clear, this is a value of @ref GeanyIndicator.
4173 * @since 0.16
4175 GEANY_API_SYMBOL
4176 void editor_indicator_clear(GeanyEditor *editor, gint indic)
4178 glong last_pos;
4180 g_return_if_fail(editor != NULL);
4182 last_pos = sci_get_length(editor->sci);
4183 if (last_pos > 0)
4185 sci_indicator_set(editor->sci, indic);
4186 sci_indicator_clear(editor->sci, 0, last_pos);
4192 * Sets an indicator @a indic on @a line.
4193 * Whitespace at the start and the end of the line is not marked.
4195 * @param editor The editor to operate on.
4196 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4197 * @param line The line number which should be marked.
4199 * @since 0.16
4201 GEANY_API_SYMBOL
4202 void editor_indicator_set_on_line(GeanyEditor *editor, gint indic, gint line)
4204 gint start, end;
4205 guint i = 0, len;
4206 gchar *linebuf;
4208 g_return_if_fail(editor != NULL);
4209 g_return_if_fail(line >= 0);
4211 start = sci_get_position_from_line(editor->sci, line);
4212 end = sci_get_position_from_line(editor->sci, line + 1);
4214 /* skip blank lines */
4215 if ((start + 1) == end ||
4216 start > end ||
4217 (sci_get_line_end_position(editor->sci, line) - start) == 0)
4219 return;
4222 len = end - start;
4223 linebuf = sci_get_line(editor->sci, line);
4225 /* don't set the indicator on whitespace */
4226 while (isspace(linebuf[i]))
4227 i++;
4228 while (len > 1 && len > i && isspace(linebuf[len - 1]))
4230 len--;
4231 end--;
4233 g_free(linebuf);
4235 editor_indicator_set_on_range(editor, indic, start + i, end);
4240 * Sets an indicator on the range specified by @a start and @a end.
4241 * No error checking or whitespace removal is performed, this should be done by the calling
4242 * function if necessary.
4244 * @param editor The editor to operate on.
4245 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4246 * @param start The starting position for the marker.
4247 * @param end The ending position for the marker.
4249 * @since 0.16
4251 GEANY_API_SYMBOL
4252 void editor_indicator_set_on_range(GeanyEditor *editor, gint indic, gint start, gint end)
4254 g_return_if_fail(editor != NULL);
4255 if (start >= end)
4256 return;
4258 sci_indicator_set(editor->sci, indic);
4259 sci_indicator_fill(editor->sci, start, end - start);
4263 /* Inserts the given colour (format should be #...), if there is a selection starting with 0x...
4264 * the replacement will also start with 0x... */
4265 void editor_insert_color(GeanyEditor *editor, const gchar *colour)
4267 g_return_if_fail(editor != NULL);
4269 if (sci_has_selection(editor->sci))
4271 gint start = sci_get_selection_start(editor->sci);
4272 const gchar *replacement = colour;
4274 if (sci_get_char_at(editor->sci, start) == '0' &&
4275 sci_get_char_at(editor->sci, start + 1) == 'x')
4277 gint end = sci_get_selection_end(editor->sci);
4279 sci_set_selection_start(editor->sci, start + 2);
4280 /* we need to also re-set the selection end in case the anchor was located before
4281 * the cursor, since set_selection_start() always moves the cursor, not the anchor */
4282 sci_set_selection_end(editor->sci, end);
4283 replacement++; /* skip the leading "0x" */
4285 else if (sci_get_char_at(editor->sci, start - 1) == '#')
4286 { /* double clicking something like #00ffff may only select 00ffff because of wordchars */
4287 replacement++; /* so skip the '#' to only replace the colour value */
4289 sci_replace_sel(editor->sci, replacement);
4291 else
4292 sci_add_text(editor->sci, colour);
4297 * Retrieves the end of line characters mode (LF, CR/LF, CR) in the given editor.
4298 * If @a editor is @c NULL, the default end of line characters are used.
4300 * @param editor @nullable The editor to operate on, or @c NULL to query the default value.
4301 * @return The used end of line characters mode.
4303 * @since 0.20
4305 GEANY_API_SYMBOL
4306 gint editor_get_eol_char_mode(GeanyEditor *editor)
4308 gint mode = file_prefs.default_eol_character;
4310 if (editor != NULL)
4311 mode = sci_get_eol_mode(editor->sci);
4313 return mode;
4318 * Retrieves the localized name (for displaying) of the used end of line characters
4319 * (LF, CR/LF, CR) in the given editor.
4320 * If @a editor is @c NULL, the default end of line characters are used.
4322 * @param editor @nullable The editor to operate on, or @c NULL to query the default value.
4323 * @return The name of the end of line characters.
4325 * @since 0.19
4327 GEANY_API_SYMBOL
4328 const gchar *editor_get_eol_char_name(GeanyEditor *editor)
4330 gint mode = file_prefs.default_eol_character;
4332 if (editor != NULL)
4333 mode = sci_get_eol_mode(editor->sci);
4335 return utils_get_eol_name(mode);
4340 * Retrieves the length of the used end of line characters (LF, CR/LF, CR) in the given editor.
4341 * If @a editor is @c NULL, the default end of line characters are used.
4342 * The returned value is 1 for CR and LF and 2 for CR/LF.
4344 * @param editor @nullable The editor to operate on, or @c NULL to query the default value.
4345 * @return The length of the end of line characters.
4347 * @since 0.19
4349 GEANY_API_SYMBOL
4350 gint editor_get_eol_char_len(GeanyEditor *editor)
4352 gint mode = file_prefs.default_eol_character;
4354 if (editor != NULL)
4355 mode = sci_get_eol_mode(editor->sci);
4357 switch (mode)
4359 case SC_EOL_CRLF: return 2; break;
4360 default: return 1; break;
4366 * Retrieves the used end of line characters (LF, CR/LF, CR) in the given editor.
4367 * If @a editor is @c NULL, the default end of line characters are used.
4368 * The returned value is either "\n", "\r\n" or "\r".
4370 * @param editor @nullable The editor to operate on, or @c NULL to query the default value.
4371 * @return The end of line characters.
4373 * @since 0.19
4375 GEANY_API_SYMBOL
4376 const gchar *editor_get_eol_char(GeanyEditor *editor)
4378 gint mode = file_prefs.default_eol_character;
4380 if (editor != NULL)
4381 mode = sci_get_eol_mode(editor->sci);
4383 return utils_get_eol_char(mode);
4387 static void fold_all(GeanyEditor *editor, gboolean want_fold)
4389 gint lines, first, i;
4391 if (editor == NULL || ! editor_prefs.folding)
4392 return;
4394 lines = sci_get_line_count(editor->sci);
4395 first = sci_get_first_visible_line(editor->sci);
4397 for (i = 0; i < lines; i++)
4399 gint level = sci_get_fold_level(editor->sci, i);
4401 if (level & SC_FOLDLEVELHEADERFLAG)
4403 if (sci_get_fold_expanded(editor->sci, i) == want_fold)
4404 sci_toggle_fold(editor->sci, i);
4407 editor_scroll_to_line(editor, first, 0.0F);
4411 void editor_unfold_all(GeanyEditor *editor)
4413 fold_all(editor, FALSE);
4417 void editor_fold_all(GeanyEditor *editor)
4419 fold_all(editor, TRUE);
4423 void editor_replace_tabs(GeanyEditor *editor, gboolean ignore_selection)
4425 gint search_pos, pos_in_line, current_tab_true_length;
4426 gint anchor_pos, caret_pos;
4427 gint tab_len;
4428 gchar *tab_str;
4429 struct Sci_TextToFind ttf;
4431 g_return_if_fail(editor != NULL);
4433 sci_start_undo_action(editor->sci);
4434 tab_len = sci_get_tab_width(editor->sci);
4435 if (sci_has_selection(editor->sci) && !ignore_selection)
4437 ttf.chrg.cpMin = sci_get_selection_start(editor->sci);
4438 ttf.chrg.cpMax = sci_get_selection_end(editor->sci);
4440 else
4442 ttf.chrg.cpMin = 0;
4443 ttf.chrg.cpMax = sci_get_length(editor->sci);
4445 ttf.lpstrText = (gchar*) "\t";
4447 anchor_pos = SSM(editor->sci, SCI_GETANCHOR, 0, 0);
4448 caret_pos = sci_get_current_position(editor->sci);
4449 while (TRUE)
4451 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4452 if (search_pos == -1)
4453 break;
4455 pos_in_line = sci_get_col_from_position(editor->sci, search_pos);
4456 current_tab_true_length = tab_len - (pos_in_line % tab_len);
4457 tab_str = g_strnfill(current_tab_true_length, ' ');
4458 sci_set_target_start(editor->sci, search_pos);
4459 sci_set_target_end(editor->sci, search_pos + 1);
4460 sci_replace_target(editor->sci, tab_str, FALSE);
4461 /* next search starts after replacement */
4462 ttf.chrg.cpMin = search_pos + current_tab_true_length - 1;
4463 /* update end of range now text has changed */
4464 ttf.chrg.cpMax += current_tab_true_length - 1;
4465 g_free(tab_str);
4467 if (anchor_pos > search_pos)
4468 anchor_pos += current_tab_true_length - 1;
4469 if (caret_pos > search_pos)
4470 caret_pos += current_tab_true_length - 1;
4472 sci_set_selection(editor->sci, anchor_pos, caret_pos);
4473 sci_end_undo_action(editor->sci);
4477 /* Replaces all occurrences all spaces of the length of a given tab_width,
4478 * optionally restricting the search to the current selection. */
4479 void editor_replace_spaces(GeanyEditor *editor, gboolean ignore_selection)
4481 gint search_pos;
4482 gint anchor_pos, caret_pos;
4483 static gdouble tab_len_f = -1.0; /* keep the last used value */
4484 gint tab_len;
4485 gchar *text;
4486 struct Sci_TextToFind ttf;
4488 g_return_if_fail(editor != NULL);
4490 if (tab_len_f < 0.0)
4491 tab_len_f = sci_get_tab_width(editor->sci);
4493 if (! dialogs_show_input_numeric(
4494 _("Enter Tab Width"),
4495 _("Enter the amount of spaces which should be replaced by a tab character."),
4496 &tab_len_f, 1, 100, 1))
4498 return;
4500 tab_len = (gint) tab_len_f;
4501 text = g_strnfill(tab_len, ' ');
4503 sci_start_undo_action(editor->sci);
4504 if (sci_has_selection(editor->sci) && !ignore_selection)
4506 ttf.chrg.cpMin = sci_get_selection_start(editor->sci);
4507 ttf.chrg.cpMax = sci_get_selection_end(editor->sci);
4509 else
4511 ttf.chrg.cpMin = 0;
4512 ttf.chrg.cpMax = sci_get_length(editor->sci);
4514 ttf.lpstrText = text;
4516 anchor_pos = SSM(editor->sci, SCI_GETANCHOR, 0, 0);
4517 caret_pos = sci_get_current_position(editor->sci);
4518 while (TRUE)
4520 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4521 if (search_pos == -1)
4522 break;
4523 /* only replace indentation because otherwise we can mess up alignment */
4524 if (search_pos > sci_get_line_indent_position(editor->sci,
4525 sci_get_line_from_position(editor->sci, search_pos)))
4527 ttf.chrg.cpMin = search_pos + tab_len;
4528 continue;
4530 sci_set_target_start(editor->sci, search_pos);
4531 sci_set_target_end(editor->sci, search_pos + tab_len);
4532 sci_replace_target(editor->sci, "\t", FALSE);
4533 ttf.chrg.cpMin = search_pos;
4534 /* update end of range now text has changed */
4535 ttf.chrg.cpMax -= tab_len - 1;
4537 if (anchor_pos > search_pos)
4538 anchor_pos -= tab_len - 1;
4539 if (caret_pos > search_pos)
4540 caret_pos -= tab_len - 1;
4542 sci_set_selection(editor->sci, anchor_pos, caret_pos);
4543 sci_end_undo_action(editor->sci);
4544 g_free(text);
4548 void editor_strip_line_trailing_spaces(GeanyEditor *editor, gint line)
4550 gint line_start = sci_get_position_from_line(editor->sci, line);
4551 gint line_end = sci_get_line_end_position(editor->sci, line);
4552 gint i = line_end - 1;
4553 gchar ch = sci_get_char_at(editor->sci, i);
4555 /* Diff hunks should keep trailing spaces */
4556 if (sci_get_lexer(editor->sci) == SCLEX_DIFF)
4557 return;
4559 while ((i >= line_start) && ((ch == ' ') || (ch == '\t')))
4561 i--;
4562 ch = sci_get_char_at(editor->sci, i);
4564 if (i < (line_end - 1))
4566 sci_set_target_start(editor->sci, i + 1);
4567 sci_set_target_end(editor->sci, line_end);
4568 sci_replace_target(editor->sci, "", FALSE);
4573 void editor_strip_trailing_spaces(GeanyEditor *editor, gboolean ignore_selection)
4575 gint start_line;
4576 gint end_line;
4577 gint line;
4579 if (sci_has_selection(editor->sci) && !ignore_selection)
4581 gint selection_start = sci_get_selection_start(editor->sci);
4582 gint selection_end = sci_get_selection_end(editor->sci);
4584 start_line = sci_get_line_from_position(editor->sci, selection_start);
4585 end_line = sci_get_line_from_position(editor->sci, selection_end);
4587 if (sci_get_col_from_position(editor->sci, selection_end) > 0)
4588 end_line++;
4590 else
4592 start_line = 0;
4593 end_line = sci_get_line_count(editor->sci);
4596 sci_start_undo_action(editor->sci);
4598 for (line = start_line; line < end_line; line++)
4600 editor_strip_line_trailing_spaces(editor, line);
4602 sci_end_undo_action(editor->sci);
4606 void editor_ensure_final_newline(GeanyEditor *editor)
4608 gint max_lines = sci_get_line_count(editor->sci);
4609 gboolean append_newline = (max_lines == 1);
4610 gint end_document = sci_get_position_from_line(editor->sci, max_lines);
4612 if (max_lines > 1)
4614 append_newline = end_document > sci_get_position_from_line(editor->sci, max_lines - 1);
4616 if (append_newline)
4618 const gchar *eol = editor_get_eol_char(editor);
4620 sci_insert_text(editor->sci, end_document, eol);
4625 void editor_set_font(GeanyEditor *editor, const gchar *font)
4627 gint style, size;
4628 gchar *font_name;
4629 PangoFontDescription *pfd;
4631 g_return_if_fail(editor);
4633 pfd = pango_font_description_from_string(font);
4634 size = pango_font_description_get_size(pfd) / PANGO_SCALE;
4635 font_name = g_strdup_printf("!%s", pango_font_description_get_family(pfd));
4636 pango_font_description_free(pfd);
4638 for (style = 0; style <= STYLE_MAX; style++)
4639 sci_set_font(editor->sci, style, font_name, size);
4641 g_free(font_name);
4643 /* zoom to 100% to prevent confusion */
4644 sci_zoom_off(editor->sci);
4648 void editor_set_line_wrapping(GeanyEditor *editor, gboolean wrap)
4650 g_return_if_fail(editor != NULL);
4652 editor->line_wrapping = wrap;
4653 sci_set_lines_wrapped(editor->sci, wrap);
4657 /** Sets the indent type for @a editor.
4658 * @param editor Editor.
4659 * @param type Indent type.
4661 * @since 0.16
4663 GEANY_API_SYMBOL
4664 void editor_set_indent_type(GeanyEditor *editor, GeanyIndentType type)
4666 editor_set_indent(editor, type, editor->indent_width);
4670 /** Sets the indent width for @a editor.
4671 * @param editor Editor.
4672 * @param width New indent width.
4674 * @since 1.27 (API 227)
4676 GEANY_API_SYMBOL
4677 void editor_set_indent_width(GeanyEditor *editor, gint width)
4679 editor_set_indent(editor, editor->indent_type, width);
4683 void editor_set_indent(GeanyEditor *editor, GeanyIndentType type, gint width)
4685 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
4686 ScintillaObject *sci = editor->sci;
4687 gboolean use_tabs = type != GEANY_INDENT_TYPE_SPACES;
4689 editor->indent_type = type;
4690 editor->indent_width = width;
4691 sci_set_use_tabs(sci, use_tabs);
4693 if (type == GEANY_INDENT_TYPE_BOTH)
4695 sci_set_tab_width(sci, iprefs->hard_tab_width);
4696 if (iprefs->hard_tab_width != 8)
4698 static gboolean warn = TRUE;
4699 if (warn)
4700 ui_set_statusbar(TRUE, _("Warning: non-standard hard tab width: %d != 8!"),
4701 iprefs->hard_tab_width);
4702 warn = FALSE;
4705 else
4706 sci_set_tab_width(sci, width);
4708 SSM(sci, SCI_SETINDENT, width, 0);
4710 /* remove indent spaces on backspace, if using any spaces to indent */
4711 SSM(sci, SCI_SETBACKSPACEUNINDENTS, type != GEANY_INDENT_TYPE_TABS, 0);
4715 /* Convenience function for editor_goto_pos() to pass in a line number. */
4716 gboolean editor_goto_line(GeanyEditor *editor, gint line_no, gint offset)
4718 gint pos;
4720 g_return_val_if_fail(editor, FALSE);
4721 if (line_no < 0 || line_no >= sci_get_line_count(editor->sci))
4722 return FALSE;
4724 if (offset != 0)
4726 gint current_line = sci_get_current_line(editor->sci);
4727 line_no *= offset;
4728 line_no = current_line + line_no;
4731 pos = sci_get_position_from_line(editor->sci, line_no);
4732 return editor_goto_pos(editor, pos, TRUE);
4736 /** Moves to position @a pos, switching to the document if necessary,
4737 * setting a marker if @a mark is set.
4739 * @param editor Editor.
4740 * @param pos The position.
4741 * @param mark Whether to set a mark on the position.
4742 * @return @c TRUE if action has been performed, otherwise @c FALSE.
4744 * @since 0.20
4746 GEANY_API_SYMBOL
4747 gboolean editor_goto_pos(GeanyEditor *editor, gint pos, gboolean mark)
4749 g_return_val_if_fail(editor, FALSE);
4750 if (G_UNLIKELY(pos < 0))
4751 return FALSE;
4753 if (mark)
4755 gint line = sci_get_line_from_position(editor->sci, pos);
4757 /* mark the tag with the yellow arrow */
4758 sci_marker_delete_all(editor->sci, 0);
4759 sci_set_marker_at_line(editor->sci, line, 0);
4762 sci_goto_pos(editor->sci, pos, TRUE);
4763 editor->scroll_percent = 0.25F;
4765 /* finally switch to the page */
4766 document_show_tab(editor->document);
4767 return TRUE;
4771 static gboolean
4772 on_editor_scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer user_data)
4774 GeanyEditor *editor = user_data;
4776 /* Handle scroll events if Alt is pressed and scroll whole pages instead of a
4777 * few lines only, maybe this could/should be done in Scintilla directly */
4778 if (event->state & GDK_MOD1_MASK)
4780 sci_send_command(editor->sci, (event->direction == GDK_SCROLL_DOWN) ? SCI_PAGEDOWN : SCI_PAGEUP);
4781 return TRUE;
4783 else if (event->state & GDK_SHIFT_MASK)
4785 gint amount = (event->direction == GDK_SCROLL_DOWN) ? 8 : -8;
4787 sci_scroll_columns(editor->sci, amount);
4788 return TRUE;
4791 return FALSE; /* let Scintilla handle all other cases */
4795 static gboolean editor_check_colourise(GeanyEditor *editor)
4797 GeanyDocument *doc = editor->document;
4799 if (!doc->priv->colourise_needed)
4800 return FALSE;
4802 doc->priv->colourise_needed = FALSE;
4804 if (doc->priv->full_colourise)
4806 sci_colourise(editor->sci, 0, -1);
4808 /* now that the current document is colourised, fold points are now accurate,
4809 * so force an update of the current function/tag. */
4810 symbols_get_current_function(NULL, NULL);
4811 ui_update_statusbar(NULL, -1);
4813 else
4815 gint start_line, end_line, start, end;
4817 start_line = SSM(doc->editor->sci, SCI_GETFIRSTVISIBLELINE, 0, 0);
4818 end_line = start_line + SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
4819 start_line = SSM(editor->sci, SCI_DOCLINEFROMVISIBLE, start_line, 0);
4820 end_line = SSM(editor->sci, SCI_DOCLINEFROMVISIBLE, end_line, 0);
4821 start = sci_get_position_from_line(editor->sci, start_line);
4822 end = sci_get_line_end_position(editor->sci, end_line);
4823 sci_colourise(editor->sci, start, end);
4826 return TRUE;
4830 /* We only want to colourise just before drawing, to save startup time and
4831 * prevent unnecessary recolouring other documents after one is saved.
4832 * Really we want a "draw" signal but there doesn't seem to be one (expose is too late,
4833 * and "show" doesn't work). */
4834 static gboolean on_editor_focus_in(GtkWidget *widget, GdkEventFocus *event, gpointer user_data)
4836 GeanyEditor *editor = user_data;
4838 editor_check_colourise(editor);
4839 return FALSE;
4843 static gboolean on_editor_expose_event(GtkWidget *widget, GdkEventExpose *event,
4844 gpointer user_data)
4846 GeanyEditor *editor = user_data;
4848 /* This is just to catch any uncolourised documents being drawn that didn't receive focus
4849 * for some reason, maybe it's not necessary but just in case. */
4850 editor_check_colourise(editor);
4851 return FALSE;
4855 #if GTK_CHECK_VERSION(3, 0, 0)
4856 static gboolean on_editor_draw(GtkWidget *widget, cairo_t *cr, gpointer user_data)
4858 return on_editor_expose_event(widget, NULL, user_data);
4860 #endif
4863 static void setup_sci_keys(ScintillaObject *sci)
4865 /* disable some Scintilla keybindings to be able to redefine them cleanly */
4866 sci_clear_cmdkey(sci, 'A' | (SCMOD_CTRL << 16)); /* select all */
4867 sci_clear_cmdkey(sci, 'D' | (SCMOD_CTRL << 16)); /* duplicate */
4868 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16)); /* line transpose */
4869 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line copy */
4870 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16)); /* line cut */
4871 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line delete */
4872 sci_clear_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line to end delete */
4873 sci_clear_cmdkey(sci, '/' | (SCMOD_CTRL << 16)); /* Previous word part */
4874 sci_clear_cmdkey(sci, '\\' | (SCMOD_CTRL << 16)); /* Next word part */
4875 sci_clear_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16)); /* scroll line up */
4876 sci_clear_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16)); /* scroll line down */
4877 sci_clear_cmdkey(sci, SCK_HOME); /* line start */
4878 sci_clear_cmdkey(sci, SCK_END); /* line end */
4879 sci_clear_cmdkey(sci, SCK_END | (SCMOD_ALT << 16)); /* visual line end */
4881 if (editor_prefs.use_gtk_word_boundaries)
4883 /* use GtkEntry-like word boundaries */
4884 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16), SCI_WORDRIGHTEND);
4885 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_WORDRIGHTENDEXTEND);
4886 sci_assign_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16), SCI_DELWORDRIGHTEND);
4888 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_ALT << 16), SCI_LINESCROLLUP);
4889 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_ALT << 16), SCI_LINESCROLLDOWN);
4890 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16), SCI_PARAUP);
4891 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARAUPEXTEND);
4892 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16), SCI_PARADOWN);
4893 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARADOWNEXTEND);
4895 sci_clear_cmdkey(sci, SCK_BACK | (SCMOD_ALT << 16)); /* clear Alt-Backspace (Undo) */
4899 /* registers a Scintilla image from a named icon from the theme */
4900 static gboolean register_named_icon(ScintillaObject *sci, guint id, const gchar *name)
4902 GError *error = NULL;
4903 GdkPixbuf *pixbuf;
4904 gint n_channels, rowstride, width, height;
4905 gint size;
4907 gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &size, NULL);
4908 pixbuf = gtk_icon_theme_load_icon(gtk_icon_theme_get_default(), name, size, 0, &error);
4909 if (! pixbuf)
4911 g_warning("failed to load icon '%s': %s", name, error->message);
4912 g_error_free(error);
4913 return FALSE;
4916 n_channels = gdk_pixbuf_get_n_channels(pixbuf);
4917 rowstride = gdk_pixbuf_get_rowstride(pixbuf);
4918 width = gdk_pixbuf_get_width(pixbuf);
4919 height = gdk_pixbuf_get_height(pixbuf);
4921 if (gdk_pixbuf_get_bits_per_sample(pixbuf) != 8 ||
4922 ! gdk_pixbuf_get_has_alpha(pixbuf) ||
4923 n_channels != 4 ||
4924 rowstride != width * n_channels)
4926 g_warning("incompatible image data for icon '%s'", name);
4927 g_object_unref(pixbuf);
4928 return FALSE;
4931 SSM(sci, SCI_RGBAIMAGESETWIDTH, width, 0);
4932 SSM(sci, SCI_RGBAIMAGESETHEIGHT, height, 0);
4933 SSM(sci, SCI_REGISTERRGBAIMAGE, id, (sptr_t)gdk_pixbuf_get_pixels(pixbuf));
4935 g_object_unref(pixbuf);
4936 return TRUE;
4940 /* Create new editor widget (scintilla).
4941 * @note The @c "sci-notify" signal is connected separately. */
4942 static ScintillaObject *create_new_sci(GeanyEditor *editor)
4944 ScintillaObject *sci;
4946 sci = SCINTILLA(scintilla_new());
4948 /* Scintilla doesn't support RTL languages properly and is primarily
4949 * intended to be used with LTR source code, so override the
4950 * GTK+ default text direction for the Scintilla widget. */
4951 gtk_widget_set_direction(GTK_WIDGET(sci), GTK_TEXT_DIR_LTR);
4953 gtk_widget_show(GTK_WIDGET(sci));
4955 sci_set_codepage(sci, SC_CP_UTF8);
4956 /*SSM(sci, SCI_SETWRAPSTARTINDENT, 4, 0);*/
4957 /* disable scintilla provided popup menu */
4958 sci_use_popup(sci, FALSE);
4960 setup_sci_keys(sci);
4962 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
4963 sci_set_lines_wrapped(sci, editor->line_wrapping);
4964 sci_set_caret_policy_x(sci, CARET_JUMPS | CARET_EVEN, 0);
4965 /*sci_set_caret_policy_y(sci, CARET_JUMPS | CARET_EVEN, 0);*/
4966 SSM(sci, SCI_AUTOCSETSEPARATOR, '\n', 0);
4967 SSM(sci, SCI_SETSCROLLWIDTHTRACKING, 1, 0);
4969 /* tag autocompletion images */
4970 register_named_icon(sci, 1, "classviewer-var");
4971 register_named_icon(sci, 2, "classviewer-method");
4973 /* necessary for column mode editing, implemented in Scintilla since 2.0 */
4974 SSM(sci, SCI_SETADDITIONALSELECTIONTYPING, 1, 0);
4976 /* virtual space */
4977 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
4979 #ifdef GDK_WINDOWING_QUARTZ
4980 /* "retina" (HiDPI) display support on OS X - requires disabling buffered draw */
4981 SSM(sci, SCI_SETBUFFEREDDRAW, 0, 0);
4982 #endif
4984 /* only connect signals if this is for the document notebook, not split window */
4985 if (editor->sci == NULL)
4987 g_signal_connect(sci, "button-press-event", G_CALLBACK(on_editor_button_press_event), editor);
4988 g_signal_connect(sci, "scroll-event", G_CALLBACK(on_editor_scroll_event), editor);
4989 g_signal_connect(sci, "motion-notify-event", G_CALLBACK(on_motion_event), NULL);
4990 g_signal_connect(sci, "focus-in-event", G_CALLBACK(on_editor_focus_in), editor);
4991 #if GTK_CHECK_VERSION(3, 0, 0)
4992 g_signal_connect(sci, "draw", G_CALLBACK(on_editor_draw), editor);
4993 #else
4994 g_signal_connect(sci, "expose-event", G_CALLBACK(on_editor_expose_event), editor);
4995 #endif
4997 return sci;
5001 /** Creates a new Scintilla @c GtkWidget based on the settings for @a editor.
5002 * @param editor Editor settings.
5003 * @return @transfer{floating} The new widget.
5005 * @since 0.15
5007 GEANY_API_SYMBOL
5008 ScintillaObject *editor_create_widget(GeanyEditor *editor)
5010 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
5011 ScintillaObject *old, *sci;
5012 GeanyIndentType old_indent_type = editor->indent_type;
5013 gint old_indent_width = editor->indent_width;
5015 /* temporarily change editor to use the new sci widget */
5016 old = editor->sci;
5017 sci = create_new_sci(editor);
5018 editor->sci = sci;
5020 editor_set_indent(editor, iprefs->type, iprefs->width);
5021 editor_set_font(editor, interface_prefs.editor_font);
5022 editor_apply_update_prefs(editor);
5024 /* if editor already had a widget, restore it */
5025 if (old)
5027 editor->indent_type = old_indent_type;
5028 editor->indent_width = old_indent_width;
5029 editor->sci = old;
5031 return sci;
5035 GeanyEditor *editor_create(GeanyDocument *doc)
5037 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
5038 GeanyEditor *editor = g_new0(GeanyEditor, 1);
5040 editor->document = doc;
5041 doc->editor = editor; /* needed in case some editor functions/callbacks expect it */
5043 editor->auto_indent = (iprefs->auto_indent_mode != GEANY_AUTOINDENT_NONE);
5044 editor->line_wrapping = get_project_pref(line_wrapping);
5045 editor->scroll_percent = -1.0F;
5046 editor->line_breaking = FALSE;
5048 editor->sci = editor_create_widget(editor);
5049 return editor;
5053 /* in case we need to free some fields in future */
5054 void editor_destroy(GeanyEditor *editor)
5056 g_free(editor);
5060 static void on_document_save(GObject *obj, GeanyDocument *doc)
5062 gchar *f = g_build_filename(app->configdir, "snippets.conf", NULL);
5064 if (utils_str_equal(doc->real_path, f))
5066 /* reload snippets */
5067 editor_snippets_free();
5068 editor_snippets_init();
5070 g_free(f);
5074 gboolean editor_complete_word_part(GeanyEditor *editor)
5076 gchar *entry;
5078 g_return_val_if_fail(editor, FALSE);
5080 if (!SSM(editor->sci, SCI_AUTOCACTIVE, 0, 0))
5081 return FALSE;
5083 entry = sci_get_string(editor->sci, SCI_AUTOCGETCURRENTTEXT, 0);
5085 /* if no word part, complete normally */
5086 if (!check_partial_completion(editor, entry))
5087 SSM(editor->sci, SCI_AUTOCCOMPLETE, 0, 0);
5089 g_free(entry);
5090 return TRUE;
5094 void editor_init(void)
5096 static GeanyIndentPrefs indent_prefs;
5097 gchar *f;
5099 memset(&editor_prefs, 0, sizeof(GeanyEditorPrefs));
5100 memset(&indent_prefs, 0, sizeof(GeanyIndentPrefs));
5101 editor_prefs.indentation = &indent_prefs;
5103 /* use g_signal_connect_after() to allow plugins connecting to the signal before the default
5104 * handler (on_editor_notify) is called */
5105 g_signal_connect_after(geany_object, "editor-notify", G_CALLBACK(on_editor_notify), NULL);
5107 f = g_build_filename(app->configdir, "snippets.conf", NULL);
5108 ui_add_config_file_menu_item(f, NULL, NULL);
5109 g_free(f);
5110 g_signal_connect(geany_object, "document-save", G_CALLBACK(on_document_save), NULL);
5114 /* TODO: Should these be user-defined instead of hard-coded? */
5115 void editor_set_indentation_guides(GeanyEditor *editor)
5117 gint mode;
5118 gint lexer;
5120 g_return_if_fail(editor != NULL);
5122 if (! editor_prefs.show_indent_guide)
5124 sci_set_indentation_guides(editor->sci, SC_IV_NONE);
5125 return;
5128 lexer = sci_get_lexer(editor->sci);
5129 switch (lexer)
5131 /* Lines added/removed are prefixed with +/- characters, so
5132 * those lines will not be shown with any indentation guides.
5133 * It can be distracting that only a few of lines in a diff/patch
5134 * file will show the guides. */
5135 case SCLEX_DIFF:
5136 mode = SC_IV_NONE;
5137 break;
5139 /* These languages use indentation for control blocks; the "look forward" method works
5140 * best here */
5141 case SCLEX_PYTHON:
5142 case SCLEX_HASKELL:
5143 case SCLEX_MAKEFILE:
5144 case SCLEX_ASM:
5145 case SCLEX_SQL:
5146 case SCLEX_COBOL:
5147 case SCLEX_PROPERTIES:
5148 case SCLEX_FORTRAN: /* Is this the best option for Fortran? */
5149 case SCLEX_CAML:
5150 mode = SC_IV_LOOKFORWARD;
5151 break;
5153 /* C-like (structured) languages benefit from the "look both" method */
5154 case SCLEX_CPP:
5155 case SCLEX_HTML:
5156 case SCLEX_PHPSCRIPT:
5157 case SCLEX_XML:
5158 case SCLEX_PERL:
5159 case SCLEX_LATEX:
5160 case SCLEX_LUA:
5161 case SCLEX_PASCAL:
5162 case SCLEX_RUBY:
5163 case SCLEX_TCL:
5164 case SCLEX_F77:
5165 case SCLEX_CSS:
5166 case SCLEX_BASH:
5167 case SCLEX_VHDL:
5168 case SCLEX_FREEBASIC:
5169 case SCLEX_D:
5170 case SCLEX_OCTAVE:
5171 case SCLEX_RUST:
5172 mode = SC_IV_LOOKBOTH;
5173 break;
5175 default:
5176 mode = SC_IV_REAL;
5177 break;
5180 sci_set_indentation_guides(editor->sci, mode);
5184 /* Apply non-document prefs that can change in the Preferences dialog */
5185 void editor_apply_update_prefs(GeanyEditor *editor)
5187 ScintillaObject *sci;
5189 g_return_if_fail(editor != NULL);
5191 if (main_status.quitting)
5192 return;
5194 sci = editor->sci;
5196 sci_set_mark_long_lines(sci, editor_get_long_line_type(),
5197 editor_get_long_line_column(), editor_prefs.long_line_color);
5199 /* update indent width, tab width */
5200 editor_set_indent(editor, editor->indent_type, editor->indent_width);
5201 sci_set_tab_indents(sci, editor_prefs.use_tab_to_indent);
5203 sci_assign_cmdkey(sci, SCK_HOME | (SCMOD_SHIFT << 16),
5204 editor_prefs.smart_home_key ? SCI_VCHOMEEXTEND : SCI_HOMEEXTEND);
5205 sci_assign_cmdkey(sci, SCK_HOME | ((SCMOD_SHIFT | SCMOD_ALT) << 16),
5206 editor_prefs.smart_home_key ? SCI_VCHOMERECTEXTEND : SCI_HOMERECTEXTEND);
5208 sci_set_autoc_max_height(sci, editor_prefs.symbolcompletion_max_height);
5209 SSM(sci, SCI_AUTOCSETDROPRESTOFWORD, editor_prefs.completion_drops_rest_of_word, 0);
5211 editor_set_indentation_guides(editor);
5213 sci_set_visible_white_spaces(sci, editor_prefs.show_white_space);
5214 sci_set_visible_eols(sci, editor_prefs.show_line_endings);
5215 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
5216 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin);
5218 sci_set_folding_margin_visible(sci, editor_prefs.folding);
5220 /* virtual space */
5221 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
5223 /* (dis)allow scrolling past end of document */
5224 sci_set_scroll_stop_at_last_line(sci, editor_prefs.scroll_stop_at_last_line);
5226 sci_set_scrollbar_mode(sci, editor_prefs.show_scrollbars);
5230 /* This is for tab-indents, space aligns formatted code. Spaces should be preserved. */
5231 static void change_tab_indentation(GeanyEditor *editor, gint line, gboolean increase)
5233 ScintillaObject *sci = editor->sci;
5234 gint pos = sci_get_position_from_line(sci, line);
5236 if (increase)
5238 sci_insert_text(sci, pos, "\t");
5240 else
5242 if (sci_get_char_at(sci, pos) == '\t')
5244 sci_set_selection(sci, pos, pos + 1);
5245 sci_replace_sel(sci, "");
5247 else /* remove spaces only if no tabs */
5249 gint width = sci_get_line_indentation(sci, line);
5251 width -= editor_get_indent_prefs(editor)->width;
5252 sci_set_line_indentation(sci, line, width);
5258 static void editor_change_line_indent(GeanyEditor *editor, gint line, gboolean increase)
5260 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
5261 ScintillaObject *sci = editor->sci;
5263 if (iprefs->type == GEANY_INDENT_TYPE_TABS)
5264 change_tab_indentation(editor, line, increase);
5265 else
5267 gint width = sci_get_line_indentation(sci, line);
5269 width += increase ? iprefs->width : -iprefs->width;
5270 sci_set_line_indentation(sci, line, width);
5275 void editor_indent(GeanyEditor *editor, gboolean increase)
5277 ScintillaObject *sci = editor->sci;
5278 gint caret_pos, caret_line, caret_offset, caret_indent_pos, caret_line_len;
5279 gint anchor_pos, anchor_line, anchor_offset, anchor_indent_pos, anchor_line_len;
5281 /* backup information needed to restore caret and anchor */
5282 caret_pos = sci_get_current_position(sci);
5283 anchor_pos = SSM(sci, SCI_GETANCHOR, 0, 0);
5284 caret_line = sci_get_line_from_position(sci, caret_pos);
5285 anchor_line = sci_get_line_from_position(sci, anchor_pos);
5286 caret_offset = caret_pos - sci_get_position_from_line(sci, caret_line);
5287 anchor_offset = anchor_pos - sci_get_position_from_line(sci, anchor_line);
5288 caret_indent_pos = sci_get_line_indent_position(sci, caret_line);
5289 anchor_indent_pos = sci_get_line_indent_position(sci, anchor_line);
5290 caret_line_len = sci_get_line_length(sci, caret_line);
5291 anchor_line_len = sci_get_line_length(sci, anchor_line);
5293 if (sci_get_lines_selected(sci) <= 1)
5295 editor_change_line_indent(editor, sci_get_current_line(sci), increase);
5297 else
5299 gint start, end;
5300 gint line, lstart, lend;
5302 editor_select_lines(editor, FALSE);
5303 start = sci_get_selection_start(sci);
5304 end = sci_get_selection_end(sci);
5305 lstart = sci_get_line_from_position(sci, start);
5306 lend = sci_get_line_from_position(sci, end);
5307 if (end == sci_get_length(sci))
5308 lend++; /* for last line with text on it */
5310 sci_start_undo_action(sci);
5311 for (line = lstart; line < lend; line++)
5313 editor_change_line_indent(editor, line, increase);
5315 sci_end_undo_action(sci);
5318 /* restore caret and anchor position */
5319 if (caret_pos >= caret_indent_pos)
5320 caret_offset += sci_get_line_length(sci, caret_line) - caret_line_len;
5321 if (anchor_pos >= anchor_indent_pos)
5322 anchor_offset += sci_get_line_length(sci, anchor_line) - anchor_line_len;
5324 SSM(sci, SCI_SETCURRENTPOS, sci_get_position_from_line(sci, caret_line) + caret_offset, 0);
5325 SSM(sci, SCI_SETANCHOR, sci_get_position_from_line(sci, anchor_line) + anchor_offset, 0);
5329 /** Gets snippet by name.
5331 * If @a editor is passed, returns a snippet specific to the document filetype.
5332 * If @a editor is @c NULL, returns a snippet from the default set.
5334 * @param editor @nullable Editor or @c NULL.
5335 * @param snippet_name Snippet name.
5336 * @return @nullable snippet or @c NULL if it was not found. Must not be freed.
5338 GEANY_API_SYMBOL
5339 const gchar *editor_find_snippet(GeanyEditor *editor, const gchar *snippet_name)
5341 const gchar *subhash_name = editor ? editor->document->file_type->name : "Default";
5342 GHashTable *subhash = g_hash_table_lookup(snippet_hash, subhash_name);
5344 return subhash ? g_hash_table_lookup(subhash, snippet_name) : NULL;
5348 /** Replaces all special sequences in @a snippet and inserts it at @a pos.
5349 * If you insert at the current position, consider calling @c sci_scroll_caret()
5350 * after this function.
5351 * @param editor .
5352 * @param pos .
5353 * @param snippet .
5355 GEANY_API_SYMBOL
5356 void editor_insert_snippet(GeanyEditor *editor, gint pos, const gchar *snippet)
5358 GString *pattern;
5360 pattern = g_string_new(snippet);
5361 snippets_make_replacements(editor, pattern);
5362 editor_insert_text_block(editor, pattern->str, pos, -1, -1, TRUE);
5363 g_string_free(pattern, TRUE);