revert e6a4fd1ad407d9c07bf965fe682bbd858285a87a as it introduced a regression
[geany-mirror/kugel-geany.git] / src / editor.c
blobeefa85d04dcfce8ce3ad5a2b8be2a72ad249dce8
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 (@c 0x9) with the correct indent
2101 * width, and \\n newline chars (@c 0xA) with the correct line ending string
2102 * for the document.
2103 * This is very useful for inserting code without having to handle the indent
2104 * type yourself (Tabs & Spaces mode can be tricky).
2105 * @param editor Editor.
2106 * @param text Intended as e.g. @c "if (foo)\n\tbar();".
2107 * @param insert_pos Document position to insert text at.
2108 * @param cursor_index If >= 0, the index into @a text to place the cursor.
2109 * @param newline_indent_size Indentation size (in spaces) to insert for each newline; use
2110 * -1 to read the indent size from the line with @a insert_pos on it.
2111 * @param replace_newlines Whether to replace newlines in text or not. If
2112 * newlines have been replaced before, this should be false, to avoid multiple
2113 * replacements of newlines, which is error prone on Windows.
2114 * @warning Make sure all \\t tab chars in @a text are intended as indent widths,
2115 * not hard tabs, as these might not be preserved.
2116 * @note This doesn't scroll the cursor in view afterwards. **/
2117 void editor_insert_text_block(GeanyEditor *editor, const gchar *text, gint insert_pos,
2118 gint cursor_index, gint newline_indent_size, gboolean replace_newlines)
2120 ScintillaObject *sci = editor->sci;
2121 gint line_start = sci_get_line_from_position(sci, insert_pos);
2122 gint line_end;
2123 gchar *whitespace;
2124 GString *buf;
2125 const gchar cur_marker[] = "__GEANY_CURSOR_MARKER__";
2126 const gchar *eol = editor_get_eol_char(editor);
2128 g_return_if_fail(text);
2129 g_return_if_fail(editor != NULL);
2130 g_return_if_fail(insert_pos >= 0);
2132 buf = g_string_new(text);
2134 if (cursor_index >= 0)
2135 g_string_insert(buf, cursor_index, cur_marker); /* remember cursor pos */
2137 if (newline_indent_size == -1)
2139 /* count indent size up to insert_pos instead of asking sci
2140 * because there may be spaces after it */
2141 gchar *tmp = sci_get_line(sci, line_start);
2142 gint idx = insert_pos - sci_get_position_from_line(sci, line_start);
2143 tmp[idx] = '\0';
2144 newline_indent_size = count_indent_size(editor, tmp);
2145 g_free(tmp);
2148 /* Add line indents (in spaces) */
2149 if (newline_indent_size > 0)
2151 whitespace = g_strnfill(newline_indent_size, ' ');
2152 setptr(whitespace, g_strconcat(eol, whitespace, NULL));
2153 utils_string_replace_all(buf, eol, whitespace);
2154 g_free(whitespace);
2157 /* transform line endings */
2158 if (replace_newlines)
2159 utils_string_replace_all(buf, "\n", eol);
2161 /* transform tabs into indent widths (in spaces) */
2162 whitespace = g_strnfill(editor_get_indent_prefs(editor)->width, ' ');
2163 utils_string_replace_all(buf, "\t", whitespace);
2164 g_free(whitespace);
2166 if (cursor_index >= 0)
2168 gint idx = utils_strpos(buf->str, cur_marker);
2170 g_string_erase(buf, idx, strlen(cur_marker));
2172 sci_insert_text(sci, insert_pos, buf->str);
2173 sci_set_current_position(sci, insert_pos + idx, FALSE);
2175 else
2176 sci_insert_text(sci, insert_pos, buf->str);
2178 /* fixup indentation (very useful for Tabs & Spaces indent type) */
2179 line_end = sci_get_line_from_position(sci, insert_pos + buf->len);
2180 fix_line_indents(editor, line_start, line_end);
2181 snippet_cursor_insert_pos = sci_get_current_position(sci);
2183 g_string_free(buf, TRUE);
2187 /* Move the cursor to the next specified cursor position in an inserted snippet.
2188 * Can, and should, be optimized to give better results */
2189 void editor_goto_next_snippet_cursor(GeanyEditor *editor)
2191 ScintillaObject *sci = editor->sci;
2192 gint current_pos = sci_get_current_position(sci);
2194 if (snippet_offsets && !g_queue_is_empty(snippet_offsets))
2196 gint offset;
2198 offset = GPOINTER_TO_INT(g_queue_pop_head(snippet_offsets));
2199 if (current_pos > snippet_cursor_insert_pos)
2200 snippet_cursor_insert_pos = offset + current_pos;
2201 else
2202 snippet_cursor_insert_pos += offset;
2204 sci_set_current_position(sci, snippet_cursor_insert_pos, FALSE);
2206 else
2208 utils_beep();
2213 static gssize snippets_make_replacements(GeanyEditor *editor, GString *pattern,
2214 gsize indent_size)
2216 gssize cur_index = -1;
2217 gchar *whitespace;
2218 gint i, tmp_pos, whitespace_len, nl_count = 0;
2219 GHashTable *specials;
2220 GList *temp_list = NULL;
2221 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
2222 gint cursor_steps, old_cursor = 0;
2224 /* replace 'special' completions */
2225 specials = g_hash_table_lookup(snippet_hash, "Special");
2226 if (G_LIKELY(specials != NULL))
2228 /* ugly hack using global_pattern */
2229 snippets_global_pattern = pattern;
2230 g_hash_table_foreach(specials, snippets_replace_specials, NULL);
2233 /* replace any %template% wildcards */
2234 snippets_replace_wildcards(editor, pattern);
2236 /* transform other wildcards */
2237 /* convert to %newlines%, else we get endless loops */
2238 utils_string_replace_all(pattern, "\n", "%newline%");
2240 /* if spaces are used, replaces all tabs with %ws%, which is later replaced
2241 * by real whitespace characters
2242 * otherwise replace all %ws% by \t, which will be replaced later by tab
2243 * characters,
2244 * this makes seperating between tab and spaces intentation pretty easy */
2245 if (iprefs->type == GEANY_INDENT_TYPE_SPACES)
2246 utils_string_replace_all(pattern, "\t", "%ws%");
2247 else
2248 utils_string_replace_all(pattern, "%ws%", "\t");
2250 whitespace = g_strnfill(iprefs->width, ' '); /* use spaces for indentation, will be fixed up */
2251 whitespace_len = strlen(whitespace);
2252 i = 0;
2253 while ((cursor_steps = utils_strpos(pattern->str, "%cursor%")) >= 0)
2255 /* replace every %newline% (up to next %cursor%) with EOL,
2256 * and update cursor_steps after */
2257 while ((tmp_pos = utils_strpos(pattern->str, "%newline%")) < cursor_steps && tmp_pos != -1)
2259 nl_count++;
2260 utils_string_replace_first(pattern, "%newline%", editor_get_eol_char(editor));
2261 cursor_steps = utils_strpos(pattern->str, "%cursor%");
2263 /* replace every %ws% (up to next %cursor%) with whitespaces,
2264 * and update cursor_steps after */
2265 while ((tmp_pos = utils_strpos(pattern->str, "%ws%")) < cursor_steps && tmp_pos != -1)
2267 utils_string_replace_first(pattern, "%ws%", whitespace);
2268 cursor_steps = utils_strpos(pattern->str, "%cursor%");
2270 /* finally replace the next %cursor% */
2271 utils_string_replace_first(pattern, "%cursor%", "");
2273 /* modify cursor_steps to take indentation count and type into account */
2275 /* We're saving the relative offset to each cursor position in a simple
2276 * linked list, including indentations between them. */
2277 if (i++ > 0)
2279 cursor_steps += (nl_count * indent_size);
2280 temp_list = g_list_append(temp_list, GINT_TO_POINTER(cursor_steps - old_cursor));
2282 else
2284 nl_count = 0;
2285 cur_index = cursor_steps;
2287 old_cursor = cursor_steps;
2289 /* replace remaining %ws% and %newline% which may occur after the last %cursor% */
2290 utils_string_replace_all(pattern, "%newline%", editor_get_eol_char(editor));
2291 utils_string_replace_all(pattern, "%ws%", whitespace);
2292 g_free(whitespace);
2294 /* We put the cursor positions for the most recent
2295 * parsed snippet first, followed by any remaining positions */
2296 i = 0;
2297 if (temp_list)
2299 GList *node;
2301 foreach_list(node, temp_list)
2302 g_queue_push_nth(snippet_offsets, node->data, i++);
2304 /* limit length of queue */
2305 while (g_queue_get_length(snippet_offsets) > 20)
2306 g_queue_pop_tail(snippet_offsets);
2308 g_list_free(temp_list);
2310 if (cur_index < 0)
2311 cur_index = pattern->len;
2313 return cur_index;
2317 static gboolean snippets_complete_constructs(GeanyEditor *editor, gint pos, const gchar *word)
2319 ScintillaObject *sci = editor->sci;
2320 gchar *str;
2321 GString *pattern;
2322 gssize cur_index = -1;
2323 gint str_len;
2324 gint ft_id = FILETYPE_ID(editor->document->file_type);
2326 str = g_strdup(word);
2327 g_strstrip(str);
2328 pattern = g_string_new(snippets_find_completion_by_name(filetypes[ft_id]->name, str));
2329 if (pattern == NULL || pattern->len == 0)
2331 g_free(str);
2332 g_string_free(pattern, TRUE);
2333 return FALSE;
2336 read_indent(editor, pos);
2338 /* remove the typed word, it will be added again by the used auto completion
2339 * (not really necessary but this makes the auto completion more flexible,
2340 * e.g. with a completion like hi=hello, so typing "hi<TAB>" will result in "hello") */
2341 str_len = strlen(str);
2342 sci_set_selection_start(sci, pos - str_len);
2343 sci_set_selection_end(sci, pos);
2344 sci_replace_sel(sci, "");
2345 pos -= str_len; /* pos has changed while deleting */
2347 cur_index = snippets_make_replacements(editor, pattern, strlen(indent));
2349 /* finally insert the text and set the cursor */
2350 editor_insert_text_block(editor, pattern->str, pos, cur_index, -1, FALSE);
2351 sci_scroll_caret(sci);
2353 g_free(str);
2354 g_string_free(pattern, TRUE);
2355 return TRUE;
2359 static gboolean at_eol(ScintillaObject *sci, gint pos)
2361 gint line = sci_get_line_from_position(sci, pos);
2362 gchar c;
2364 /* skip any trailing spaces */
2365 while (TRUE)
2367 c = sci_get_char_at(sci, pos);
2368 if (c == ' ' || c == '\t')
2369 pos++;
2370 else
2371 break;
2374 return (pos == sci_get_line_end_position(sci, line));
2378 gboolean editor_complete_snippet(GeanyEditor *editor, gint pos)
2380 gboolean result = FALSE;
2381 const gchar *wc;
2382 const gchar *word;
2383 ScintillaObject *sci;
2385 g_return_val_if_fail(editor != NULL, FALSE);
2387 sci = editor->sci;
2388 if (sci_has_selection(sci))
2389 return FALSE;
2390 /* return if we are editing an existing line (chars on right of cursor) */
2391 if (keybindings_lookup_item(GEANY_KEY_GROUP_EDITOR,
2392 GEANY_KEYS_EDITOR_COMPLETESNIPPET)->key == GDK_space &&
2393 ! editor_prefs.complete_snippets_whilst_editing && ! at_eol(sci, pos))
2394 return FALSE;
2396 wc = snippets_find_completion_by_name("Special", "wordchars");
2397 word = editor_read_word_stem(editor, pos, wc);
2399 /* prevent completion of "for " */
2400 if (NZV(word) &&
2401 ! isspace(sci_get_char_at(sci, pos - 1))) /* pos points to the line end char so use pos -1 */
2403 sci_start_undo_action(sci); /* needed because we insert a space separately from construct */
2404 result = snippets_complete_constructs(editor, pos, word);
2405 sci_end_undo_action(sci);
2406 if (result)
2407 sci_cancel(sci); /* cancel any autocompletion list, etc */
2409 return result;
2413 void editor_show_macro_list(GeanyEditor *editor)
2415 GString *words;
2417 if (editor == NULL || editor->document->file_type == NULL)
2418 return;
2420 words = symbols_get_macro_list(editor->document->file_type->lang);
2421 if (words == NULL)
2422 return;
2424 SSM(editor->sci, SCI_USERLISTSHOW, 1, (sptr_t) words->str);
2425 g_string_free(words, TRUE);
2429 static void insert_closing_tag(GeanyEditor *editor, gint pos, gchar ch, const gchar *tag_name)
2431 ScintillaObject *sci = editor->sci;
2432 gchar *to_insert = NULL;
2434 if (ch == '/')
2436 const gchar *gt = ">";
2437 /* if there is already a '>' behind the cursor, don't add it */
2438 if (sci_get_char_at(sci, pos) == '>')
2439 gt = "";
2441 to_insert = g_strconcat(tag_name, gt, NULL);
2443 else
2444 to_insert = g_strconcat("</", tag_name, ">", NULL);
2446 sci_start_undo_action(sci);
2447 sci_replace_sel(sci, to_insert);
2448 if (ch == '>')
2450 sci_set_selection(sci, pos, pos);
2451 if (utils_str_equal(tag_name, "table"))
2452 auto_table(editor, pos);
2454 sci_end_undo_action(sci);
2455 g_free(to_insert);
2460 * (stolen from anjuta and heavily modified)
2461 * This routine will auto complete XML or HTML tags that are still open by closing them
2462 * @param ch The character we are dealing with, currently only works with the '>' character
2463 * @return True if handled, false otherwise
2465 static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch)
2467 ScintillaObject *sci = editor->sci;
2468 gint lexer = sci_get_lexer(sci);
2469 gint min, style;
2470 gchar *str_found, sel[512];
2471 gboolean result = FALSE;
2473 /* If the user has turned us off, quit now.
2474 * This may make sense only in certain languages */
2475 if (! editor_prefs.auto_close_xml_tags || (lexer != SCLEX_HTML && lexer != SCLEX_XML))
2476 return FALSE;
2478 /* return if we are inside any embedded script */
2479 style = sci_get_style_at(sci, pos);
2480 if (style > SCE_H_XCCOMMENT && ! is_string_style(lexer, style))
2481 return FALSE;
2483 /* if ch is /, check for </, else quit */
2484 if (ch == '/' && sci_get_char_at(sci, pos - 2) != '<')
2485 return FALSE;
2487 /* Grab the last 512 characters or so */
2488 min = pos - (sizeof(sel) - 1);
2489 if (min < 0) min = 0;
2491 if (pos - min < 3)
2492 return FALSE; /* Smallest tag is 3 characters e.g. <p> */
2494 sci_get_text_range(sci, min, pos, sel);
2495 sel[sizeof(sel) - 1] = '\0';
2497 if (ch == '>' && sel[pos - min - 2] == '/')
2498 /* User typed something like "<br/>" */
2499 return FALSE;
2501 str_found = utils_find_open_xml_tag(sel, pos - min, (ch == '/'));
2503 /* when found string is something like br, img or another short tag, quit */
2504 if (utils_str_equal(str_found, "br")
2505 || utils_str_equal(str_found, "hr")
2506 || utils_str_equal(str_found, "img")
2507 || utils_str_equal(str_found, "base")
2508 || utils_str_equal(str_found, "basefont") /* < or not < */
2509 || utils_str_equal(str_found, "frame")
2510 || utils_str_equal(str_found, "input")
2511 || utils_str_equal(str_found, "link")
2512 || utils_str_equal(str_found, "area")
2513 || utils_str_equal(str_found, "meta"))
2515 /* ignore tag */
2517 else if (NZV(str_found))
2519 insert_closing_tag(editor, pos, ch, str_found);
2520 result = TRUE;
2522 g_free(str_found);
2523 return result;
2527 /* like sci_get_line_indentation(), but for a string. */
2528 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent)
2530 const gchar *ptr;
2531 gsize tab_size = sci_get_tab_width(editor->sci);
2532 gsize count = 0;
2534 g_return_val_if_fail(base_indent, 0);
2536 for (ptr = base_indent; *ptr != 0; ptr++)
2538 switch (*ptr)
2540 case ' ':
2541 count++;
2542 break;
2543 case '\t':
2544 count += tab_size;
2545 break;
2548 return count;
2552 static void auto_table(GeanyEditor *editor, gint pos)
2554 ScintillaObject *sci = editor->sci;
2555 gchar *table;
2556 gint indent_pos;
2557 const gchar *indent_str;
2559 if (sci_get_lexer(sci) != SCLEX_HTML) return;
2561 read_indent(editor, pos);
2562 indent_pos = sci_get_line_indent_position(sci, sci_get_line_from_position(sci, pos));
2563 if ((pos - 7) != indent_pos) /* 7 == strlen("<table>") */
2565 gint i;
2566 guint x;
2568 x = strlen(indent);
2569 /* find the start of the <table tag */
2570 i = 1;
2571 while (i <= pos && sci_get_char_at(sci, pos - i) != '<') i++;
2572 /* add all non whitespace before the tag to the indent string */
2573 while ((pos - i) != indent_pos && x < sizeof(indent) - 1)
2575 indent[x++] = ' ';
2576 i++;
2578 indent[x] = '\0';
2581 if (! editor->auto_indent)
2582 indent_str = "";
2583 else
2584 indent_str = "\t";
2586 table = g_strconcat("\n", indent_str, "<tr>\n",
2587 indent_str, indent_str, "<td> </td>\n",
2588 indent_str, "</tr>\n",
2589 NULL);
2590 editor_insert_text_block(editor, table, pos, -1,
2591 count_indent_size(editor, indent), TRUE);
2592 g_free(table);
2596 static void real_comment_multiline(GeanyEditor *editor, gint line_start, gint last_line)
2598 const gchar *eol;
2599 gchar *str_begin, *str_end, *co, *cc;
2600 gint line_len;
2602 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2604 eol = editor_get_eol_char(editor);
2605 co = editor->document->file_type->comment_open;
2606 cc = editor->document->file_type->comment_close;
2607 str_begin = g_strdup_printf("%s%s", (co != NULL) ? co : "", eol);
2608 str_end = g_strdup_printf("%s%s", (cc != NULL) ? cc : "", eol);
2610 /* insert the comment strings */
2611 sci_insert_text(editor->sci, line_start, str_begin);
2612 line_len = sci_get_position_from_line(editor->sci, last_line + 2);
2613 sci_insert_text(editor->sci, line_len, str_end);
2615 g_free(str_begin);
2616 g_free(str_end);
2620 static void real_uncomment_multiline(GeanyEditor *editor)
2622 /* find the beginning of the multi line comment */
2623 gint pos, line, len, x;
2624 gchar *linebuf;
2625 GeanyDocument *doc;
2627 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2628 doc = editor->document;
2630 /* remove comment open chars */
2631 pos = document_find_text(doc, doc->file_type->comment_open, 0, TRUE, FALSE, NULL);
2632 SSM(editor->sci, SCI_DELETEBACK, 0, 0);
2634 /* check whether the line is empty and can be deleted */
2635 line = sci_get_line_from_position(editor->sci, pos);
2636 len = sci_get_line_length(editor->sci, line);
2637 linebuf = sci_get_line(editor->sci, line);
2638 x = 0;
2639 while (linebuf[x] != '\0' && isspace(linebuf[x])) x++;
2640 if (x == len) SSM(editor->sci, SCI_LINEDELETE, 0, 0);
2641 g_free(linebuf);
2643 /* remove comment close chars */
2644 pos = document_find_text(doc, doc->file_type->comment_close, 0, FALSE, FALSE, NULL);
2645 SSM(editor->sci, SCI_DELETEBACK, 0, 0);
2647 /* check whether the line is empty and can be deleted */
2648 line = sci_get_line_from_position(editor->sci, pos);
2649 len = sci_get_line_length(editor->sci, line);
2650 linebuf = sci_get_line(editor->sci, line);
2651 x = 0;
2652 while (linebuf[x] != '\0' && isspace(linebuf[x])) x++;
2653 if (x == len) SSM(editor->sci, SCI_LINEDELETE, 0, 0);
2654 g_free(linebuf);
2658 static gint get_multiline_comment_style(GeanyEditor *editor, gint line_start)
2660 gint lexer = sci_get_lexer(editor->sci);
2661 gint style_comment;
2663 /* List only those lexers which support multi line comments */
2664 switch (lexer)
2666 case SCLEX_XML:
2667 case SCLEX_HTML:
2669 if (is_style_php(sci_get_style_at(editor->sci, line_start)))
2670 style_comment = SCE_HPHP_COMMENT;
2671 else
2672 style_comment = SCE_H_COMMENT;
2673 break;
2675 case SCLEX_HASKELL: style_comment = SCE_HA_COMMENTBLOCK; break;
2676 case SCLEX_LUA: style_comment = SCE_LUA_COMMENT; break;
2677 case SCLEX_CSS: style_comment = SCE_CSS_COMMENT; break;
2678 case SCLEX_SQL: style_comment = SCE_SQL_COMMENT; break;
2679 case SCLEX_CAML: style_comment = SCE_CAML_COMMENT; break;
2680 case SCLEX_D: style_comment = SCE_D_COMMENT; break;
2681 case SCLEX_PASCAL: style_comment = SCE_PAS_COMMENT; break;
2682 default: style_comment = SCE_C_COMMENT;
2685 return style_comment;
2689 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise
2690 * returns the amount of uncommented single comment lines, in case of multi line uncomment
2691 * it returns just 1 */
2692 gint editor_do_uncomment(GeanyEditor *editor, gint line, gboolean toggle)
2694 gint first_line, last_line;
2695 gint x, i, line_start, line_len;
2696 gint sel_start, sel_end;
2697 gint count = 0;
2698 gsize co_len;
2699 gchar sel[256], *co, *cc;
2700 gboolean break_loop = FALSE, single_line = FALSE;
2701 GeanyFiletype *ft;
2703 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, 0);
2705 if (line < 0)
2706 { /* use selection or current line */
2707 sel_start = sci_get_selection_start(editor->sci);
2708 sel_end = sci_get_selection_end(editor->sci);
2710 first_line = sci_get_line_from_position(editor->sci, sel_start);
2711 /* Find the last line with chars selected (not EOL char) */
2712 last_line = sci_get_line_from_position(editor->sci,
2713 sel_end - editor_get_eol_char_len(editor));
2714 last_line = MAX(first_line, last_line);
2716 else
2718 first_line = last_line = line;
2719 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
2722 ft = editor->document->file_type;
2724 /* detection of HTML vs PHP code, if non-PHP set filetype to XML */
2725 line_start = sci_get_position_from_line(editor->sci, first_line);
2726 if (ft->id == GEANY_FILETYPES_PHP)
2728 if (! is_style_php(sci_get_style_at(editor->sci, line_start)))
2729 ft = filetypes[GEANY_FILETYPES_XML];
2732 co = ft->comment_open;
2733 cc = ft->comment_close;
2734 if (co == NULL)
2735 return 0;
2737 co_len = strlen(co);
2738 if (co_len == 0)
2739 return 0;
2741 sci_start_undo_action(editor->sci);
2743 for (i = first_line; (i <= last_line) && (! break_loop); i++)
2745 gint buf_len;
2747 line_start = sci_get_position_from_line(editor->sci, i);
2748 line_len = sci_get_line_length(editor->sci, i);
2749 x = 0;
2751 buf_len = MIN((gint)sizeof(sel) - 1, line_len - 1);
2752 if (buf_len <= 0)
2753 continue;
2754 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
2755 sel[buf_len] = '\0';
2757 while (isspace(sel[x])) x++;
2759 /* to skip blank lines */
2760 if (x < line_len && sel[x] != '\0')
2762 /* use single line comment */
2763 if (cc == NULL || strlen(cc) == 0)
2765 single_line = TRUE;
2767 if (toggle)
2769 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
2770 if (strncmp(sel + x, co, co_len) != 0 ||
2771 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) != 0)
2772 continue;
2774 co_len += tm_len;
2776 else
2778 if (strncmp(sel + x, co, co_len) != 0)
2779 continue;
2782 sci_set_selection(editor->sci, line_start + x, line_start + x + co_len);
2783 sci_replace_sel(editor->sci, "");
2784 count++;
2786 /* use multi line comment */
2787 else
2789 gint style_comment;
2791 /* skip lines which are already comments */
2792 style_comment = get_multiline_comment_style(editor, line_start);
2793 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
2795 real_uncomment_multiline(editor);
2796 count = 1;
2799 /* break because we are already on the last line */
2800 break_loop = TRUE;
2801 break;
2805 sci_end_undo_action(editor->sci);
2807 /* restore selection if there is one
2808 * but don't touch the selection if caller is editor_do_comment_toggle */
2809 if (! toggle && sel_start < sel_end)
2811 if (single_line)
2813 sci_set_selection_start(editor->sci, sel_start - co_len);
2814 sci_set_selection_end(editor->sci, sel_end - (count * co_len));
2816 else
2818 gint eol_len = editor_get_eol_char_len(editor);
2819 sci_set_selection_start(editor->sci, sel_start - co_len - eol_len);
2820 sci_set_selection_end(editor->sci, sel_end - co_len - eol_len);
2824 return count;
2828 void editor_do_comment_toggle(GeanyEditor *editor)
2830 gint first_line, last_line;
2831 gint x, i, line_start, line_len, first_line_start;
2832 gint sel_start, sel_end;
2833 gint count_commented = 0, count_uncommented = 0;
2834 gchar sel[256], *co, *cc;
2835 gboolean break_loop = FALSE, single_line = FALSE;
2836 gboolean first_line_was_comment = FALSE;
2837 gsize co_len;
2838 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
2839 GeanyFiletype *ft;
2841 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2843 sel_start = sci_get_selection_start(editor->sci);
2844 sel_end = sci_get_selection_end(editor->sci);
2846 ft = editor->document->file_type;
2848 first_line = sci_get_line_from_position(editor->sci,
2849 sci_get_selection_start(editor->sci));
2850 /* Find the last line with chars selected (not EOL char) */
2851 last_line = sci_get_line_from_position(editor->sci,
2852 sci_get_selection_end(editor->sci) - editor_get_eol_char_len(editor));
2853 last_line = MAX(first_line, last_line);
2855 /* detection of HTML vs PHP code, if non-PHP set filetype to XML */
2856 first_line_start = sci_get_position_from_line(editor->sci, first_line);
2857 if (ft->id == GEANY_FILETYPES_PHP)
2859 if (! is_style_php(sci_get_style_at(editor->sci, first_line_start)))
2860 ft = filetypes[GEANY_FILETYPES_XML];
2863 co = ft->comment_open;
2864 cc = ft->comment_close;
2865 if (co == NULL)
2866 return;
2868 co_len = strlen(co);
2869 if (co_len == 0)
2870 return;
2872 sci_start_undo_action(editor->sci);
2874 for (i = first_line; (i <= last_line) && (! break_loop); i++)
2876 gint buf_len;
2878 line_start = sci_get_position_from_line(editor->sci, i);
2879 line_len = sci_get_line_length(editor->sci, i);
2880 x = 0;
2882 buf_len = MIN((gint)sizeof(sel) - 1, line_len - 1);
2883 if (buf_len < 0)
2884 continue;
2885 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
2886 sel[buf_len] = '\0';
2888 while (isspace(sel[x])) x++;
2890 /* use single line comment */
2891 if (cc == NULL || strlen(cc) == 0)
2893 gboolean do_continue = FALSE;
2894 single_line = TRUE;
2896 if (strncmp(sel + x, co, co_len) == 0 &&
2897 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) == 0)
2899 do_continue = TRUE;
2902 if (do_continue && i == first_line)
2903 first_line_was_comment = TRUE;
2905 if (do_continue)
2907 count_uncommented += editor_do_uncomment(editor, i, TRUE);
2908 continue;
2911 /* we are still here, so the above lines were not already comments, so comment it */
2912 editor_do_comment(editor, i, TRUE, TRUE);
2913 count_commented++;
2915 /* use multi line comment */
2916 else
2918 gint style_comment;
2920 /* skip lines which are already comments */
2921 style_comment = get_multiline_comment_style(editor, line_start);
2922 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
2924 real_uncomment_multiline(editor);
2925 count_uncommented++;
2927 else
2929 real_comment_multiline(editor, line_start, last_line);
2930 count_commented++;
2933 /* break because we are already on the last line */
2934 break_loop = TRUE;
2935 break;
2939 sci_end_undo_action(editor->sci);
2941 co_len += tm_len;
2943 /* restore selection if there is one */
2944 if (sel_start < sel_end)
2946 if (single_line)
2948 gint a = (first_line_was_comment) ? - co_len : co_len;
2950 /* don't modify sel_start when the selection starts within indentation */
2951 read_indent(editor, sel_start);
2952 if ((sel_start - first_line_start) <= (gint) strlen(indent))
2953 a = 0;
2955 sci_set_selection_start(editor->sci, sel_start + a);
2956 sci_set_selection_end(editor->sci, sel_end +
2957 (count_commented * co_len) - (count_uncommented * co_len));
2959 else
2961 gint eol_len = editor_get_eol_char_len(editor);
2962 if (count_uncommented > 0)
2964 sci_set_selection_start(editor->sci, sel_start - co_len + eol_len);
2965 sci_set_selection_end(editor->sci, sel_end - co_len + eol_len);
2967 else if (count_commented > 0)
2969 sci_set_selection_start(editor->sci, sel_start + co_len - eol_len);
2970 sci_set_selection_end(editor->sci, sel_end + co_len - eol_len);
2974 else if (count_uncommented > 0)
2976 gint eol_len = single_line ? 0: editor_get_eol_char_len(editor);
2977 sci_set_current_position(editor->sci, sel_start - co_len + eol_len, TRUE);
2979 else if (count_commented > 0)
2981 gint eol_len = single_line ? 0: editor_get_eol_char_len(editor);
2982 sci_set_current_position(editor->sci, sel_start + co_len - eol_len, TRUE);
2987 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise */
2988 void editor_do_comment(GeanyEditor *editor, gint line, gboolean allow_empty_lines, gboolean toggle)
2990 gint first_line, last_line;
2991 gint x, i, line_start, line_len;
2992 gint sel_start, sel_end, co_len;
2993 gchar sel[256], *co, *cc;
2994 gboolean break_loop = FALSE, single_line = FALSE;
2995 GeanyFiletype *ft;
2997 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2999 if (line < 0)
3000 { /* use selection or current line */
3001 sel_start = sci_get_selection_start(editor->sci);
3002 sel_end = sci_get_selection_end(editor->sci);
3004 first_line = sci_get_line_from_position(editor->sci, sel_start);
3005 /* Find the last line with chars selected (not EOL char) */
3006 last_line = sci_get_line_from_position(editor->sci,
3007 sel_end - editor_get_eol_char_len(editor));
3008 last_line = MAX(first_line, last_line);
3010 else
3012 first_line = last_line = line;
3013 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
3016 ft = editor->document->file_type;
3018 /* detection of HTML vs PHP code, if non-PHP set filetype to XML */
3019 line_start = sci_get_position_from_line(editor->sci, first_line);
3020 if (ft->id == GEANY_FILETYPES_PHP)
3022 if (! is_style_php(sci_get_style_at(editor->sci, line_start)))
3023 ft = filetypes[GEANY_FILETYPES_XML];
3026 co = ft->comment_open;
3027 cc = ft->comment_close;
3028 if (co == NULL)
3029 return;
3031 co_len = strlen(co);
3032 if (co_len == 0)
3033 return;
3035 sci_start_undo_action(editor->sci);
3037 for (i = first_line; (i <= last_line) && (! break_loop); i++)
3039 gint buf_len;
3041 line_start = sci_get_position_from_line(editor->sci, i);
3042 line_len = sci_get_line_length(editor->sci, i);
3043 x = 0;
3045 buf_len = MIN((gint)sizeof(sel) - 1, line_len - 1);
3046 if (buf_len < 0)
3047 continue;
3048 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3049 sel[buf_len] = '\0';
3051 while (isspace(sel[x])) x++;
3053 /* to skip blank lines */
3054 if (allow_empty_lines || (x < line_len && sel[x] != '\0'))
3056 /* use single line comment */
3057 if (cc == NULL || strlen(cc) == 0)
3059 gint start = line_start;
3060 single_line = TRUE;
3062 if (ft->comment_use_indent)
3063 start = line_start + x;
3065 if (toggle)
3067 gchar *text = g_strconcat(co, editor_prefs.comment_toggle_mark, NULL);
3068 sci_insert_text(editor->sci, start, text);
3069 g_free(text);
3071 else
3072 sci_insert_text(editor->sci, start, co);
3074 /* use multi line comment */
3075 else
3077 gint style_comment;
3079 /* skip lines which are already comments */
3080 style_comment = get_multiline_comment_style(editor, line_start);
3081 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3082 continue;
3084 real_comment_multiline(editor, line_start, last_line);
3086 /* break because we are already on the last line */
3087 break_loop = TRUE;
3088 break;
3092 sci_end_undo_action(editor->sci);
3094 /* restore selection if there is one
3095 * but don't touch the selection if caller is editor_do_comment_toggle */
3096 if (! toggle && sel_start < sel_end)
3098 if (single_line)
3100 sci_set_selection_start(editor->sci, sel_start + co_len);
3101 sci_set_selection_end(editor->sci, sel_end + ((i - first_line) * co_len));
3103 else
3105 gint eol_len = editor_get_eol_char_len(editor);
3106 sci_set_selection_start(editor->sci, sel_start + co_len + eol_len);
3107 sci_set_selection_end(editor->sci, sel_end + co_len + eol_len);
3113 static gboolean brace_timeout_active = FALSE;
3115 static gboolean delay_match_brace(G_GNUC_UNUSED gpointer user_data)
3117 GeanyDocument *doc = document_get_current();
3118 GeanyEditor *editor;
3119 gint brace_pos = GPOINTER_TO_INT(user_data);
3120 gint end_pos, cur_pos;
3122 brace_timeout_active = FALSE;
3123 if (!doc)
3124 return FALSE;
3126 editor = doc->editor;
3127 cur_pos = sci_get_current_position(editor->sci) - 1;
3129 if (cur_pos != brace_pos)
3131 cur_pos++;
3132 if (cur_pos != brace_pos)
3134 /* we have moved past the original brace_pos, but after the timeout
3135 * we may now be on a new brace, so check again */
3136 editor_highlight_braces(editor, cur_pos);
3137 return FALSE;
3140 if (!utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3142 editor_highlight_braces(editor, cur_pos);
3143 return FALSE;
3145 end_pos = sci_find_matching_brace(editor->sci, brace_pos);
3147 if (end_pos >= 0)
3149 gint col = MIN(sci_get_col_from_position(editor->sci, brace_pos),
3150 sci_get_col_from_position(editor->sci, end_pos));
3151 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, col, 0);
3152 SSM(editor->sci, SCI_BRACEHIGHLIGHT, brace_pos, end_pos);
3154 else
3156 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3157 SSM(editor->sci, SCI_BRACEBADLIGHT, brace_pos, 0);
3159 return FALSE;
3163 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos)
3165 gint brace_pos = cur_pos - 1;
3167 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3168 SSM(editor->sci, SCI_BRACEBADLIGHT, (uptr_t)-1, 0);
3170 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3172 brace_pos++;
3173 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3175 return;
3178 if (!brace_timeout_active)
3180 brace_timeout_active = TRUE;
3181 /* delaying matching makes scrolling faster e.g. holding down arrow keys */
3182 g_timeout_add(100, delay_match_brace, GINT_TO_POINTER(brace_pos));
3187 static gboolean in_block_comment(gint lexer, gint style)
3189 switch (lexer)
3191 case SCLEX_CPP:
3192 return (style == SCE_C_COMMENT ||
3193 style == SCE_C_COMMENTDOC);
3195 case SCLEX_PASCAL:
3196 return (style == SCE_PAS_COMMENT ||
3197 style == SCE_PAS_COMMENT2);
3199 case SCLEX_D:
3200 return (style == SCE_D_COMMENT ||
3201 style == SCE_D_COMMENTDOC ||
3202 style == SCE_D_COMMENTNESTED);
3204 case SCLEX_HTML:
3205 return (style == SCE_HPHP_COMMENT);
3207 case SCLEX_CSS:
3208 return (style == SCE_CSS_COMMENT);
3210 default:
3211 return FALSE;
3216 static gboolean is_comment_char(gchar c, gint lexer)
3218 if ((c == '*' || c == '+') && lexer == SCLEX_D)
3219 return TRUE;
3220 else
3221 if (c == '*')
3222 return TRUE;
3224 return FALSE;
3228 static void auto_multiline(GeanyEditor *editor, gint cur_line)
3230 ScintillaObject *sci = editor->sci;
3231 gint indent_pos, style;
3232 gint lexer = sci_get_lexer(sci);
3234 /* Use the start of the line enter was pressed on, to avoid any doc keyword styles */
3235 indent_pos = sci_get_line_indent_position(sci, cur_line - 1);
3236 style = sci_get_style_at(sci, indent_pos);
3237 if (!in_block_comment(lexer, style))
3238 return;
3240 /* Check whether the comment block continues on this line */
3241 indent_pos = sci_get_line_indent_position(sci, cur_line);
3242 if (sci_get_style_at(sci, indent_pos) == style)
3244 gchar *previous_line = sci_get_line(sci, cur_line - 1);
3245 /* the type of comment, '*' (C/C++/Java), '+' and the others (D) */
3246 gchar *continuation = "*";
3247 gchar *whitespace = ""; /* to hold whitespace if needed */
3248 gchar *result;
3249 gint len = strlen(previous_line);
3250 gint i;
3252 /* find and stop at end of multi line comment */
3253 i = len - 1;
3254 while (i >= 0 && isspace(previous_line[i])) i--;
3255 if (i >= 1 && is_comment_char(previous_line[i - 1], lexer) && previous_line[i] == '/')
3257 gint indent_len, indent_width;
3259 indent_pos = sci_get_line_indent_position(sci, cur_line);
3260 indent_len = sci_get_col_from_position(sci, indent_pos);
3261 indent_width = editor_get_indent_prefs(editor)->width;
3263 /* if there is one too many spaces, delete the last space,
3264 * to return to the indent used before the multiline comment was started. */
3265 if (indent_len % indent_width == 1)
3266 SSM(sci, SCI_DELETEBACKNOTLINE, 0, 0); /* remove whitespace indent */
3267 g_free(previous_line);
3268 return;
3270 /* check whether we are on the second line of multi line comment */
3271 i = 0;
3272 while (i < len && isspace(previous_line[i])) i++; /* get to start of the line */
3274 if (i + 1 < len &&
3275 previous_line[i] == '/' && is_comment_char(previous_line[i + 1], lexer))
3276 { /* we are on the second line of a multi line comment, so we have to insert white space */
3277 whitespace = " ";
3280 if (G_UNLIKELY(style == SCE_D_COMMENTNESTED))
3281 continuation = "+"; /* for nested comments in D */
3283 result = g_strconcat(whitespace, continuation, " ", NULL);
3284 sci_add_text(sci, result);
3285 g_free(result);
3287 g_free(previous_line);
3292 /* Checks whether the given style is a string for the given lexer.
3293 * It doesn't handle LEX_HTML, this should be done by the caller.
3294 * Returns true if the style is a string, FALSE otherwise.
3296 * Don't forget STRINGEOL, to prevent completion whilst typing a string with no closing char.
3298 static gboolean is_string_style(gint lexer, gint style)
3300 switch (lexer)
3302 case SCLEX_CPP:
3303 return (style == SCE_C_CHARACTER ||
3304 style == SCE_C_STRING ||
3305 style == SCE_C_STRINGEOL);
3307 case SCLEX_PASCAL:
3308 return (style == SCE_PAS_CHARACTER ||
3309 style == SCE_PAS_STRING ||
3310 style == SCE_PAS_STRINGEOL);
3312 case SCLEX_D:
3313 return (style == SCE_D_STRING ||
3314 style == SCE_D_STRINGEOL ||
3315 style == SCE_D_CHARACTER ||
3316 style == SCE_D_STRINGB ||
3317 style == SCE_D_STRINGR);
3319 case SCLEX_PYTHON:
3320 return (style == SCE_P_STRING ||
3321 style == SCE_P_TRIPLE ||
3322 style == SCE_P_TRIPLEDOUBLE ||
3323 style == SCE_P_CHARACTER ||
3324 style == SCE_P_STRINGEOL);
3326 case SCLEX_F77:
3327 case SCLEX_FORTRAN:
3328 return (style == SCE_F_STRING1 ||
3329 style == SCE_F_STRING2 ||
3330 style == SCE_F_STRINGEOL);
3332 case SCLEX_PERL:
3333 return (/*style == SCE_PL_STRING ||*/ /* may want variable autocompletion "$(foo)" */
3334 style == SCE_PL_CHARACTER ||
3335 style == SCE_PL_HERE_DELIM ||
3336 style == SCE_PL_HERE_Q ||
3337 style == SCE_PL_HERE_QQ ||
3338 style == SCE_PL_HERE_QX ||
3339 style == SCE_PL_POD ||
3340 style == SCE_PL_STRING_Q ||
3341 style == SCE_PL_STRING_QQ ||
3342 style == SCE_PL_STRING_QX ||
3343 style == SCE_PL_STRING_QR ||
3344 style == SCE_PL_STRING_QW ||
3345 style == SCE_PL_POD_VERB);
3347 case SCLEX_R:
3348 return (style == SCE_R_STRING);
3350 case SCLEX_RUBY:
3351 return (style == SCE_RB_CHARACTER ||
3352 style == SCE_RB_STRING ||
3353 style == SCE_RB_HERE_DELIM ||
3354 style == SCE_RB_HERE_Q ||
3355 style == SCE_RB_HERE_QQ ||
3356 style == SCE_RB_HERE_QX ||
3357 style == SCE_RB_POD);
3359 case SCLEX_BASH:
3360 return (style == SCE_SH_STRING);
3362 case SCLEX_SQL:
3363 return (style == SCE_SQL_STRING);
3365 case SCLEX_TCL:
3366 return (style == SCE_TCL_IN_QUOTE);
3368 case SCLEX_LUA:
3369 return (style == SCE_LUA_LITERALSTRING ||
3370 style == SCE_LUA_CHARACTER ||
3371 style == SCE_LUA_STRINGEOL ||
3372 style == SCE_LUA_STRING);
3374 case SCLEX_HASKELL:
3375 return (style == SCE_HA_CHARACTER ||
3376 style == SCE_HA_STRING);
3378 case SCLEX_FREEBASIC:
3379 return (style == SCE_B_STRING ||
3380 style == SCE_B_STRINGEOL);
3382 case SCLEX_MATLAB:
3383 return (style == SCE_MATLAB_STRING ||
3384 style == SCE_MATLAB_DOUBLEQUOTESTRING);
3386 case SCLEX_HTML:
3387 return (
3388 style == SCE_HBA_STRING ||
3389 style == SCE_HBA_STRINGEOL ||
3390 style == SCE_HB_STRING ||
3391 style == SCE_HB_STRINGEOL ||
3392 style == SCE_H_CDATA ||
3393 style == SCE_H_DOUBLESTRING ||
3394 style == SCE_HJA_DOUBLESTRING ||
3395 style == SCE_HJA_SINGLESTRING ||
3396 style == SCE_HJA_STRINGEOL ||
3397 style == SCE_HJ_DOUBLESTRING ||
3398 style == SCE_HJ_SINGLESTRING ||
3399 style == SCE_HJ_STRINGEOL ||
3400 style == SCE_HPA_CHARACTER ||
3401 style == SCE_HPA_STRING ||
3402 style == SCE_HPA_TRIPLE ||
3403 style == SCE_HPA_TRIPLEDOUBLE ||
3404 style == SCE_HP_CHARACTER ||
3405 style == SCE_HPHP_HSTRING ||
3406 style == SCE_HPHP_HSTRING || /* HSTRING is a heredoc */
3407 style == SCE_HPHP_HSTRING_VARIABLE ||
3408 style == SCE_HPHP_SIMPLESTRING ||
3409 style == SCE_HPHP_SIMPLESTRING ||
3410 style == SCE_HP_STRING ||
3411 style == SCE_HP_TRIPLE ||
3412 style == SCE_HP_TRIPLEDOUBLE ||
3413 style == SCE_H_SGML_DOUBLESTRING ||
3414 style == SCE_H_SGML_SIMPLESTRING ||
3415 style == SCE_H_SINGLESTRING);
3417 case SCLEX_CMAKE:
3418 return (style == SCE_CMAKE_STRINGDQ ||
3419 style == SCE_CMAKE_STRINGLQ ||
3420 style == SCE_CMAKE_STRINGRQ ||
3421 style == SCE_CMAKE_STRINGVAR);
3423 case SCLEX_NSIS:
3424 return (style == SCE_NSIS_STRINGDQ ||
3425 style == SCE_NSIS_STRINGLQ ||
3426 style == SCE_NSIS_STRINGRQ ||
3427 style == SCE_NSIS_STRINGVAR);
3429 case SCLEX_ADA:
3430 return (style == SCE_ADA_CHARACTER ||
3431 style == SCE_ADA_STRING ||
3432 style == SCE_ADA_CHARACTEREOL ||
3433 style == SCE_ADA_STRINGEOL);
3435 return FALSE;
3439 /* Checks whether the given style is a comment for the given lexer.
3440 * It doesn't handle LEX_HTML, this should be done by the caller.
3441 * Returns true if the style is a comment, FALSE otherwise.
3443 static gboolean is_comment_style(gint lexer, gint style)
3445 switch (lexer)
3447 case SCLEX_CPP:
3448 return (style == SCE_C_COMMENT ||
3449 style == SCE_C_COMMENTLINE ||
3450 style == SCE_C_COMMENTDOC ||
3451 style == SCE_C_COMMENTLINEDOC ||
3452 style == SCE_C_COMMENTDOCKEYWORD ||
3453 style == SCE_C_COMMENTDOCKEYWORDERROR);
3455 case SCLEX_PASCAL:
3456 return (style == SCE_PAS_COMMENT ||
3457 style == SCE_PAS_COMMENT2 ||
3458 style == SCE_PAS_COMMENTLINE);
3460 case SCLEX_D:
3461 return (style == SCE_D_COMMENT ||
3462 style == SCE_D_COMMENTLINE ||
3463 style == SCE_D_COMMENTDOC ||
3464 style == SCE_D_COMMENTNESTED ||
3465 style == SCE_D_COMMENTLINEDOC ||
3466 style == SCE_D_COMMENTDOCKEYWORD ||
3467 style == SCE_D_COMMENTDOCKEYWORDERROR);
3469 case SCLEX_PYTHON:
3470 return (style == SCE_P_COMMENTLINE ||
3471 style == SCE_P_COMMENTBLOCK);
3473 case SCLEX_F77:
3474 case SCLEX_FORTRAN:
3475 return (style == SCE_F_COMMENT);
3477 case SCLEX_PERL:
3478 return (style == SCE_PL_COMMENTLINE);
3480 case SCLEX_PROPERTIES:
3481 return (style == SCE_PROPS_COMMENT);
3483 case SCLEX_PO:
3484 return (style == SCE_PO_COMMENT);
3486 case SCLEX_LATEX:
3487 return (style == SCE_L_COMMENT);
3489 case SCLEX_MAKEFILE:
3490 return (style == SCE_MAKE_COMMENT);
3492 case SCLEX_RUBY:
3493 return (style == SCE_RB_COMMENTLINE);
3495 case SCLEX_BASH:
3496 return (style == SCE_SH_COMMENTLINE);
3498 case SCLEX_R:
3499 return (style == SCE_R_COMMENT);
3501 case SCLEX_SQL:
3502 return (style == SCE_SQL_COMMENT ||
3503 style == SCE_SQL_COMMENTLINE ||
3504 style == SCE_SQL_COMMENTDOC);
3506 case SCLEX_TCL:
3507 return (style == SCE_TCL_COMMENT ||
3508 style == SCE_TCL_COMMENTLINE ||
3509 style == SCE_TCL_COMMENT_BOX ||
3510 style == SCE_TCL_BLOCK_COMMENT);
3512 case SCLEX_MATLAB:
3513 return (style == SCE_MATLAB_COMMENT);
3515 case SCLEX_LUA:
3516 return (style == SCE_LUA_COMMENT ||
3517 style == SCE_LUA_COMMENTLINE ||
3518 style == SCE_LUA_COMMENTDOC);
3520 case SCLEX_HASKELL:
3521 return (style == SCE_HA_COMMENTLINE ||
3522 style == SCE_HA_COMMENTBLOCK ||
3523 style == SCE_HA_COMMENTBLOCK2 ||
3524 style == SCE_HA_COMMENTBLOCK3);
3526 case SCLEX_FREEBASIC:
3527 return (style == SCE_B_COMMENT);
3529 case SCLEX_YAML:
3530 return (style == SCE_YAML_COMMENT);
3532 case SCLEX_HTML:
3533 return (
3534 style == SCE_HBA_COMMENTLINE ||
3535 style == SCE_HB_COMMENTLINE ||
3536 style == SCE_H_COMMENT ||
3537 style == SCE_HJA_COMMENT ||
3538 style == SCE_HJA_COMMENTDOC ||
3539 style == SCE_HJA_COMMENTLINE ||
3540 style == SCE_HJ_COMMENT ||
3541 style == SCE_HJ_COMMENTDOC ||
3542 style == SCE_HJ_COMMENTLINE ||
3543 style == SCE_HPA_COMMENTLINE ||
3544 style == SCE_HP_COMMENTLINE ||
3545 style == SCE_HPHP_COMMENT ||
3546 style == SCE_HPHP_COMMENTLINE ||
3547 style == SCE_H_SGML_COMMENT);
3549 case SCLEX_CMAKE:
3550 return (style == SCE_CMAKE_COMMENT);
3552 case SCLEX_NSIS:
3553 return (style == SCE_NSIS_COMMENT ||
3554 style == SCE_NSIS_COMMENTBOX);
3556 case SCLEX_ADA:
3557 return (style == SCE_ADA_COMMENTLINE ||
3558 style == SCE_NSIS_COMMENTBOX);
3560 return FALSE;
3564 /* Checks whether the given style is normal code (not string, comment, preprocessor, etc).
3565 * It doesn't handle LEX_HTML, this should be done by the caller.
3567 static gboolean is_code_style(gint lexer, gint style)
3569 switch (lexer)
3571 case SCLEX_CPP:
3572 if (style == SCE_C_PREPROCESSOR)
3573 return FALSE;
3574 break;
3576 return !(is_comment_style(lexer, style) ||
3577 is_string_style(lexer, style));
3581 #if 0
3582 static gboolean editor_lexer_is_c_like(gint lexer)
3584 switch (lexer)
3586 case SCLEX_CPP:
3587 case SCLEX_D:
3588 return TRUE;
3590 default:
3591 return FALSE;
3594 #endif
3597 /* Returns: -1 if lexer doesn't support type keywords */
3598 gint editor_lexer_get_type_keyword_idx(gint lexer)
3600 switch (lexer)
3602 case SCLEX_CPP:
3603 case SCLEX_D:
3604 return 3;
3606 default:
3607 return -1;
3612 /* inserts a three-line comment at one line above current cursor position */
3613 void editor_insert_multiline_comment(GeanyEditor *editor)
3615 gchar *text;
3616 gint text_len;
3617 gint line;
3618 gint pos;
3619 gboolean have_multiline_comment = FALSE;
3620 GeanyDocument *doc;
3622 g_return_if_fail(editor != NULL &&
3623 editor->document->file_type != NULL && editor->document->file_type->comment_open != NULL);
3625 doc = editor->document;
3627 if (doc->file_type->comment_close != NULL && strlen(doc->file_type->comment_close) > 0)
3628 have_multiline_comment = TRUE;
3630 /* insert three lines one line above of the current position */
3631 line = sci_get_line_from_position(editor->sci, editor_info.click_pos);
3632 pos = sci_get_position_from_line(editor->sci, line);
3634 /* use the indent on the current line but only when comment indentation is used
3635 * and we don't have multi line comment characters */
3636 if (editor->auto_indent &&
3637 ! have_multiline_comment && doc->file_type->comment_use_indent)
3639 read_indent(editor, editor_info.click_pos);
3640 text = g_strdup_printf("%s\n%s\n%s\n", indent, indent, indent);
3641 text_len = strlen(text);
3643 else
3645 text = g_strdup("\n\n\n");
3646 text_len = 3;
3648 sci_insert_text(editor->sci, pos, text);
3649 g_free(text);
3652 /* select the inserted lines for commenting */
3653 sci_set_selection_start(editor->sci, pos);
3654 sci_set_selection_end(editor->sci, pos + text_len);
3656 editor_do_comment(editor, -1, TRUE, FALSE);
3658 /* set the current position to the start of the first inserted line */
3659 pos += strlen(doc->file_type->comment_open);
3661 /* on multi line comment jump to the next line, otherwise add the length of added indentation */
3662 if (have_multiline_comment)
3663 pos += 1;
3664 else
3665 pos += strlen(indent);
3667 sci_set_current_position(editor->sci, pos, TRUE);
3668 /* reset the selection */
3669 sci_set_anchor(editor->sci, pos);
3673 /* Note: If the editor is pending a redraw, set document::scroll_percent instead.
3674 * Scroll the view to make line appear at percent_of_view.
3675 * line can be -1 to use the current position. */
3676 void editor_scroll_to_line(GeanyEditor *editor, gint line, gfloat percent_of_view)
3678 gint vis1, los, delta;
3679 GtkWidget *wid;
3681 g_return_if_fail(editor != NULL);
3683 wid = GTK_WIDGET(editor->sci);
3685 if (! wid->window || ! gdk_window_is_viewable(wid->window))
3686 return; /* prevent gdk_window_scroll warning */
3688 if (line == -1)
3689 line = sci_get_current_line(editor->sci);
3691 /* sci 'visible line' != doc line number because of folding and line wrapping */
3692 /* calling SCI_VISIBLEFROMDOCLINE for line is more accurate than calling
3693 * SCI_DOCLINEFROMVISIBLE for vis1. */
3694 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0);
3695 vis1 = SSM(editor->sci, SCI_GETFIRSTVISIBLELINE, 0, 0);
3696 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
3697 delta = (line - vis1) - los * percent_of_view;
3698 sci_scroll_lines(editor->sci, delta);
3699 sci_scroll_caret(editor->sci); /* needed for horizontal scrolling */
3703 /* creates and inserts one tab or whitespace of the amount of the tab width */
3704 void editor_insert_alternative_whitespace(GeanyEditor *editor)
3706 gchar *text;
3707 GeanyIndentPrefs iprefs = *editor_get_indent_prefs(editor);
3709 g_return_if_fail(editor != NULL);
3711 switch (iprefs.type)
3713 case GEANY_INDENT_TYPE_TABS:
3714 iprefs.type = GEANY_INDENT_TYPE_SPACES;
3715 break;
3716 case GEANY_INDENT_TYPE_SPACES:
3717 case GEANY_INDENT_TYPE_BOTH: /* most likely we want a tab */
3718 iprefs.type = GEANY_INDENT_TYPE_TABS;
3719 break;
3721 text = get_whitespace(&iprefs, iprefs.width);
3722 sci_add_text(editor->sci, text);
3723 g_free(text);
3727 void editor_select_word(GeanyEditor *editor)
3729 gint pos;
3730 gint start;
3731 gint end;
3733 g_return_if_fail(editor != NULL);
3735 pos = SSM(editor->sci, SCI_GETCURRENTPOS, 0, 0);
3736 start = SSM(editor->sci, SCI_WORDSTARTPOSITION, pos, TRUE);
3737 end = SSM(editor->sci, SCI_WORDENDPOSITION, pos, TRUE);
3739 if (start == end) /* caret in whitespaces sequence */
3741 /* look forward but reverse the selection direction,
3742 * so the caret end up stay as near as the original position. */
3743 end = SSM(editor->sci, SCI_WORDENDPOSITION, pos, FALSE);
3744 start = SSM(editor->sci, SCI_WORDENDPOSITION, end, TRUE);
3745 if (start == end)
3746 return;
3749 sci_set_selection(editor->sci, start, end);
3753 /* extra_line is for selecting the cursor line (or anchor line) at the bottom of a selection,
3754 * when those lines have no selection (cursor at start of line). */
3755 void editor_select_lines(GeanyEditor *editor, gboolean extra_line)
3757 gint start, end, line;
3759 g_return_if_fail(editor != NULL);
3761 start = sci_get_selection_start(editor->sci);
3762 end = sci_get_selection_end(editor->sci);
3764 /* check if whole lines are already selected */
3765 if (! extra_line && start != end &&
3766 sci_get_col_from_position(editor->sci, start) == 0 &&
3767 sci_get_col_from_position(editor->sci, end) == 0)
3768 return;
3770 line = sci_get_line_from_position(editor->sci, start);
3771 start = sci_get_position_from_line(editor->sci, line);
3773 line = sci_get_line_from_position(editor->sci, end);
3774 end = sci_get_position_from_line(editor->sci, line + 1);
3776 sci_set_selection(editor->sci, start, end);
3780 /* find the start or end of a paragraph by searching all lines in direction (UP or DOWN)
3781 * starting at the given line and return the found line or return -1 if called on an empty line */
3782 static gint find_paragraph_stop(GeanyEditor *editor, gint line, gint direction)
3784 gboolean found_end = FALSE;
3785 gint step;
3786 gchar *line_buf, *x;
3787 ScintillaObject *sci = editor->sci;
3789 /* first check current line and return -1 if it is empty to skip creating of a selection */
3790 line_buf = x = sci_get_line(sci, line);
3791 while (isspace(*x))
3792 x++;
3793 if (*x == '\0')
3795 g_free(line_buf);
3796 return -1;
3799 if (direction == GTK_DIR_UP)
3800 step = -1;
3801 else
3802 step = 1;
3804 while (! found_end)
3806 line += step;
3808 /* sci_get_line checks for sanity of the given line, sci_get_line always return a string
3809 * containing at least '\0' so no need to check for NULL */
3810 line_buf = x = sci_get_line(sci, line);
3812 /* check whether after skipping all whitespace we are at end of line and if so, assume
3813 * this line as end of paragraph */
3814 while (isspace(*x))
3815 x++;
3816 if (*x == '\0')
3818 found_end = TRUE;
3819 if (line == -1)
3820 /* called on the first line but there is no previous line so return line 0 */
3821 line = 0;
3823 g_free(line_buf);
3825 return line;
3829 void editor_select_paragraph(GeanyEditor *editor)
3831 gint pos_start, pos_end, line_start, line_found;
3833 g_return_if_fail(editor != NULL);
3835 line_start = SSM(editor->sci, SCI_LINEFROMPOSITION,
3836 SSM(editor->sci, SCI_GETCURRENTPOS, 0, 0), 0);
3838 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_UP);
3839 if (line_found == -1)
3840 return;
3842 /* find_paragraph_stop returns the emtpy line(previous to the real start of the paragraph),
3843 * so use the next line for selection start */
3844 if (line_found > 0)
3845 line_found++;
3847 pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3849 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_DOWN);
3850 pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3852 sci_set_selection(editor->sci, pos_start, pos_end);
3856 /* simple indentation to indent the current line with the same indent as the previous one */
3857 static void smart_line_indentation(GeanyEditor *editor, gint first_line, gint last_line)
3859 gint i, sel_start = 0, sel_end = 0;
3861 /* get previous line and use it for read_indent to use that line
3862 * (otherwise it would fail on a line only containing "{" in advanced indentation mode) */
3863 read_indent(editor, sci_get_position_from_line(editor->sci, first_line - 1));
3865 for (i = first_line; i <= last_line; i++)
3867 /* skip the first line or if the indentation of the previous and current line are equal */
3868 if (i == 0 ||
3869 SSM(editor->sci, SCI_GETLINEINDENTATION, i - 1, 0) ==
3870 SSM(editor->sci, SCI_GETLINEINDENTATION, i, 0))
3871 continue;
3873 sel_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
3874 sel_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
3875 if (sel_start < sel_end)
3877 sci_set_selection(editor->sci, sel_start, sel_end);
3878 sci_replace_sel(editor->sci, "");
3880 sci_insert_text(editor->sci, sel_start, indent);
3885 /* simple indentation to indent the current line with the same indent as the previous one */
3886 void editor_smart_line_indentation(GeanyEditor *editor, gint pos)
3888 gint first_line, last_line;
3889 gint first_sel_start, first_sel_end;
3890 ScintillaObject *sci;
3892 g_return_if_fail(editor != NULL);
3894 sci = editor->sci;
3896 first_sel_start = sci_get_selection_start(sci);
3897 first_sel_end = sci_get_selection_end(sci);
3899 first_line = sci_get_line_from_position(sci, first_sel_start);
3900 /* Find the last line with chars selected (not EOL char) */
3901 last_line = sci_get_line_from_position(sci, first_sel_end - editor_get_eol_char_len(editor));
3902 last_line = MAX(first_line, last_line);
3904 if (pos == -1)
3905 pos = first_sel_start;
3907 sci_start_undo_action(sci);
3909 smart_line_indentation(editor, first_line, last_line);
3911 /* set cursor position if there was no selection */
3912 if (first_sel_start == first_sel_end)
3914 gint indent_pos = SSM(sci, SCI_GETLINEINDENTPOSITION, first_line, 0);
3916 /* use indent position as user may wish to change indentation afterwards */
3917 sci_set_current_position(sci, indent_pos, FALSE);
3919 else
3921 /* fully select all the lines affected */
3922 sci_set_selection_start(sci, sci_get_position_from_line(sci, first_line));
3923 sci_set_selection_end(sci, sci_get_position_from_line(sci, last_line + 1));
3926 sci_end_undo_action(sci);
3930 /* increase / decrease current line or selection by one space */
3931 void editor_indentation_by_one_space(GeanyEditor *editor, gint pos, gboolean decrease)
3933 gint i, first_line, last_line, line_start, indentation_end, count = 0;
3934 gint sel_start, sel_end, first_line_offset = 0;
3936 g_return_if_fail(editor != NULL);
3938 sel_start = sci_get_selection_start(editor->sci);
3939 sel_end = sci_get_selection_end(editor->sci);
3941 first_line = sci_get_line_from_position(editor->sci, sel_start);
3942 /* Find the last line with chars selected (not EOL char) */
3943 last_line = sci_get_line_from_position(editor->sci, sel_end - editor_get_eol_char_len(editor));
3944 last_line = MAX(first_line, last_line);
3946 if (pos == -1)
3947 pos = sel_start;
3949 sci_start_undo_action(editor->sci);
3951 for (i = first_line; i <= last_line; i++)
3953 indentation_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
3954 if (decrease)
3956 line_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
3957 /* searching backwards for a space to remove */
3958 while (sci_get_char_at(editor->sci, indentation_end) != ' ' && indentation_end > line_start)
3959 indentation_end--;
3961 if (sci_get_char_at(editor->sci, indentation_end) == ' ')
3963 sci_set_selection(editor->sci, indentation_end, indentation_end + 1);
3964 sci_replace_sel(editor->sci, "");
3965 count--;
3966 if (i == first_line)
3967 first_line_offset = -1;
3970 else
3972 sci_insert_text(editor->sci, indentation_end, " ");
3973 count++;
3974 if (i == first_line)
3975 first_line_offset = 1;
3979 /* set cursor position */
3980 if (sel_start < sel_end)
3982 gint start = sel_start + first_line_offset;
3983 if (first_line_offset < 0)
3984 start = MAX(sel_start + first_line_offset,
3985 SSM(editor->sci, SCI_POSITIONFROMLINE, first_line, 0));
3987 sci_set_selection_start(editor->sci, start);
3988 sci_set_selection_end(editor->sci, sel_end + count);
3990 else
3991 sci_set_current_position(editor->sci, pos + count, FALSE);
3993 sci_end_undo_action(editor->sci);
3997 void editor_finalize()
3999 scintilla_release_resources();
4003 /* wordchars: NULL or a string containing characters to match a word.
4004 * Returns: the current selection or the current word. */
4005 gchar *editor_get_default_selection(GeanyEditor *editor, gboolean use_current_word,
4006 const gchar *wordchars)
4008 gchar *s = NULL;
4010 g_return_val_if_fail(editor != NULL, NULL);
4012 if (sci_get_lines_selected(editor->sci) == 1)
4014 gint len = sci_get_selected_text_length(editor->sci);
4016 s = g_malloc(len + 1);
4017 sci_get_selected_text(editor->sci, s);
4019 else if (sci_get_lines_selected(editor->sci) == 0 && use_current_word)
4020 { /* use the word at current cursor position */
4021 gchar word[GEANY_MAX_WORD_LENGTH];
4023 editor_find_current_word(editor, -1, word, sizeof(word), wordchars);
4024 if (word[0] != '\0')
4025 s = g_strdup(word);
4027 return s;
4031 /* Note: Usually the line should be made visible (not folded) before calling this.
4032 * Returns: TRUE if line is/will be displayed to the user, or FALSE if it is
4033 * outside the *vertical* view.
4034 * Warning: You may need horizontal scrolling to make the cursor visible - so always call
4035 * sci_scroll_caret() when this returns TRUE. */
4036 gboolean editor_line_in_view(GeanyEditor *editor, gint line)
4038 gint vis1, los;
4040 g_return_val_if_fail(editor != NULL, FALSE);
4042 /* If line is wrapped the result may occur on another virtual line than the first and may be
4043 * still hidden, so increase the line number to check for the next document line */
4044 if (SSM(editor->sci, SCI_WRAPCOUNT, line, 0) > 1)
4045 line++;
4047 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0); /* convert to visible line number */
4048 vis1 = SSM(editor->sci, SCI_GETFIRSTVISIBLELINE, 0, 0);
4049 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
4051 return (line >= vis1 && line < vis1 + los);
4055 /* If the current line is outside the current view window, scroll the line
4056 * so it appears at percent_of_view. */
4057 void editor_display_current_line(GeanyEditor *editor, gfloat percent_of_view)
4059 gint line;
4061 g_return_if_fail(editor != NULL);
4063 line = sci_get_current_line(editor->sci);
4065 /* unfold maybe folded results */
4066 sci_ensure_line_is_visible(editor->sci, line);
4068 /* scroll the line if it's off screen */
4069 if (! editor_line_in_view(editor, line))
4070 editor->scroll_percent = percent_of_view;
4071 else
4072 sci_scroll_caret(editor->sci); /* may need horizontal scrolling */
4077 * Deletes all currently set indicators in the @a editor window.
4078 * Error indicators (red squiggly underlines) and usual line markers are removed.
4080 * @param editor The editor to operate on.
4082 void editor_indicator_clear_errors(GeanyEditor *editor)
4084 editor_indicator_clear(editor, GEANY_INDICATOR_ERROR);
4085 sci_marker_delete_all(editor->sci, 0); /* remove the yellow error line marker */
4090 * Deletes all currently set indicators matching @a indic in the @a editor window.
4092 * @param editor The editor to operate on.
4093 * @param indic The indicator number to clear, this is a value of @ref GeanyIndicator.
4095 * @since 0.16
4097 void editor_indicator_clear(GeanyEditor *editor, gint indic)
4099 glong last_pos;
4101 g_return_if_fail(editor != NULL);
4103 last_pos = sci_get_length(editor->sci);
4104 if (last_pos > 0)
4106 sci_indicator_set(editor->sci, indic);
4107 sci_indicator_clear(editor->sci, 0, last_pos);
4113 * Sets an indicator @a indic on @a line.
4114 * Whitespace at the start and the end of the line is not marked.
4116 * @param editor The editor to operate on.
4117 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4118 * @param line The line number which should be marked.
4120 * @since 0.16
4122 void editor_indicator_set_on_line(GeanyEditor *editor, gint indic, gint line)
4124 gint start, end;
4125 guint i = 0, len;
4126 gchar *linebuf;
4128 g_return_if_fail(editor != NULL);
4129 g_return_if_fail(line >= 0);
4131 start = sci_get_position_from_line(editor->sci, line);
4132 end = sci_get_position_from_line(editor->sci, line + 1);
4134 /* skip blank lines */
4135 if ((start + 1) == end ||
4136 start > end ||
4137 sci_get_line_length(editor->sci, line) == editor_get_eol_char_len(editor))
4139 return;
4142 len = end - start;
4143 linebuf = sci_get_line(editor->sci, line);
4145 /* don't set the indicator on whitespace */
4146 while (isspace(linebuf[i]))
4147 i++;
4148 while (len > 1 && len > i && isspace(linebuf[len - 1]))
4150 len--;
4151 end--;
4153 g_free(linebuf);
4155 editor_indicator_set_on_range(editor, indic, start + i, end);
4160 * Sets an indicator on the range specified by @a start and @a end.
4161 * No error checking or whitespace removal is performed, this should be done by the calling
4162 * function if necessary.
4164 * @param editor The editor to operate on.
4165 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4166 * @param start The starting position for the marker.
4167 * @param end The ending position for the marker.
4169 * @since 0.16
4171 void editor_indicator_set_on_range(GeanyEditor *editor, gint indic, gint start, gint end)
4173 g_return_if_fail(editor != NULL);
4174 if (start >= end)
4175 return;
4177 sci_indicator_set(editor->sci, indic);
4178 sci_indicator_fill(editor->sci, start, end - start);
4182 /* Inserts the given colour (format should be #...), if there is a selection starting with 0x...
4183 * the replacement will also start with 0x... */
4184 void editor_insert_color(GeanyEditor *editor, const gchar *colour)
4186 g_return_if_fail(editor != NULL);
4188 if (sci_has_selection(editor->sci))
4190 gint start = sci_get_selection_start(editor->sci);
4191 const gchar *replacement = colour;
4193 if (sci_get_char_at(editor->sci, start) == '0' &&
4194 sci_get_char_at(editor->sci, start + 1) == 'x')
4196 sci_set_selection_start(editor->sci, start + 2);
4197 sci_set_selection_end(editor->sci, start + 8);
4198 replacement++; /* skip the leading "0x" */
4200 else if (sci_get_char_at(editor->sci, start - 1) == '#')
4201 { /* double clicking something like #00ffff may only select 00ffff because of wordchars */
4202 replacement++; /* so skip the '#' to only replace the colour value */
4204 sci_replace_sel(editor->sci, replacement);
4206 else
4207 sci_add_text(editor->sci, colour);
4212 * Retrieves the localized name (for displaying) of the used end of line characters
4213 * (LF, CR/LF, CR) in the given editor.
4214 * If @a editor is @c NULL, the default end of line characters are used.
4216 * @param editor The editor to operate on, or @c NULL to query the default value.
4217 * @return The name of the end of line characters.
4219 * @since 0.19
4221 const gchar *editor_get_eol_char_name(GeanyEditor *editor)
4223 gint mode = file_prefs.default_eol_character;
4225 if (editor != NULL)
4226 mode = sci_get_eol_mode(editor->sci);
4228 return utils_get_eol_name(mode);
4233 * Retrieves the length of the used end of line characters (LF, CR/LF, CR) in the given editor.
4234 * If @a editor is @c NULL, the default end of line characters are used.
4235 * The returned value is 1 for CR and LF and 2 for CR/LF.
4237 * @param editor The editor to operate on, or @c NULL to query the default value.
4238 * @return The length of the end of line characters.
4240 * @since 0.19
4242 gint editor_get_eol_char_len(GeanyEditor *editor)
4244 gint mode = file_prefs.default_eol_character;
4246 if (editor != NULL)
4247 mode = sci_get_eol_mode(editor->sci);
4249 switch (mode)
4251 case SC_EOL_CRLF: return 2; break;
4252 default: return 1; break;
4258 * Retrieves the used end of line characters (LF, CR/LF, CR) in the given editor.
4259 * If @a editor is @c NULL, the default end of line characters are used.
4260 * The returned value is either "\n", "\r\n" or "\r".
4262 * @param editor The editor to operate on, or @c NULL to query the default value.
4263 * @return The end of line characters.
4265 * @since 0.19
4267 const gchar *editor_get_eol_char(GeanyEditor *editor)
4269 gint mode = file_prefs.default_eol_character;
4271 if (editor != NULL)
4272 mode = sci_get_eol_mode(editor->sci);
4274 switch (mode)
4276 case SC_EOL_CRLF: return "\r\n"; break;
4277 case SC_EOL_CR: return "\r"; break;
4278 default: return "\n"; break;
4283 static void fold_all(GeanyEditor *editor, gboolean want_fold)
4285 gint lines, first, i;
4287 if (editor == NULL || ! editor_prefs.folding)
4288 return;
4290 lines = sci_get_line_count(editor->sci);
4291 first = sci_get_first_visible_line(editor->sci);
4293 for (i = 0; i < lines; i++)
4295 gint level = sci_get_fold_level(editor->sci, i);
4297 if (level & SC_FOLDLEVELHEADERFLAG)
4299 if (sci_get_fold_expanded(editor->sci, i) == want_fold)
4300 sci_toggle_fold(editor->sci, i);
4303 editor_scroll_to_line(editor, first, 0.0F);
4307 void editor_unfold_all(GeanyEditor *editor)
4309 fold_all(editor, FALSE);
4313 void editor_fold_all(GeanyEditor *editor)
4315 fold_all(editor, TRUE);
4319 void editor_replace_tabs(GeanyEditor *editor)
4321 gint search_pos, pos_in_line, current_tab_true_length;
4322 gint tab_len;
4323 gchar *tab_str;
4324 struct Sci_TextToFind ttf;
4326 g_return_if_fail(editor != NULL);
4328 sci_start_undo_action(editor->sci);
4329 tab_len = sci_get_tab_width(editor->sci);
4330 ttf.chrg.cpMin = 0;
4331 ttf.chrg.cpMax = sci_get_length(editor->sci);
4332 ttf.lpstrText = (gchar*) "\t";
4334 while (TRUE)
4336 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4337 if (search_pos == -1)
4338 break;
4340 pos_in_line = sci_get_col_from_position(editor->sci, search_pos);
4341 current_tab_true_length = tab_len - (pos_in_line % tab_len);
4342 tab_str = g_strnfill(current_tab_true_length, ' ');
4343 sci_set_target_start(editor->sci, search_pos);
4344 sci_set_target_end(editor->sci, search_pos + 1);
4345 sci_replace_target(editor->sci, tab_str, FALSE);
4346 /* next search starts after replacement */
4347 ttf.chrg.cpMin = search_pos + current_tab_true_length - 1;
4348 /* update end of range now text has changed */
4349 ttf.chrg.cpMax += current_tab_true_length - 1;
4350 g_free(tab_str);
4352 sci_end_undo_action(editor->sci);
4356 /* Replaces all occurrences all spaces of the length of a given tab_width. */
4357 void editor_replace_spaces(GeanyEditor *editor)
4359 gint search_pos;
4360 static gdouble tab_len_f = -1.0; /* keep the last used value */
4361 gint tab_len;
4362 struct Sci_TextToFind ttf;
4364 g_return_if_fail(editor != NULL);
4366 if (tab_len_f < 0.0)
4367 tab_len_f = sci_get_tab_width(editor->sci);
4369 if (! dialogs_show_input_numeric(
4370 _("Enter Tab Width"),
4371 _("Enter the amount of spaces which should be replaced by a tab character."),
4372 &tab_len_f, 1, 100, 1))
4374 return;
4376 tab_len = (gint) tab_len_f;
4378 sci_start_undo_action(editor->sci);
4379 ttf.chrg.cpMin = 0;
4380 ttf.chrg.cpMax = sci_get_length(editor->sci);
4381 ttf.lpstrText = g_strnfill(tab_len, ' ');
4383 while (TRUE)
4385 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4386 if (search_pos == -1)
4387 break;
4389 sci_set_target_start(editor->sci, search_pos);
4390 sci_set_target_end(editor->sci, search_pos + tab_len);
4391 sci_replace_target(editor->sci, "\t", FALSE);
4392 ttf.chrg.cpMin = search_pos;
4393 /* update end of range now text has changed */
4394 ttf.chrg.cpMax -= tab_len - 1;
4396 sci_end_undo_action(editor->sci);
4397 g_free(ttf.lpstrText);
4401 void editor_strip_line_trailing_spaces(GeanyEditor *editor, gint line)
4403 gint line_start = sci_get_position_from_line(editor->sci, line);
4404 gint line_end = sci_get_line_end_position(editor->sci, line);
4405 gint i = line_end - 1;
4406 gchar ch = sci_get_char_at(editor->sci, i);
4408 while ((i >= line_start) && ((ch == ' ') || (ch == '\t')))
4410 i--;
4411 ch = sci_get_char_at(editor->sci, i);
4413 if (i < (line_end - 1))
4415 sci_set_target_start(editor->sci, i + 1);
4416 sci_set_target_end(editor->sci, line_end);
4417 sci_replace_target(editor->sci, "", FALSE);
4422 void editor_strip_trailing_spaces(GeanyEditor *editor)
4424 gint max_lines = sci_get_line_count(editor->sci);
4425 gint line;
4427 sci_start_undo_action(editor->sci);
4429 for (line = 0; line < max_lines; line++)
4431 editor_strip_line_trailing_spaces(editor, line);
4433 sci_end_undo_action(editor->sci);
4437 void editor_ensure_final_newline(GeanyEditor *editor)
4439 gint max_lines = sci_get_line_count(editor->sci);
4440 gboolean append_newline = (max_lines == 1);
4441 gint end_document = sci_get_position_from_line(editor->sci, max_lines);
4443 if (max_lines > 1)
4445 append_newline = end_document > sci_get_position_from_line(editor->sci, max_lines - 1);
4447 if (append_newline)
4449 const gchar *eol = "\n";
4450 switch (sci_get_eol_mode(editor->sci))
4452 case SC_EOL_CRLF:
4453 eol = "\r\n";
4454 break;
4455 case SC_EOL_CR:
4456 eol = "\r";
4457 break;
4459 sci_insert_text(editor->sci, end_document, eol);
4464 void editor_set_font(GeanyEditor *editor, const gchar *font)
4466 gint style, size;
4467 gchar *font_name;
4468 PangoFontDescription *pfd;
4470 g_return_if_fail(editor);
4472 pfd = pango_font_description_from_string(font);
4473 size = pango_font_description_get_size(pfd) / PANGO_SCALE;
4474 font_name = g_strdup_printf("!%s", pango_font_description_get_family(pfd));
4475 pango_font_description_free(pfd);
4477 for (style = 0; style <= 127; style++)
4478 sci_set_font(editor->sci, style, font_name, size);
4480 /* line number and braces */
4481 sci_set_font(editor->sci, STYLE_LINENUMBER, font_name, size);
4482 sci_set_font(editor->sci, STYLE_BRACELIGHT, font_name, size);
4483 sci_set_font(editor->sci, STYLE_BRACEBAD, font_name, size);
4484 g_free(font_name);
4486 /* zoom to 100% to prevent confusion */
4487 sci_zoom_off(editor->sci);
4491 void editor_set_line_wrapping(GeanyEditor *editor, gboolean wrap)
4493 g_return_if_fail(editor != NULL);
4495 editor->line_wrapping = wrap;
4496 sci_set_lines_wrapped(editor->sci, wrap);
4500 /** Sets the indent type for @a editor.
4501 * @param editor Editor.
4502 * @param type Indent type.
4504 * @since 0.16
4506 void editor_set_indent_type(GeanyEditor *editor, GeanyIndentType type)
4508 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
4509 ScintillaObject *sci = editor->sci;
4510 gboolean use_tabs = type != GEANY_INDENT_TYPE_SPACES;
4512 editor->indent_type = type;
4513 sci_set_use_tabs(sci, use_tabs);
4515 if (type == GEANY_INDENT_TYPE_BOTH)
4516 sci_set_tab_width(sci, iprefs->hard_tab_width);
4517 else
4518 sci_set_tab_width(sci, iprefs->width);
4519 SSM(sci, SCI_SETINDENT, iprefs->width, 0);
4521 /* remove indent spaces on backspace, if using any spaces to indent */
4522 SSM(sci, SCI_SETBACKSPACEUNINDENTS, type != GEANY_INDENT_TYPE_TABS, 0);
4526 /* Convenience function for editor_goto_pos() to pass in a line number. */
4527 gboolean editor_goto_line(GeanyEditor *editor, gint line)
4529 gint pos;
4531 g_return_val_if_fail(editor, FALSE);
4532 if (line < 0 || line >= sci_get_line_count(editor->sci))
4533 return FALSE;
4535 pos = sci_get_position_from_line(editor->sci, line);
4536 return editor_goto_pos(editor, pos, TRUE);
4540 /* Move to position @a pos, switching to the document if necessary,
4541 * setting a marker if @a mark is set. */
4542 gboolean editor_goto_pos(GeanyEditor *editor, gint pos, gboolean mark)
4544 gint page_num;
4546 g_return_val_if_fail(editor, FALSE);
4547 if (G_UNLIKELY(pos < 0))
4548 return FALSE;
4550 if (mark)
4552 gint line = sci_get_line_from_position(editor->sci, pos);
4554 /* mark the tag with the yellow arrow */
4555 sci_marker_delete_all(editor->sci, 0);
4556 sci_set_marker_at_line(editor->sci, line, 0);
4559 sci_goto_pos(editor->sci, pos, TRUE);
4560 editor->scroll_percent = 0.25F;
4562 /* finally switch to the page */
4563 page_num = gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook), GTK_WIDGET(editor->sci));
4564 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
4566 return TRUE;
4570 static gboolean
4571 on_editor_scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer user_data)
4573 GeanyEditor *editor = user_data;
4575 /* Handle scroll events if Alt is pressed and scroll whole pages instead of a
4576 * few lines only, maybe this could/should be done in Scintilla directly */
4577 if (event->state & GDK_MOD1_MASK)
4579 sci_send_command(editor->sci, (event->direction == GDK_SCROLL_DOWN) ? SCI_PAGEDOWN : SCI_PAGEUP);
4580 return TRUE;
4582 else if (event->state & GDK_SHIFT_MASK)
4584 gint amount = (event->direction == GDK_SCROLL_DOWN) ? 8 : -8;
4586 sci_scroll_columns(editor->sci, amount);
4587 return TRUE;
4590 return FALSE; /* let Scintilla handle all other cases */
4594 static gboolean editor_check_colourise(GeanyEditor *editor)
4596 GeanyDocument *doc = editor->document;
4598 if (!doc->priv->colourise_needed)
4599 return FALSE;
4601 doc->priv->colourise_needed = FALSE;
4602 sci_colourise(editor->sci, 0, -1);
4604 /* now that the current document is colourised, fold points are now accurate,
4605 * so force an update of the current function/tag. */
4606 symbols_get_current_function(NULL, NULL);
4607 ui_update_statusbar(NULL, -1);
4609 return TRUE;
4613 /* We only want to colourise just before drawing, to save startup time and
4614 * prevent unnecessary recolouring other documents after one is saved.
4615 * Really we want a "draw" signal but there doesn't seem to be one (expose is too late,
4616 * and "show" doesn't work). */
4617 static gboolean on_editor_focus_in(GtkWidget *widget, GdkEventFocus *event, gpointer user_data)
4619 GeanyEditor *editor = user_data;
4621 editor_check_colourise(editor);
4622 return FALSE;
4626 /* This is just to catch any uncolourised documents being drawn that didn't receive focus
4627 * for some reason, maybe it's not necessary but just in case. */
4628 static gboolean on_editor_expose_event(GtkWidget *widget, GdkEventExpose *event,
4629 gpointer user_data)
4631 GeanyEditor *editor = user_data;
4633 editor_check_colourise(editor);
4634 return FALSE;
4638 static void setup_sci_keys(ScintillaObject *sci)
4640 /* disable some Scintilla keybindings to be able to redefine them cleanly */
4641 sci_clear_cmdkey(sci, 'A' | (SCMOD_CTRL << 16)); /* select all */
4642 sci_clear_cmdkey(sci, 'D' | (SCMOD_CTRL << 16)); /* duplicate */
4643 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16)); /* line transpose */
4644 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line copy */
4645 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16)); /* line cut */
4646 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line delete */
4647 sci_clear_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line to end delete */
4648 sci_clear_cmdkey(sci, '/' | (SCMOD_CTRL << 16)); /* Previous word part */
4649 sci_clear_cmdkey(sci, '\\' | (SCMOD_CTRL << 16)); /* Next word part */
4650 sci_clear_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16)); /* scroll line up */
4651 sci_clear_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16)); /* scroll line down */
4652 sci_clear_cmdkey(sci, SCK_HOME); /* line start */
4653 sci_clear_cmdkey(sci, SCK_END); /* line end */
4654 sci_clear_cmdkey(sci, SCK_END | (SCMOD_ALT << 16)); /* visual line end */
4656 if (editor_prefs.use_gtk_word_boundaries)
4658 /* use GtkEntry-like word boundaries */
4659 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16), SCI_WORDRIGHTEND);
4660 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_WORDRIGHTENDEXTEND);
4661 sci_assign_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16), SCI_DELWORDRIGHTEND);
4663 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_ALT << 16), SCI_LINESCROLLUP);
4664 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_ALT << 16), SCI_LINESCROLLDOWN);
4665 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16), SCI_PARAUP);
4666 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARAUPEXTEND);
4667 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16), SCI_PARADOWN);
4668 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARADOWNEXTEND);
4670 sci_clear_cmdkey(sci, SCK_BACK | (SCMOD_ALT << 16)); /* clear Alt-Backspace (Undo) */
4674 #include "icons/16x16/classviewer-var.xpm"
4675 #include "icons/16x16/classviewer-method.xpm"
4677 /* Create new editor widget (scintilla).
4678 * @note The @c "sci-notify" signal is connected separately. */
4679 static ScintillaObject *create_new_sci(GeanyEditor *editor)
4681 ScintillaObject *sci;
4683 sci = SCINTILLA(scintilla_new());
4685 gtk_widget_show(GTK_WIDGET(sci));
4687 sci_set_codepage(sci, SC_CP_UTF8);
4688 /*SSM(sci, SCI_SETWRAPSTARTINDENT, 4, 0);*/
4689 /* disable scintilla provided popup menu */
4690 sci_use_popup(sci, FALSE);
4692 setup_sci_keys(sci);
4694 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
4695 sci_set_lines_wrapped(sci, editor_prefs.line_wrapping);
4696 sci_set_scrollbar_mode(sci, editor_prefs.show_scrollbars);
4697 sci_set_caret_policy_x(sci, CARET_JUMPS | CARET_EVEN, 0);
4698 /*sci_set_caret_policy_y(sci, CARET_JUMPS | CARET_EVEN, 0);*/
4699 SSM(sci, SCI_AUTOCSETSEPARATOR, '\n', 0);
4700 SSM(sci, SCI_SETSCROLLWIDTHTRACKING, 1, 0);
4702 /* tag autocompletion images */
4703 SSM(sci, SCI_REGISTERIMAGE, 1, (sptr_t)classviewer_var);
4704 SSM(sci, SCI_REGISTERIMAGE, 2, (sptr_t)classviewer_method);
4706 /* necessary for column mode editing, implemented in Scintilla since 2.0 */
4707 SSM(sci, SCI_SETADDITIONALSELECTIONTYPING, 1, 0);
4709 /* virtual space */
4710 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
4712 /* only connect signals if this is for the document notebook, not split window */
4713 if (editor->sci == NULL)
4715 g_signal_connect(sci, "button-press-event", G_CALLBACK(on_editor_button_press_event), editor);
4716 g_signal_connect(sci, "scroll-event", G_CALLBACK(on_editor_scroll_event), editor);
4717 g_signal_connect(sci, "motion-notify-event", G_CALLBACK(on_motion_event), NULL);
4718 g_signal_connect(sci, "focus-in-event", G_CALLBACK(on_editor_focus_in), editor);
4719 g_signal_connect(sci, "expose-event", G_CALLBACK(on_editor_expose_event), editor);
4721 return sci;
4725 /** Creates a new Scintilla @c GtkWidget based on the settings for @a editor.
4726 * @param editor Editor settings.
4727 * @return The new widget.
4729 * @since 0.15
4731 ScintillaObject *editor_create_widget(GeanyEditor *editor)
4733 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4734 ScintillaObject *old, *sci;
4736 /* temporarily change editor to use the new sci widget */
4737 old = editor->sci;
4738 sci = create_new_sci(editor);
4739 editor->sci = sci;
4741 editor_set_indent_type(editor, iprefs->type);
4742 editor_set_font(editor, interface_prefs.editor_font);
4743 editor_apply_update_prefs(editor);
4745 /* if editor already had a widget, restore it */
4746 if (old)
4747 editor->sci = old;
4748 return sci;
4752 GeanyEditor *editor_create(GeanyDocument *doc)
4754 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4755 GeanyEditor *editor = g_new0(GeanyEditor, 1);
4757 editor->document = doc;
4758 doc->editor = editor; /* needed in case some editor functions/callbacks expect it */
4760 editor->auto_indent = (iprefs->auto_indent_mode != GEANY_AUTOINDENT_NONE);
4761 editor->line_wrapping = editor_prefs.line_wrapping;
4762 editor->scroll_percent = -1.0F;
4763 editor->line_breaking = FALSE;
4765 editor->sci = editor_create_widget(editor);
4766 return editor;
4770 /* in case we need to free some fields in future */
4771 void editor_destroy(GeanyEditor *editor)
4773 g_free(editor);
4777 static void on_document_save(GObject *obj, GeanyDocument *doc)
4779 g_return_if_fail(NZV(doc->real_path));
4781 if (utils_str_equal(doc->real_path,
4782 utils_build_path(app->configdir, "snippets.conf", NULL)))
4784 /* reload snippets */
4785 editor_snippets_free();
4786 editor_snippets_init();
4791 gboolean editor_complete_word_part(GeanyEditor *editor)
4793 gchar *entry;
4795 g_return_val_if_fail(editor, FALSE);
4797 if (!SSM(editor->sci, SCI_AUTOCACTIVE, 0, 0))
4798 return FALSE;
4800 entry = sci_get_string(editor->sci, SCI_AUTOCGETCURRENTTEXT, 0);
4802 /* if no word part, complete normally */
4803 if (!check_partial_completion(editor, entry))
4804 SSM(editor->sci, SCI_AUTOCCOMPLETE, 0, 0);
4806 g_free(entry);
4807 return TRUE;
4811 void editor_init(void)
4813 static GeanyIndentPrefs indent_prefs;
4815 memset(&editor_prefs, 0, sizeof(GeanyEditorPrefs));
4816 memset(&indent_prefs, 0, sizeof(GeanyIndentPrefs));
4817 editor_prefs.indentation = &indent_prefs;
4819 /* use g_signal_connect_after() to allow plugins connecting to the signal before the default
4820 * handler (on_editor_notify) is called */
4821 g_signal_connect_after(geany_object, "editor-notify", G_CALLBACK(on_editor_notify), NULL);
4823 ui_add_config_file_menu_item(utils_build_path(app->configdir, "snippets.conf", NULL),
4824 NULL, NULL);
4825 g_signal_connect(geany_object, "document-save", G_CALLBACK(on_document_save), NULL);
4829 /* TODO: Should these be user-defined instead of hard-coded? */
4830 void editor_set_indentation_guides(GeanyEditor *editor)
4832 gint mode;
4833 gint lexer;
4835 g_return_if_fail(editor != NULL);
4837 if (! editor_prefs.show_indent_guide)
4839 sci_set_indentation_guides(editor->sci, SC_IV_NONE);
4840 return;
4843 lexer = sci_get_lexer(editor->sci);
4844 switch (lexer)
4846 /* Lines added/removed are prefixed with +/- characters, so
4847 * those lines will not be shown with any indentation guides.
4848 * It can be distracting that only a few of lines in a diff/patch
4849 * file will show the guides. */
4850 case SCLEX_DIFF:
4851 mode = SC_IV_NONE;
4852 break;
4854 /* These languages use indentation for control blocks; the "look forward" method works
4855 * best here */
4856 case SCLEX_PYTHON:
4857 case SCLEX_HASKELL:
4858 case SCLEX_MAKEFILE:
4859 case SCLEX_ASM:
4860 case SCLEX_SQL:
4861 case SCLEX_PROPERTIES:
4862 case SCLEX_FORTRAN: /* Is this the best option for Fortran? */
4863 case SCLEX_CAML:
4864 mode = SC_IV_LOOKFORWARD;
4865 break;
4867 /* C-like (structured) languages benefit from the "look both" method */
4868 case SCLEX_CPP:
4869 case SCLEX_HTML:
4870 case SCLEX_XML:
4871 case SCLEX_PERL:
4872 case SCLEX_LATEX:
4873 case SCLEX_LUA:
4874 case SCLEX_PASCAL:
4875 case SCLEX_RUBY:
4876 case SCLEX_TCL:
4877 case SCLEX_F77:
4878 case SCLEX_CSS:
4879 case SCLEX_BASH:
4880 case SCLEX_VHDL:
4881 case SCLEX_FREEBASIC:
4882 case SCLEX_D:
4883 case SCLEX_MATLAB:
4884 mode = SC_IV_LOOKBOTH;
4885 break;
4887 default:
4888 mode = SC_IV_REAL;
4889 break;
4892 sci_set_indentation_guides(editor->sci, mode);
4896 /* Apply just the prefs that can change in the Preferences dialog */
4897 void editor_apply_update_prefs(GeanyEditor *editor)
4899 ScintillaObject *sci;
4901 g_return_if_fail(editor != NULL);
4903 sci = editor->sci;
4905 sci_set_mark_long_lines(sci, editor_get_long_line_type(),
4906 editor_get_long_line_column(), editor_prefs.long_line_color);
4908 /* update indent width, tab width */
4909 editor_set_indent_type(editor, editor->indent_type);
4910 sci_set_tab_indents(sci, editor_prefs.use_tab_to_indent);
4912 sci_set_autoc_max_height(sci, editor_prefs.symbolcompletion_max_height);
4913 SSM(sci, SCI_AUTOCSETDROPRESTOFWORD, editor_prefs.completion_drops_rest_of_word, 0);
4915 editor_set_indentation_guides(editor);
4917 sci_set_visible_white_spaces(sci, editor_prefs.show_white_space);
4918 sci_set_visible_eols(sci, editor_prefs.show_line_endings);
4919 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
4920 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin, 0);
4922 sci_set_folding_margin_visible(sci, editor_prefs.folding);
4924 /* virtual space */
4925 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
4927 /* (dis)allow scrolling past end of document */
4928 sci_set_scroll_stop_at_last_line(sci, editor_prefs.scroll_stop_at_last_line);
4932 /* This is for tab-indents, space aligns formatted code. Spaces should be preserved. */
4933 static void change_tab_indentation(GeanyEditor *editor, gint line, gboolean increase)
4935 ScintillaObject *sci = editor->sci;
4936 gint pos = sci_get_position_from_line(sci, line);
4938 if (increase)
4940 sci_insert_text(sci, pos, "\t");
4942 else
4944 if (sci_get_char_at(sci, pos) == '\t')
4946 sci_set_selection(sci, pos, pos + 1);
4947 sci_replace_sel(sci, "");
4949 else /* remove spaces only if no tabs */
4951 gint width = sci_get_line_indentation(sci, line);
4953 width -= editor_get_indent_prefs(editor)->width;
4954 sci_set_line_indentation(sci, line, width);
4960 static void editor_change_line_indent(GeanyEditor *editor, gint line, gboolean increase)
4962 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
4963 ScintillaObject *sci = editor->sci;
4965 if (iprefs->type == GEANY_INDENT_TYPE_TABS)
4966 change_tab_indentation(editor, line, increase);
4967 else
4969 gint width = sci_get_line_indentation(sci, line);
4971 width += increase ? iprefs->width : -iprefs->width;
4972 sci_set_line_indentation(sci, line, width);
4977 void editor_indent(GeanyEditor *editor, gboolean increase)
4979 ScintillaObject *sci = editor->sci;
4980 gint start, end;
4981 gint line, lstart, lend;
4983 if (sci_get_lines_selected(sci) <= 1)
4985 line = sci_get_current_line(sci);
4986 editor_change_line_indent(editor, line, increase);
4987 return;
4989 editor_select_lines(editor, FALSE);
4990 start = sci_get_selection_start(sci);
4991 end = sci_get_selection_end(sci);
4992 lstart = sci_get_line_from_position(sci, start);
4993 lend = sci_get_line_from_position(sci, end);
4994 if (end == sci_get_length(sci))
4995 lend++; /* for last line with text on it */
4997 sci_start_undo_action(sci);
4998 for (line = lstart; line < lend; line++)
5000 editor_change_line_indent(editor, line, increase);
5002 sci_end_undo_action(sci);
5004 /* set cursor/selection */
5005 if (lend > lstart)
5007 sci_set_selection_start(sci, start);
5008 end = sci_get_position_from_line(sci, lend);
5009 sci_set_selection_end(sci, end);
5010 editor_select_lines(editor, FALSE);
5012 else
5014 sci_set_current_line(sci, lstart);