Fix inserting snippets with an indent when using Mac CR line
[geany-mirror.git] / src / editor.c
blob5c98a479391819119895c6315356c34a33afcf9d
1 /*
2 * editor.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005-2010 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2010 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com>
6 * Copyright 2009-2010 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
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 * $Id$
25 /**
26 * @file editor.h
27 * Editor-related functions for @ref GeanyEditor.
28 * Geany uses the Scintilla editing widget, and this file is mostly built around
29 * Scintilla's functionality.
30 * @see sciwrappers.h.
32 /* Callbacks for the Scintilla widget (ScintillaObject).
33 * Most important is the sci-notify callback, handled in on_editor_notification().
34 * This includes auto-indentation, comments, auto-completion, calltips, etc.
35 * Also some general Scintilla-related functions.
39 #include <ctype.h>
40 #include <string.h>
42 #include <gdk/gdkkeysyms.h>
44 #include "SciLexer.h"
45 #include "geany.h"
47 #include "support.h"
48 #include "editor.h"
49 #include "document.h"
50 #include "documentprivate.h"
51 #include "filetypes.h"
52 #include "sciwrappers.h"
53 #include "ui_utils.h"
54 #include "utils.h"
55 #include "dialogs.h"
56 #include "symbols.h"
57 #include "callbacks.h"
58 #include "templates.h"
59 #include "keybindings.h"
60 #include "project.h"
61 #include "projectprivate.h"
64 /* Note: use sciwrappers.h instead where possible.
65 * Do not use SSM in files unrelated to scintilla. */
66 #define SSM(s, m, w, l) scintilla_send_message(s, m, w, l)
69 static GHashTable *snippet_hash = NULL;
70 static GQueue *snippet_offsets = NULL;
71 static gint snippet_cursor_insert_pos;
73 /* holds word under the mouse or keyboard cursor */
74 static gchar current_word[GEANY_MAX_WORD_LENGTH];
76 /* Initialised in keyfile.c. */
77 GeanyEditorPrefs editor_prefs;
79 EditorInfo editor_info = {current_word, -1};
81 static struct
83 gchar *text;
84 gboolean set;
85 gchar *last_word;
86 guint tag_index;
87 gint pos;
88 ScintillaObject *sci;
89 } calltip = {NULL, FALSE, NULL, 0, 0, NULL};
91 static gchar indent[100];
94 static void on_new_line_added(GeanyEditor *editor);
95 static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch);
96 static void insert_indent_after_line(GeanyEditor *editor, gint line);
97 static void auto_multiline(GeanyEditor *editor, gint pos);
98 static gboolean is_code_style(gint lexer, gint style);
99 static gboolean is_string_style(gint lexer, gint style);
100 static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c);
101 static void auto_table(GeanyEditor *editor, gint pos);
102 static void close_block(GeanyEditor *editor, gint pos);
103 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos);
104 static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, size_t wordlen,
105 const gchar *wc, gboolean stem);
106 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent);
109 void editor_snippets_free(void)
111 g_hash_table_destroy(snippet_hash);
112 g_queue_free(snippet_offsets);
116 void editor_snippets_init(void)
118 gsize i, j, len = 0, len_keys = 0;
119 gchar *sysconfigfile, *userconfigfile;
120 gchar **groups_user, **groups_sys;
121 gchar **keys_user, **keys_sys;
122 gchar *value;
123 GKeyFile *sysconfig = g_key_file_new();
124 GKeyFile *userconfig = g_key_file_new();
125 GHashTable *tmp;
127 snippet_offsets = g_queue_new();
129 sysconfigfile = g_strconcat(app->datadir, G_DIR_SEPARATOR_S, "snippets.conf", NULL);
130 userconfigfile = g_strconcat(app->configdir, G_DIR_SEPARATOR_S, "snippets.conf", NULL);
132 /* check for old autocomplete.conf files (backwards compatibility) */
133 if (! g_file_test(userconfigfile, G_FILE_TEST_IS_REGULAR | G_FILE_TEST_IS_SYMLINK))
134 setptr(userconfigfile,
135 g_strconcat(app->configdir, G_DIR_SEPARATOR_S, "autocomplete.conf", NULL));
137 /* load the actual config files */
138 g_key_file_load_from_file(sysconfig, sysconfigfile, G_KEY_FILE_NONE, NULL);
139 g_key_file_load_from_file(userconfig, userconfigfile, G_KEY_FILE_NONE, NULL);
141 /* keys are strings, values are GHashTables, so use g_free and g_hash_table_destroy */
142 snippet_hash =
143 g_hash_table_new_full(g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_hash_table_destroy);
145 /* first read all globally defined auto completions */
146 groups_sys = g_key_file_get_groups(sysconfig, &len);
147 for (i = 0; i < len; i++)
149 keys_sys = g_key_file_get_keys(sysconfig, groups_sys[i], &len_keys, NULL);
150 /* create new hash table for the read section (=> filetype) */
151 tmp = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
152 g_hash_table_insert(snippet_hash, g_strdup(groups_sys[i]), tmp);
154 for (j = 0; j < len_keys; j++)
156 g_hash_table_insert(tmp, g_strdup(keys_sys[j]),
157 utils_get_setting_string(sysconfig, groups_sys[i], keys_sys[j], ""));
159 g_strfreev(keys_sys);
162 /* now read defined completions in user's configuration directory and add / replace them */
163 groups_user = g_key_file_get_groups(userconfig, &len);
164 for (i = 0; i < len; i++)
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);
191 g_free(sysconfigfile);
192 g_free(userconfigfile);
193 g_strfreev(groups_sys);
194 g_strfreev(groups_user);
195 g_key_file_free(sysconfig);
196 g_key_file_free(userconfig);
200 static gboolean on_editor_button_press_event(GtkWidget *widget, GdkEventButton *event,
201 gpointer data)
203 GeanyEditor *editor = data;
204 GeanyDocument *doc = editor->document;
206 /* it's very unlikely we got a 'real' click even on 0, 0, so assume it is a
207 * fake event to show the editor menu triggered by a key event where we want to use the
208 * text cursor position. */
209 if (event->x > 0.0 && event->y > 0.0)
210 editor_info.click_pos = sci_get_position_from_xy(editor->sci,
211 (gint)event->x, (gint)event->y, FALSE);
212 else
213 editor_info.click_pos = sci_get_current_position(editor->sci);
215 if (event->button == 1)
217 guint state = event->state & gtk_accelerator_get_default_mod_mask();
219 if (event->type == GDK_BUTTON_PRESS && editor_prefs.disable_dnd)
221 gint ss = sci_get_selection_start(editor->sci);
222 sci_set_selection_end(editor->sci, ss);
224 if (event->type == GDK_BUTTON_PRESS && state == GDK_CONTROL_MASK)
226 sci_set_current_position(editor->sci, editor_info.click_pos, FALSE);
228 editor_find_current_word(editor, editor_info.click_pos,
229 current_word, sizeof current_word, NULL);
230 if (*current_word)
231 return symbols_goto_tag(current_word, TRUE);
232 else
233 keybindings_send_command(GEANY_KEY_GROUP_GOTO, GEANY_KEYS_GOTO_MATCHINGBRACE);
234 return TRUE;
236 return document_check_disk_status(doc, FALSE);
239 /* calls the edit popup menu in the editor */
240 if (event->button == 3)
242 gboolean can_goto;
244 editor_find_current_word(editor, editor_info.click_pos,
245 current_word, sizeof current_word, NULL);
247 can_goto = sci_has_selection(editor->sci) || current_word[0] != '\0';
248 ui_update_popup_goto_items(can_goto);
249 ui_update_popup_copy_items(doc);
250 ui_update_insert_include_item(doc, 0);
252 g_signal_emit_by_name(geany_object, "update-editor-menu",
253 current_word, editor_info.click_pos, doc);
255 gtk_menu_popup(GTK_MENU(main_widgets.editor_menu),
256 NULL, NULL, NULL, NULL, event->button, event->time);
258 return TRUE;
260 return FALSE;
264 static gboolean is_style_php(gint style)
266 if ((style >= SCE_HPHP_DEFAULT && style <= SCE_HPHP_OPERATOR) ||
267 style == SCE_HPHP_COMPLEX_VARIABLE)
269 return TRUE;
272 return FALSE;
276 gint editor_get_long_line_type(void)
278 if (app->project)
279 switch (app->project->long_line_behaviour)
281 case 0: /* marker disabled */
282 return 2;
283 case 1: /* use global settings */
284 break;
285 case 2: /* custom (enabled) */
286 return editor_prefs.long_line_global_type;
289 if (!editor_prefs.long_line_global_enabled)
290 return 2;
291 else
292 return editor_prefs.long_line_global_type;
296 gint editor_get_long_line_column(void)
298 if (app->project && app->project->long_line_behaviour != 1 /* use global settings */)
299 return app->project->long_line_column;
300 else
301 return editor_prefs.long_line_global_column;
305 void editor_toggle_fold(GeanyEditor *editor, gint line, gint modifiers)
307 ScintillaObject *sci;
309 g_return_if_fail(editor != NULL);
311 sci = editor->sci;
313 sci_toggle_fold(sci, line);
315 /* extra toggling of child fold points
316 * use when editor_prefs.unfold_all_children is set and Shift is NOT pressed or when
317 * editor_prefs.unfold_all_children is NOT set but Shift is pressed */
318 if ((editor_prefs.unfold_all_children && ! (modifiers & SCMOD_SHIFT)) ||
319 (! editor_prefs.unfold_all_children && (modifiers & SCMOD_SHIFT)))
321 gint last_line = SSM(sci, SCI_GETLASTCHILD, line, -1);
322 gint i;
324 if (sci_get_line_is_visible(sci, line + 1))
325 { /* unfold all children of the current fold point */
326 for (i = line; i < last_line; i++)
328 if (! sci_get_line_is_visible(sci, i))
330 sci_toggle_fold(sci, sci_get_fold_parent(sci, i));
334 else
335 { /* fold all children of the current fold point */
336 for (i = line; i < last_line; i++)
338 gint level = sci_get_fold_level(sci, i);
339 if (level & SC_FOLDLEVELHEADERFLAG)
341 if (sci_get_fold_expanded(sci, i))
342 sci_toggle_fold(sci, i);
350 static void on_margin_click(GeanyEditor *editor, SCNotification *nt)
352 /* left click to marker margin marks the line */
353 if (nt->margin == 1)
355 gint line = sci_get_line_from_position(editor->sci, nt->position);
357 /*sci_marker_delete_all(editor->sci, 1);*/
358 sci_toggle_marker_at_line(editor->sci, line, 1); /* toggle the marker */
360 /* left click on the folding margin to toggle folding state of current line */
361 else if (nt->margin == 2 && editor_prefs.folding)
363 gint line = sci_get_line_from_position(editor->sci, nt->position);
364 editor_toggle_fold(editor, line, nt->modifiers);
369 static void on_update_ui(GeanyEditor *editor, G_GNUC_UNUSED SCNotification *nt)
371 ScintillaObject *sci = editor->sci;
372 gint pos = sci_get_current_position(sci);
374 /* undo / redo menu update */
375 ui_update_popup_reundo_items(editor->document);
377 /* brace highlighting */
378 editor_highlight_braces(editor, pos);
380 ui_update_statusbar(editor->document, pos);
382 /* Visible lines are only laid out accurately once [SCN_UPDATEUI] is sent,
383 * so we need to only call sci_scroll_to_line here, because the document
384 * may have line wrapping and folding enabled.
385 * http://scintilla.sourceforge.net/ScintillaDoc.html#LineWrapping */
386 if (editor->scroll_percent > 0.0F)
388 editor_scroll_to_line(editor, -1, editor->scroll_percent);
389 editor->scroll_percent = -1.0F; /* disable further scrolling */
391 #if 0
392 /** experimental code for inverting selections */
394 gint i;
395 for (i = SSM(sci, SCI_GETSELECTIONSTART, 0, 0); i < SSM(sci, SCI_GETSELECTIONEND, 0, 0); i++)
397 /* need to get colour from getstyleat(), but how? */
398 SSM(sci, SCI_STYLESETFORE, STYLE_DEFAULT, 0);
399 SSM(sci, SCI_STYLESETBACK, STYLE_DEFAULT, 0);
402 sci_get_style_at(sci, pos);
404 #endif
408 static void check_line_breaking(GeanyEditor *editor, gint pos, gchar c)
410 ScintillaObject *sci = editor->sci;
411 gint line, lstart, col;
413 if (!editor->line_breaking)
414 return;
416 col = sci_get_col_from_position(sci, pos);
418 if (c == GDK_space)
419 pos--; /* Look for previous space, not the new one */
421 line = sci_get_current_line(sci);
423 lstart = sci_get_position_from_line(sci, line);
425 /* use column instead of position which might be different with multibyte characters */
426 if (col < editor_prefs.line_break_column)
427 return;
429 /* look for the last space before line_break_column */
430 pos = MIN(pos, lstart + editor_prefs.line_break_column);
432 while (pos > lstart)
434 c = sci_get_char_at(sci, --pos);
435 if (c == GDK_space)
437 gint diff, last_pos, last_col;
438 const gchar *eol = editor_get_eol_char(editor);
440 /* remember the distance between the current column and the last column on the line
441 * (we use column position in case the previous line gets altered, such as removing
442 * trailing spaces or in case it contains multibyte characters) */
443 last_pos = sci_get_line_end_position(sci, line);
444 last_col = sci_get_col_from_position(sci, last_pos);
445 diff = last_col - col;
447 /* break the line after the space */
448 sci_insert_text(sci, pos + 1, eol);
449 line++;
451 /* set position as if user had pressed return */
452 pos = sci_get_position_from_line(sci, line);
453 sci_set_current_position(sci, pos, FALSE);
454 /* add indentation, comment multilines, etc */
455 on_new_line_added(editor);
457 /* correct cursor position (might not be at line end) */
458 last_pos = sci_get_line_end_position(sci, line);
459 last_col = sci_get_col_from_position(sci, last_pos); /* get last column on line */
460 /* last column - distance is the desired column, then retrieve its document position */
461 pos = SSM(sci, SCI_FINDCOLUMN, line, last_col - diff);
462 sci_set_current_position(sci, pos, FALSE);
464 return;
470 static void show_autocomplete(ScintillaObject *sci, gint rootlen, const gchar *words)
472 /* store whether a calltip is showing, so we can reshow it after autocompletion */
473 calltip.set = SSM(sci, SCI_CALLTIPACTIVE, 0, 0);
474 SSM(sci, SCI_AUTOCSHOW, rootlen, (sptr_t) words);
478 static void show_tags_list(GeanyEditor *editor, const GPtrArray *tags, gsize rootlen)
480 ScintillaObject *sci = editor->sci;
482 g_return_if_fail(tags);
484 if (tags->len > 0)
486 GString *words = g_string_sized_new(150);
487 guint j;
489 for (j = 0; j < tags->len; ++j)
491 TMTag *tag = tags->pdata[j];
493 if (j > 0)
494 g_string_append_c(words, '\n');
496 if (j == editor_prefs.autocompletion_max_entries)
498 g_string_append(words, "...");
499 break;
501 g_string_append(words, tag->name);
503 /* for now, tag types don't all follow C, so just look at arglist */
504 if (NZV(tag->atts.entry.arglist))
505 g_string_append(words, "?2");
506 else
507 g_string_append(words, "?1");
509 show_autocomplete(sci, rootlen, words->str);
510 g_string_free(words, TRUE);
515 /* do not use with long strings */
516 static gboolean match_last_chars(ScintillaObject *sci, gint pos, const gchar *str)
518 gsize len = strlen(str);
519 gchar *buf;
521 g_return_val_if_fail(len < 100, FALSE);
523 buf = g_alloca(len + 1);
524 sci_get_text_range(sci, pos - len, pos, buf);
525 return strcmp(str, buf) == 0;
529 static gboolean reshow_calltip(gpointer data)
531 GeanyDocument *doc;
533 g_return_val_if_fail(calltip.sci != NULL, FALSE);
535 SSM(calltip.sci, SCI_CALLTIPCANCEL, 0, 0);
536 doc = document_get_current();
538 if (doc && doc->editor->sci == calltip.sci)
540 /* we use the position where the calltip was previously started as SCI_GETCURRENTPOS
541 * may be completely wrong in case the user cancelled the auto completion with the mouse */
542 SSM(calltip.sci, SCI_CALLTIPSHOW, calltip.pos, (sptr_t) calltip.text);
544 return FALSE;
548 static void request_reshowing_calltip(SCNotification *nt)
550 if (calltip.set)
552 /* delay the reshow of the calltip window to make sure it is actually displayed,
553 * without it might be not visible on SCN_AUTOCCANCEL */
554 g_idle_add(reshow_calltip, NULL);
559 static void autocomplete_scope(GeanyEditor *editor)
561 ScintillaObject *sci = editor->sci;
562 gint pos = sci_get_current_position(editor->sci);
563 gchar typed = sci_get_char_at(sci, pos - 1);
564 gchar *name;
565 const GPtrArray *tags = NULL;
566 const TMTag *tag;
567 GeanyFiletype *ft = editor->document->file_type;
569 if (ft->id == GEANY_FILETYPES_C || ft->id == GEANY_FILETYPES_CPP)
571 if (match_last_chars(sci, pos, "->") || match_last_chars(sci, pos, "::"))
572 pos--;
573 else if (typed != '.')
574 return;
576 else if (typed != '.')
577 return;
579 /* allow for a space between word and operator */
580 if (isspace(sci_get_char_at(sci, pos - 2)))
581 pos--;
582 name = editor_get_word_at_pos(editor, pos - 1, NULL);
583 if (!name)
584 return;
586 tags = tm_workspace_find(name, tm_tag_max_t, NULL, FALSE, ft->lang);
587 g_free(name);
588 if (!tags || tags->len == 0)
589 return;
591 tag = g_ptr_array_index(tags, 0);
592 name = tag->atts.entry.var_type;
593 if (name)
595 TMWorkObject *obj = editor->document->tm_file;
597 tags = tm_workspace_find_scope_members(obj ? obj->tags_array : NULL,
598 name, TRUE, FALSE);
599 if (tags)
600 show_tags_list(editor, tags, 0);
605 static void on_char_added(GeanyEditor *editor, SCNotification *nt)
607 ScintillaObject *sci = editor->sci;
608 gint pos = sci_get_current_position(sci);
610 switch (nt->ch)
612 case '\r':
613 { /* simple indentation (only for CR format) */
614 if (sci_get_eol_mode(sci) == SC_EOL_CR)
615 on_new_line_added(editor);
616 break;
618 case '\n':
619 { /* simple indentation (for CR/LF and LF format) */
620 on_new_line_added(editor);
621 break;
623 case '>':
624 editor_start_auto_complete(editor, pos, FALSE); /* C/C++ ptr-> scope completion */
625 /* fall through */
626 case '/':
627 { /* close xml-tags */
628 handle_xml(editor, pos, nt->ch);
629 break;
631 case '(':
633 auto_close_chars(sci, pos, nt->ch);
634 /* show calltips */
635 editor_show_calltip(editor, --pos);
636 break;
638 case ')':
639 { /* hide calltips */
640 if (SSM(sci, SCI_CALLTIPACTIVE, 0, 0))
642 SSM(sci, SCI_CALLTIPCANCEL, 0, 0);
644 g_free(calltip.text);
645 calltip.text = NULL;
646 calltip.pos = 0;
647 calltip.sci = NULL;
648 calltip.set = FALSE;
649 break;
651 case '{':
652 case '[':
653 case '"':
654 case '\'':
656 auto_close_chars(sci, pos, nt->ch);
657 break;
659 case '}':
660 { /* closing bracket handling */
661 if (editor->auto_indent)
662 close_block(editor, pos - 1);
663 break;
665 /* scope autocompletion */
666 case '.':
667 case ':': /* C/C++ class:: syntax */
668 /* tag autocompletion */
669 default:
670 #if 0
671 if (! editor_start_auto_complete(editor, pos, FALSE))
672 request_reshowing_calltip(nt);
673 #else
674 editor_start_auto_complete(editor, pos, FALSE);
675 #endif
677 check_line_breaking(editor, pos, nt->ch);
681 /* expand() and fold_changed() are copied from SciTE (thanks) to fix #1923350. */
682 static void expand(ScintillaObject *sci, gint *line, gboolean doExpand,
683 gboolean force, gint visLevels, gint level)
685 gint lineMaxSubord = SSM(sci, SCI_GETLASTCHILD, *line, level & SC_FOLDLEVELNUMBERMASK);
686 gint levelLine = level;
687 (*line)++;
688 while (*line <= lineMaxSubord)
690 if (G_UNLIKELY(force))
692 if (visLevels > 0)
693 SSM(sci, SCI_SHOWLINES, *line, *line);
694 else
695 SSM(sci, SCI_HIDELINES, *line, *line);
697 else
699 if (doExpand)
700 SSM(sci, SCI_SHOWLINES, *line, *line);
702 if (levelLine == -1)
703 levelLine = SSM(sci, SCI_GETFOLDLEVEL, *line, 0);
704 if (levelLine & SC_FOLDLEVELHEADERFLAG)
706 if (G_UNLIKELY(force))
708 if (visLevels > 1)
709 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
710 else
711 SSM(sci, SCI_SETFOLDEXPANDED, *line, 0);
712 expand(sci, line, doExpand, force, visLevels - 1, -1);
714 else
716 if (doExpand)
718 if (!sci_get_fold_expanded(sci, *line))
719 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
720 expand(sci, line, TRUE, force, visLevels - 1, -1);
722 else
724 expand(sci, line, FALSE, force, visLevels - 1, -1);
728 else
730 (*line)++;
736 static void fold_changed(ScintillaObject *sci, gint line, gint levelNow, gint levelPrev)
738 if (levelNow & SC_FOLDLEVELHEADERFLAG)
740 if (! (levelPrev & SC_FOLDLEVELHEADERFLAG))
742 /* Adding a fold point */
743 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
744 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
747 else if (levelPrev & SC_FOLDLEVELHEADERFLAG)
749 if (! sci_get_fold_expanded(sci, line))
750 { /* Removing the fold from one that has been contracted so should expand
751 * otherwise lines are left invisible with no way to make them visible */
752 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
753 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
756 if (! (levelNow & SC_FOLDLEVELWHITEFLAG) &&
757 ((levelPrev & SC_FOLDLEVELNUMBERMASK) > (levelNow & SC_FOLDLEVELNUMBERMASK)))
759 /* See if should still be hidden */
760 gint parentLine = sci_get_fold_parent(sci, line);
761 if (parentLine < 0)
763 SSM(sci, SCI_SHOWLINES, line, line);
765 else if (sci_get_fold_expanded(sci, parentLine) &&
766 sci_get_line_is_visible(sci, parentLine))
768 SSM(sci, SCI_SHOWLINES, line, line);
774 static void ensure_range_visible(ScintillaObject *sci, gint posStart, gint posEnd,
775 gboolean enforcePolicy)
777 gint lineStart = sci_get_line_from_position(sci, MIN(posStart, posEnd));
778 gint lineEnd = sci_get_line_from_position(sci, MAX(posStart, posEnd));
779 gint line;
781 for (line = lineStart; line <= lineEnd; line++)
783 SSM(sci, enforcePolicy ? SCI_ENSUREVISIBLEENFORCEPOLICY : SCI_ENSUREVISIBLE, line, 0);
788 static void auto_update_margin_width(GeanyEditor *editor)
790 gint next_linecount = 1;
791 gint linecount = sci_get_line_count(editor->sci);
792 GeanyDocument *doc = editor->document;
794 while (next_linecount <= linecount)
795 next_linecount *= 10;
797 if (editor->document->priv->line_count != next_linecount)
799 doc->priv->line_count = next_linecount;
800 sci_set_line_numbers(editor->sci, TRUE, 0);
805 static void partial_complete(ScintillaObject *sci, const gchar *text)
807 gint pos = sci_get_current_position(sci);
809 sci_insert_text(sci, pos, text);
810 sci_set_current_position(sci, pos + strlen(text), TRUE);
814 /* Complete the next word part from @a entry */
815 static gboolean check_partial_completion(GeanyEditor *editor, const gchar *entry)
817 gchar *stem, *ptr, *text = utils_strdupa(entry);
819 read_current_word(editor, -1, current_word, sizeof current_word, NULL, TRUE);
820 stem = current_word;
821 if (strstr(text, stem) != text)
822 return FALSE; /* shouldn't happen */
823 if (strlen(text) <= strlen(stem))
824 return FALSE;
826 text += strlen(stem); /* skip stem */
827 ptr = strstr(text + 1, "_");
828 if (ptr)
830 ptr[1] = '\0';
831 partial_complete(editor->sci, text);
832 return TRUE;
834 else
836 /* CamelCase */
837 foreach_str(ptr, text + 1)
839 if (!ptr[0])
840 break;
841 if (g_ascii_isupper(*ptr) && g_ascii_islower(ptr[1]))
843 ptr[0] = '\0';
844 partial_complete(editor->sci, text);
845 return TRUE;
849 return FALSE;
853 /* Callback for the "sci-notify" signal to emit a "editor-notify" signal.
854 * Plugins can connect to the "editor-notify" signal. */
855 void editor_sci_notify_cb(G_GNUC_UNUSED GtkWidget *widget, G_GNUC_UNUSED gint scn,
856 gpointer scnt, gpointer data)
858 GeanyEditor *editor = data;
859 gboolean retval;
861 g_return_if_fail(editor != NULL);
863 g_signal_emit_by_name(geany_object, "editor-notify", editor, scnt, &retval);
867 static gboolean on_editor_notify(G_GNUC_UNUSED GObject *object, GeanyEditor *editor,
868 SCNotification *nt, G_GNUC_UNUSED gpointer data)
870 ScintillaObject *sci = editor->sci;
871 GeanyDocument *doc = editor->document;
873 switch (nt->nmhdr.code)
875 case SCN_SAVEPOINTLEFT:
876 document_set_text_changed(doc, TRUE);
877 break;
879 case SCN_SAVEPOINTREACHED:
880 document_set_text_changed(doc, FALSE);
881 break;
883 case SCN_MODIFYATTEMPTRO:
884 utils_beep();
885 break;
887 case SCN_MARGINCLICK:
888 on_margin_click(editor, nt);
889 break;
891 case SCN_UPDATEUI:
892 on_update_ui(editor, nt);
893 break;
895 case SCN_MODIFIED:
896 if (editor_prefs.show_linenumber_margin && (nt->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT)) && nt->linesAdded)
898 /* automatically adjust Scintilla's line numbers margin width */
899 auto_update_margin_width(editor);
901 if (nt->modificationType & SC_STARTACTION && ! ignore_callback)
903 /* get notified about undo changes */
904 document_undo_add(doc, UNDO_SCINTILLA, NULL);
906 if (editor_prefs.folding && (nt->modificationType & SC_MOD_CHANGEFOLD) != 0)
908 /* handle special fold cases, e.g. #1923350 */
909 fold_changed(sci, nt->line, nt->foldLevelNow, nt->foldLevelPrev);
911 break;
913 case SCN_CHARADDED:
914 on_char_added(editor, nt);
915 break;
917 case SCN_USERLISTSELECTION:
918 if (nt->listType == 1)
920 sci_add_text(sci, nt->text);
922 break;
924 case SCN_AUTOCSELECTION:
925 if (g_str_equal(nt->text, "..."))
927 sci_cancel(sci);
928 utils_beep();
929 break;
931 /* fall through */
932 case SCN_AUTOCCANCELLED:
933 /* now that autocomplete is finishing or was cancelled, reshow calltips
934 * if they were showing */
935 request_reshowing_calltip(nt);
936 break;
938 #ifdef GEANY_DEBUG
939 case SCN_STYLENEEDED:
940 geany_debug("style");
941 break;
942 #endif
943 case SCN_NEEDSHOWN:
944 ensure_range_visible(sci, nt->position, nt->position + nt->length, FALSE);
945 break;
947 case SCN_URIDROPPED:
948 if (nt->text != NULL)
950 document_open_file_list(nt->text, -1);
952 break;
954 case SCN_CALLTIPCLICK:
955 if (nt->position > 0)
957 switch (nt->position)
959 case 1: /* up arrow */
960 if (calltip.tag_index > 0)
961 calltip.tag_index--;
962 break;
964 case 2: calltip.tag_index++; break; /* down arrow */
966 editor_show_calltip(editor, -1);
968 break;
970 /* we always return FALSE here to let plugins handle the event too */
971 return FALSE;
975 /* Note: this is the same as sci_get_tab_width(), but is still useful when you don't have
976 * a scintilla pointer. */
977 static gint get_tab_width(const GeanyIndentPrefs *indent_prefs)
979 if (indent_prefs->type == GEANY_INDENT_TYPE_BOTH)
980 return indent_prefs->hard_tab_width;
982 return indent_prefs->width; /* tab width = indent width */
986 /* Returns a string containing width chars of whitespace, filled with simple space
987 * characters or with the right number of tab characters, according to the indent prefs.
988 * (Result is filled with tabs *and* spaces if width isn't a multiple of
989 * the tab width). */
990 static gchar *
991 get_whitespace(const GeanyIndentPrefs *iprefs, gint width)
993 g_return_val_if_fail(width >= 0, NULL);
995 if (width == 0)
996 return g_strdup("");
998 if (iprefs->type == GEANY_INDENT_TYPE_SPACES)
1000 return g_strnfill(width, ' ');
1002 else
1003 { /* first fill text with tabs and fill the rest with spaces */
1004 const gint tab_width = get_tab_width(iprefs);
1005 gint tabs = width / tab_width;
1006 gint spaces = width % tab_width;
1007 gint len = tabs + spaces;
1008 gchar *str;
1010 str = g_malloc(len + 1);
1012 memset(str, '\t', tabs);
1013 memset(str + tabs, ' ', spaces);
1014 str[len] = '\0';
1015 return str;
1020 static const GeanyIndentPrefs *
1021 get_default_indent_prefs(void)
1023 static GeanyIndentPrefs iprefs;
1025 iprefs = app->project ? *app->project->priv->indentation : *editor_prefs.indentation;
1026 return &iprefs;
1030 /** Gets the indentation prefs for the editor.
1031 * In future, the prefs might be different according to project or filetype.
1032 * @warning Always get a fresh result instead of keeping a pointer to it if the editor
1033 * settings may have changed, or if this function has been called for a different @a editor.
1034 * @param editor The editor, or @c NULL to get the default indent prefs.
1035 * @return The indent prefs. */
1036 const GeanyIndentPrefs *
1037 editor_get_indent_prefs(GeanyEditor *editor)
1039 static GeanyIndentPrefs iprefs;
1041 iprefs = *get_default_indent_prefs();
1043 if (editor == NULL)
1044 return &iprefs;
1046 iprefs.type = editor->indent_type;
1048 /* if per-document auto-indent is enabled, but we don't have a global mode set,
1049 * just use basic auto-indenting */
1050 if (editor->auto_indent && iprefs.auto_indent_mode == GEANY_AUTOINDENT_NONE)
1051 iprefs.auto_indent_mode = GEANY_AUTOINDENT_BASIC;
1053 if (!editor->auto_indent)
1054 iprefs.auto_indent_mode = GEANY_AUTOINDENT_NONE;
1056 return &iprefs;
1060 static void on_new_line_added(GeanyEditor *editor)
1062 ScintillaObject *sci = editor->sci;
1063 gint line = sci_get_current_line(sci);
1065 /* simple indentation */
1066 if (editor->auto_indent)
1068 insert_indent_after_line(editor, line - 1);
1071 if (editor_prefs.auto_continue_multiline)
1072 { /* " * " auto completion in multiline C/C++/D/Java comments */
1073 auto_multiline(editor, line);
1076 if (editor_prefs.newline_strip)
1077 { /* strip the trailing spaces on the previous line */
1078 editor_strip_line_trailing_spaces(editor, line - 1);
1083 static gboolean lexer_has_braces(ScintillaObject *sci)
1085 gint lexer = sci_get_lexer(sci);
1087 switch (lexer)
1089 case SCLEX_CPP:
1090 case SCLEX_D:
1091 case SCLEX_HTML: /* for PHP & JS */
1092 case SCLEX_PASCAL: /* for multiline comments? */
1093 case SCLEX_BASH:
1094 case SCLEX_PERL:
1095 case SCLEX_TCL:
1096 return TRUE;
1097 default:
1098 return FALSE;
1103 /* Read indent chars for the line that pos is on into indent global variable.
1104 * Note: Use sci_get_line_indentation() and get_whitespace()/editor_insert_text_block()
1105 * instead in any new code. */
1106 static void read_indent(GeanyEditor *editor, gint pos)
1108 ScintillaObject *sci = editor->sci;
1109 guint i, len, j = 0;
1110 gint line;
1111 gchar *linebuf;
1113 line = sci_get_line_from_position(sci, pos);
1115 len = sci_get_line_length(sci, line);
1116 linebuf = sci_get_line(sci, line);
1118 for (i = 0; i < len && j <= (sizeof(indent) - 1); i++)
1120 if (linebuf[i] == ' ' || linebuf[i] == '\t') /* simple indentation */
1121 indent[j++] = linebuf[i];
1122 else
1123 break;
1125 indent[j] = '\0';
1126 g_free(linebuf);
1130 static gint get_brace_indent(ScintillaObject *sci, gint line)
1132 guint i, len;
1133 gint ret = 0;
1134 gchar *linebuf;
1136 len = sci_get_line_length(sci, line);
1137 linebuf = sci_get_line(sci, line);
1139 for (i = 0; i < len; i++)
1141 /* i == (len - 1) prevents wrong indentation after lines like
1142 * " { return bless({}, shift); }" (Perl) */
1143 if (linebuf[i] == '{' && i == (len - 1))
1145 ret++;
1146 break;
1148 else
1150 gint k = len - 1;
1152 while (k > 0 && isspace(linebuf[k])) k--;
1154 /* if last non-whitespace character is a { increase indentation by a tab
1155 * e.g. for (...) { */
1156 if (linebuf[k] == '{')
1158 ret++;
1160 break;
1163 g_free(linebuf);
1164 return ret;
1168 static gint get_python_indent(ScintillaObject *sci, gint line)
1170 gint last_char = sci_get_line_end_position(sci, line) - 1;
1172 /* add extra indentation for Python after colon */
1173 if (sci_get_char_at(sci, last_char) == ':' &&
1174 sci_get_style_at(sci, last_char) == SCE_P_OPERATOR)
1176 return 1;
1178 return 0;
1182 static gint get_indent_size_after_line(GeanyEditor *editor, gint line)
1184 ScintillaObject *sci = editor->sci;
1185 gint size;
1186 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1188 g_return_val_if_fail(line >= 0, 0);
1190 size = sci_get_line_indentation(sci, line);
1192 if (iprefs->auto_indent_mode > GEANY_AUTOINDENT_BASIC)
1194 if (lexer_has_braces(sci))
1195 size += iprefs->width * get_brace_indent(sci, line);
1196 else
1197 if (FILETYPE_ID(editor->document->file_type) == GEANY_FILETYPES_PYTHON)
1198 size += iprefs->width * get_python_indent(sci, line);
1200 return size;
1204 static void insert_indent_after_line(GeanyEditor *editor, gint line)
1206 ScintillaObject *sci = editor->sci;
1207 gint line_indent = sci_get_line_indentation(sci, line);
1208 gint size = get_indent_size_after_line(editor, line);
1209 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1210 gchar *text;
1212 if (size == 0)
1213 return;
1215 if (iprefs->type == GEANY_INDENT_TYPE_TABS && size == line_indent)
1217 /* support tab indents, space aligns style - copy last line 'indent' exactly */
1218 gint start = sci_get_position_from_line(sci, line);
1219 gint end = sci_get_line_indent_position(sci, line);
1221 text = sci_get_contents_range(sci, start, end);
1223 else
1225 text = get_whitespace(iprefs, size);
1227 sci_add_text(sci, text);
1228 g_free(text);
1232 static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c)
1234 const gchar *closing_char = NULL;
1235 gint end_pos = -1;
1237 if (utils_isbrace(c, 0))
1238 end_pos = sci_find_matching_brace(sci, pos - 1);
1240 switch (c)
1242 case '(':
1243 if ((editor_prefs.autoclose_chars & GEANY_AC_PARENTHESIS) && end_pos == -1)
1244 closing_char = ")";
1245 break;
1246 case '{':
1247 if ((editor_prefs.autoclose_chars & GEANY_AC_CBRACKET) && end_pos == -1)
1248 closing_char = "}";
1249 break;
1250 case '[':
1251 if ((editor_prefs.autoclose_chars & GEANY_AC_SBRACKET) && end_pos == -1)
1252 closing_char = "]";
1253 break;
1254 case '\'':
1255 if (editor_prefs.autoclose_chars & GEANY_AC_SQUOTE)
1256 closing_char = "'";
1257 break;
1258 case '"':
1259 if (editor_prefs.autoclose_chars & GEANY_AC_DQUOTE)
1260 closing_char = "\"";
1261 break;
1264 if (closing_char != NULL)
1266 sci_add_text(sci, closing_char);
1267 sci_set_current_position(sci, pos, TRUE);
1272 /* Finds a corresponding matching brace to the given pos
1273 * (this is taken from Scintilla Editor.cxx,
1274 * fit to work with close_block) */
1275 static gint brace_match(ScintillaObject *sci, gint pos)
1277 gchar chBrace = sci_get_char_at(sci, pos);
1278 gchar chSeek = utils_brace_opposite(chBrace);
1279 gchar chAtPos;
1280 gint direction = -1;
1281 gint styBrace;
1282 gint depth = 1;
1283 gint styAtPos;
1285 styBrace = sci_get_style_at(sci, pos);
1287 if (utils_is_opening_brace(chBrace, editor_prefs.brace_match_ltgt))
1288 direction = 1;
1290 pos = pos + direction;
1291 while ((pos >= 0) && (pos < sci_get_length(sci)))
1293 chAtPos = sci_get_char_at(sci, pos - 1);
1294 styAtPos = sci_get_style_at(sci, pos);
1296 if ((pos > sci_get_end_styled(sci)) || (styAtPos == styBrace))
1298 if (chAtPos == chBrace)
1299 depth++;
1300 if (chAtPos == chSeek)
1301 depth--;
1302 if (depth == 0)
1303 return pos;
1305 pos = pos + direction;
1307 return -1;
1311 /* Called after typing '}'. */
1312 static void close_block(GeanyEditor *editor, gint pos)
1314 GeanyDocument *doc;
1315 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1316 gint x = 0, cnt = 0;
1317 gint line, line_len, eol_char_len;
1318 gchar *text, *line_buf;
1319 ScintillaObject *sci;
1320 gint line_indent, last_indent;
1322 if (iprefs->auto_indent_mode < GEANY_AUTOINDENT_CURRENTCHARS)
1323 return;
1324 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
1326 sci = editor->sci;
1327 doc = editor->document;
1329 if (! lexer_has_braces(sci))
1330 return;
1332 line = sci_get_line_from_position(sci, pos);
1333 line_len = sci_get_line_length(sci, line);
1334 /* set eol_char_len to 0 if on last line, because there is no EOL char */
1335 eol_char_len = (line == (sci_get_line_count(sci) - 1)) ? 0 :
1336 editor_get_eol_char_len(editor);
1338 /* check that the line is empty, to not kill text in the line */
1339 line_buf = sci_get_line(sci, line);
1340 line_buf[line_len - eol_char_len] = '\0';
1341 while (x < (line_len - eol_char_len))
1343 if (isspace(line_buf[x]))
1344 cnt++;
1345 x++;
1347 g_free(line_buf);
1349 if ((line_len - eol_char_len - 1) != cnt)
1350 return;
1352 if (iprefs->auto_indent_mode == GEANY_AUTOINDENT_MATCHBRACES)
1354 gint start_brace = brace_match(sci, pos);
1356 if (start_brace >= 0)
1358 gint line_start;
1359 gint brace_line = sci_get_line_from_position(sci, start_brace);
1360 gint size = sci_get_line_indentation(sci, brace_line);
1361 gchar *ind = get_whitespace(iprefs, size);
1363 text = g_strconcat(ind, "}", NULL);
1364 line_start = sci_get_position_from_line(sci, line);
1365 sci_set_anchor(sci, line_start);
1366 sci_replace_sel(sci, text);
1367 g_free(text);
1368 g_free(ind);
1369 return;
1371 /* fall through - unmatched brace (possibly because of TCL, PHP lexer bugs) */
1374 /* GEANY_AUTOINDENT_CURRENTCHARS */
1375 line_indent = sci_get_line_indentation(sci, line);
1376 last_indent = sci_get_line_indentation(sci, line - 1);
1378 if (line_indent < last_indent)
1379 return;
1380 line_indent -= iprefs->width;
1381 line_indent = MAX(0, line_indent);
1382 sci_set_line_indentation(sci, line, line_indent);
1386 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1387 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1388 * position can be -1, then the current position is used.
1389 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1390 static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, size_t wordlen,
1391 const gchar *wc, gboolean stem)
1393 gint line, line_start, startword, endword;
1394 gchar *chunk;
1395 ScintillaObject *sci;
1397 g_return_if_fail(editor != NULL);
1398 sci = editor->sci;
1400 if (pos == -1)
1401 pos = sci_get_current_position(sci);
1403 line = sci_get_line_from_position(sci, pos);
1404 line_start = sci_get_position_from_line(sci, line);
1405 startword = pos - line_start;
1406 endword = pos - line_start;
1408 word[0] = '\0';
1409 chunk = sci_get_line(sci, line);
1411 if (wc == NULL)
1412 wc = GEANY_WORDCHARS;
1414 /* the checks for "c < 0" are to allow any Unicode character which should make the code
1415 * a little bit more Unicode safe, anyway, this allows also any Unicode punctuation,
1416 * TODO: improve this code */
1417 while (startword > 0 && (strchr(wc, chunk[startword - 1]) || chunk[startword - 1] < 0))
1418 startword--;
1419 if (!stem)
1421 while (chunk[endword] != 0 && (strchr(wc, chunk[endword]) || chunk[endword] < 0))
1422 endword++;
1425 if (startword != endword)
1427 chunk[endword] = '\0';
1429 g_strlcpy(word, chunk + startword, wordlen); /* ensure null terminated */
1431 else
1432 g_strlcpy(word, "", wordlen);
1434 g_free(chunk);
1438 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1439 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1440 * position can be -1, then the current position is used.
1441 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1442 void editor_find_current_word(GeanyEditor *editor, gint pos, gchar *word, size_t wordlen,
1443 const gchar *wc)
1445 read_current_word(editor, pos, word, wordlen, wc, FALSE);
1450 * Finds the word at the position specified by @a pos. If any word is found, it is returned.
1451 * Otherwise NULL is returned.
1452 * Additional wordchars can be specified to define what to consider as a word.
1454 * @param editor The editor to operate on.
1455 * @param pos The position where the word should be read from.
1456 * Maybe @c -1 to use the current position.
1457 * @param wordchars The wordchars to separate words. wordchars mean all characters to count
1458 * as part of a word. Maybe @c NULL to use the default wordchars,
1459 * see @ref GEANY_WORDCHARS.
1461 * @return A newly-allocated string containing the word at the given @a pos or @c NULL.
1462 * Should be freed when no longer needed.
1464 * @since 0.16
1466 gchar *editor_get_word_at_pos(GeanyEditor *editor, gint pos, const gchar *wordchars)
1468 static gchar cword[GEANY_MAX_WORD_LENGTH];
1470 g_return_val_if_fail(editor != NULL, FALSE);
1472 read_current_word(editor, pos, cword, sizeof(cword), wordchars, FALSE);
1474 return (*cword == '\0') ? NULL : g_strdup(cword);
1478 /* Read the word up to position @a pos. */
1479 static const gchar *
1480 editor_read_word_stem(GeanyEditor *editor, gint pos, const gchar *wordchars)
1482 static gchar word[GEANY_MAX_WORD_LENGTH];
1484 read_current_word(editor, pos, word, sizeof word, wordchars, TRUE);
1486 return (*word) ? word : NULL;
1490 static gint find_previous_brace(ScintillaObject *sci, gint pos)
1492 gchar c;
1493 gint orig_pos = pos;
1495 c = sci_get_char_at(sci, pos);
1496 while (pos >= 0 && pos > orig_pos - 300)
1498 c = sci_get_char_at(sci, pos);
1499 pos--;
1500 if (utils_is_opening_brace(c, editor_prefs.brace_match_ltgt))
1501 return pos;
1503 return -1;
1507 static gint find_start_bracket(ScintillaObject *sci, gint pos)
1509 gchar c;
1510 gint brackets = 0;
1511 gint orig_pos = pos;
1513 c = sci_get_char_at(sci, pos);
1514 while (pos > 0 && pos > orig_pos - 300)
1516 c = sci_get_char_at(sci, pos);
1517 if (c == ')') brackets++;
1518 else if (c == '(') brackets--;
1519 pos--;
1520 if (brackets < 0) return pos; /* found start bracket */
1522 return -1;
1526 static gboolean append_calltip(GString *str, const TMTag *tag, filetype_id ft_id)
1528 if (! tag->atts.entry.arglist)
1529 return FALSE;
1531 if (ft_id != GEANY_FILETYPES_PASCAL)
1532 { /* usual calltips: "retval tagname (arglist)" */
1533 if (tag->atts.entry.var_type)
1535 guint i;
1537 g_string_append(str, tag->atts.entry.var_type);
1538 for (i = 0; i < tag->atts.entry.pointerOrder; i++)
1540 g_string_append_c(str, '*');
1542 g_string_append_c(str, ' ');
1544 if (tag->atts.entry.scope)
1546 const gchar *cosep = symbols_get_context_separator(ft_id);
1548 g_string_append(str, tag->atts.entry.scope);
1549 g_string_append(str, cosep);
1551 g_string_append(str, tag->name);
1552 g_string_append_c(str, ' ');
1553 g_string_append(str, tag->atts.entry.arglist);
1555 else
1556 { /* special case Pascal calltips: "tagname (arglist) : retval" */
1557 g_string_append(str, tag->name);
1558 g_string_append_c(str, ' ');
1559 g_string_append(str, tag->atts.entry.arglist);
1561 if (NZV(tag->atts.entry.var_type))
1563 g_string_append(str, " : ");
1564 g_string_append(str, tag->atts.entry.var_type);
1568 return TRUE;
1572 static gchar *find_calltip(const gchar *word, GeanyFiletype *ft)
1574 const GPtrArray *tags;
1575 const gint arg_types = tm_tag_function_t | tm_tag_prototype_t |
1576 tm_tag_method_t | tm_tag_macro_with_arg_t;
1577 TMTagAttrType *attrs = NULL;
1578 TMTag *tag;
1579 GString *str = NULL;
1580 guint i;
1582 g_return_val_if_fail(ft && word && *word, NULL);
1584 /* use all types in case language uses wrong tag type e.g. python "members" instead of "methods" */
1585 tags = tm_workspace_find(word, tm_tag_max_t, attrs, FALSE, ft->lang);
1586 if (tags->len == 0)
1587 return NULL;
1589 tag = TM_TAG(tags->pdata[0]);
1591 if (tag->type == tm_tag_class_t && FILETYPE_ID(ft) == GEANY_FILETYPES_D)
1593 /* user typed e.g. 'new Classname(' so lookup D constructor Classname::this() */
1594 tags = tm_workspace_find_scoped("this", tag->name,
1595 arg_types, attrs, FALSE, ft->lang, TRUE);
1596 if (tags->len == 0)
1597 return NULL;
1600 /* remove tags with no argument list */
1601 for (i = 0; i < tags->len; i++)
1603 tag = TM_TAG(tags->pdata[i]);
1605 if (! tag->atts.entry.arglist)
1606 tags->pdata[i] = NULL;
1608 tm_tags_prune((GPtrArray *) tags);
1609 if (tags->len == 0)
1610 return NULL;
1611 else
1612 { /* remove duplicate calltips */
1613 TMTagAttrType sort_attr[] = {tm_tag_attr_name_t, tm_tag_attr_scope_t,
1614 tm_tag_attr_arglist_t, 0};
1616 tm_tags_sort((GPtrArray *) tags, sort_attr, TRUE);
1619 /* if the current word has changed since last time, start with the first tag match */
1620 if (! utils_str_equal(word, calltip.last_word))
1621 calltip.tag_index = 0;
1622 /* cache the current word for next time */
1623 g_free(calltip.last_word);
1624 calltip.last_word = g_strdup(word);
1625 calltip.tag_index = MIN(calltip.tag_index, tags->len - 1); /* ensure tag_index is in range */
1627 for (i = calltip.tag_index; i < tags->len; i++)
1629 tag = TM_TAG(tags->pdata[i]);
1631 if (str == NULL)
1633 str = g_string_new(NULL);
1634 if (calltip.tag_index > 0)
1635 g_string_prepend(str, "\001 "); /* up arrow */
1636 append_calltip(str, tag, FILETYPE_ID(ft));
1638 else /* add a down arrow */
1640 if (calltip.tag_index > 0) /* already have an up arrow */
1641 g_string_insert_c(str, 1, '\002');
1642 else
1643 g_string_prepend(str, "\002 ");
1644 break;
1647 if (str)
1649 gchar *result = str->str;
1651 g_string_free(str, FALSE);
1652 return result;
1654 return NULL;
1658 /* use pos = -1 to search for the previous unmatched open bracket. */
1659 gboolean editor_show_calltip(GeanyEditor *editor, gint pos)
1661 gint orig_pos = pos; /* the position for the calltip */
1662 gint lexer;
1663 gint style;
1664 gchar word[GEANY_MAX_WORD_LENGTH];
1665 gchar *str;
1666 ScintillaObject *sci;
1668 g_return_val_if_fail(editor != NULL, FALSE);
1669 g_return_val_if_fail(editor->document->file_type != NULL, FALSE);
1671 sci = editor->sci;
1673 lexer = sci_get_lexer(sci);
1675 if (pos == -1)
1677 /* position of '(' is unknown, so go backwards from current position to find it */
1678 pos = sci_get_current_position(sci);
1679 pos--;
1680 orig_pos = pos;
1681 pos = (lexer == SCLEX_LATEX) ? find_previous_brace(sci, pos) :
1682 find_start_bracket(sci, pos);
1683 if (pos == -1)
1684 return FALSE;
1687 /* the style 1 before the brace (which may be highlighted) */
1688 style = sci_get_style_at(sci, pos - 1);
1689 if (! is_code_style(lexer, style))
1690 return FALSE;
1692 word[0] = '\0';
1693 editor_find_current_word(editor, pos - 1, word, sizeof word, NULL);
1694 if (word[0] == '\0')
1695 return FALSE;
1697 str = find_calltip(word, editor->document->file_type);
1698 if (str)
1700 g_free(calltip.text); /* free the old calltip */
1701 calltip.text = str;
1702 calltip.pos = orig_pos;
1703 calltip.sci = sci;
1704 calltip.set = TRUE;
1705 utils_wrap_string(calltip.text, -1);
1706 SSM(sci, SCI_CALLTIPSHOW, orig_pos, (sptr_t) calltip.text);
1707 return TRUE;
1709 return FALSE;
1713 gchar *editor_get_calltip_text(GeanyEditor *editor, const TMTag *tag)
1715 GString *str;
1717 g_return_val_if_fail(editor != NULL, NULL);
1719 str = g_string_new(NULL);
1720 if (append_calltip(str, tag, FILETYPE_ID(editor->document->file_type)))
1721 return g_string_free(str, FALSE);
1722 else
1723 return g_string_free(str, TRUE);
1727 /* HTML entities auto completion from html_entities.tags text file */
1728 static gboolean
1729 autocomplete_html(ScintillaObject *sci, const gchar *root, gsize rootlen)
1731 guint i, j = 0;
1732 gboolean found = FALSE;
1733 GString *words;
1734 const gchar **entities = symbols_get_html_entities();
1736 if (*root != '&' || G_UNLIKELY(entities == NULL))
1737 return FALSE;
1739 words = g_string_sized_new(500);
1740 for (i = 0; ; i++)
1742 if (entities[i] == NULL)
1743 break;
1744 else if (entities[i][0] == '#')
1745 continue;
1747 if (! strncmp(entities[i], root, rootlen))
1749 if (j++ > 0)
1750 g_string_append_c(words, '\n');
1751 g_string_append(words, entities[i]);
1752 found = TRUE;
1755 if (found)
1756 show_autocomplete(sci, rootlen, words->str);
1758 g_string_free(words, TRUE);
1759 return found;
1763 /* Current document & global tags autocompletion */
1764 static gboolean
1765 autocomplete_tags(GeanyEditor *editor, const gchar *root, gsize rootlen)
1767 TMTagAttrType attrs[] = { tm_tag_attr_name_t, 0 };
1768 const GPtrArray *tags;
1769 GeanyDocument *doc;
1771 g_return_val_if_fail(editor, FALSE);
1773 doc = editor->document;
1775 tags = tm_workspace_find(root, tm_tag_max_t, attrs, TRUE, doc->file_type->lang);
1776 if (tags)
1778 show_tags_list(editor, tags, rootlen);
1779 return tags->len > 0;
1781 return FALSE;
1785 /* Check whether to use entity autocompletion:
1786 * - always in a HTML file except when inside embedded JavaScript, Python, ASP, ...
1787 * - in a PHP file only when we are outside of <? ?> */
1788 static gboolean autocomplete_check_for_html(gint ft_id, gint style)
1790 /* use entity completion when style is not JavaScript, ASP, Python, PHP, ...
1791 * (everything after SCE_HJ_START is for embedded scripting languages) */
1792 if (ft_id == GEANY_FILETYPES_HTML && style < SCE_HJ_START)
1793 return TRUE;
1795 if (ft_id == GEANY_FILETYPES_PHP)
1797 /* use entity completion when style is outside of PHP styles */
1798 if (! is_style_php(style))
1799 return TRUE;
1802 return FALSE;
1806 /* Algorithm based on based on Scite's StartAutoCompleteWord() */
1807 static GString *get_doc_words(ScintillaObject *sci, gchar *root, gsize rootlen)
1809 gchar *word;
1810 gint len, current, word_end;
1811 gint pos_find, flags;
1812 guint word_length;
1813 gsize nmatches = 0;
1814 GString *words;
1815 struct Sci_TextToFind ttf;
1817 len = sci_get_length(sci);
1818 current = sci_get_current_position(sci) - rootlen;
1820 ttf.lpstrText = root;
1821 ttf.chrg.cpMin = 0;
1822 ttf.chrg.cpMax = len;
1823 ttf.chrgText.cpMin = 0;
1824 ttf.chrgText.cpMax = 0;
1825 flags = SCFIND_WORDSTART | SCFIND_MATCHCASE;
1827 words = g_string_sized_new(256);
1828 /* put space before first entry to make searching with strstr easy */
1829 g_string_append_c(words, ' ');
1831 /* search the whole document for the word root and collect results */
1832 pos_find = scintilla_send_message(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
1833 while (pos_find >= 0 && pos_find < len)
1835 word_end = pos_find + rootlen;
1836 if (pos_find != current)
1838 while (word_end < len && strchr(GEANY_WORDCHARS, sci_get_char_at(sci, word_end)) != NULL)
1839 word_end++;
1841 word_length = word_end - pos_find;
1842 if (word_length > rootlen)
1844 word = g_malloc0(word_length + 3);
1845 sci_get_text_range(sci, pos_find, word_end, word + 1);
1846 word[0] = ' ';
1847 word[word_length + 1] = ' ';
1848 /* search the words string whether we already have the word in, otherwise add it */
1849 if (strstr(words->str, word) == NULL)
1851 g_string_append(words, word + 1);
1852 nmatches++;
1854 g_free(word);
1856 if (nmatches == editor_prefs.autocompletion_max_entries)
1857 break;
1860 ttf.chrg.cpMin = word_end;
1861 pos_find = scintilla_send_message(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
1864 if (words->len > 1)
1866 g_strdelimit(words->str, " ", '\n');
1867 words->str[words->len - 1] = '\0'; /* remove the trailing '\n' */
1868 return words;
1870 g_string_free(words, TRUE);
1871 return NULL;
1875 static gboolean autocomplete_doc_word(GeanyEditor *editor, gchar *root, gsize rootlen)
1877 ScintillaObject *sci = editor->sci;
1878 GString *words;
1879 GString *str;
1880 gchar *ptr;
1881 GSList *node, *list = NULL;
1883 words = get_doc_words(sci, root, rootlen);
1884 if (!words)
1886 scintilla_send_message(sci, SCI_AUTOCCANCEL, 0, 0);
1887 return FALSE;
1890 /* words are unsorted, make list of words */
1891 foreach_str(ptr, words->str)
1893 if (*ptr == '\n')
1895 list = g_slist_prepend(list, ptr + 1);
1896 /* terminate previous string in list */
1897 ptr[0] = 0x0;
1898 ptr++;
1901 list = g_slist_sort(list, (GCompareFunc)utils_str_casecmp);
1903 str = g_string_sized_new(words->len);
1904 foreach_slist(node, list)
1906 g_string_append(str, node->data);
1907 if (node->next)
1908 g_string_append_c(str, '\n');
1910 if (g_slist_length(list) >= editor_prefs.autocompletion_max_entries)
1911 g_string_append(str, "\n...");
1913 g_slist_free(list);
1914 g_string_free(words, TRUE);
1916 show_autocomplete(sci, rootlen, str->str);
1917 g_string_free(str, TRUE);
1918 return TRUE;
1922 gboolean editor_start_auto_complete(GeanyEditor *editor, gint pos, gboolean force)
1924 gint line, line_start, line_len, line_pos, current, rootlen, startword, lexer, style;
1925 gchar *linebuf, *root;
1926 ScintillaObject *sci;
1927 gboolean ret = FALSE;
1928 gchar *wordchars;
1929 GeanyFiletype *ft;
1931 if (! editor_prefs.auto_complete_symbols && ! force)
1932 return FALSE;
1934 g_return_val_if_fail(editor != NULL, FALSE);
1936 /* If we are at the beginning of the document, we skip autocompletion as we can't determine the
1937 * necessary styling information */
1938 if (G_UNLIKELY(pos < 2))
1939 return FALSE;
1941 sci = editor->sci;
1942 ft = editor->document->file_type;
1944 line = sci_get_line_from_position(sci, pos);
1945 line_start = sci_get_position_from_line(sci, line);
1946 line_len = sci_get_line_length(sci, line);
1947 line_pos = pos - line_start - 1;
1948 current = pos - line_start;
1949 startword = current;
1950 lexer = sci_get_lexer(sci);
1951 style = sci_get_style_at(sci, pos - 2);
1953 /* don't autocomplete in comments and strings */
1954 if (!force && !is_code_style(lexer, style))
1955 return FALSE;
1957 autocomplete_scope(editor);
1959 linebuf = sci_get_line(sci, line);
1961 if (ft->id == GEANY_FILETYPES_LATEX)
1962 wordchars = GEANY_WORDCHARS"\\"; /* add \ to word chars if we are in a LaTeX file */
1963 else if (ft->id == GEANY_FILETYPES_HTML || ft->id == GEANY_FILETYPES_PHP)
1964 wordchars = GEANY_WORDCHARS"&"; /* add & to word chars if we are in a PHP or HTML file */
1965 else
1966 wordchars = GEANY_WORDCHARS;
1968 /* find the start of the current word */
1969 while ((startword > 0) && (strchr(wordchars, linebuf[startword - 1])))
1970 startword--;
1971 linebuf[current] = '\0';
1972 root = linebuf + startword;
1973 rootlen = current - startword;
1975 if (rootlen > 0)
1977 if (autocomplete_check_for_html(ft->id, style))
1979 /* Allow something like "&quot;some text&quot;". The above startword calculation
1980 * only works on words but for HTML entity completion we also want to have completion
1981 * based on '&' within words. */
1982 gchar *tmp = strchr(root, '&');
1983 if (tmp != NULL)
1985 root = tmp;
1986 rootlen = strlen(tmp);
1988 ret = autocomplete_html(sci, root, rootlen);
1990 else
1992 /* force is set when called by keyboard shortcut, otherwise start at the
1993 * editor_prefs.symbolcompletion_min_chars'th char */
1994 if (force || rootlen >= editor_prefs.symbolcompletion_min_chars)
1996 /* complete tags, except if forcing when completion is already visible */
1997 if (!(force && SSM(sci, SCI_AUTOCACTIVE, 0, 0)))
1998 ret = autocomplete_tags(editor, root, rootlen);
2000 /* If forcing and there's nothing else to show, complete from words in document */
2001 if (!ret && (force || editor_prefs.autocomplete_doc_words))
2002 ret = autocomplete_doc_word(editor, root, rootlen);
2006 if (!ret && force)
2007 utils_beep();
2009 g_free(linebuf);
2010 return ret;
2014 static const gchar *snippets_find_completion_by_name(const gchar *type, const gchar *name)
2016 gchar *result = NULL;
2017 GHashTable *tmp;
2019 g_return_val_if_fail(type != NULL && name != NULL, NULL);
2021 tmp = g_hash_table_lookup(snippet_hash, type);
2022 if (tmp != NULL)
2024 result = g_hash_table_lookup(tmp, name);
2026 /* whether nothing is set for the current filetype(tmp is NULL) or
2027 * the particular completion for this filetype is not set (result is NULL) */
2028 if (tmp == NULL || result == NULL)
2030 tmp = g_hash_table_lookup(snippet_hash, "Default");
2031 if (tmp != NULL)
2033 result = g_hash_table_lookup(tmp, name);
2036 /* if result is still NULL here, no completion could be found */
2038 /* result is owned by the hash table and will be freed when the table will destroyed */
2039 return result;
2043 /* This is very ugly but passing the pattern to ac_replace_specials() doesn't work because it is
2044 * modified when replacing a completion but the foreach function still passes the old pointer
2045 * to ac_replace_specials, so we use a global pointer outside of ac_replace_specials and
2046 * ac_complete_constructs. Any hints to improve this are welcome. */
2047 static GString *snippets_global_pattern = NULL;
2049 static void snippets_replace_specials(gpointer key, gpointer value, gpointer user_data)
2051 gchar *needle;
2053 g_return_if_fail(key != NULL);
2054 g_return_if_fail(value != NULL);
2056 needle = g_strconcat("%", (gchar*) key, "%", NULL);
2058 utils_string_replace_all(snippets_global_pattern, needle, (gchar*) value);
2059 g_free(needle);
2063 static void snippets_replace_wildcards(GeanyEditor *editor, GString *text)
2065 const gchar *file_name = DOC_FILENAME(editor->document);
2066 gchar *basename = g_path_get_basename(file_name);
2068 templates_replace_default_dates(text);
2069 templates_replace_valist(text, "{filename}", basename, NULL);
2070 templates_replace_command(text, file_name, editor->document->file_type->name, NULL);
2072 g_free(basename);
2076 /* this only works with spaces only indentation on the lines */
2077 static void fix_line_indents(GeanyEditor *editor, gint line_start, gint line_end)
2079 ScintillaObject *sci = editor->sci;
2080 gint line, cur_line, cur_col, pos;
2082 /* get the line, col position as fixing indentation will move cursor to start of line */
2083 pos = sci_get_current_position(sci);
2084 cur_col = sci_get_col_from_position(sci, pos);
2085 cur_line = sci_get_current_line(sci);
2087 for (line = line_start; line <= line_end; line++)
2089 gint size = sci_get_line_indentation(sci, line);
2091 /* set to 0 first to trigger proper indent creation */
2092 sci_set_line_indentation(sci, line, 0);
2093 sci_set_line_indentation(sci, line, size);
2095 pos = scintilla_send_message(sci, SCI_FINDCOLUMN, cur_line, cur_col);
2096 sci_set_current_position(sci, pos, FALSE);
2100 /** Inserts text, replacing \\t tab chars with the correct indent width, and \\n newline
2101 * chars with the correct line ending string.
2102 * @param editor The editor to operate on.
2103 * @param text Intended as e.g. "if (1)\n\tdo_something();"
2104 * @param insert_pos Position, where to start with inserting text block.
2105 * @param cursor_index If >= 0, the index into @a text to place the cursor.
2106 * @param newline_indent_size Indentation size (in spaces) to insert for each newline; use
2107 * -1 to read the indent size from the line with @a insert_pos on it.
2108 * @param replace_newlines Whether to replace newlines in text or not. If
2109 * newlines have been replaced before, this should be false, to avoid multiple
2110 * replacements of newlines, which is error prone on Windows.
2111 * @warning Make sure all \\t tab chars in @a text are intended as indent widths,
2112 * NOT any hard tabs (you get those when copying document text with the Tabs
2113 * & Spaces indent mode set).
2114 * @note This doesn't scroll the cursor in view afterwards. **/
2115 void editor_insert_text_block(GeanyEditor *editor, const gchar *text, gint insert_pos,
2116 gint cursor_index, gint newline_indent_size, gboolean replace_newlines)
2118 ScintillaObject *sci = editor->sci;
2119 gint line_start = sci_get_line_from_position(sci, insert_pos);
2120 gint line_end;
2121 gchar *whitespace;
2122 GString *buf;
2123 const gchar cur_marker[] = "__GEANY_CURSOR_MARKER__";
2124 const gchar *eol = editor_get_eol_char(editor);
2126 g_return_if_fail(text);
2127 g_return_if_fail(editor != NULL);
2128 g_return_if_fail(insert_pos >= 0);
2130 buf = g_string_new(text);
2132 if (cursor_index >= 0)
2133 g_string_insert(buf, cursor_index, cur_marker); /* remember cursor pos */
2135 if (newline_indent_size == -1)
2137 /* count indent size up to insert_pos instead of asking sci
2138 * because there may be spaces after it */
2139 gchar *tmp = sci_get_line(sci, line_start);
2140 gint idx = insert_pos - sci_get_position_from_line(sci, line_start);
2141 tmp[idx] = '\0';
2142 newline_indent_size = count_indent_size(editor, tmp);
2143 g_free(tmp);
2146 /* Add line indents (in spaces) */
2147 if (newline_indent_size > 0)
2149 whitespace = g_strnfill(newline_indent_size, ' ');
2150 setptr(whitespace, g_strconcat(eol, whitespace, NULL));
2151 utils_string_replace_all(buf, eol, whitespace);
2152 g_free(whitespace);
2155 /* transform line endings */
2156 if (replace_newlines)
2157 utils_string_replace_all(buf, "\n", eol);
2159 /* transform tabs into indent widths (in spaces) */
2160 whitespace = g_strnfill(editor_get_indent_prefs(editor)->width, ' ');
2161 utils_string_replace_all(buf, "\t", whitespace);
2162 g_free(whitespace);
2164 if (cursor_index >= 0)
2166 gint idx = utils_strpos(buf->str, cur_marker);
2168 g_string_erase(buf, idx, strlen(cur_marker));
2170 sci_insert_text(sci, insert_pos, buf->str);
2171 sci_set_current_position(sci, insert_pos + idx, FALSE);
2173 else
2174 sci_insert_text(sci, insert_pos, buf->str);
2176 /* fixup indentation (very useful for Tabs & Spaces indent type) */
2177 line_end = sci_get_line_from_position(sci, insert_pos + buf->len);
2178 fix_line_indents(editor, line_start, line_end);
2179 snippet_cursor_insert_pos = sci_get_current_position(sci);
2181 g_string_free(buf, TRUE);
2185 /* Move the cursor to the next specified cursor position in an inserted snippet.
2186 * Can, and should, be optimized to give better results */
2187 void editor_goto_next_snippet_cursor(GeanyEditor *editor)
2189 ScintillaObject *sci = editor->sci;
2190 gint current_pos = sci_get_current_position(sci);
2192 if (snippet_offsets && !g_queue_is_empty(snippet_offsets))
2194 gint offset;
2196 offset = GPOINTER_TO_INT(g_queue_pop_head(snippet_offsets));
2197 if (current_pos > snippet_cursor_insert_pos)
2198 snippet_cursor_insert_pos = offset + current_pos;
2199 else
2200 snippet_cursor_insert_pos += offset;
2202 sci_set_current_position(sci, snippet_cursor_insert_pos, FALSE);
2204 else
2206 utils_beep();
2211 static gssize snippets_make_replacements(GeanyEditor *editor, GString *pattern,
2212 gsize indent_size)
2214 gssize cur_index = -1;
2215 gchar *whitespace;
2216 gint i, tmp_pos, whitespace_len, nl_count = 0;
2217 GHashTable *specials;
2218 GList *temp_list = NULL;
2219 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
2220 gint cursor_steps, old_cursor = 0;
2222 /* replace 'special' completions */
2223 specials = g_hash_table_lookup(snippet_hash, "Special");
2224 if (G_LIKELY(specials != NULL))
2226 /* ugly hack using global_pattern */
2227 snippets_global_pattern = pattern;
2228 g_hash_table_foreach(specials, snippets_replace_specials, NULL);
2231 /* replace any %template% wildcards */
2232 snippets_replace_wildcards(editor, pattern);
2234 /* transform other wildcards */
2235 /* convert to %newlines%, else we get endless loops */
2236 utils_string_replace_all(pattern, "\n", "%newline%");
2238 /* if spaces are used, replaces all tabs with %ws%, which is later replaced
2239 * by real whitespace characters
2240 * otherwise replace all %ws% by \t, which will be replaced later by tab
2241 * characters,
2242 * this makes seperating between tab and spaces intentation pretty easy */
2243 if (iprefs->type == GEANY_INDENT_TYPE_SPACES)
2244 utils_string_replace_all(pattern, "\t", "%ws%");
2245 else
2246 utils_string_replace_all(pattern, "%ws%", "\t");
2248 whitespace = g_strnfill(iprefs->width, ' '); /* use spaces for indentation, will be fixed up */
2249 whitespace_len = strlen(whitespace);
2250 i = 0;
2251 while ((cursor_steps = utils_strpos(pattern->str, "%cursor%")) >= 0)
2253 /* replace every %newline% (up to next %cursor%) with EOL,
2254 * and update cursor_steps after */
2255 while ((tmp_pos = utils_strpos(pattern->str, "%newline%")) < cursor_steps && tmp_pos != -1)
2257 nl_count++;
2258 utils_string_replace_first(pattern, "%newline%", editor_get_eol_char(editor));
2259 cursor_steps = utils_strpos(pattern->str, "%cursor%");
2261 /* replace every %ws% (up to next %cursor%) with whitespaces,
2262 * and update cursor_steps after */
2263 while ((tmp_pos = utils_strpos(pattern->str, "%ws%")) < cursor_steps && tmp_pos != -1)
2265 utils_string_replace_first(pattern, "%ws%", whitespace);
2266 cursor_steps = utils_strpos(pattern->str, "%cursor%");
2268 /* finally replace the next %cursor% */
2269 utils_string_replace_first(pattern, "%cursor%", "");
2271 /* modify cursor_steps to take indentation count and type into account */
2273 /* We're saving the relative offset to each cursor position in a simple
2274 * linked list, including indentations between them. */
2275 if (i++ > 0)
2277 cursor_steps += (nl_count * indent_size);
2278 temp_list = g_list_append(temp_list, GINT_TO_POINTER(cursor_steps - old_cursor));
2280 else
2282 nl_count = 0;
2283 cur_index = cursor_steps;
2285 old_cursor = cursor_steps;
2287 /* replace remaining %ws% and %newline% which may occur after the last %cursor% */
2288 utils_string_replace_all(pattern, "%newline%", editor_get_eol_char(editor));
2289 utils_string_replace_all(pattern, "%ws%", whitespace);
2290 g_free(whitespace);
2292 /* We put the cursor positions for the most recent
2293 * parsed snippet first, followed by any remaining positions */
2294 i = 0;
2295 if (temp_list)
2297 GList *node;
2299 foreach_list(node, temp_list)
2300 g_queue_push_nth(snippet_offsets, node->data, i++);
2302 /* limit length of queue */
2303 while (g_queue_get_length(snippet_offsets) > 20)
2304 g_queue_pop_tail(snippet_offsets);
2306 g_list_free(temp_list);
2308 if (cur_index < 0)
2309 cur_index = pattern->len;
2311 return cur_index;
2315 static gboolean snippets_complete_constructs(GeanyEditor *editor, gint pos, const gchar *word)
2317 ScintillaObject *sci = editor->sci;
2318 gchar *str;
2319 GString *pattern;
2320 gssize cur_index = -1;
2321 gint str_len;
2322 gint ft_id = FILETYPE_ID(editor->document->file_type);
2324 str = g_strdup(word);
2325 g_strstrip(str);
2326 pattern = g_string_new(snippets_find_completion_by_name(filetypes[ft_id]->name, str));
2327 if (pattern == NULL || pattern->len == 0)
2329 g_free(str);
2330 g_string_free(pattern, TRUE);
2331 return FALSE;
2334 read_indent(editor, pos);
2336 /* remove the typed word, it will be added again by the used auto completion
2337 * (not really necessary but this makes the auto completion more flexible,
2338 * e.g. with a completion like hi=hello, so typing "hi<TAB>" will result in "hello") */
2339 str_len = strlen(str);
2340 sci_set_selection_start(sci, pos - str_len);
2341 sci_set_selection_end(sci, pos);
2342 sci_replace_sel(sci, "");
2343 pos -= str_len; /* pos has changed while deleting */
2345 cur_index = snippets_make_replacements(editor, pattern, strlen(indent));
2347 /* finally insert the text and set the cursor */
2348 editor_insert_text_block(editor, pattern->str, pos, cur_index, -1, FALSE);
2349 sci_scroll_caret(sci);
2351 g_free(str);
2352 g_string_free(pattern, TRUE);
2353 return TRUE;
2357 static gboolean at_eol(ScintillaObject *sci, gint pos)
2359 gint line = sci_get_line_from_position(sci, pos);
2360 gchar c;
2362 /* skip any trailing spaces */
2363 while (TRUE)
2365 c = sci_get_char_at(sci, pos);
2366 if (c == ' ' || c == '\t')
2367 pos++;
2368 else
2369 break;
2372 return (pos == sci_get_line_end_position(sci, line));
2376 gboolean editor_complete_snippet(GeanyEditor *editor, gint pos)
2378 gboolean result = FALSE;
2379 const gchar *wc;
2380 const gchar *word;
2381 ScintillaObject *sci;
2383 g_return_val_if_fail(editor != NULL, FALSE);
2385 sci = editor->sci;
2386 if (sci_has_selection(sci))
2387 return FALSE;
2388 /* return if we are editing an existing line (chars on right of cursor) */
2389 if (keybindings_lookup_item(GEANY_KEY_GROUP_EDITOR,
2390 GEANY_KEYS_EDITOR_COMPLETESNIPPET)->key == GDK_space &&
2391 ! editor_prefs.complete_snippets_whilst_editing && ! at_eol(sci, pos))
2392 return FALSE;
2394 wc = snippets_find_completion_by_name("Special", "wordchars");
2395 word = editor_read_word_stem(editor, pos, wc);
2397 /* prevent completion of "for " */
2398 if (NZV(word) &&
2399 ! isspace(sci_get_char_at(sci, pos - 1))) /* pos points to the line end char so use pos -1 */
2401 sci_start_undo_action(sci); /* needed because we insert a space separately from construct */
2402 result = snippets_complete_constructs(editor, pos, word);
2403 sci_end_undo_action(sci);
2404 if (result)
2405 sci_cancel(sci); /* cancel any autocompletion list, etc */
2407 return result;
2411 void editor_show_macro_list(GeanyEditor *editor)
2413 GString *words;
2415 if (editor == NULL || editor->document->file_type == NULL)
2416 return;
2418 words = symbols_get_macro_list(editor->document->file_type->lang);
2419 if (words == NULL)
2420 return;
2422 SSM(editor->sci, SCI_USERLISTSHOW, 1, (sptr_t) words->str);
2423 g_string_free(words, TRUE);
2427 static void insert_closing_tag(GeanyEditor *editor, gint pos, gchar ch, const gchar *tag_name)
2429 ScintillaObject *sci = editor->sci;
2430 gchar *to_insert = NULL;
2432 if (ch == '/')
2434 const gchar *gt = ">";
2435 /* if there is already a '>' behind the cursor, don't add it */
2436 if (sci_get_char_at(sci, pos) == '>')
2437 gt = "";
2439 to_insert = g_strconcat(tag_name, gt, NULL);
2441 else
2442 to_insert = g_strconcat("</", tag_name, ">", NULL);
2444 sci_start_undo_action(sci);
2445 sci_replace_sel(sci, to_insert);
2446 if (ch == '>')
2448 sci_set_selection(sci, pos, pos);
2449 if (utils_str_equal(tag_name, "table"))
2450 auto_table(editor, pos);
2452 sci_end_undo_action(sci);
2453 g_free(to_insert);
2458 * (stolen from anjuta and heavily modified)
2459 * This routine will auto complete XML or HTML tags that are still open by closing them
2460 * @param ch The character we are dealing with, currently only works with the '>' character
2461 * @return True if handled, false otherwise
2463 static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch)
2465 ScintillaObject *sci = editor->sci;
2466 gint lexer = sci_get_lexer(sci);
2467 gint min, style;
2468 gchar *str_found, sel[512];
2469 gboolean result = FALSE;
2471 /* If the user has turned us off, quit now.
2472 * This may make sense only in certain languages */
2473 if (! editor_prefs.auto_close_xml_tags || (lexer != SCLEX_HTML && lexer != SCLEX_XML))
2474 return FALSE;
2476 /* return if we are inside any embedded script */
2477 style = sci_get_style_at(sci, pos);
2478 if (style > SCE_H_XCCOMMENT && ! is_string_style(lexer, style))
2479 return FALSE;
2481 /* if ch is /, check for </, else quit */
2482 if (ch == '/' && sci_get_char_at(sci, pos - 2) != '<')
2483 return FALSE;
2485 /* Grab the last 512 characters or so */
2486 min = pos - (sizeof(sel) - 1);
2487 if (min < 0) min = 0;
2489 if (pos - min < 3)
2490 return FALSE; /* Smallest tag is 3 characters e.g. <p> */
2492 sci_get_text_range(sci, min, pos, sel);
2493 sel[sizeof(sel) - 1] = '\0';
2495 if (ch == '>' && sel[pos - min - 2] == '/')
2496 /* User typed something like "<br/>" */
2497 return FALSE;
2499 str_found = utils_find_open_xml_tag(sel, pos - min, (ch == '/'));
2501 /* when found string is something like br, img or another short tag, quit */
2502 if (utils_str_equal(str_found, "br")
2503 || utils_str_equal(str_found, "hr")
2504 || utils_str_equal(str_found, "img")
2505 || utils_str_equal(str_found, "base")
2506 || utils_str_equal(str_found, "basefont") /* < or not < */
2507 || utils_str_equal(str_found, "frame")
2508 || utils_str_equal(str_found, "input")
2509 || utils_str_equal(str_found, "link")
2510 || utils_str_equal(str_found, "area")
2511 || utils_str_equal(str_found, "meta"))
2513 /* ignore tag */
2515 else if (NZV(str_found))
2517 insert_closing_tag(editor, pos, ch, str_found);
2518 result = TRUE;
2520 g_free(str_found);
2521 return result;
2525 /* like sci_get_line_indentation(), but for a string. */
2526 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent)
2528 const gchar *ptr;
2529 gsize tab_size = sci_get_tab_width(editor->sci);
2530 gsize count = 0;
2532 g_return_val_if_fail(base_indent, 0);
2534 for (ptr = base_indent; *ptr != 0; ptr++)
2536 switch (*ptr)
2538 case ' ':
2539 count++;
2540 break;
2541 case '\t':
2542 count += tab_size;
2543 break;
2546 return count;
2550 static void auto_table(GeanyEditor *editor, gint pos)
2552 ScintillaObject *sci = editor->sci;
2553 gchar *table;
2554 gint indent_pos;
2555 const gchar *indent_str;
2557 if (sci_get_lexer(sci) != SCLEX_HTML) return;
2559 read_indent(editor, pos);
2560 indent_pos = sci_get_line_indent_position(sci, sci_get_line_from_position(sci, pos));
2561 if ((pos - 7) != indent_pos) /* 7 == strlen("<table>") */
2563 gint i;
2564 guint x;
2566 x = strlen(indent);
2567 /* find the start of the <table tag */
2568 i = 1;
2569 while (i <= pos && sci_get_char_at(sci, pos - i) != '<') i++;
2570 /* add all non whitespace before the tag to the indent string */
2571 while ((pos - i) != indent_pos && x < sizeof(indent) - 1)
2573 indent[x++] = ' ';
2574 i++;
2576 indent[x] = '\0';
2579 if (! editor->auto_indent)
2580 indent_str = "";
2581 else
2582 indent_str = "\t";
2584 table = g_strconcat("\n", indent_str, "<tr>\n",
2585 indent_str, indent_str, "<td> </td>\n",
2586 indent_str, "</tr>\n",
2587 NULL);
2588 editor_insert_text_block(editor, table, pos, -1,
2589 count_indent_size(editor, indent), TRUE);
2590 g_free(table);
2594 static void real_comment_multiline(GeanyEditor *editor, gint line_start, gint last_line)
2596 const gchar *eol;
2597 gchar *str_begin, *str_end, *co, *cc;
2598 gint line_len;
2600 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2602 eol = editor_get_eol_char(editor);
2603 co = editor->document->file_type->comment_open;
2604 cc = editor->document->file_type->comment_close;
2605 str_begin = g_strdup_printf("%s%s", (co != NULL) ? co : "", eol);
2606 str_end = g_strdup_printf("%s%s", (cc != NULL) ? cc : "", eol);
2608 /* insert the comment strings */
2609 sci_insert_text(editor->sci, line_start, str_begin);
2610 line_len = sci_get_position_from_line(editor->sci, last_line + 2);
2611 sci_insert_text(editor->sci, line_len, str_end);
2613 g_free(str_begin);
2614 g_free(str_end);
2618 static void real_uncomment_multiline(GeanyEditor *editor)
2620 /* find the beginning of the multi line comment */
2621 gint pos, line, len, x;
2622 gchar *linebuf;
2623 GeanyDocument *doc;
2625 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2626 doc = editor->document;
2628 /* remove comment open chars */
2629 pos = document_find_text(doc, doc->file_type->comment_open, 0, TRUE, FALSE, NULL);
2630 SSM(editor->sci, SCI_DELETEBACK, 0, 0);
2632 /* check whether the line is empty and can be deleted */
2633 line = sci_get_line_from_position(editor->sci, pos);
2634 len = sci_get_line_length(editor->sci, line);
2635 linebuf = sci_get_line(editor->sci, line);
2636 x = 0;
2637 while (linebuf[x] != '\0' && isspace(linebuf[x])) x++;
2638 if (x == len) SSM(editor->sci, SCI_LINEDELETE, 0, 0);
2639 g_free(linebuf);
2641 /* remove comment close chars */
2642 pos = document_find_text(doc, doc->file_type->comment_close, 0, FALSE, FALSE, NULL);
2643 SSM(editor->sci, SCI_DELETEBACK, 0, 0);
2645 /* check whether the line is empty and can be deleted */
2646 line = sci_get_line_from_position(editor->sci, pos);
2647 len = sci_get_line_length(editor->sci, line);
2648 linebuf = sci_get_line(editor->sci, line);
2649 x = 0;
2650 while (linebuf[x] != '\0' && isspace(linebuf[x])) x++;
2651 if (x == len) SSM(editor->sci, SCI_LINEDELETE, 0, 0);
2652 g_free(linebuf);
2656 static gint get_multiline_comment_style(GeanyEditor *editor, gint line_start)
2658 gint lexer = sci_get_lexer(editor->sci);
2659 gint style_comment;
2661 /* List only those lexers which support multi line comments */
2662 switch (lexer)
2664 case SCLEX_XML:
2665 case SCLEX_HTML:
2667 if (is_style_php(sci_get_style_at(editor->sci, line_start)))
2668 style_comment = SCE_HPHP_COMMENT;
2669 else
2670 style_comment = SCE_H_COMMENT;
2671 break;
2673 case SCLEX_HASKELL: style_comment = SCE_HA_COMMENTBLOCK; break;
2674 case SCLEX_LUA: style_comment = SCE_LUA_COMMENT; break;
2675 case SCLEX_CSS: style_comment = SCE_CSS_COMMENT; break;
2676 case SCLEX_SQL: style_comment = SCE_SQL_COMMENT; break;
2677 case SCLEX_CAML: style_comment = SCE_CAML_COMMENT; break;
2678 case SCLEX_D: style_comment = SCE_D_COMMENT; break;
2679 case SCLEX_PASCAL: style_comment = SCE_PAS_COMMENT; break;
2680 default: style_comment = SCE_C_COMMENT;
2683 return style_comment;
2687 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise
2688 * returns the amount of uncommented single comment lines, in case of multi line uncomment
2689 * it returns just 1 */
2690 gint editor_do_uncomment(GeanyEditor *editor, gint line, gboolean toggle)
2692 gint first_line, last_line;
2693 gint x, i, line_start, line_len;
2694 gint sel_start, sel_end;
2695 gint count = 0;
2696 gsize co_len;
2697 gchar sel[256], *co, *cc;
2698 gboolean break_loop = FALSE, single_line = FALSE;
2699 GeanyFiletype *ft;
2701 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, 0);
2703 if (line < 0)
2704 { /* use selection or current line */
2705 sel_start = sci_get_selection_start(editor->sci);
2706 sel_end = sci_get_selection_end(editor->sci);
2708 first_line = sci_get_line_from_position(editor->sci, sel_start);
2709 /* Find the last line with chars selected (not EOL char) */
2710 last_line = sci_get_line_from_position(editor->sci,
2711 sel_end - editor_get_eol_char_len(editor));
2712 last_line = MAX(first_line, last_line);
2714 else
2716 first_line = last_line = line;
2717 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
2720 ft = editor->document->file_type;
2722 /* detection of HTML vs PHP code, if non-PHP set filetype to XML */
2723 line_start = sci_get_position_from_line(editor->sci, first_line);
2724 if (ft->id == GEANY_FILETYPES_PHP)
2726 if (! is_style_php(sci_get_style_at(editor->sci, line_start)))
2727 ft = filetypes[GEANY_FILETYPES_XML];
2730 co = ft->comment_open;
2731 cc = ft->comment_close;
2732 if (co == NULL)
2733 return 0;
2735 co_len = strlen(co);
2736 if (co_len == 0)
2737 return 0;
2739 sci_start_undo_action(editor->sci);
2741 for (i = first_line; (i <= last_line) && (! break_loop); i++)
2743 gint buf_len;
2745 line_start = sci_get_position_from_line(editor->sci, i);
2746 line_len = sci_get_line_length(editor->sci, i);
2747 x = 0;
2749 buf_len = MIN((gint)sizeof(sel) - 1, line_len - 1);
2750 if (buf_len <= 0)
2751 continue;
2752 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
2753 sel[buf_len] = '\0';
2755 while (isspace(sel[x])) x++;
2757 /* to skip blank lines */
2758 if (x < line_len && sel[x] != '\0')
2760 /* use single line comment */
2761 if (cc == NULL || strlen(cc) == 0)
2763 single_line = TRUE;
2765 if (toggle)
2767 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
2768 if (strncmp(sel + x, co, co_len) != 0 ||
2769 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) != 0)
2770 continue;
2772 co_len += tm_len;
2774 else
2776 if (strncmp(sel + x, co, co_len) != 0)
2777 continue;
2780 sci_set_selection(editor->sci, line_start + x, line_start + x + co_len);
2781 sci_replace_sel(editor->sci, "");
2782 count++;
2784 /* use multi line comment */
2785 else
2787 gint style_comment;
2789 /* skip lines which are already comments */
2790 style_comment = get_multiline_comment_style(editor, line_start);
2791 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
2793 real_uncomment_multiline(editor);
2794 count = 1;
2797 /* break because we are already on the last line */
2798 break_loop = TRUE;
2799 break;
2803 sci_end_undo_action(editor->sci);
2805 /* restore selection if there is one
2806 * but don't touch the selection if caller is editor_do_comment_toggle */
2807 if (! toggle && sel_start < sel_end)
2809 if (single_line)
2811 sci_set_selection_start(editor->sci, sel_start - co_len);
2812 sci_set_selection_end(editor->sci, sel_end - (count * co_len));
2814 else
2816 gint eol_len = editor_get_eol_char_len(editor);
2817 sci_set_selection_start(editor->sci, sel_start - co_len - eol_len);
2818 sci_set_selection_end(editor->sci, sel_end - co_len - eol_len);
2822 return count;
2826 void editor_do_comment_toggle(GeanyEditor *editor)
2828 gint first_line, last_line;
2829 gint x, i, line_start, line_len, first_line_start;
2830 gint sel_start, sel_end;
2831 gint count_commented = 0, count_uncommented = 0;
2832 gchar sel[256], *co, *cc;
2833 gboolean break_loop = FALSE, single_line = FALSE;
2834 gboolean first_line_was_comment = FALSE;
2835 gsize co_len;
2836 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
2837 GeanyFiletype *ft;
2839 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2841 sel_start = sci_get_selection_start(editor->sci);
2842 sel_end = sci_get_selection_end(editor->sci);
2844 ft = editor->document->file_type;
2846 first_line = sci_get_line_from_position(editor->sci,
2847 sci_get_selection_start(editor->sci));
2848 /* Find the last line with chars selected (not EOL char) */
2849 last_line = sci_get_line_from_position(editor->sci,
2850 sci_get_selection_end(editor->sci) - editor_get_eol_char_len(editor));
2851 last_line = MAX(first_line, last_line);
2853 /* detection of HTML vs PHP code, if non-PHP set filetype to XML */
2854 first_line_start = sci_get_position_from_line(editor->sci, first_line);
2855 if (ft->id == GEANY_FILETYPES_PHP)
2857 if (! is_style_php(sci_get_style_at(editor->sci, first_line_start)))
2858 ft = filetypes[GEANY_FILETYPES_XML];
2861 co = ft->comment_open;
2862 cc = ft->comment_close;
2863 if (co == NULL)
2864 return;
2866 co_len = strlen(co);
2867 if (co_len == 0)
2868 return;
2870 sci_start_undo_action(editor->sci);
2872 for (i = first_line; (i <= last_line) && (! break_loop); i++)
2874 gint buf_len;
2876 line_start = sci_get_position_from_line(editor->sci, i);
2877 line_len = sci_get_line_length(editor->sci, i);
2878 x = 0;
2880 buf_len = MIN((gint)sizeof(sel) - 1, line_len - 1);
2881 if (buf_len < 0)
2882 continue;
2883 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
2884 sel[buf_len] = '\0';
2886 while (isspace(sel[x])) x++;
2888 /* use single line comment */
2889 if (cc == NULL || strlen(cc) == 0)
2891 gboolean do_continue = FALSE;
2892 single_line = TRUE;
2894 if (strncmp(sel + x, co, co_len) == 0 &&
2895 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) == 0)
2897 do_continue = TRUE;
2900 if (do_continue && i == first_line)
2901 first_line_was_comment = TRUE;
2903 if (do_continue)
2905 count_uncommented += editor_do_uncomment(editor, i, TRUE);
2906 continue;
2909 /* we are still here, so the above lines were not already comments, so comment it */
2910 editor_do_comment(editor, i, TRUE, TRUE);
2911 count_commented++;
2913 /* use multi line comment */
2914 else
2916 gint style_comment;
2918 /* skip lines which are already comments */
2919 style_comment = get_multiline_comment_style(editor, line_start);
2920 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
2922 real_uncomment_multiline(editor);
2923 count_uncommented++;
2925 else
2927 real_comment_multiline(editor, line_start, last_line);
2928 count_commented++;
2931 /* break because we are already on the last line */
2932 break_loop = TRUE;
2933 break;
2937 sci_end_undo_action(editor->sci);
2939 co_len += tm_len;
2941 /* restore selection if there is one */
2942 if (sel_start < sel_end)
2944 if (single_line)
2946 gint a = (first_line_was_comment) ? - co_len : co_len;
2948 /* don't modify sel_start when the selection starts within indentation */
2949 read_indent(editor, sel_start);
2950 if ((sel_start - first_line_start) <= (gint) strlen(indent))
2951 a = 0;
2953 sci_set_selection_start(editor->sci, sel_start + a);
2954 sci_set_selection_end(editor->sci, sel_end +
2955 (count_commented * co_len) - (count_uncommented * co_len));
2957 else
2959 gint eol_len = editor_get_eol_char_len(editor);
2960 if (count_uncommented > 0)
2962 sci_set_selection_start(editor->sci, sel_start - co_len + eol_len);
2963 sci_set_selection_end(editor->sci, sel_end - co_len + eol_len);
2965 else if (count_commented > 0)
2967 sci_set_selection_start(editor->sci, sel_start + co_len - eol_len);
2968 sci_set_selection_end(editor->sci, sel_end + co_len - eol_len);
2972 else if (count_uncommented > 0)
2974 gint eol_len = single_line ? 0: editor_get_eol_char_len(editor);
2975 sci_set_current_position(editor->sci, sel_start - co_len + eol_len, TRUE);
2977 else if (count_commented > 0)
2979 gint eol_len = single_line ? 0: editor_get_eol_char_len(editor);
2980 sci_set_current_position(editor->sci, sel_start + co_len - eol_len, TRUE);
2985 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise */
2986 void editor_do_comment(GeanyEditor *editor, gint line, gboolean allow_empty_lines, gboolean toggle)
2988 gint first_line, last_line;
2989 gint x, i, line_start, line_len;
2990 gint sel_start, sel_end, co_len;
2991 gchar sel[256], *co, *cc;
2992 gboolean break_loop = FALSE, single_line = FALSE;
2993 GeanyFiletype *ft;
2995 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2997 if (line < 0)
2998 { /* use selection or current line */
2999 sel_start = sci_get_selection_start(editor->sci);
3000 sel_end = sci_get_selection_end(editor->sci);
3002 first_line = sci_get_line_from_position(editor->sci, sel_start);
3003 /* Find the last line with chars selected (not EOL char) */
3004 last_line = sci_get_line_from_position(editor->sci,
3005 sel_end - editor_get_eol_char_len(editor));
3006 last_line = MAX(first_line, last_line);
3008 else
3010 first_line = last_line = line;
3011 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
3014 ft = editor->document->file_type;
3016 /* detection of HTML vs PHP code, if non-PHP set filetype to XML */
3017 line_start = sci_get_position_from_line(editor->sci, first_line);
3018 if (ft->id == GEANY_FILETYPES_PHP)
3020 if (! is_style_php(sci_get_style_at(editor->sci, line_start)))
3021 ft = filetypes[GEANY_FILETYPES_XML];
3024 co = ft->comment_open;
3025 cc = ft->comment_close;
3026 if (co == NULL)
3027 return;
3029 co_len = strlen(co);
3030 if (co_len == 0)
3031 return;
3033 sci_start_undo_action(editor->sci);
3035 for (i = first_line; (i <= last_line) && (! break_loop); i++)
3037 gint buf_len;
3039 line_start = sci_get_position_from_line(editor->sci, i);
3040 line_len = sci_get_line_length(editor->sci, i);
3041 x = 0;
3043 buf_len = MIN((gint)sizeof(sel) - 1, line_len - 1);
3044 if (buf_len < 0)
3045 continue;
3046 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3047 sel[buf_len] = '\0';
3049 while (isspace(sel[x])) x++;
3051 /* to skip blank lines */
3052 if (allow_empty_lines || (x < line_len && sel[x] != '\0'))
3054 /* use single line comment */
3055 if (cc == NULL || strlen(cc) == 0)
3057 gint start = line_start;
3058 single_line = TRUE;
3060 if (ft->comment_use_indent)
3061 start = line_start + x;
3063 if (toggle)
3065 gchar *text = g_strconcat(co, editor_prefs.comment_toggle_mark, NULL);
3066 sci_insert_text(editor->sci, start, text);
3067 g_free(text);
3069 else
3070 sci_insert_text(editor->sci, start, co);
3072 /* use multi line comment */
3073 else
3075 gint style_comment;
3077 /* skip lines which are already comments */
3078 style_comment = get_multiline_comment_style(editor, line_start);
3079 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3080 continue;
3082 real_comment_multiline(editor, line_start, last_line);
3084 /* break because we are already on the last line */
3085 break_loop = TRUE;
3086 break;
3090 sci_end_undo_action(editor->sci);
3092 /* restore selection if there is one
3093 * but don't touch the selection if caller is editor_do_comment_toggle */
3094 if (! toggle && sel_start < sel_end)
3096 if (single_line)
3098 sci_set_selection_start(editor->sci, sel_start + co_len);
3099 sci_set_selection_end(editor->sci, sel_end + ((i - first_line) * co_len));
3101 else
3103 gint eol_len = editor_get_eol_char_len(editor);
3104 sci_set_selection_start(editor->sci, sel_start + co_len + eol_len);
3105 sci_set_selection_end(editor->sci, sel_end + co_len + eol_len);
3111 static gboolean brace_timeout_active = FALSE;
3113 static gboolean delay_match_brace(G_GNUC_UNUSED gpointer user_data)
3115 GeanyDocument *doc = document_get_current();
3116 GeanyEditor *editor;
3117 gint brace_pos = GPOINTER_TO_INT(user_data);
3118 gint end_pos, cur_pos;
3120 brace_timeout_active = FALSE;
3121 if (!doc)
3122 return FALSE;
3124 editor = doc->editor;
3125 cur_pos = sci_get_current_position(editor->sci) - 1;
3127 if (cur_pos != brace_pos)
3129 cur_pos++;
3130 if (cur_pos != brace_pos)
3132 /* we have moved past the original brace_pos, but after the timeout
3133 * we may now be on a new brace, so check again */
3134 editor_highlight_braces(editor, cur_pos);
3135 return FALSE;
3138 if (!utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3140 editor_highlight_braces(editor, cur_pos);
3141 return FALSE;
3143 end_pos = sci_find_matching_brace(editor->sci, brace_pos);
3145 if (end_pos >= 0)
3147 gint col = MIN(sci_get_col_from_position(editor->sci, brace_pos),
3148 sci_get_col_from_position(editor->sci, end_pos));
3149 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, col, 0);
3150 SSM(editor->sci, SCI_BRACEHIGHLIGHT, brace_pos, end_pos);
3152 else
3154 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3155 SSM(editor->sci, SCI_BRACEBADLIGHT, brace_pos, 0);
3157 return FALSE;
3161 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos)
3163 gint brace_pos = cur_pos - 1;
3165 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3166 SSM(editor->sci, SCI_BRACEBADLIGHT, (uptr_t)-1, 0);
3168 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3170 brace_pos++;
3171 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3173 return;
3176 if (!brace_timeout_active)
3178 brace_timeout_active = TRUE;
3179 /* delaying matching makes scrolling faster e.g. holding down arrow keys */
3180 g_timeout_add(100, delay_match_brace, GINT_TO_POINTER(brace_pos));
3185 static gboolean in_block_comment(gint lexer, gint style)
3187 switch (lexer)
3189 case SCLEX_CPP:
3190 return (style == SCE_C_COMMENT ||
3191 style == SCE_C_COMMENTDOC);
3193 case SCLEX_PASCAL:
3194 return (style == SCE_PAS_COMMENT ||
3195 style == SCE_PAS_COMMENT2);
3197 case SCLEX_D:
3198 return (style == SCE_D_COMMENT ||
3199 style == SCE_D_COMMENTDOC ||
3200 style == SCE_D_COMMENTNESTED);
3202 case SCLEX_HTML:
3203 return (style == SCE_HPHP_COMMENT);
3205 case SCLEX_CSS:
3206 return (style == SCE_CSS_COMMENT);
3208 default:
3209 return FALSE;
3214 static gboolean is_comment_char(gchar c, gint lexer)
3216 if ((c == '*' || c == '+') && lexer == SCLEX_D)
3217 return TRUE;
3218 else
3219 if (c == '*')
3220 return TRUE;
3222 return FALSE;
3226 static void auto_multiline(GeanyEditor *editor, gint cur_line)
3228 ScintillaObject *sci = editor->sci;
3229 gint indent_pos, style;
3230 gint lexer = sci_get_lexer(sci);
3232 /* Use the start of the line enter was pressed on, to avoid any doc keyword styles */
3233 indent_pos = sci_get_line_indent_position(sci, cur_line - 1);
3234 style = sci_get_style_at(sci, indent_pos);
3235 if (!in_block_comment(lexer, style))
3236 return;
3238 /* Check whether the comment block continues on this line */
3239 indent_pos = sci_get_line_indent_position(sci, cur_line);
3240 if (sci_get_style_at(sci, indent_pos) == style)
3242 gchar *previous_line = sci_get_line(sci, cur_line - 1);
3243 /* the type of comment, '*' (C/C++/Java), '+' and the others (D) */
3244 gchar *continuation = "*";
3245 gchar *whitespace = ""; /* to hold whitespace if needed */
3246 gchar *result;
3247 gint len = strlen(previous_line);
3248 gint i;
3250 /* find and stop at end of multi line comment */
3251 i = len - 1;
3252 while (i >= 0 && isspace(previous_line[i])) i--;
3253 if (i >= 1 && is_comment_char(previous_line[i - 1], lexer) && previous_line[i] == '/')
3255 gint indent_len, indent_width;
3257 indent_pos = sci_get_line_indent_position(sci, cur_line);
3258 indent_len = sci_get_col_from_position(sci, indent_pos);
3259 indent_width = editor_get_indent_prefs(editor)->width;
3261 /* if there is one too many spaces, delete the last space,
3262 * to return to the indent used before the multiline comment was started. */
3263 if (indent_len % indent_width == 1)
3264 SSM(sci, SCI_DELETEBACKNOTLINE, 0, 0); /* remove whitespace indent */
3265 g_free(previous_line);
3266 return;
3268 /* check whether we are on the second line of multi line comment */
3269 i = 0;
3270 while (i < len && isspace(previous_line[i])) i++; /* get to start of the line */
3272 if (i + 1 < len &&
3273 previous_line[i] == '/' && is_comment_char(previous_line[i + 1], lexer))
3274 { /* we are on the second line of a multi line comment, so we have to insert white space */
3275 whitespace = " ";
3278 if (G_UNLIKELY(style == SCE_D_COMMENTNESTED))
3279 continuation = "+"; /* for nested comments in D */
3281 result = g_strconcat(whitespace, continuation, " ", NULL);
3282 sci_add_text(sci, result);
3283 g_free(result);
3285 g_free(previous_line);
3290 /* Checks whether the given style is a string for the given lexer.
3291 * It doesn't handle LEX_HTML, this should be done by the caller.
3292 * Returns true if the style is a string, FALSE otherwise.
3294 * Don't forget STRINGEOL, to prevent completion whilst typing a string with no closing char.
3296 static gboolean is_string_style(gint lexer, gint style)
3298 switch (lexer)
3300 case SCLEX_CPP:
3301 return (style == SCE_C_CHARACTER ||
3302 style == SCE_C_STRING ||
3303 style == SCE_C_STRINGEOL);
3305 case SCLEX_PASCAL:
3306 return (style == SCE_PAS_CHARACTER ||
3307 style == SCE_PAS_STRING ||
3308 style == SCE_PAS_STRINGEOL);
3310 case SCLEX_D:
3311 return (style == SCE_D_STRING ||
3312 style == SCE_D_STRINGEOL ||
3313 style == SCE_D_CHARACTER ||
3314 style == SCE_D_STRINGB ||
3315 style == SCE_D_STRINGR);
3317 case SCLEX_PYTHON:
3318 return (style == SCE_P_STRING ||
3319 style == SCE_P_TRIPLE ||
3320 style == SCE_P_TRIPLEDOUBLE ||
3321 style == SCE_P_CHARACTER ||
3322 style == SCE_P_STRINGEOL);
3324 case SCLEX_F77:
3325 case SCLEX_FORTRAN:
3326 return (style == SCE_F_STRING1 ||
3327 style == SCE_F_STRING2 ||
3328 style == SCE_F_STRINGEOL);
3330 case SCLEX_PERL:
3331 return (/*style == SCE_PL_STRING ||*/ /* may want variable autocompletion "$(foo)" */
3332 style == SCE_PL_CHARACTER ||
3333 style == SCE_PL_HERE_DELIM ||
3334 style == SCE_PL_HERE_Q ||
3335 style == SCE_PL_HERE_QQ ||
3336 style == SCE_PL_HERE_QX ||
3337 style == SCE_PL_POD ||
3338 style == SCE_PL_STRING_Q ||
3339 style == SCE_PL_STRING_QQ ||
3340 style == SCE_PL_STRING_QX ||
3341 style == SCE_PL_STRING_QR ||
3342 style == SCE_PL_STRING_QW ||
3343 style == SCE_PL_POD_VERB);
3345 case SCLEX_R:
3346 return (style == SCE_R_STRING);
3348 case SCLEX_RUBY:
3349 return (style == SCE_RB_CHARACTER ||
3350 style == SCE_RB_STRING ||
3351 style == SCE_RB_HERE_DELIM ||
3352 style == SCE_RB_HERE_Q ||
3353 style == SCE_RB_HERE_QQ ||
3354 style == SCE_RB_HERE_QX ||
3355 style == SCE_RB_POD);
3357 case SCLEX_BASH:
3358 return (style == SCE_SH_STRING);
3360 case SCLEX_SQL:
3361 return (style == SCE_SQL_STRING);
3363 case SCLEX_TCL:
3364 return (style == SCE_TCL_IN_QUOTE);
3366 case SCLEX_LUA:
3367 return (style == SCE_LUA_LITERALSTRING ||
3368 style == SCE_LUA_CHARACTER ||
3369 style == SCE_LUA_STRINGEOL ||
3370 style == SCE_LUA_STRING);
3372 case SCLEX_HASKELL:
3373 return (style == SCE_HA_CHARACTER ||
3374 style == SCE_HA_STRING);
3376 case SCLEX_FREEBASIC:
3377 return (style == SCE_B_STRING ||
3378 style == SCE_B_STRINGEOL);
3380 case SCLEX_MATLAB:
3381 return (style == SCE_MATLAB_STRING ||
3382 style == SCE_MATLAB_DOUBLEQUOTESTRING);
3384 case SCLEX_HTML:
3385 return (
3386 style == SCE_HBA_STRING ||
3387 style == SCE_HBA_STRINGEOL ||
3388 style == SCE_HB_STRING ||
3389 style == SCE_HB_STRINGEOL ||
3390 style == SCE_H_CDATA ||
3391 style == SCE_H_DOUBLESTRING ||
3392 style == SCE_HJA_DOUBLESTRING ||
3393 style == SCE_HJA_SINGLESTRING ||
3394 style == SCE_HJA_STRINGEOL ||
3395 style == SCE_HJ_DOUBLESTRING ||
3396 style == SCE_HJ_SINGLESTRING ||
3397 style == SCE_HJ_STRINGEOL ||
3398 style == SCE_HPA_CHARACTER ||
3399 style == SCE_HPA_STRING ||
3400 style == SCE_HPA_TRIPLE ||
3401 style == SCE_HPA_TRIPLEDOUBLE ||
3402 style == SCE_HP_CHARACTER ||
3403 style == SCE_HPHP_HSTRING ||
3404 style == SCE_HPHP_HSTRING || /* HSTRING is a heredoc */
3405 style == SCE_HPHP_HSTRING_VARIABLE ||
3406 style == SCE_HPHP_SIMPLESTRING ||
3407 style == SCE_HPHP_SIMPLESTRING ||
3408 style == SCE_HP_STRING ||
3409 style == SCE_HP_TRIPLE ||
3410 style == SCE_HP_TRIPLEDOUBLE ||
3411 style == SCE_H_SGML_DOUBLESTRING ||
3412 style == SCE_H_SGML_SIMPLESTRING ||
3413 style == SCE_H_SINGLESTRING);
3415 case SCLEX_CMAKE:
3416 return (style == SCE_CMAKE_STRINGDQ ||
3417 style == SCE_CMAKE_STRINGLQ ||
3418 style == SCE_CMAKE_STRINGRQ ||
3419 style == SCE_CMAKE_STRINGVAR);
3421 case SCLEX_NSIS:
3422 return (style == SCE_NSIS_STRINGDQ ||
3423 style == SCE_NSIS_STRINGLQ ||
3424 style == SCE_NSIS_STRINGRQ ||
3425 style == SCE_NSIS_STRINGVAR);
3427 case SCLEX_ADA:
3428 return (style == SCE_ADA_CHARACTER ||
3429 style == SCE_ADA_STRING ||
3430 style == SCE_ADA_CHARACTEREOL ||
3431 style == SCE_ADA_STRINGEOL);
3433 return FALSE;
3437 /* Checks whether the given style is a comment for the given lexer.
3438 * It doesn't handle LEX_HTML, this should be done by the caller.
3439 * Returns true if the style is a comment, FALSE otherwise.
3441 static gboolean is_comment_style(gint lexer, gint style)
3443 switch (lexer)
3445 case SCLEX_CPP:
3446 return (style == SCE_C_COMMENT ||
3447 style == SCE_C_COMMENTLINE ||
3448 style == SCE_C_COMMENTDOC ||
3449 style == SCE_C_COMMENTLINEDOC ||
3450 style == SCE_C_COMMENTDOCKEYWORD ||
3451 style == SCE_C_COMMENTDOCKEYWORDERROR);
3453 case SCLEX_PASCAL:
3454 return (style == SCE_PAS_COMMENT ||
3455 style == SCE_PAS_COMMENT2 ||
3456 style == SCE_PAS_COMMENTLINE);
3458 case SCLEX_D:
3459 return (style == SCE_D_COMMENT ||
3460 style == SCE_D_COMMENTLINE ||
3461 style == SCE_D_COMMENTDOC ||
3462 style == SCE_D_COMMENTNESTED ||
3463 style == SCE_D_COMMENTLINEDOC ||
3464 style == SCE_D_COMMENTDOCKEYWORD ||
3465 style == SCE_D_COMMENTDOCKEYWORDERROR);
3467 case SCLEX_PYTHON:
3468 return (style == SCE_P_COMMENTLINE ||
3469 style == SCE_P_COMMENTBLOCK);
3471 case SCLEX_F77:
3472 case SCLEX_FORTRAN:
3473 return (style == SCE_F_COMMENT);
3475 case SCLEX_PERL:
3476 return (style == SCE_PL_COMMENTLINE);
3478 case SCLEX_PROPERTIES:
3479 return (style == SCE_PROPS_COMMENT);
3481 case SCLEX_PO:
3482 return (style == SCE_PO_COMMENT);
3484 case SCLEX_LATEX:
3485 return (style == SCE_L_COMMENT);
3487 case SCLEX_MAKEFILE:
3488 return (style == SCE_MAKE_COMMENT);
3490 case SCLEX_RUBY:
3491 return (style == SCE_RB_COMMENTLINE);
3493 case SCLEX_BASH:
3494 return (style == SCE_SH_COMMENTLINE);
3496 case SCLEX_R:
3497 return (style == SCE_R_COMMENT);
3499 case SCLEX_SQL:
3500 return (style == SCE_SQL_COMMENT ||
3501 style == SCE_SQL_COMMENTLINE ||
3502 style == SCE_SQL_COMMENTDOC);
3504 case SCLEX_TCL:
3505 return (style == SCE_TCL_COMMENT ||
3506 style == SCE_TCL_COMMENTLINE ||
3507 style == SCE_TCL_COMMENT_BOX ||
3508 style == SCE_TCL_BLOCK_COMMENT);
3510 case SCLEX_MATLAB:
3511 return (style == SCE_MATLAB_COMMENT);
3513 case SCLEX_LUA:
3514 return (style == SCE_LUA_COMMENT ||
3515 style == SCE_LUA_COMMENTLINE ||
3516 style == SCE_LUA_COMMENTDOC);
3518 case SCLEX_HASKELL:
3519 return (style == SCE_HA_COMMENTLINE ||
3520 style == SCE_HA_COMMENTBLOCK ||
3521 style == SCE_HA_COMMENTBLOCK2 ||
3522 style == SCE_HA_COMMENTBLOCK3);
3524 case SCLEX_FREEBASIC:
3525 return (style == SCE_B_COMMENT);
3527 case SCLEX_YAML:
3528 return (style == SCE_YAML_COMMENT);
3530 case SCLEX_HTML:
3531 return (
3532 style == SCE_HBA_COMMENTLINE ||
3533 style == SCE_HB_COMMENTLINE ||
3534 style == SCE_H_COMMENT ||
3535 style == SCE_HJA_COMMENT ||
3536 style == SCE_HJA_COMMENTDOC ||
3537 style == SCE_HJA_COMMENTLINE ||
3538 style == SCE_HJ_COMMENT ||
3539 style == SCE_HJ_COMMENTDOC ||
3540 style == SCE_HJ_COMMENTLINE ||
3541 style == SCE_HPA_COMMENTLINE ||
3542 style == SCE_HP_COMMENTLINE ||
3543 style == SCE_HPHP_COMMENT ||
3544 style == SCE_HPHP_COMMENTLINE ||
3545 style == SCE_H_SGML_COMMENT);
3547 case SCLEX_CMAKE:
3548 return (style == SCE_CMAKE_COMMENT);
3550 case SCLEX_NSIS:
3551 return (style == SCE_NSIS_COMMENT ||
3552 style == SCE_NSIS_COMMENTBOX);
3554 case SCLEX_ADA:
3555 return (style == SCE_ADA_COMMENTLINE ||
3556 style == SCE_NSIS_COMMENTBOX);
3558 return FALSE;
3562 /* Checks whether the given style is normal code (not string, comment, preprocessor, etc).
3563 * It doesn't handle LEX_HTML, this should be done by the caller.
3565 static gboolean is_code_style(gint lexer, gint style)
3567 switch (lexer)
3569 case SCLEX_CPP:
3570 if (style == SCE_C_PREPROCESSOR)
3571 return FALSE;
3572 break;
3574 return !(is_comment_style(lexer, style) ||
3575 is_string_style(lexer, style));
3579 #if 0
3580 static gboolean editor_lexer_is_c_like(gint lexer)
3582 switch (lexer)
3584 case SCLEX_CPP:
3585 case SCLEX_D:
3586 return TRUE;
3588 default:
3589 return FALSE;
3592 #endif
3595 /* Returns: -1 if lexer doesn't support type keywords */
3596 gint editor_lexer_get_type_keyword_idx(gint lexer)
3598 switch (lexer)
3600 case SCLEX_CPP:
3601 case SCLEX_D:
3602 return 3;
3604 default:
3605 return -1;
3610 /* inserts a three-line comment at one line above current cursor position */
3611 void editor_insert_multiline_comment(GeanyEditor *editor)
3613 gchar *text;
3614 gint text_len;
3615 gint line;
3616 gint pos;
3617 gboolean have_multiline_comment = FALSE;
3618 GeanyDocument *doc;
3620 g_return_if_fail(editor != NULL &&
3621 editor->document->file_type != NULL && editor->document->file_type->comment_open != NULL);
3623 doc = editor->document;
3625 if (doc->file_type->comment_close != NULL && strlen(doc->file_type->comment_close) > 0)
3626 have_multiline_comment = TRUE;
3628 /* insert three lines one line above of the current position */
3629 line = sci_get_line_from_position(editor->sci, editor_info.click_pos);
3630 pos = sci_get_position_from_line(editor->sci, line);
3632 /* use the indent on the current line but only when comment indentation is used
3633 * and we don't have multi line comment characters */
3634 if (editor->auto_indent &&
3635 ! have_multiline_comment && doc->file_type->comment_use_indent)
3637 read_indent(editor, editor_info.click_pos);
3638 text = g_strdup_printf("%s\n%s\n%s\n", indent, indent, indent);
3639 text_len = strlen(text);
3641 else
3643 text = g_strdup("\n\n\n");
3644 text_len = 3;
3646 sci_insert_text(editor->sci, pos, text);
3647 g_free(text);
3650 /* select the inserted lines for commenting */
3651 sci_set_selection_start(editor->sci, pos);
3652 sci_set_selection_end(editor->sci, pos + text_len);
3654 editor_do_comment(editor, -1, TRUE, FALSE);
3656 /* set the current position to the start of the first inserted line */
3657 pos += strlen(doc->file_type->comment_open);
3659 /* on multi line comment jump to the next line, otherwise add the length of added indentation */
3660 if (have_multiline_comment)
3661 pos += 1;
3662 else
3663 pos += strlen(indent);
3665 sci_set_current_position(editor->sci, pos, TRUE);
3666 /* reset the selection */
3667 sci_set_anchor(editor->sci, pos);
3671 /* Note: If the editor is pending a redraw, set document::scroll_percent instead.
3672 * Scroll the view to make line appear at percent_of_view.
3673 * line can be -1 to use the current position. */
3674 void editor_scroll_to_line(GeanyEditor *editor, gint line, gfloat percent_of_view)
3676 gint vis1, los, delta;
3677 GtkWidget *wid;
3679 g_return_if_fail(editor != NULL);
3681 wid = GTK_WIDGET(editor->sci);
3683 if (! wid->window || ! gdk_window_is_viewable(wid->window))
3684 return; /* prevent gdk_window_scroll warning */
3686 if (line == -1)
3687 line = sci_get_current_line(editor->sci);
3689 /* sci 'visible line' != doc line number because of folding and line wrapping */
3690 /* calling SCI_VISIBLEFROMDOCLINE for line is more accurate than calling
3691 * SCI_DOCLINEFROMVISIBLE for vis1. */
3692 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0);
3693 vis1 = SSM(editor->sci, SCI_GETFIRSTVISIBLELINE, 0, 0);
3694 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
3695 delta = (line - vis1) - los * percent_of_view;
3696 sci_scroll_lines(editor->sci, delta);
3697 sci_scroll_caret(editor->sci); /* needed for horizontal scrolling */
3701 /* creates and inserts one tab or whitespace of the amount of the tab width */
3702 void editor_insert_alternative_whitespace(GeanyEditor *editor)
3704 gchar *text;
3705 GeanyIndentPrefs iprefs = *editor_get_indent_prefs(editor);
3707 g_return_if_fail(editor != NULL);
3709 switch (iprefs.type)
3711 case GEANY_INDENT_TYPE_TABS:
3712 iprefs.type = GEANY_INDENT_TYPE_SPACES;
3713 break;
3714 case GEANY_INDENT_TYPE_SPACES:
3715 case GEANY_INDENT_TYPE_BOTH: /* most likely we want a tab */
3716 iprefs.type = GEANY_INDENT_TYPE_TABS;
3717 break;
3719 text = get_whitespace(&iprefs, iprefs.width);
3720 sci_add_text(editor->sci, text);
3721 g_free(text);
3725 void editor_select_word(GeanyEditor *editor)
3727 gint pos;
3728 gint start;
3729 gint end;
3731 g_return_if_fail(editor != NULL);
3733 pos = SSM(editor->sci, SCI_GETCURRENTPOS, 0, 0);
3734 start = SSM(editor->sci, SCI_WORDSTARTPOSITION, pos, TRUE);
3735 end = SSM(editor->sci, SCI_WORDENDPOSITION, pos, TRUE);
3737 if (start == end) /* caret in whitespaces sequence */
3739 /* look forward but reverse the selection direction,
3740 * so the caret end up stay as near as the original position. */
3741 end = SSM(editor->sci, SCI_WORDENDPOSITION, pos, FALSE);
3742 start = SSM(editor->sci, SCI_WORDENDPOSITION, end, TRUE);
3743 if (start == end)
3744 return;
3747 sci_set_selection(editor->sci, start, end);
3751 /* extra_line is for selecting the cursor line (or anchor line) at the bottom of a selection,
3752 * when those lines have no selection (cursor at start of line). */
3753 void editor_select_lines(GeanyEditor *editor, gboolean extra_line)
3755 gint start, end, line;
3757 g_return_if_fail(editor != NULL);
3759 start = sci_get_selection_start(editor->sci);
3760 end = sci_get_selection_end(editor->sci);
3762 /* check if whole lines are already selected */
3763 if (! extra_line && start != end &&
3764 sci_get_col_from_position(editor->sci, start) == 0 &&
3765 sci_get_col_from_position(editor->sci, end) == 0)
3766 return;
3768 line = sci_get_line_from_position(editor->sci, start);
3769 start = sci_get_position_from_line(editor->sci, line);
3771 line = sci_get_line_from_position(editor->sci, end);
3772 end = sci_get_position_from_line(editor->sci, line + 1);
3774 sci_set_selection(editor->sci, start, end);
3778 /* find the start or end of a paragraph by searching all lines in direction (UP or DOWN)
3779 * starting at the given line and return the found line or return -1 if called on an empty line */
3780 static gint find_paragraph_stop(GeanyEditor *editor, gint line, gint direction)
3782 gboolean found_end = FALSE;
3783 gint step;
3784 gchar *line_buf, *x;
3785 ScintillaObject *sci = editor->sci;
3787 /* first check current line and return -1 if it is empty to skip creating of a selection */
3788 line_buf = x = sci_get_line(sci, line);
3789 while (isspace(*x))
3790 x++;
3791 if (*x == '\0')
3793 g_free(line_buf);
3794 return -1;
3797 if (direction == GTK_DIR_UP)
3798 step = -1;
3799 else
3800 step = 1;
3802 while (! found_end)
3804 line += step;
3806 /* sci_get_line checks for sanity of the given line, sci_get_line always return a string
3807 * containing at least '\0' so no need to check for NULL */
3808 line_buf = x = sci_get_line(sci, line);
3810 /* check whether after skipping all whitespace we are at end of line and if so, assume
3811 * this line as end of paragraph */
3812 while (isspace(*x))
3813 x++;
3814 if (*x == '\0')
3816 found_end = TRUE;
3817 if (line == -1)
3818 /* called on the first line but there is no previous line so return line 0 */
3819 line = 0;
3821 g_free(line_buf);
3823 return line;
3827 void editor_select_paragraph(GeanyEditor *editor)
3829 gint pos_start, pos_end, line_start, line_found;
3831 g_return_if_fail(editor != NULL);
3833 line_start = SSM(editor->sci, SCI_LINEFROMPOSITION,
3834 SSM(editor->sci, SCI_GETCURRENTPOS, 0, 0), 0);
3836 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_UP);
3837 if (line_found == -1)
3838 return;
3840 /* find_paragraph_stop returns the emtpy line(previous to the real start of the paragraph),
3841 * so use the next line for selection start */
3842 if (line_found > 0)
3843 line_found++;
3845 pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3847 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_DOWN);
3848 pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3850 sci_set_selection(editor->sci, pos_start, pos_end);
3854 /* simple indentation to indent the current line with the same indent as the previous one */
3855 static void smart_line_indentation(GeanyEditor *editor, gint first_line, gint last_line)
3857 gint i, sel_start = 0, sel_end = 0;
3859 /* get previous line and use it for read_indent to use that line
3860 * (otherwise it would fail on a line only containing "{" in advanced indentation mode) */
3861 read_indent(editor, sci_get_position_from_line(editor->sci, first_line - 1));
3863 for (i = first_line; i <= last_line; i++)
3865 /* skip the first line or if the indentation of the previous and current line are equal */
3866 if (i == 0 ||
3867 SSM(editor->sci, SCI_GETLINEINDENTATION, i - 1, 0) ==
3868 SSM(editor->sci, SCI_GETLINEINDENTATION, i, 0))
3869 continue;
3871 sel_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
3872 sel_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
3873 if (sel_start < sel_end)
3875 sci_set_selection(editor->sci, sel_start, sel_end);
3876 sci_replace_sel(editor->sci, "");
3878 sci_insert_text(editor->sci, sel_start, indent);
3883 /* simple indentation to indent the current line with the same indent as the previous one */
3884 void editor_smart_line_indentation(GeanyEditor *editor, gint pos)
3886 gint first_line, last_line;
3887 gint first_sel_start, first_sel_end;
3888 ScintillaObject *sci;
3890 g_return_if_fail(editor != NULL);
3892 sci = editor->sci;
3894 first_sel_start = sci_get_selection_start(sci);
3895 first_sel_end = sci_get_selection_end(sci);
3897 first_line = sci_get_line_from_position(sci, first_sel_start);
3898 /* Find the last line with chars selected (not EOL char) */
3899 last_line = sci_get_line_from_position(sci, first_sel_end - editor_get_eol_char_len(editor));
3900 last_line = MAX(first_line, last_line);
3902 if (pos == -1)
3903 pos = first_sel_start;
3905 sci_start_undo_action(sci);
3907 smart_line_indentation(editor, first_line, last_line);
3909 /* set cursor position if there was no selection */
3910 if (first_sel_start == first_sel_end)
3912 gint indent_pos = SSM(sci, SCI_GETLINEINDENTPOSITION, first_line, 0);
3914 /* use indent position as user may wish to change indentation afterwards */
3915 sci_set_current_position(sci, indent_pos, FALSE);
3917 else
3919 /* fully select all the lines affected */
3920 sci_set_selection_start(sci, sci_get_position_from_line(sci, first_line));
3921 sci_set_selection_end(sci, sci_get_position_from_line(sci, last_line + 1));
3924 sci_end_undo_action(sci);
3928 /* increase / decrease current line or selection by one space */
3929 void editor_indentation_by_one_space(GeanyEditor *editor, gint pos, gboolean decrease)
3931 gint i, first_line, last_line, line_start, indentation_end, count = 0;
3932 gint sel_start, sel_end, first_line_offset = 0;
3934 g_return_if_fail(editor != NULL);
3936 sel_start = sci_get_selection_start(editor->sci);
3937 sel_end = sci_get_selection_end(editor->sci);
3939 first_line = sci_get_line_from_position(editor->sci, sel_start);
3940 /* Find the last line with chars selected (not EOL char) */
3941 last_line = sci_get_line_from_position(editor->sci, sel_end - editor_get_eol_char_len(editor));
3942 last_line = MAX(first_line, last_line);
3944 if (pos == -1)
3945 pos = sel_start;
3947 sci_start_undo_action(editor->sci);
3949 for (i = first_line; i <= last_line; i++)
3951 indentation_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
3952 if (decrease)
3954 line_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
3955 /* searching backwards for a space to remove */
3956 while (sci_get_char_at(editor->sci, indentation_end) != ' ' && indentation_end > line_start)
3957 indentation_end--;
3959 if (sci_get_char_at(editor->sci, indentation_end) == ' ')
3961 sci_set_selection(editor->sci, indentation_end, indentation_end + 1);
3962 sci_replace_sel(editor->sci, "");
3963 count--;
3964 if (i == first_line)
3965 first_line_offset = -1;
3968 else
3970 sci_insert_text(editor->sci, indentation_end, " ");
3971 count++;
3972 if (i == first_line)
3973 first_line_offset = 1;
3977 /* set cursor position */
3978 if (sel_start < sel_end)
3980 gint start = sel_start + first_line_offset;
3981 if (first_line_offset < 0)
3982 start = MAX(sel_start + first_line_offset,
3983 SSM(editor->sci, SCI_POSITIONFROMLINE, first_line, 0));
3985 sci_set_selection_start(editor->sci, start);
3986 sci_set_selection_end(editor->sci, sel_end + count);
3988 else
3989 sci_set_current_position(editor->sci, pos + count, FALSE);
3991 sci_end_undo_action(editor->sci);
3995 void editor_finalize()
3997 scintilla_release_resources();
4001 /* wordchars: NULL or a string containing characters to match a word.
4002 * Returns: the current selection or the current word. */
4003 gchar *editor_get_default_selection(GeanyEditor *editor, gboolean use_current_word,
4004 const gchar *wordchars)
4006 gchar *s = NULL;
4008 g_return_val_if_fail(editor != NULL, NULL);
4010 if (sci_get_lines_selected(editor->sci) == 1)
4012 gint len = sci_get_selected_text_length(editor->sci);
4014 s = g_malloc(len + 1);
4015 sci_get_selected_text(editor->sci, s);
4017 else if (sci_get_lines_selected(editor->sci) == 0 && use_current_word)
4018 { /* use the word at current cursor position */
4019 gchar word[GEANY_MAX_WORD_LENGTH];
4021 editor_find_current_word(editor, -1, word, sizeof(word), wordchars);
4022 if (word[0] != '\0')
4023 s = g_strdup(word);
4025 return s;
4029 /* Note: Usually the line should be made visible (not folded) before calling this.
4030 * Returns: TRUE if line is/will be displayed to the user, or FALSE if it is
4031 * outside the *vertical* view.
4032 * Warning: You may need horizontal scrolling to make the cursor visible - so always call
4033 * sci_scroll_caret() when this returns TRUE. */
4034 gboolean editor_line_in_view(GeanyEditor *editor, gint line)
4036 gint vis1, los;
4038 g_return_val_if_fail(editor != NULL, FALSE);
4040 /* If line is wrapped the result may occur on another virtual line than the first and may be
4041 * still hidden, so increase the line number to check for the next document line */
4042 if (SSM(editor->sci, SCI_WRAPCOUNT, line, 0) > 1)
4043 line++;
4045 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0); /* convert to visible line number */
4046 vis1 = SSM(editor->sci, SCI_GETFIRSTVISIBLELINE, 0, 0);
4047 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
4049 return (line >= vis1 && line < vis1 + los);
4053 /* If the current line is outside the current view window, scroll the line
4054 * so it appears at percent_of_view. */
4055 void editor_display_current_line(GeanyEditor *editor, gfloat percent_of_view)
4057 gint line;
4059 g_return_if_fail(editor != NULL);
4061 line = sci_get_current_line(editor->sci);
4063 /* unfold maybe folded results */
4064 sci_ensure_line_is_visible(editor->sci, line);
4066 /* scroll the line if it's off screen */
4067 if (! editor_line_in_view(editor, line))
4068 editor->scroll_percent = percent_of_view;
4069 else
4070 sci_scroll_caret(editor->sci); /* may need horizontal scrolling */
4075 * Deletes all currently set indicators in the @a editor window.
4076 * Error indicators (red squiggly underlines) and usual line markers are removed.
4078 * @param editor The editor to operate on.
4080 void editor_indicator_clear_errors(GeanyEditor *editor)
4082 editor_indicator_clear(editor, GEANY_INDICATOR_ERROR);
4083 sci_marker_delete_all(editor->sci, 0); /* remove the yellow error line marker */
4088 * Deletes all currently set indicators matching @a indic in the @a editor window.
4090 * @param editor The editor to operate on.
4091 * @param indic The indicator number to clear, this is a value of @ref GeanyIndicator.
4093 * @since 0.16
4095 void editor_indicator_clear(GeanyEditor *editor, gint indic)
4097 glong last_pos;
4099 g_return_if_fail(editor != NULL);
4101 last_pos = sci_get_length(editor->sci);
4102 if (last_pos > 0)
4104 sci_indicator_set(editor->sci, indic);
4105 sci_indicator_clear(editor->sci, 0, last_pos);
4111 * Sets an indicator @a indic on @a line.
4112 * Whitespace at the start and the end of the line is not marked.
4114 * @param editor The editor to operate on.
4115 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4116 * @param line The line number which should be marked.
4118 * @since 0.16
4120 void editor_indicator_set_on_line(GeanyEditor *editor, gint indic, gint line)
4122 gint start, end;
4123 guint i = 0, len;
4124 gchar *linebuf;
4126 g_return_if_fail(editor != NULL);
4127 g_return_if_fail(line >= 0);
4129 start = sci_get_position_from_line(editor->sci, line);
4130 end = sci_get_position_from_line(editor->sci, line + 1);
4132 /* skip blank lines */
4133 if ((start + 1) == end ||
4134 start > end ||
4135 sci_get_line_length(editor->sci, line) == editor_get_eol_char_len(editor))
4137 return;
4140 len = end - start;
4141 linebuf = sci_get_line(editor->sci, line);
4143 /* don't set the indicator on whitespace */
4144 while (isspace(linebuf[i]))
4145 i++;
4146 while (len > 1 && len > i && isspace(linebuf[len - 1]))
4148 len--;
4149 end--;
4151 g_free(linebuf);
4153 editor_indicator_set_on_range(editor, indic, start + i, end);
4158 * Sets an indicator on the range specified by @a start and @a end.
4159 * No error checking or whitespace removal is performed, this should be done by the calling
4160 * function if necessary.
4162 * @param editor The editor to operate on.
4163 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4164 * @param start The starting position for the marker.
4165 * @param end The ending position for the marker.
4167 * @since 0.16
4169 void editor_indicator_set_on_range(GeanyEditor *editor, gint indic, gint start, gint end)
4171 g_return_if_fail(editor != NULL);
4172 if (start >= end)
4173 return;
4175 sci_indicator_set(editor->sci, indic);
4176 sci_indicator_fill(editor->sci, start, end - start);
4180 /* Inserts the given colour (format should be #...), if there is a selection starting with 0x...
4181 * the replacement will also start with 0x... */
4182 void editor_insert_color(GeanyEditor *editor, const gchar *colour)
4184 g_return_if_fail(editor != NULL);
4186 if (sci_has_selection(editor->sci))
4188 gint start = sci_get_selection_start(editor->sci);
4189 const gchar *replacement = colour;
4191 if (sci_get_char_at(editor->sci, start) == '0' &&
4192 sci_get_char_at(editor->sci, start + 1) == 'x')
4194 sci_set_selection_start(editor->sci, start + 2);
4195 sci_set_selection_end(editor->sci, start + 8);
4196 replacement++; /* skip the leading "0x" */
4198 else if (sci_get_char_at(editor->sci, start - 1) == '#')
4199 { /* double clicking something like #00ffff may only select 00ffff because of wordchars */
4200 replacement++; /* so skip the '#' to only replace the colour value */
4202 sci_replace_sel(editor->sci, replacement);
4204 else
4205 sci_add_text(editor->sci, colour);
4210 * Retrieves the localized name (for displaying) of the used end of line characters
4211 * (LF, CR/LF, CR) in the given editor.
4212 * If @a editor is @c NULL, the default end of line characters are used.
4214 * @param editor The editor to operate on, or @c NULL to query the default value.
4215 * @return The name of the end of line characters.
4217 * @since 0.19
4219 const gchar *editor_get_eol_char_name(GeanyEditor *editor)
4221 gint mode = file_prefs.default_eol_character;
4223 if (editor != NULL)
4224 mode = sci_get_eol_mode(editor->sci);
4226 return utils_get_eol_name(mode);
4231 * Retrieves the length of the used end of line characters (LF, CR/LF, CR) in the given editor.
4232 * If @a editor is @c NULL, the default end of line characters are used.
4233 * The returned value is 1 for CR and LF and 2 for CR/LF.
4235 * @param editor The editor to operate on, or @c NULL to query the default value.
4236 * @return The length of the end of line characters.
4238 * @since 0.19
4240 gint editor_get_eol_char_len(GeanyEditor *editor)
4242 gint mode = file_prefs.default_eol_character;
4244 if (editor != NULL)
4245 mode = sci_get_eol_mode(editor->sci);
4247 switch (mode)
4249 case SC_EOL_CRLF: return 2; break;
4250 default: return 1; break;
4256 * Retrieves the used end of line characters (LF, CR/LF, CR) in the given editor.
4257 * If @a editor is @c NULL, the default end of line characters are used.
4258 * The returned value is either "\n", "\r\n" or "\r".
4260 * @param editor The editor to operate on, or @c NULL to query the default value.
4261 * @return The end of line characters.
4263 * @since 0.19
4265 const gchar *editor_get_eol_char(GeanyEditor *editor)
4267 gint mode = file_prefs.default_eol_character;
4269 if (editor != NULL)
4270 mode = sci_get_eol_mode(editor->sci);
4272 switch (mode)
4274 case SC_EOL_CRLF: return "\r\n"; break;
4275 case SC_EOL_CR: return "\r"; break;
4276 default: return "\n"; break;
4281 static void fold_all(GeanyEditor *editor, gboolean want_fold)
4283 gint lines, first, i;
4285 if (editor == NULL || ! editor_prefs.folding)
4286 return;
4288 lines = sci_get_line_count(editor->sci);
4289 first = sci_get_first_visible_line(editor->sci);
4291 for (i = 0; i < lines; i++)
4293 gint level = sci_get_fold_level(editor->sci, i);
4295 if (level & SC_FOLDLEVELHEADERFLAG)
4297 if (sci_get_fold_expanded(editor->sci, i) == want_fold)
4298 sci_toggle_fold(editor->sci, i);
4301 editor_scroll_to_line(editor, first, 0.0F);
4305 void editor_unfold_all(GeanyEditor *editor)
4307 fold_all(editor, FALSE);
4311 void editor_fold_all(GeanyEditor *editor)
4313 fold_all(editor, TRUE);
4317 void editor_replace_tabs(GeanyEditor *editor)
4319 gint search_pos, pos_in_line, current_tab_true_length;
4320 gint tab_len;
4321 gchar *tab_str;
4322 struct Sci_TextToFind ttf;
4324 g_return_if_fail(editor != NULL);
4326 sci_start_undo_action(editor->sci);
4327 tab_len = sci_get_tab_width(editor->sci);
4328 ttf.chrg.cpMin = 0;
4329 ttf.chrg.cpMax = sci_get_length(editor->sci);
4330 ttf.lpstrText = (gchar*) "\t";
4332 while (TRUE)
4334 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4335 if (search_pos == -1)
4336 break;
4338 pos_in_line = sci_get_col_from_position(editor->sci, search_pos);
4339 current_tab_true_length = tab_len - (pos_in_line % tab_len);
4340 tab_str = g_strnfill(current_tab_true_length, ' ');
4341 sci_set_target_start(editor->sci, search_pos);
4342 sci_set_target_end(editor->sci, search_pos + 1);
4343 sci_replace_target(editor->sci, tab_str, FALSE);
4344 /* next search starts after replacement */
4345 ttf.chrg.cpMin = search_pos + current_tab_true_length - 1;
4346 /* update end of range now text has changed */
4347 ttf.chrg.cpMax += current_tab_true_length - 1;
4348 g_free(tab_str);
4350 sci_end_undo_action(editor->sci);
4354 /* Replaces all occurrences all spaces of the length of a given tab_width. */
4355 void editor_replace_spaces(GeanyEditor *editor)
4357 gint search_pos;
4358 static gdouble tab_len_f = -1.0; /* keep the last used value */
4359 gint tab_len;
4360 struct Sci_TextToFind ttf;
4362 g_return_if_fail(editor != NULL);
4364 if (tab_len_f < 0.0)
4365 tab_len_f = sci_get_tab_width(editor->sci);
4367 if (! dialogs_show_input_numeric(
4368 _("Enter Tab Width"),
4369 _("Enter the amount of spaces which should be replaced by a tab character."),
4370 &tab_len_f, 1, 100, 1))
4372 return;
4374 tab_len = (gint) tab_len_f;
4376 sci_start_undo_action(editor->sci);
4377 ttf.chrg.cpMin = 0;
4378 ttf.chrg.cpMax = sci_get_length(editor->sci);
4379 ttf.lpstrText = g_strnfill(tab_len, ' ');
4381 while (TRUE)
4383 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4384 if (search_pos == -1)
4385 break;
4387 sci_set_target_start(editor->sci, search_pos);
4388 sci_set_target_end(editor->sci, search_pos + tab_len);
4389 sci_replace_target(editor->sci, "\t", FALSE);
4390 ttf.chrg.cpMin = search_pos;
4391 /* update end of range now text has changed */
4392 ttf.chrg.cpMax -= tab_len - 1;
4394 sci_end_undo_action(editor->sci);
4395 g_free(ttf.lpstrText);
4399 void editor_strip_line_trailing_spaces(GeanyEditor *editor, gint line)
4401 gint line_start = sci_get_position_from_line(editor->sci, line);
4402 gint line_end = sci_get_line_end_position(editor->sci, line);
4403 gint i = line_end - 1;
4404 gchar ch = sci_get_char_at(editor->sci, i);
4406 while ((i >= line_start) && ((ch == ' ') || (ch == '\t')))
4408 i--;
4409 ch = sci_get_char_at(editor->sci, i);
4411 if (i < (line_end - 1))
4413 sci_set_target_start(editor->sci, i + 1);
4414 sci_set_target_end(editor->sci, line_end);
4415 sci_replace_target(editor->sci, "", FALSE);
4420 void editor_strip_trailing_spaces(GeanyEditor *editor)
4422 gint max_lines = sci_get_line_count(editor->sci);
4423 gint line;
4425 sci_start_undo_action(editor->sci);
4427 for (line = 0; line < max_lines; line++)
4429 editor_strip_line_trailing_spaces(editor, line);
4431 sci_end_undo_action(editor->sci);
4435 void editor_ensure_final_newline(GeanyEditor *editor)
4437 gint max_lines = sci_get_line_count(editor->sci);
4438 gboolean append_newline = (max_lines == 1);
4439 gint end_document = sci_get_position_from_line(editor->sci, max_lines);
4441 if (max_lines > 1)
4443 append_newline = end_document > sci_get_position_from_line(editor->sci, max_lines - 1);
4445 if (append_newline)
4447 const gchar *eol = "\n";
4448 switch (sci_get_eol_mode(editor->sci))
4450 case SC_EOL_CRLF:
4451 eol = "\r\n";
4452 break;
4453 case SC_EOL_CR:
4454 eol = "\r";
4455 break;
4457 sci_insert_text(editor->sci, end_document, eol);
4462 void editor_set_font(GeanyEditor *editor, const gchar *font)
4464 gint style, size;
4465 gchar *font_name;
4466 PangoFontDescription *pfd;
4468 g_return_if_fail(editor);
4470 pfd = pango_font_description_from_string(font);
4471 size = pango_font_description_get_size(pfd) / PANGO_SCALE;
4472 font_name = g_strdup_printf("!%s", pango_font_description_get_family(pfd));
4473 pango_font_description_free(pfd);
4475 for (style = 0; style <= 127; style++)
4476 sci_set_font(editor->sci, style, font_name, size);
4478 /* line number and braces */
4479 sci_set_font(editor->sci, STYLE_LINENUMBER, font_name, size);
4480 sci_set_font(editor->sci, STYLE_BRACELIGHT, font_name, size);
4481 sci_set_font(editor->sci, STYLE_BRACEBAD, font_name, size);
4482 g_free(font_name);
4484 /* zoom to 100% to prevent confusion */
4485 sci_zoom_off(editor->sci);
4489 void editor_set_line_wrapping(GeanyEditor *editor, gboolean wrap)
4491 g_return_if_fail(editor != NULL);
4493 editor->line_wrapping = wrap;
4494 sci_set_lines_wrapped(editor->sci, wrap);
4498 /** Sets the indent type for @a editor.
4499 * @param editor Editor.
4500 * @param type Indent type.
4502 * @since 0.16
4504 void editor_set_indent_type(GeanyEditor *editor, GeanyIndentType type)
4506 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
4507 ScintillaObject *sci = editor->sci;
4508 gboolean use_tabs = type != GEANY_INDENT_TYPE_SPACES;
4510 editor->indent_type = type;
4511 sci_set_use_tabs(sci, use_tabs);
4513 if (type == GEANY_INDENT_TYPE_BOTH)
4514 sci_set_tab_width(sci, iprefs->hard_tab_width);
4515 else
4516 sci_set_tab_width(sci, iprefs->width);
4517 SSM(sci, SCI_SETINDENT, iprefs->width, 0);
4519 /* remove indent spaces on backspace, if using any spaces to indent */
4520 SSM(sci, SCI_SETBACKSPACEUNINDENTS, type != GEANY_INDENT_TYPE_TABS, 0);
4524 /* Convenience function for editor_goto_pos() to pass in a line number. */
4525 gboolean editor_goto_line(GeanyEditor *editor, gint line)
4527 gint pos;
4529 g_return_val_if_fail(editor, FALSE);
4530 if (line < 0 || line >= sci_get_line_count(editor->sci))
4531 return FALSE;
4533 pos = sci_get_position_from_line(editor->sci, line);
4534 return editor_goto_pos(editor, pos, TRUE);
4538 /* Move to position @a pos, switching to the document if necessary,
4539 * setting a marker if @a mark is set. */
4540 gboolean editor_goto_pos(GeanyEditor *editor, gint pos, gboolean mark)
4542 gint page_num;
4544 g_return_val_if_fail(editor, FALSE);
4545 if (G_UNLIKELY(pos < 0))
4546 return FALSE;
4548 if (mark)
4550 gint line = sci_get_line_from_position(editor->sci, pos);
4552 /* mark the tag with the yellow arrow */
4553 sci_marker_delete_all(editor->sci, 0);
4554 sci_set_marker_at_line(editor->sci, line, 0);
4557 sci_goto_pos(editor->sci, pos, TRUE);
4558 editor->scroll_percent = 0.25F;
4560 /* finally switch to the page */
4561 page_num = gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook), GTK_WIDGET(editor->sci));
4562 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
4564 return TRUE;
4568 static gboolean
4569 on_editor_scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer user_data)
4571 GeanyEditor *editor = user_data;
4573 /* Handle scroll events if Alt is pressed and scroll whole pages instead of a
4574 * few lines only, maybe this could/should be done in Scintilla directly */
4575 if (event->state & GDK_MOD1_MASK)
4577 sci_send_command(editor->sci, (event->direction == GDK_SCROLL_DOWN) ? SCI_PAGEDOWN : SCI_PAGEUP);
4578 return TRUE;
4580 else if (event->state & GDK_SHIFT_MASK)
4582 gint amount = (event->direction == GDK_SCROLL_DOWN) ? 8 : -8;
4584 sci_scroll_columns(editor->sci, amount);
4585 return TRUE;
4588 return FALSE; /* let Scintilla handle all other cases */
4592 static gboolean editor_check_colourise(GeanyEditor *editor)
4594 GeanyDocument *doc = editor->document;
4596 if (!doc->priv->colourise_needed)
4597 return FALSE;
4599 doc->priv->colourise_needed = FALSE;
4600 sci_colourise(editor->sci, 0, -1);
4602 /* now that the current document is colourised, fold points are now accurate,
4603 * so force an update of the current function/tag. */
4604 symbols_get_current_function(NULL, NULL);
4605 ui_update_statusbar(NULL, -1);
4607 return TRUE;
4611 /* We only want to colourise just before drawing, to save startup time and
4612 * prevent unnecessary recolouring other documents after one is saved.
4613 * Really we want a "draw" signal but there doesn't seem to be one (expose is too late,
4614 * and "show" doesn't work). */
4615 static gboolean on_editor_focus_in(GtkWidget *widget, GdkEventFocus *event, gpointer user_data)
4617 GeanyEditor *editor = user_data;
4619 editor_check_colourise(editor);
4620 return FALSE;
4624 /* This is just to catch any uncolourised documents being drawn that didn't receive focus
4625 * for some reason, maybe it's not necessary but just in case. */
4626 static gboolean on_editor_expose_event(GtkWidget *widget, GdkEventExpose *event,
4627 gpointer user_data)
4629 GeanyEditor *editor = user_data;
4631 editor_check_colourise(editor);
4632 return FALSE;
4636 static void setup_sci_keys(ScintillaObject *sci)
4638 /* disable some Scintilla keybindings to be able to redefine them cleanly */
4639 sci_clear_cmdkey(sci, 'A' | (SCMOD_CTRL << 16)); /* select all */
4640 sci_clear_cmdkey(sci, 'D' | (SCMOD_CTRL << 16)); /* duplicate */
4641 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16)); /* line transpose */
4642 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line copy */
4643 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16)); /* line cut */
4644 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line delete */
4645 sci_clear_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line to end delete */
4646 sci_clear_cmdkey(sci, '/' | (SCMOD_CTRL << 16)); /* Previous word part */
4647 sci_clear_cmdkey(sci, '\\' | (SCMOD_CTRL << 16)); /* Next word part */
4648 sci_clear_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16)); /* scroll line up */
4649 sci_clear_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16)); /* scroll line down */
4650 sci_clear_cmdkey(sci, SCK_HOME); /* line start */
4651 sci_clear_cmdkey(sci, SCK_END); /* line end */
4652 sci_clear_cmdkey(sci, SCK_END | (SCMOD_ALT << 16)); /* visual line end */
4654 if (editor_prefs.use_gtk_word_boundaries)
4656 /* use GtkEntry-like word boundaries */
4657 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16), SCI_WORDRIGHTEND);
4658 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_WORDRIGHTENDEXTEND);
4659 sci_assign_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16), SCI_DELWORDRIGHTEND);
4661 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_ALT << 16), SCI_LINESCROLLUP);
4662 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_ALT << 16), SCI_LINESCROLLDOWN);
4663 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16), SCI_PARAUP);
4664 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARAUPEXTEND);
4665 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16), SCI_PARADOWN);
4666 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARADOWNEXTEND);
4668 sci_clear_cmdkey(sci, SCK_BACK | (SCMOD_ALT << 16)); /* clear Alt-Backspace (Undo) */
4672 #include "icons/16x16/classviewer-var.xpm"
4673 #include "icons/16x16/classviewer-method.xpm"
4675 /* Create new editor widget (scintilla).
4676 * @note The @c "sci-notify" signal is connected separately. */
4677 static ScintillaObject *create_new_sci(GeanyEditor *editor)
4679 ScintillaObject *sci;
4681 sci = SCINTILLA(scintilla_new());
4683 gtk_widget_show(GTK_WIDGET(sci));
4685 sci_set_codepage(sci, SC_CP_UTF8);
4686 /*SSM(sci, SCI_SETWRAPSTARTINDENT, 4, 0);*/
4687 /* disable scintilla provided popup menu */
4688 sci_use_popup(sci, FALSE);
4690 setup_sci_keys(sci);
4692 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
4693 sci_set_lines_wrapped(sci, editor_prefs.line_wrapping);
4694 sci_set_scrollbar_mode(sci, editor_prefs.show_scrollbars);
4695 sci_set_caret_policy_x(sci, CARET_JUMPS | CARET_EVEN, 0);
4696 /*sci_set_caret_policy_y(sci, CARET_JUMPS | CARET_EVEN, 0);*/
4697 SSM(sci, SCI_AUTOCSETSEPARATOR, '\n', 0);
4698 SSM(sci, SCI_SETSCROLLWIDTHTRACKING, 1, 0);
4700 /* tag autocompletion images */
4701 SSM(sci, SCI_REGISTERIMAGE, 1, (sptr_t)classviewer_var);
4702 SSM(sci, SCI_REGISTERIMAGE, 2, (sptr_t)classviewer_method);
4704 /* necessary for column mode editing, implemented in Scintilla since 2.0 */
4705 SSM(sci, SCI_SETADDITIONALSELECTIONTYPING, 1, 0);
4707 /* virtual space */
4708 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
4710 /* only connect signals if this is for the document notebook, not split window */
4711 if (editor->sci == NULL)
4713 g_signal_connect(sci, "button-press-event", G_CALLBACK(on_editor_button_press_event), editor);
4714 g_signal_connect(sci, "scroll-event", G_CALLBACK(on_editor_scroll_event), editor);
4715 g_signal_connect(sci, "motion-notify-event", G_CALLBACK(on_motion_event), NULL);
4716 g_signal_connect(sci, "focus-in-event", G_CALLBACK(on_editor_focus_in), editor);
4717 g_signal_connect(sci, "expose-event", G_CALLBACK(on_editor_expose_event), editor);
4719 return sci;
4723 /** Creates a new Scintilla @c GtkWidget based on the settings for @a editor.
4724 * @param editor Editor settings.
4725 * @return The new widget.
4727 * @since 0.15
4729 ScintillaObject *editor_create_widget(GeanyEditor *editor)
4731 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4732 ScintillaObject *old, *sci;
4734 /* temporarily change editor to use the new sci widget */
4735 old = editor->sci;
4736 sci = create_new_sci(editor);
4737 editor->sci = sci;
4739 editor_set_indent_type(editor, iprefs->type);
4740 editor_set_font(editor, interface_prefs.editor_font);
4741 editor_apply_update_prefs(editor);
4743 /* if editor already had a widget, restore it */
4744 if (old)
4745 editor->sci = old;
4746 return sci;
4750 GeanyEditor *editor_create(GeanyDocument *doc)
4752 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4753 GeanyEditor *editor = g_new0(GeanyEditor, 1);
4755 editor->document = doc;
4756 doc->editor = editor; /* needed in case some editor functions/callbacks expect it */
4758 editor->auto_indent = (iprefs->auto_indent_mode != GEANY_AUTOINDENT_NONE);
4759 editor->line_wrapping = editor_prefs.line_wrapping;
4760 editor->scroll_percent = -1.0F;
4761 editor->line_breaking = FALSE;
4763 editor->sci = editor_create_widget(editor);
4764 return editor;
4768 /* in case we need to free some fields in future */
4769 void editor_destroy(GeanyEditor *editor)
4771 g_free(editor);
4775 static void on_document_save(GObject *obj, GeanyDocument *doc)
4777 g_return_if_fail(NZV(doc->real_path));
4779 if (utils_str_equal(doc->real_path,
4780 utils_build_path(app->configdir, "snippets.conf", NULL)))
4782 /* reload snippets */
4783 editor_snippets_free();
4784 editor_snippets_init();
4789 gboolean editor_complete_word_part(GeanyEditor *editor)
4791 gchar *entry;
4793 g_return_val_if_fail(editor, FALSE);
4795 if (!SSM(editor->sci, SCI_AUTOCACTIVE, 0, 0))
4796 return FALSE;
4798 entry = sci_get_string(editor->sci, SCI_AUTOCGETCURRENTTEXT, 0);
4800 /* if no word part, complete normally */
4801 if (!check_partial_completion(editor, entry))
4802 SSM(editor->sci, SCI_AUTOCCOMPLETE, 0, 0);
4804 g_free(entry);
4805 return TRUE;
4809 void editor_init(void)
4811 static GeanyIndentPrefs indent_prefs;
4813 memset(&editor_prefs, 0, sizeof(GeanyEditorPrefs));
4814 memset(&indent_prefs, 0, sizeof(GeanyIndentPrefs));
4815 editor_prefs.indentation = &indent_prefs;
4817 /* use g_signal_connect_after() to allow plugins connecting to the signal before the default
4818 * handler (on_editor_notify) is called */
4819 g_signal_connect_after(geany_object, "editor-notify", G_CALLBACK(on_editor_notify), NULL);
4821 ui_add_config_file_menu_item(utils_build_path(app->configdir, "snippets.conf", NULL),
4822 NULL, NULL);
4823 g_signal_connect(geany_object, "document-save", G_CALLBACK(on_document_save), NULL);
4827 /* TODO: Should these be user-defined instead of hard-coded? */
4828 void editor_set_indentation_guides(GeanyEditor *editor)
4830 gint mode;
4831 gint lexer;
4833 g_return_if_fail(editor != NULL);
4835 if (! editor_prefs.show_indent_guide)
4837 sci_set_indentation_guides(editor->sci, SC_IV_NONE);
4838 return;
4841 lexer = sci_get_lexer(editor->sci);
4842 switch (lexer)
4844 /* Lines added/removed are prefixed with +/- characters, so
4845 * those lines will not be shown with any indentation guides.
4846 * It can be distracting that only a few of lines in a diff/patch
4847 * file will show the guides. */
4848 case SCLEX_DIFF:
4849 mode = SC_IV_NONE;
4850 break;
4852 /* These languages use indentation for control blocks; the "look forward" method works
4853 * best here */
4854 case SCLEX_PYTHON:
4855 case SCLEX_HASKELL:
4856 case SCLEX_MAKEFILE:
4857 case SCLEX_ASM:
4858 case SCLEX_SQL:
4859 case SCLEX_PROPERTIES:
4860 case SCLEX_FORTRAN: /* Is this the best option for Fortran? */
4861 case SCLEX_CAML:
4862 mode = SC_IV_LOOKFORWARD;
4863 break;
4865 /* C-like (structured) languages benefit from the "look both" method */
4866 case SCLEX_CPP:
4867 case SCLEX_HTML:
4868 case SCLEX_XML:
4869 case SCLEX_PERL:
4870 case SCLEX_LATEX:
4871 case SCLEX_LUA:
4872 case SCLEX_PASCAL:
4873 case SCLEX_RUBY:
4874 case SCLEX_TCL:
4875 case SCLEX_F77:
4876 case SCLEX_CSS:
4877 case SCLEX_BASH:
4878 case SCLEX_VHDL:
4879 case SCLEX_FREEBASIC:
4880 case SCLEX_D:
4881 case SCLEX_MATLAB:
4882 mode = SC_IV_LOOKBOTH;
4883 break;
4885 default:
4886 mode = SC_IV_REAL;
4887 break;
4890 sci_set_indentation_guides(editor->sci, mode);
4894 /* Apply just the prefs that can change in the Preferences dialog */
4895 void editor_apply_update_prefs(GeanyEditor *editor)
4897 ScintillaObject *sci;
4899 g_return_if_fail(editor != NULL);
4901 sci = editor->sci;
4903 sci_set_mark_long_lines(sci, editor_get_long_line_type(),
4904 editor_get_long_line_column(), editor_prefs.long_line_color);
4906 /* update indent width, tab width */
4907 editor_set_indent_type(editor, editor->indent_type);
4908 sci_set_tab_indents(sci, editor_prefs.use_tab_to_indent);
4910 sci_set_autoc_max_height(sci, editor_prefs.symbolcompletion_max_height);
4911 SSM(sci, SCI_AUTOCSETDROPRESTOFWORD, editor_prefs.completion_drops_rest_of_word, 0);
4913 editor_set_indentation_guides(editor);
4915 sci_set_visible_white_spaces(sci, editor_prefs.show_white_space);
4916 sci_set_visible_eols(sci, editor_prefs.show_line_endings);
4917 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
4918 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin, 0);
4920 sci_set_folding_margin_visible(sci, editor_prefs.folding);
4922 /* virtual space */
4923 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
4925 /* (dis)allow scrolling past end of document */
4926 sci_set_scroll_stop_at_last_line(sci, editor_prefs.scroll_stop_at_last_line);
4930 /* This is for tab-indents, space aligns formatted code. Spaces should be preserved. */
4931 static void change_tab_indentation(GeanyEditor *editor, gint line, gboolean increase)
4933 ScintillaObject *sci = editor->sci;
4934 gint pos = sci_get_position_from_line(sci, line);
4936 if (increase)
4938 sci_insert_text(sci, pos, "\t");
4940 else
4942 if (sci_get_char_at(sci, pos) == '\t')
4944 sci_set_selection(sci, pos, pos + 1);
4945 sci_replace_sel(sci, "");
4947 else /* remove spaces only if no tabs */
4949 gint width = sci_get_line_indentation(sci, line);
4951 width -= editor_get_indent_prefs(editor)->width;
4952 sci_set_line_indentation(sci, line, width);
4958 static void editor_change_line_indent(GeanyEditor *editor, gint line, gboolean increase)
4960 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
4961 ScintillaObject *sci = editor->sci;
4963 if (iprefs->type == GEANY_INDENT_TYPE_TABS)
4964 change_tab_indentation(editor, line, increase);
4965 else
4967 gint width = sci_get_line_indentation(sci, line);
4969 width += increase ? iprefs->width : -iprefs->width;
4970 sci_set_line_indentation(sci, line, width);
4975 void editor_indent(GeanyEditor *editor, gboolean increase)
4977 ScintillaObject *sci = editor->sci;
4978 gint start, end;
4979 gint line, lstart, lend;
4981 if (sci_get_lines_selected(sci) <= 1)
4983 line = sci_get_current_line(sci);
4984 editor_change_line_indent(editor, line, increase);
4985 return;
4987 editor_select_lines(editor, FALSE);
4988 start = sci_get_selection_start(sci);
4989 end = sci_get_selection_end(sci);
4990 lstart = sci_get_line_from_position(sci, start);
4991 lend = sci_get_line_from_position(sci, end);
4992 if (end == sci_get_length(sci))
4993 lend++; /* for last line with text on it */
4995 sci_start_undo_action(sci);
4996 for (line = lstart; line < lend; line++)
4998 editor_change_line_indent(editor, line, increase);
5000 sci_end_undo_action(sci);
5002 /* set cursor/selection */
5003 if (lend > lstart)
5005 sci_set_selection_start(sci, start);
5006 end = sci_get_position_from_line(sci, lend);
5007 sci_set_selection_end(sci, end);
5008 editor_select_lines(editor, FALSE);
5010 else
5012 sci_set_current_line(sci, lstart);