Fix 'null' listed in both primary and secondary keyword lists.
[geany-mirror.git] / src / editor.c
blob886fddaf7c6e7075a6537e04fe2e6ddcad3c6d95
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 #ifdef HAVE_REGEX_H
48 # include <regex.h>
49 #else
50 # include "gnuregex.h"
51 #endif
53 #include "support.h"
54 #include "editor.h"
55 #include "document.h"
56 #include "documentprivate.h"
57 #include "filetypes.h"
58 #include "sciwrappers.h"
59 #include "ui_utils.h"
60 #include "utils.h"
61 #include "dialogs.h"
62 #include "symbols.h"
63 #include "callbacks.h"
64 #include "templates.h"
65 #include "keybindings.h"
66 #include "project.h"
67 #include "projectprivate.h"
70 /* Note: use sciwrappers.h instead where possible.
71 * Do not use SSM in files unrelated to scintilla. */
72 #define SSM(s, m, w, l) scintilla_send_message(s, m, w, l)
75 static GHashTable *snippet_hash = NULL;
76 static GQueue *snippet_offsets = NULL;
77 static gint snippet_cursor_insert_pos;
79 /* holds word under the mouse or keyboard cursor */
80 static gchar current_word[GEANY_MAX_WORD_LENGTH];
82 /* Initialised in keyfile.c. */
83 GeanyEditorPrefs editor_prefs;
85 EditorInfo editor_info = {current_word, -1};
87 static struct
89 gchar *text;
90 gboolean set;
91 gchar *last_word;
92 guint tag_index;
93 gint pos;
94 ScintillaObject *sci;
95 } calltip = {NULL, FALSE, NULL, 0, 0, NULL};
97 static enum
99 AUTOC_CANCELLED,
100 AUTOC_SCOPE,
101 AUTOC_TAGS,
102 AUTOC_DOC_WORDS
103 } autocompletion_mode = AUTOC_CANCELLED;
105 static gchar indent[100];
108 static void on_new_line_added(GeanyEditor *editor);
109 static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch);
110 static void insert_indent_after_line(GeanyEditor *editor, gint line);
111 static void auto_multiline(GeanyEditor *editor, gint pos);
112 static gboolean is_code_style(gint lexer, gint style);
113 static gboolean is_string_style(gint lexer, gint style);
114 static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c);
115 static void auto_table(GeanyEditor *editor, gint pos);
116 static void close_block(GeanyEditor *editor, gint pos);
117 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos);
118 static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, size_t wordlen,
119 const gchar *wc, gboolean stem);
120 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent);
123 void editor_snippets_free(void)
125 g_hash_table_destroy(snippet_hash);
126 g_queue_free(snippet_offsets);
130 void editor_snippets_init(void)
132 gsize i, j, len = 0, len_keys = 0;
133 gchar *sysconfigfile, *userconfigfile;
134 gchar **groups_user, **groups_sys;
135 gchar **keys_user, **keys_sys;
136 gchar *value;
137 GKeyFile *sysconfig = g_key_file_new();
138 GKeyFile *userconfig = g_key_file_new();
139 GHashTable *tmp;
141 snippet_offsets = g_queue_new();
143 sysconfigfile = g_strconcat(app->datadir, G_DIR_SEPARATOR_S, "snippets.conf", NULL);
144 userconfigfile = g_strconcat(app->configdir, G_DIR_SEPARATOR_S, "snippets.conf", NULL);
146 /* check for old autocomplete.conf files (backwards compatibility) */
147 if (! g_file_test(userconfigfile, G_FILE_TEST_IS_REGULAR | G_FILE_TEST_IS_SYMLINK))
148 setptr(userconfigfile,
149 g_strconcat(app->configdir, G_DIR_SEPARATOR_S, "autocomplete.conf", NULL));
151 /* load the actual config files */
152 g_key_file_load_from_file(sysconfig, sysconfigfile, G_KEY_FILE_NONE, NULL);
153 g_key_file_load_from_file(userconfig, userconfigfile, G_KEY_FILE_NONE, NULL);
155 /* keys are strings, values are GHashTables, so use g_free and g_hash_table_destroy */
156 snippet_hash =
157 g_hash_table_new_full(g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_hash_table_destroy);
159 /* first read all globally defined auto completions */
160 groups_sys = g_key_file_get_groups(sysconfig, &len);
161 for (i = 0; i < len; i++)
163 keys_sys = g_key_file_get_keys(sysconfig, groups_sys[i], &len_keys, NULL);
164 /* create new hash table for the read section (=> filetype) */
165 tmp = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
166 g_hash_table_insert(snippet_hash, g_strdup(groups_sys[i]), tmp);
168 for (j = 0; j < len_keys; j++)
170 g_hash_table_insert(tmp, g_strdup(keys_sys[j]),
171 utils_get_setting_string(sysconfig, groups_sys[i], keys_sys[j], ""));
173 g_strfreev(keys_sys);
176 /* now read defined completions in user's configuration directory and add / replace them */
177 groups_user = g_key_file_get_groups(userconfig, &len);
178 for (i = 0; i < len; i++)
180 keys_user = g_key_file_get_keys(userconfig, groups_user[i], &len_keys, NULL);
182 tmp = g_hash_table_lookup(snippet_hash, groups_user[i]);
183 if (tmp == NULL)
184 { /* new key found, create hash table */
185 tmp = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
186 g_hash_table_insert(snippet_hash, g_strdup(groups_user[i]), tmp);
188 for (j = 0; j < len_keys; j++)
190 value = g_hash_table_lookup(tmp, keys_user[j]);
191 if (value == NULL)
192 { /* value = NULL means the key doesn't yet exist, so insert */
193 g_hash_table_insert(tmp, g_strdup(keys_user[j]),
194 utils_get_setting_string(userconfig, groups_user[i], keys_user[j], ""));
196 else
197 { /* old key and value will be freed by destroy function (g_free) */
198 g_hash_table_replace(tmp, g_strdup(keys_user[j]),
199 utils_get_setting_string(userconfig, groups_user[i], keys_user[j], ""));
202 g_strfreev(keys_user);
205 g_free(sysconfigfile);
206 g_free(userconfigfile);
207 g_strfreev(groups_sys);
208 g_strfreev(groups_user);
209 g_key_file_free(sysconfig);
210 g_key_file_free(userconfig);
214 static gboolean on_editor_button_press_event(GtkWidget *widget, GdkEventButton *event,
215 gpointer data)
217 GeanyEditor *editor = data;
218 GeanyDocument *doc = editor->document;
220 /* it's very unlikely we got a 'real' click even on 0, 0, so assume it is a
221 * fake event to show the editor menu triggered by a key event where we want to use the
222 * text cursor position. */
223 if (event->x > 0.0 && event->y > 0.0)
224 editor_info.click_pos = sci_get_position_from_xy(editor->sci,
225 (gint)event->x, (gint)event->y, FALSE);
226 else
227 editor_info.click_pos = sci_get_current_position(editor->sci);
229 if (event->button == 1)
231 guint state = event->state & gtk_accelerator_get_default_mod_mask();
233 if (event->type == GDK_BUTTON_PRESS && editor_prefs.disable_dnd)
235 gint ss = sci_get_selection_start(editor->sci);
236 sci_set_selection_end(editor->sci, ss);
238 if (event->type == GDK_BUTTON_PRESS && state == GDK_CONTROL_MASK)
240 sci_set_current_position(editor->sci, editor_info.click_pos, FALSE);
242 editor_find_current_word(editor, editor_info.click_pos,
243 current_word, sizeof current_word, NULL);
244 if (*current_word)
245 return symbols_goto_tag(current_word, TRUE);
246 else
247 keybindings_send_command(GEANY_KEY_GROUP_GOTO, GEANY_KEYS_GOTO_MATCHINGBRACE);
248 return TRUE;
250 return document_check_disk_status(doc, FALSE);
253 /* calls the edit popup menu in the editor */
254 if (event->button == 3)
256 gboolean can_goto;
258 editor_find_current_word(editor, editor_info.click_pos,
259 current_word, sizeof current_word, NULL);
261 can_goto = sci_has_selection(editor->sci) || current_word[0] != '\0';
262 ui_update_popup_goto_items(can_goto);
263 ui_update_popup_copy_items(doc);
264 ui_update_insert_include_item(doc, 0);
266 g_signal_emit_by_name(geany_object, "update-editor-menu",
267 current_word, editor_info.click_pos, doc);
269 gtk_menu_popup(GTK_MENU(main_widgets.editor_menu),
270 NULL, NULL, NULL, NULL, event->button, event->time);
272 return TRUE;
274 return FALSE;
278 static gboolean is_style_php(gint style)
280 if ((style >= SCE_HPHP_DEFAULT && style <= SCE_HPHP_OPERATOR) ||
281 style == SCE_HPHP_COMPLEX_VARIABLE)
283 return TRUE;
286 return FALSE;
290 gint editor_get_long_line_type(void)
292 if (app->project)
293 switch (app->project->long_line_behaviour)
295 case 0: /* marker disabled */
296 return 2;
297 case 1: /* use global settings */
298 break;
299 case 2: /* custom (enabled) */
300 return editor_prefs.long_line_global_type;
303 if (!editor_prefs.long_line_global_enabled)
304 return 2;
305 else
306 return editor_prefs.long_line_global_type;
310 gint editor_get_long_line_column(void)
312 if (app->project && app->project->long_line_behaviour != 1 /* use global settings */)
313 return app->project->long_line_column;
314 else
315 return editor_prefs.long_line_global_column;
319 void editor_toggle_fold(GeanyEditor *editor, gint line, gint modifiers)
321 ScintillaObject *sci;
323 g_return_if_fail(editor != NULL);
325 sci = editor->sci;
327 sci_toggle_fold(sci, line);
329 /* extra toggling of child fold points
330 * use when editor_prefs.unfold_all_children is set and Shift is NOT pressed or when
331 * editor_prefs.unfold_all_children is NOT set but Shift is pressed */
332 if ((editor_prefs.unfold_all_children && ! (modifiers & SCMOD_SHIFT)) ||
333 (! editor_prefs.unfold_all_children && (modifiers & SCMOD_SHIFT)))
335 gint last_line = SSM(sci, SCI_GETLASTCHILD, line, -1);
336 gint i;
338 if (sci_get_line_is_visible(sci, line + 1))
339 { /* unfold all children of the current fold point */
340 for (i = line; i < last_line; i++)
342 if (! sci_get_line_is_visible(sci, i))
344 sci_toggle_fold(sci, sci_get_fold_parent(sci, i));
348 else
349 { /* fold all children of the current fold point */
350 for (i = line; i < last_line; i++)
352 gint level = sci_get_fold_level(sci, i);
353 if (level & SC_FOLDLEVELHEADERFLAG)
355 if (sci_get_fold_expanded(sci, i))
356 sci_toggle_fold(sci, i);
364 static void on_margin_click(GeanyEditor *editor, SCNotification *nt)
366 /* left click to marker margin marks the line */
367 if (nt->margin == 1)
369 gint line = sci_get_line_from_position(editor->sci, nt->position);
371 /*sci_marker_delete_all(editor->sci, 1);*/
372 sci_toggle_marker_at_line(editor->sci, line, 1); /* toggle the marker */
374 /* left click on the folding margin to toggle folding state of current line */
375 else if (nt->margin == 2 && editor_prefs.folding)
377 gint line = sci_get_line_from_position(editor->sci, nt->position);
378 editor_toggle_fold(editor, line, nt->modifiers);
383 static void on_update_ui(GeanyEditor *editor, G_GNUC_UNUSED SCNotification *nt)
385 ScintillaObject *sci = editor->sci;
386 gint pos = sci_get_current_position(sci);
388 /* undo / redo menu update */
389 ui_update_popup_reundo_items(editor->document);
391 /* brace highlighting */
392 editor_highlight_braces(editor, pos);
394 ui_update_statusbar(editor->document, pos);
396 /* Visible lines are only laid out accurately once [SCN_UPDATEUI] is sent,
397 * so we need to only call sci_scroll_to_line here, because the document
398 * may have line wrapping and folding enabled.
399 * http://scintilla.sourceforge.net/ScintillaDoc.html#LineWrapping */
400 if (editor->scroll_percent > 0.0F)
402 editor_scroll_to_line(editor, -1, editor->scroll_percent);
403 editor->scroll_percent = -1.0F; /* disable further scrolling */
405 #if 0
406 /** experimental code for inverting selections */
408 gint i;
409 for (i = SSM(sci, SCI_GETSELECTIONSTART, 0, 0); i < SSM(sci, SCI_GETSELECTIONEND, 0, 0); i++)
411 /* need to get colour from getstyleat(), but how? */
412 SSM(sci, SCI_STYLESETFORE, STYLE_DEFAULT, 0);
413 SSM(sci, SCI_STYLESETBACK, STYLE_DEFAULT, 0);
416 sci_get_style_at(sci, pos);
418 #endif
422 static void check_line_breaking(GeanyEditor *editor, gint pos, gchar c)
424 ScintillaObject *sci = editor->sci;
425 gint line, lstart, col;
427 if (!editor->line_breaking)
428 return;
430 col = sci_get_col_from_position(sci, pos);
432 if (c == GDK_space)
433 pos--; /* Look for previous space, not the new one */
435 line = sci_get_current_line(sci);
437 lstart = sci_get_position_from_line(sci, line);
439 /* use column instead of position which might be different with multibyte characters */
440 if (col < editor_prefs.line_break_column)
441 return;
443 /* look for the last space before line_break_column */
444 pos = MIN(pos, lstart + editor_prefs.line_break_column);
446 while (pos > lstart)
448 c = sci_get_char_at(sci, --pos);
449 if (c == GDK_space)
451 gint diff, last_pos, last_col;
452 const gchar *eol = editor_get_eol_char(editor);
454 /* remember the distance between the current column and the last column on the line
455 * (we use column position in case the previous line gets altered, such as removing
456 * trailing spaces or in case it contains multibyte characters) */
457 last_pos = sci_get_line_end_position(sci, line);
458 last_col = sci_get_col_from_position(sci, last_pos);
459 diff = last_col - col;
461 /* break the line after the space */
462 sci_insert_text(sci, pos + 1, eol);
463 line++;
465 /* set position as if user had pressed return */
466 pos = sci_get_position_from_line(sci, line);
467 sci_set_current_position(sci, pos, FALSE);
468 /* add indentation, comment multilines, etc */
469 on_new_line_added(editor);
471 /* correct cursor position (might not be at line end) */
472 last_pos = sci_get_line_end_position(sci, line);
473 last_col = sci_get_col_from_position(sci, last_pos); /* get last column on line */
474 /* last column - distance is the desired column, then retrieve its document position */
475 pos = SSM(sci, SCI_FINDCOLUMN, line, last_col - diff);
476 sci_set_current_position(sci, pos, FALSE);
478 return;
484 static void show_autocomplete(ScintillaObject *sci, gint rootlen, const gchar *words)
486 /* store whether a calltip is showing, so we can reshow it after autocompletion */
487 calltip.set = SSM(sci, SCI_CALLTIPACTIVE, 0, 0);
488 SSM(sci, SCI_AUTOCSHOW, rootlen, (sptr_t) words);
492 static void show_tags_list(GeanyEditor *editor, const GPtrArray *tags, gsize rootlen)
494 ScintillaObject *sci = editor->sci;
496 g_return_if_fail(tags);
498 if (tags->len > 0)
500 GString *words = g_string_sized_new(150);
501 guint j;
503 for (j = 0; j < tags->len; ++j)
505 TMTag *tag = tags->pdata[j];
507 if (j > 0)
508 g_string_append_c(words, '\n');
510 if (j == editor_prefs.autocompletion_max_entries)
512 g_string_append(words, "...");
513 break;
515 g_string_append(words, tag->name);
517 /* for now, tag types don't all follow C, so just look at arglist */
518 if (NZV(tag->atts.entry.arglist))
519 g_string_append(words, "?2");
520 else
521 g_string_append(words, "?1");
523 show_autocomplete(sci, rootlen, words->str);
524 g_string_free(words, TRUE);
529 /* do not use with long strings */
530 static gboolean match_last_chars(ScintillaObject *sci, gint pos, const gchar *str)
532 gsize len = strlen(str);
533 gchar *buf;
535 g_return_val_if_fail(len < 100, FALSE);
537 buf = g_alloca(len + 1);
538 sci_get_text_range(sci, pos - len, pos, buf);
539 return strcmp(str, buf) == 0;
543 static gboolean reshow_calltip(gpointer data)
545 GeanyDocument *doc;
547 g_return_val_if_fail(calltip.sci != NULL, FALSE);
549 SSM(calltip.sci, SCI_CALLTIPCANCEL, 0, 0);
550 doc = document_get_current();
552 if (doc && doc->editor->sci == calltip.sci)
554 /* we use the position where the calltip was previously started as SCI_GETCURRENTPOS
555 * may be completely wrong in case the user cancelled the auto completion with the mouse */
556 SSM(calltip.sci, SCI_CALLTIPSHOW, calltip.pos, (sptr_t) calltip.text);
558 return FALSE;
562 static void request_reshowing_calltip(SCNotification *nt)
564 if (calltip.set)
566 /* delay the reshow of the calltip window to make sure it is actually displayed,
567 * without it might be not visible on SCN_AUTOCCANCEL */
568 g_idle_add(reshow_calltip, NULL);
573 static void autocomplete_scope(GeanyEditor *editor)
575 ScintillaObject *sci = editor->sci;
576 gint pos = sci_get_current_position(editor->sci);
577 gchar typed = sci_get_char_at(sci, pos - 1);
578 gchar *name;
579 const GPtrArray *tags = NULL;
580 const TMTag *tag;
581 GeanyFiletype *ft = editor->document->file_type;
583 if (ft->id == GEANY_FILETYPES_C || ft->id == GEANY_FILETYPES_CPP)
585 if (match_last_chars(sci, pos, "->") || match_last_chars(sci, pos, "::"))
586 pos--;
587 else if (typed != '.')
588 return;
590 else if (typed != '.')
591 return;
593 /* allow for a space between word and operator */
594 if (isspace(sci_get_char_at(sci, pos - 2)))
595 pos--;
596 name = editor_get_word_at_pos(editor, pos - 1, NULL);
597 if (!name)
598 return;
600 tags = tm_workspace_find(name, tm_tag_max_t, NULL, FALSE, ft->lang);
601 g_free(name);
602 if (!tags || tags->len == 0)
603 return;
605 tag = g_ptr_array_index(tags, 0);
606 name = tag->atts.entry.var_type;
607 if (name)
609 TMWorkObject *obj = editor->document->tm_file;
611 tags = tm_workspace_find_scope_members(obj ? obj->tags_array : NULL,
612 name, TRUE, FALSE);
613 if (tags)
615 autocompletion_mode = AUTOC_SCOPE;
616 show_tags_list(editor, tags, 0);
622 static void on_char_added(GeanyEditor *editor, SCNotification *nt)
624 ScintillaObject *sci = editor->sci;
625 gint pos = sci_get_current_position(sci);
627 switch (nt->ch)
629 case '\r':
630 { /* simple indentation (only for CR format) */
631 if (sci_get_eol_mode(sci) == SC_EOL_CR)
632 on_new_line_added(editor);
633 break;
635 case '\n':
636 { /* simple indentation (for CR/LF and LF format) */
637 on_new_line_added(editor);
638 break;
640 case '>':
641 editor_start_auto_complete(editor, pos, FALSE); /* C/C++ ptr-> scope completion */
642 /* fall through */
643 case '/':
644 { /* close xml-tags */
645 handle_xml(editor, pos, nt->ch);
646 break;
648 case '(':
650 auto_close_chars(sci, pos, nt->ch);
651 /* show calltips */
652 editor_show_calltip(editor, --pos);
653 break;
655 case ')':
656 { /* hide calltips */
657 if (SSM(sci, SCI_CALLTIPACTIVE, 0, 0))
659 SSM(sci, SCI_CALLTIPCANCEL, 0, 0);
661 g_free(calltip.text);
662 calltip.text = NULL;
663 calltip.pos = 0;
664 calltip.sci = NULL;
665 calltip.set = FALSE;
666 break;
668 case '{':
669 case '[':
670 case '"':
671 case '\'':
673 auto_close_chars(sci, pos, nt->ch);
674 break;
676 case '}':
677 { /* closing bracket handling */
678 if (editor->auto_indent)
679 close_block(editor, pos - 1);
680 break;
682 /* scope autocompletion */
683 case '.':
684 case ':': /* C/C++ class:: syntax */
685 /* tag autocompletion */
686 default:
687 #if 0
688 if (! editor_start_auto_complete(editor, pos, FALSE))
689 request_reshowing_calltip(nt);
690 #else
691 editor_start_auto_complete(editor, pos, FALSE);
692 #endif
694 check_line_breaking(editor, pos, nt->ch);
698 /* expand() and fold_changed() are copied from SciTE (thanks) to fix #1923350. */
699 static void expand(ScintillaObject *sci, gint *line, gboolean doExpand,
700 gboolean force, gint visLevels, gint level)
702 gint lineMaxSubord = SSM(sci, SCI_GETLASTCHILD, *line, level & SC_FOLDLEVELNUMBERMASK);
703 gint levelLine = level;
704 (*line)++;
705 while (*line <= lineMaxSubord)
707 if (G_UNLIKELY(force))
709 if (visLevels > 0)
710 SSM(sci, SCI_SHOWLINES, *line, *line);
711 else
712 SSM(sci, SCI_HIDELINES, *line, *line);
714 else
716 if (doExpand)
717 SSM(sci, SCI_SHOWLINES, *line, *line);
719 if (levelLine == -1)
720 levelLine = SSM(sci, SCI_GETFOLDLEVEL, *line, 0);
721 if (levelLine & SC_FOLDLEVELHEADERFLAG)
723 if (G_UNLIKELY(force))
725 if (visLevels > 1)
726 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
727 else
728 SSM(sci, SCI_SETFOLDEXPANDED, *line, 0);
729 expand(sci, line, doExpand, force, visLevels - 1, -1);
731 else
733 if (doExpand)
735 if (!sci_get_fold_expanded(sci, *line))
736 SSM(sci, SCI_SETFOLDEXPANDED, *line, 1);
737 expand(sci, line, TRUE, force, visLevels - 1, -1);
739 else
741 expand(sci, line, FALSE, force, visLevels - 1, -1);
745 else
747 (*line)++;
753 static void fold_changed(ScintillaObject *sci, gint line, gint levelNow, gint levelPrev)
755 if (levelNow & SC_FOLDLEVELHEADERFLAG)
757 if (! (levelPrev & SC_FOLDLEVELHEADERFLAG))
759 /* Adding a fold point */
760 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
761 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
764 else if (levelPrev & SC_FOLDLEVELHEADERFLAG)
766 if (! sci_get_fold_expanded(sci, line))
767 { /* Removing the fold from one that has been contracted so should expand
768 * otherwise lines are left invisible with no way to make them visible */
769 SSM(sci, SCI_SETFOLDEXPANDED, line, 1);
770 expand(sci, &line, TRUE, FALSE, 0, levelPrev);
773 if (! (levelNow & SC_FOLDLEVELWHITEFLAG) &&
774 ((levelPrev & SC_FOLDLEVELNUMBERMASK) > (levelNow & SC_FOLDLEVELNUMBERMASK)))
776 /* See if should still be hidden */
777 gint parentLine = sci_get_fold_parent(sci, line);
778 if (parentLine < 0)
780 SSM(sci, SCI_SHOWLINES, line, line);
782 else if (sci_get_fold_expanded(sci, parentLine) &&
783 sci_get_line_is_visible(sci, parentLine))
785 SSM(sci, SCI_SHOWLINES, line, line);
791 static void ensure_range_visible(ScintillaObject *sci, gint posStart, gint posEnd,
792 gboolean enforcePolicy)
794 gint lineStart = sci_get_line_from_position(sci, MIN(posStart, posEnd));
795 gint lineEnd = sci_get_line_from_position(sci, MAX(posStart, posEnd));
796 gint line;
798 for (line = lineStart; line <= lineEnd; line++)
800 SSM(sci, enforcePolicy ? SCI_ENSUREVISIBLEENFORCEPOLICY : SCI_ENSUREVISIBLE, line, 0);
805 static void auto_update_margin_width(GeanyEditor *editor)
807 gint next_linecount = 1;
808 gint linecount = sci_get_line_count(editor->sci);
809 GeanyDocument *doc = editor->document;
811 while (next_linecount <= linecount)
812 next_linecount *= 10;
814 if (editor->document->priv->line_count != next_linecount)
816 doc->priv->line_count = next_linecount;
817 sci_set_line_numbers(editor->sci, TRUE, 0);
822 static void partial_complete(ScintillaObject *sci, const gchar *text)
824 gint pos = sci_get_current_position(sci);
826 sci_insert_text(sci, pos, text);
827 sci_set_current_position(sci, pos + strlen(text), TRUE);
831 /* Complete the next word part from @a entry */
832 static gboolean check_partial_completion(GeanyEditor *editor, const gchar *entry)
834 gchar *stem, *ptr, *text = utils_strdupa(entry);
836 read_current_word(editor, -1, current_word, sizeof current_word, NULL, TRUE);
837 stem = current_word;
838 if (strstr(text, stem) != text)
839 return FALSE; /* shouldn't happen */
840 if (strlen(text) <= strlen(stem))
841 return FALSE;
843 text += strlen(stem); /* skip stem */
844 ptr = strstr(text + 1, "_");
845 if (ptr)
847 ptr[1] = '\0';
848 partial_complete(editor->sci, text);
849 return TRUE;
851 else
853 /* CamelCase */
854 foreach_str(ptr, text + 1)
856 if (!ptr[0])
857 break;
858 if (g_ascii_isupper(*ptr) && g_ascii_islower(ptr[1]))
860 ptr[0] = '\0';
861 partial_complete(editor->sci, text);
862 return TRUE;
866 return FALSE;
870 /* Callback for the "sci-notify" signal to emit a "editor-notify" signal.
871 * Plugins can connect to the "editor-notify" signal. */
872 void editor_sci_notify_cb(G_GNUC_UNUSED GtkWidget *widget, G_GNUC_UNUSED gint scn,
873 gpointer scnt, gpointer data)
875 GeanyEditor *editor = data;
876 gboolean retval;
878 g_return_if_fail(editor != NULL);
880 g_signal_emit_by_name(geany_object, "editor-notify", editor, scnt, &retval);
884 static gboolean on_editor_notify(G_GNUC_UNUSED GObject *object, GeanyEditor *editor,
885 SCNotification *nt, G_GNUC_UNUSED gpointer data)
887 ScintillaObject *sci = editor->sci;
888 GeanyDocument *doc = editor->document;
890 switch (nt->nmhdr.code)
892 case SCN_SAVEPOINTLEFT:
893 document_set_text_changed(doc, TRUE);
894 break;
896 case SCN_SAVEPOINTREACHED:
897 document_set_text_changed(doc, FALSE);
898 break;
900 case SCN_MODIFYATTEMPTRO:
901 utils_beep();
902 break;
904 case SCN_MARGINCLICK:
905 on_margin_click(editor, nt);
906 break;
908 case SCN_UPDATEUI:
909 on_update_ui(editor, nt);
910 break;
912 case SCN_MODIFIED:
913 if (editor_prefs.show_linenumber_margin && (nt->modificationType & (SC_MOD_INSERTTEXT | SC_MOD_DELETETEXT)) && nt->linesAdded)
915 /* automatically adjust Scintilla's line numbers margin width */
916 auto_update_margin_width(editor);
918 if (nt->modificationType & SC_STARTACTION && ! ignore_callback)
920 /* get notified about undo changes */
921 document_undo_add(doc, UNDO_SCINTILLA, NULL);
923 if (editor_prefs.folding && (nt->modificationType & SC_MOD_CHANGEFOLD) != 0)
925 /* handle special fold cases, e.g. #1923350 */
926 fold_changed(sci, nt->line, nt->foldLevelNow, nt->foldLevelPrev);
928 break;
930 case SCN_CHARADDED:
931 on_char_added(editor, nt);
932 break;
934 case SCN_USERLISTSELECTION:
935 if (nt->listType == 1)
937 sci_add_text(sci, nt->text);
939 break;
941 case SCN_AUTOCSELECTION:
942 if (g_str_equal(nt->text, "..."))
944 sci_cancel(sci);
945 utils_beep();
946 break;
948 /* fall through */
949 case SCN_AUTOCCANCELLED:
950 /* now that autocomplete is finishing or was cancelled, reshow calltips
951 * if they were showing */
952 autocompletion_mode = AUTOC_CANCELLED;
953 request_reshowing_calltip(nt);
954 break;
956 #ifdef GEANY_DEBUG
957 case SCN_STYLENEEDED:
958 geany_debug("style");
959 break;
960 #endif
961 case SCN_NEEDSHOWN:
962 ensure_range_visible(sci, nt->position, nt->position + nt->length, FALSE);
963 break;
965 case SCN_URIDROPPED:
966 if (nt->text != NULL)
968 document_open_file_list(nt->text, -1);
970 break;
972 case SCN_CALLTIPCLICK:
973 if (nt->position > 0)
975 switch (nt->position)
977 case 1: /* up arrow */
978 if (calltip.tag_index > 0)
979 calltip.tag_index--;
980 break;
982 case 2: calltip.tag_index++; break; /* down arrow */
984 editor_show_calltip(editor, -1);
986 break;
988 case SCN_ZOOM:
989 /* recalculate line margin width */
990 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin, 0);
991 break;
993 /* we always return FALSE here to let plugins handle the event too */
994 return FALSE;
998 /* Note: this is the same as sci_get_tab_width(), but is still useful when you don't have
999 * a scintilla pointer. */
1000 static gint get_tab_width(const GeanyIndentPrefs *indent_prefs)
1002 if (indent_prefs->type == GEANY_INDENT_TYPE_BOTH)
1003 return indent_prefs->hard_tab_width;
1005 return indent_prefs->width; /* tab width = indent width */
1009 /* Returns a string containing width chars of whitespace, filled with simple space
1010 * characters or with the right number of tab characters, according to the indent prefs.
1011 * (Result is filled with tabs *and* spaces if width isn't a multiple of
1012 * the tab width). */
1013 static gchar *
1014 get_whitespace(const GeanyIndentPrefs *iprefs, gint width)
1016 g_return_val_if_fail(width >= 0, NULL);
1018 if (width == 0)
1019 return g_strdup("");
1021 if (iprefs->type == GEANY_INDENT_TYPE_SPACES)
1023 return g_strnfill(width, ' ');
1025 else
1026 { /* first fill text with tabs and fill the rest with spaces */
1027 const gint tab_width = get_tab_width(iprefs);
1028 gint tabs = width / tab_width;
1029 gint spaces = width % tab_width;
1030 gint len = tabs + spaces;
1031 gchar *str;
1033 str = g_malloc(len + 1);
1035 memset(str, '\t', tabs);
1036 memset(str + tabs, ' ', spaces);
1037 str[len] = '\0';
1038 return str;
1043 static const GeanyIndentPrefs *
1044 get_default_indent_prefs(void)
1046 static GeanyIndentPrefs iprefs;
1048 iprefs = app->project ? *app->project->priv->indentation : *editor_prefs.indentation;
1049 return &iprefs;
1053 /** Gets the indentation prefs for the editor.
1054 * In future, the prefs might be different according to project or filetype.
1055 * @warning Always get a fresh result instead of keeping a pointer to it if the editor
1056 * settings may have changed, or if this function has been called for a different @a editor.
1057 * @param editor The editor, or @c NULL to get the default indent prefs.
1058 * @return The indent prefs. */
1059 const GeanyIndentPrefs *
1060 editor_get_indent_prefs(GeanyEditor *editor)
1062 static GeanyIndentPrefs iprefs;
1064 iprefs = *get_default_indent_prefs();
1066 if (editor == NULL)
1067 return &iprefs;
1069 iprefs.type = editor->indent_type;
1071 /* if per-document auto-indent is enabled, but we don't have a global mode set,
1072 * just use basic auto-indenting */
1073 if (editor->auto_indent && iprefs.auto_indent_mode == GEANY_AUTOINDENT_NONE)
1074 iprefs.auto_indent_mode = GEANY_AUTOINDENT_BASIC;
1076 if (!editor->auto_indent)
1077 iprefs.auto_indent_mode = GEANY_AUTOINDENT_NONE;
1079 return &iprefs;
1083 static void on_new_line_added(GeanyEditor *editor)
1085 ScintillaObject *sci = editor->sci;
1086 gint line = sci_get_current_line(sci);
1088 /* simple indentation */
1089 if (editor->auto_indent)
1091 insert_indent_after_line(editor, line - 1);
1094 if (editor_prefs.auto_continue_multiline)
1095 { /* " * " auto completion in multiline C/C++/D/Java comments */
1096 auto_multiline(editor, line);
1099 if (editor_prefs.newline_strip)
1100 { /* strip the trailing spaces on the previous line */
1101 editor_strip_line_trailing_spaces(editor, line - 1);
1106 static gboolean lexer_has_braces(ScintillaObject *sci)
1108 gint lexer = sci_get_lexer(sci);
1110 switch (lexer)
1112 case SCLEX_CPP:
1113 case SCLEX_D:
1114 case SCLEX_HTML: /* for PHP & JS */
1115 case SCLEX_PASCAL: /* for multiline comments? */
1116 case SCLEX_BASH:
1117 case SCLEX_PERL:
1118 case SCLEX_TCL:
1119 return TRUE;
1120 default:
1121 return FALSE;
1126 /* Read indent chars for the line that pos is on into indent global variable.
1127 * Note: Use sci_get_line_indentation() and get_whitespace()/editor_insert_text_block()
1128 * instead in any new code. */
1129 static void read_indent(GeanyEditor *editor, gint pos)
1131 ScintillaObject *sci = editor->sci;
1132 guint i, len, j = 0;
1133 gint line;
1134 gchar *linebuf;
1136 line = sci_get_line_from_position(sci, pos);
1138 len = sci_get_line_length(sci, line);
1139 linebuf = sci_get_line(sci, line);
1141 for (i = 0; i < len && j <= (sizeof(indent) - 1); i++)
1143 if (linebuf[i] == ' ' || linebuf[i] == '\t') /* simple indentation */
1144 indent[j++] = linebuf[i];
1145 else
1146 break;
1148 indent[j] = '\0';
1149 g_free(linebuf);
1153 static gint get_brace_indent(ScintillaObject *sci, gint line)
1155 guint i, len;
1156 gint ret = 0;
1157 gchar *linebuf;
1159 len = sci_get_line_length(sci, line);
1160 linebuf = sci_get_line(sci, line);
1162 for (i = 0; i < len; i++)
1164 /* i == (len - 1) prevents wrong indentation after lines like
1165 * " { return bless({}, shift); }" (Perl) */
1166 if (linebuf[i] == '{' && i == (len - 1))
1168 ret++;
1169 break;
1171 else
1173 gint k = len - 1;
1175 while (k > 0 && isspace(linebuf[k])) k--;
1177 /* if last non-whitespace character is a { increase indentation by a tab
1178 * e.g. for (...) { */
1179 if (linebuf[k] == '{')
1181 ret++;
1183 break;
1186 g_free(linebuf);
1187 return ret;
1191 static gint get_python_indent(ScintillaObject *sci, gint line)
1193 gint last_char = sci_get_line_end_position(sci, line) - 1;
1195 /* add extra indentation for Python after colon */
1196 if (sci_get_char_at(sci, last_char) == ':' &&
1197 sci_get_style_at(sci, last_char) == SCE_P_OPERATOR)
1199 return 1;
1201 return 0;
1205 static gint get_indent_size_after_line(GeanyEditor *editor, gint line)
1207 ScintillaObject *sci = editor->sci;
1208 gint size;
1209 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1211 g_return_val_if_fail(line >= 0, 0);
1213 size = sci_get_line_indentation(sci, line);
1215 if (iprefs->auto_indent_mode > GEANY_AUTOINDENT_BASIC)
1217 if (lexer_has_braces(sci))
1218 size += iprefs->width * get_brace_indent(sci, line);
1219 else
1220 if (FILETYPE_ID(editor->document->file_type) == GEANY_FILETYPES_PYTHON)
1221 size += iprefs->width * get_python_indent(sci, line);
1223 return size;
1227 static void insert_indent_after_line(GeanyEditor *editor, gint line)
1229 ScintillaObject *sci = editor->sci;
1230 gint line_indent = sci_get_line_indentation(sci, line);
1231 gint size = get_indent_size_after_line(editor, line);
1232 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1233 gchar *text;
1235 if (size == 0)
1236 return;
1238 if (iprefs->type == GEANY_INDENT_TYPE_TABS && size == line_indent)
1240 /* support tab indents, space aligns style - copy last line 'indent' exactly */
1241 gint start = sci_get_position_from_line(sci, line);
1242 gint end = sci_get_line_indent_position(sci, line);
1244 text = sci_get_contents_range(sci, start, end);
1246 else
1248 text = get_whitespace(iprefs, size);
1250 sci_add_text(sci, text);
1251 g_free(text);
1255 static void auto_close_chars(ScintillaObject *sci, gint pos, gchar c)
1257 const gchar *closing_char = NULL;
1258 gint end_pos = -1;
1260 if (utils_isbrace(c, 0))
1261 end_pos = sci_find_matching_brace(sci, pos - 1);
1263 switch (c)
1265 case '(':
1266 if ((editor_prefs.autoclose_chars & GEANY_AC_PARENTHESIS) && end_pos == -1)
1267 closing_char = ")";
1268 break;
1269 case '{':
1270 if ((editor_prefs.autoclose_chars & GEANY_AC_CBRACKET) && end_pos == -1)
1271 closing_char = "}";
1272 break;
1273 case '[':
1274 if ((editor_prefs.autoclose_chars & GEANY_AC_SBRACKET) && end_pos == -1)
1275 closing_char = "]";
1276 break;
1277 case '\'':
1278 if (editor_prefs.autoclose_chars & GEANY_AC_SQUOTE)
1279 closing_char = "'";
1280 break;
1281 case '"':
1282 if (editor_prefs.autoclose_chars & GEANY_AC_DQUOTE)
1283 closing_char = "\"";
1284 break;
1287 if (closing_char != NULL)
1289 sci_add_text(sci, closing_char);
1290 sci_set_current_position(sci, pos, TRUE);
1295 /* Finds a corresponding matching brace to the given pos
1296 * (this is taken from Scintilla Editor.cxx,
1297 * fit to work with close_block) */
1298 static gint brace_match(ScintillaObject *sci, gint pos)
1300 gchar chBrace = sci_get_char_at(sci, pos);
1301 gchar chSeek = utils_brace_opposite(chBrace);
1302 gchar chAtPos;
1303 gint direction = -1;
1304 gint styBrace;
1305 gint depth = 1;
1306 gint styAtPos;
1308 styBrace = sci_get_style_at(sci, pos);
1310 if (utils_is_opening_brace(chBrace, editor_prefs.brace_match_ltgt))
1311 direction = 1;
1313 pos = pos + direction;
1314 while ((pos >= 0) && (pos < sci_get_length(sci)))
1316 chAtPos = sci_get_char_at(sci, pos - 1);
1317 styAtPos = sci_get_style_at(sci, pos);
1319 if ((pos > sci_get_end_styled(sci)) || (styAtPos == styBrace))
1321 if (chAtPos == chBrace)
1322 depth++;
1323 if (chAtPos == chSeek)
1324 depth--;
1325 if (depth == 0)
1326 return pos;
1328 pos = pos + direction;
1330 return -1;
1334 /* Called after typing '}'. */
1335 static void close_block(GeanyEditor *editor, gint pos)
1337 GeanyDocument *doc;
1338 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1339 gint x = 0, cnt = 0;
1340 gint line, line_len, eol_char_len;
1341 gchar *text, *line_buf;
1342 ScintillaObject *sci;
1343 gint line_indent, last_indent;
1345 if (iprefs->auto_indent_mode < GEANY_AUTOINDENT_CURRENTCHARS)
1346 return;
1347 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
1349 sci = editor->sci;
1350 doc = editor->document;
1352 if (! lexer_has_braces(sci))
1353 return;
1355 line = sci_get_line_from_position(sci, pos);
1356 line_len = sci_get_line_length(sci, line);
1357 /* set eol_char_len to 0 if on last line, because there is no EOL char */
1358 eol_char_len = (line == (sci_get_line_count(sci) - 1)) ? 0 :
1359 editor_get_eol_char_len(editor);
1361 /* check that the line is empty, to not kill text in the line */
1362 line_buf = sci_get_line(sci, line);
1363 line_buf[line_len - eol_char_len] = '\0';
1364 while (x < (line_len - eol_char_len))
1366 if (isspace(line_buf[x]))
1367 cnt++;
1368 x++;
1370 g_free(line_buf);
1372 if ((line_len - eol_char_len - 1) != cnt)
1373 return;
1375 if (iprefs->auto_indent_mode == GEANY_AUTOINDENT_MATCHBRACES)
1377 gint start_brace = brace_match(sci, pos);
1379 if (start_brace >= 0)
1381 gint line_start;
1382 gint brace_line = sci_get_line_from_position(sci, start_brace);
1383 gint size = sci_get_line_indentation(sci, brace_line);
1384 gchar *ind = get_whitespace(iprefs, size);
1386 text = g_strconcat(ind, "}", NULL);
1387 line_start = sci_get_position_from_line(sci, line);
1388 sci_set_anchor(sci, line_start);
1389 sci_replace_sel(sci, text);
1390 g_free(text);
1391 g_free(ind);
1392 return;
1394 /* fall through - unmatched brace (possibly because of TCL, PHP lexer bugs) */
1397 /* GEANY_AUTOINDENT_CURRENTCHARS */
1398 line_indent = sci_get_line_indentation(sci, line);
1399 last_indent = sci_get_line_indentation(sci, line - 1);
1401 if (line_indent < last_indent)
1402 return;
1403 line_indent -= iprefs->width;
1404 line_indent = MAX(0, line_indent);
1405 sci_set_line_indentation(sci, line, line_indent);
1409 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1410 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1411 * position can be -1, then the current position is used.
1412 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1413 static void read_current_word(GeanyEditor *editor, gint pos, gchar *word, size_t wordlen,
1414 const gchar *wc, gboolean stem)
1416 gint line, line_start, startword, endword;
1417 gchar *chunk;
1418 ScintillaObject *sci;
1420 g_return_if_fail(editor != NULL);
1421 sci = editor->sci;
1423 if (pos == -1)
1424 pos = sci_get_current_position(sci);
1426 line = sci_get_line_from_position(sci, pos);
1427 line_start = sci_get_position_from_line(sci, line);
1428 startword = pos - line_start;
1429 endword = pos - line_start;
1431 word[0] = '\0';
1432 chunk = sci_get_line(sci, line);
1434 if (wc == NULL)
1435 wc = GEANY_WORDCHARS;
1437 /* the checks for "c < 0" are to allow any Unicode character which should make the code
1438 * a little bit more Unicode safe, anyway, this allows also any Unicode punctuation,
1439 * TODO: improve this code */
1440 while (startword > 0 && (strchr(wc, chunk[startword - 1]) || chunk[startword - 1] < 0))
1441 startword--;
1442 if (!stem)
1444 while (chunk[endword] != 0 && (strchr(wc, chunk[endword]) || chunk[endword] < 0))
1445 endword++;
1448 if (startword != endword)
1450 chunk[endword] = '\0';
1452 g_strlcpy(word, chunk + startword, wordlen); /* ensure null terminated */
1454 else
1455 g_strlcpy(word, "", wordlen);
1457 g_free(chunk);
1461 /* Reads the word at given cursor position and writes it into the given buffer. The buffer will be
1462 * NULL terminated in any case, even when the word is truncated because wordlen is too small.
1463 * position can be -1, then the current position is used.
1464 * wc are the wordchars to use, if NULL, GEANY_WORDCHARS will be used */
1465 void editor_find_current_word(GeanyEditor *editor, gint pos, gchar *word, size_t wordlen,
1466 const gchar *wc)
1468 read_current_word(editor, pos, word, wordlen, wc, FALSE);
1473 * Finds the word at the position specified by @a pos. If any word is found, it is returned.
1474 * Otherwise NULL is returned.
1475 * Additional wordchars can be specified to define what to consider as a word.
1477 * @param editor The editor to operate on.
1478 * @param pos The position where the word should be read from.
1479 * Maybe @c -1 to use the current position.
1480 * @param wordchars The wordchars to separate words. wordchars mean all characters to count
1481 * as part of a word. Maybe @c NULL to use the default wordchars,
1482 * see @ref GEANY_WORDCHARS.
1484 * @return A newly-allocated string containing the word at the given @a pos or @c NULL.
1485 * Should be freed when no longer needed.
1487 * @since 0.16
1489 gchar *editor_get_word_at_pos(GeanyEditor *editor, gint pos, const gchar *wordchars)
1491 static gchar cword[GEANY_MAX_WORD_LENGTH];
1493 g_return_val_if_fail(editor != NULL, FALSE);
1495 read_current_word(editor, pos, cword, sizeof(cword), wordchars, FALSE);
1497 return (*cword == '\0') ? NULL : g_strdup(cword);
1501 /* Read the word up to position @a pos. */
1502 static const gchar *
1503 editor_read_word_stem(GeanyEditor *editor, gint pos, const gchar *wordchars)
1505 static gchar word[GEANY_MAX_WORD_LENGTH];
1507 read_current_word(editor, pos, word, sizeof word, wordchars, TRUE);
1509 return (*word) ? word : NULL;
1513 static gint find_previous_brace(ScintillaObject *sci, gint pos)
1515 gchar c;
1516 gint orig_pos = pos;
1518 c = sci_get_char_at(sci, pos);
1519 while (pos >= 0 && pos > orig_pos - 300)
1521 c = sci_get_char_at(sci, pos);
1522 pos--;
1523 if (utils_is_opening_brace(c, editor_prefs.brace_match_ltgt))
1524 return pos;
1526 return -1;
1530 static gint find_start_bracket(ScintillaObject *sci, gint pos)
1532 gchar c;
1533 gint brackets = 0;
1534 gint orig_pos = pos;
1536 c = sci_get_char_at(sci, pos);
1537 while (pos > 0 && pos > orig_pos - 300)
1539 c = sci_get_char_at(sci, pos);
1540 if (c == ')') brackets++;
1541 else if (c == '(') brackets--;
1542 pos--;
1543 if (brackets < 0) return pos; /* found start bracket */
1545 return -1;
1549 static gboolean append_calltip(GString *str, const TMTag *tag, filetype_id ft_id)
1551 if (! tag->atts.entry.arglist)
1552 return FALSE;
1554 if (ft_id != GEANY_FILETYPES_PASCAL)
1555 { /* usual calltips: "retval tagname (arglist)" */
1556 if (tag->atts.entry.var_type)
1558 guint i;
1560 g_string_append(str, tag->atts.entry.var_type);
1561 for (i = 0; i < tag->atts.entry.pointerOrder; i++)
1563 g_string_append_c(str, '*');
1565 g_string_append_c(str, ' ');
1567 if (tag->atts.entry.scope)
1569 const gchar *cosep = symbols_get_context_separator(ft_id);
1571 g_string_append(str, tag->atts.entry.scope);
1572 g_string_append(str, cosep);
1574 g_string_append(str, tag->name);
1575 g_string_append_c(str, ' ');
1576 g_string_append(str, tag->atts.entry.arglist);
1578 else
1579 { /* special case Pascal calltips: "tagname (arglist) : retval" */
1580 g_string_append(str, tag->name);
1581 g_string_append_c(str, ' ');
1582 g_string_append(str, tag->atts.entry.arglist);
1584 if (NZV(tag->atts.entry.var_type))
1586 g_string_append(str, " : ");
1587 g_string_append(str, tag->atts.entry.var_type);
1591 return TRUE;
1595 static gchar *find_calltip(const gchar *word, GeanyFiletype *ft)
1597 const GPtrArray *tags;
1598 const gint arg_types = tm_tag_function_t | tm_tag_prototype_t |
1599 tm_tag_method_t | tm_tag_macro_with_arg_t;
1600 TMTagAttrType *attrs = NULL;
1601 TMTag *tag;
1602 GString *str = NULL;
1603 guint i;
1605 g_return_val_if_fail(ft && word && *word, NULL);
1607 /* use all types in case language uses wrong tag type e.g. python "members" instead of "methods" */
1608 tags = tm_workspace_find(word, tm_tag_max_t, attrs, FALSE, ft->lang);
1609 if (tags->len == 0)
1610 return NULL;
1612 tag = TM_TAG(tags->pdata[0]);
1614 if (tag->type == tm_tag_class_t && FILETYPE_ID(ft) == GEANY_FILETYPES_D)
1616 /* user typed e.g. 'new Classname(' so lookup D constructor Classname::this() */
1617 tags = tm_workspace_find_scoped("this", tag->name,
1618 arg_types, attrs, FALSE, ft->lang, TRUE);
1619 if (tags->len == 0)
1620 return NULL;
1623 /* remove tags with no argument list */
1624 for (i = 0; i < tags->len; i++)
1626 tag = TM_TAG(tags->pdata[i]);
1628 if (! tag->atts.entry.arglist)
1629 tags->pdata[i] = NULL;
1631 tm_tags_prune((GPtrArray *) tags);
1632 if (tags->len == 0)
1633 return NULL;
1634 else
1635 { /* remove duplicate calltips */
1636 TMTagAttrType sort_attr[] = {tm_tag_attr_name_t, tm_tag_attr_scope_t,
1637 tm_tag_attr_arglist_t, 0};
1639 tm_tags_sort((GPtrArray *) tags, sort_attr, TRUE);
1642 /* if the current word has changed since last time, start with the first tag match */
1643 if (! utils_str_equal(word, calltip.last_word))
1644 calltip.tag_index = 0;
1645 /* cache the current word for next time */
1646 g_free(calltip.last_word);
1647 calltip.last_word = g_strdup(word);
1648 calltip.tag_index = MIN(calltip.tag_index, tags->len - 1); /* ensure tag_index is in range */
1650 for (i = calltip.tag_index; i < tags->len; i++)
1652 tag = TM_TAG(tags->pdata[i]);
1654 if (str == NULL)
1656 str = g_string_new(NULL);
1657 if (calltip.tag_index > 0)
1658 g_string_prepend(str, "\001 "); /* up arrow */
1659 append_calltip(str, tag, FILETYPE_ID(ft));
1661 else /* add a down arrow */
1663 if (calltip.tag_index > 0) /* already have an up arrow */
1664 g_string_insert_c(str, 1, '\002');
1665 else
1666 g_string_prepend(str, "\002 ");
1667 break;
1670 if (str)
1672 gchar *result = str->str;
1674 g_string_free(str, FALSE);
1675 return result;
1677 return NULL;
1681 /* use pos = -1 to search for the previous unmatched open bracket. */
1682 gboolean editor_show_calltip(GeanyEditor *editor, gint pos)
1684 gint orig_pos = pos; /* the position for the calltip */
1685 gint lexer;
1686 gint style;
1687 gchar word[GEANY_MAX_WORD_LENGTH];
1688 gchar *str;
1689 ScintillaObject *sci;
1691 g_return_val_if_fail(editor != NULL, FALSE);
1692 g_return_val_if_fail(editor->document->file_type != NULL, FALSE);
1694 sci = editor->sci;
1696 lexer = sci_get_lexer(sci);
1698 if (pos == -1)
1700 /* position of '(' is unknown, so go backwards from current position to find it */
1701 pos = sci_get_current_position(sci);
1702 pos--;
1703 orig_pos = pos;
1704 pos = (lexer == SCLEX_LATEX) ? find_previous_brace(sci, pos) :
1705 find_start_bracket(sci, pos);
1706 if (pos == -1)
1707 return FALSE;
1710 /* the style 1 before the brace (which may be highlighted) */
1711 style = sci_get_style_at(sci, pos - 1);
1712 if (! is_code_style(lexer, style))
1713 return FALSE;
1715 word[0] = '\0';
1716 editor_find_current_word(editor, pos - 1, word, sizeof word, NULL);
1717 if (word[0] == '\0')
1718 return FALSE;
1720 str = find_calltip(word, editor->document->file_type);
1721 if (str)
1723 g_free(calltip.text); /* free the old calltip */
1724 calltip.text = str;
1725 calltip.pos = orig_pos;
1726 calltip.sci = sci;
1727 calltip.set = TRUE;
1728 utils_wrap_string(calltip.text, -1);
1729 SSM(sci, SCI_CALLTIPSHOW, orig_pos, (sptr_t) calltip.text);
1730 return TRUE;
1732 return FALSE;
1736 gchar *editor_get_calltip_text(GeanyEditor *editor, const TMTag *tag)
1738 GString *str;
1740 g_return_val_if_fail(editor != NULL, NULL);
1742 str = g_string_new(NULL);
1743 if (append_calltip(str, tag, FILETYPE_ID(editor->document->file_type)))
1744 return g_string_free(str, FALSE);
1745 else
1746 return g_string_free(str, TRUE);
1750 /* HTML entities auto completion from html_entities.tags text file */
1751 static gboolean
1752 autocomplete_html(ScintillaObject *sci, const gchar *root, gsize rootlen)
1754 guint i, j = 0;
1755 gboolean found = FALSE;
1756 GString *words;
1757 const gchar **entities = symbols_get_html_entities();
1759 if (*root != '&' || G_UNLIKELY(entities == NULL))
1760 return FALSE;
1762 words = g_string_sized_new(500);
1763 for (i = 0; ; i++)
1765 if (entities[i] == NULL)
1766 break;
1767 else if (entities[i][0] == '#')
1768 continue;
1770 if (! strncmp(entities[i], root, rootlen))
1772 if (j++ > 0)
1773 g_string_append_c(words, '\n');
1774 g_string_append(words, entities[i]);
1775 found = TRUE;
1778 if (found)
1779 show_autocomplete(sci, rootlen, words->str);
1781 g_string_free(words, TRUE);
1782 return found;
1786 /* Current document & global tags autocompletion */
1787 static gboolean
1788 autocomplete_tags(GeanyEditor *editor, const gchar *root, gsize rootlen)
1790 TMTagAttrType attrs[] = { tm_tag_attr_name_t, 0 };
1791 const GPtrArray *tags;
1792 GeanyDocument *doc;
1794 g_return_val_if_fail(editor, FALSE);
1796 doc = editor->document;
1798 tags = tm_workspace_find(root, tm_tag_max_t, attrs, TRUE, doc->file_type->lang);
1799 if (tags)
1801 autocompletion_mode = AUTOC_TAGS;
1802 show_tags_list(editor, tags, rootlen);
1803 return tags->len > 0;
1805 return FALSE;
1809 /* Check whether to use entity autocompletion:
1810 * - always in a HTML file except when inside embedded JavaScript, Python, ASP, ...
1811 * - in a PHP file only when we are outside of <? ?> */
1812 static gboolean autocomplete_check_for_html(gint ft_id, gint style)
1814 /* use entity completion when style is not JavaScript, ASP, Python, PHP, ...
1815 * (everything after SCE_HJ_START is for embedded scripting languages) */
1816 if (ft_id == GEANY_FILETYPES_HTML && style < SCE_HJ_START)
1817 return TRUE;
1819 if (ft_id == GEANY_FILETYPES_PHP)
1821 /* use entity completion when style is outside of PHP styles */
1822 if (! is_style_php(style))
1823 return TRUE;
1826 return FALSE;
1830 /* Algorithm based on based on Scite's StartAutoCompleteWord() */
1831 static GString *get_doc_words(ScintillaObject *sci, gchar *root, gsize rootlen)
1833 gchar *word;
1834 gint len, current, word_end;
1835 gint pos_find, flags;
1836 guint word_length;
1837 gsize nmatches = 0;
1838 GString *words;
1839 struct Sci_TextToFind ttf;
1841 len = sci_get_length(sci);
1842 current = sci_get_current_position(sci) - rootlen;
1844 ttf.lpstrText = root;
1845 ttf.chrg.cpMin = 0;
1846 ttf.chrg.cpMax = len;
1847 ttf.chrgText.cpMin = 0;
1848 ttf.chrgText.cpMax = 0;
1849 flags = SCFIND_WORDSTART | SCFIND_MATCHCASE;
1851 words = g_string_sized_new(256);
1852 /* put space before first entry to make searching with strstr easy */
1853 g_string_append_c(words, ' ');
1855 /* search the whole document for the word root and collect results */
1856 pos_find = scintilla_send_message(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
1857 while (pos_find >= 0 && pos_find < len)
1859 word_end = pos_find + rootlen;
1860 if (pos_find != current)
1862 while (word_end < len && strchr(GEANY_WORDCHARS, sci_get_char_at(sci, word_end)) != NULL)
1863 word_end++;
1865 word_length = word_end - pos_find;
1866 if (word_length > rootlen)
1868 word = g_malloc0(word_length + 3);
1869 sci_get_text_range(sci, pos_find, word_end, word + 1);
1870 word[0] = ' ';
1871 word[word_length + 1] = ' ';
1872 /* search the words string whether we already have the word in, otherwise add it */
1873 if (strstr(words->str, word) == NULL)
1875 g_string_append(words, word + 1);
1876 nmatches++;
1878 g_free(word);
1880 if (nmatches == editor_prefs.autocompletion_max_entries)
1881 break;
1884 ttf.chrg.cpMin = word_end;
1885 pos_find = scintilla_send_message(sci, SCI_FINDTEXT, flags, (uptr_t) &ttf);
1888 if (words->len > 1)
1890 g_strdelimit(words->str, " ", '\n');
1891 words->str[words->len - 1] = '\0'; /* remove the trailing '\n' */
1892 return words;
1894 g_string_free(words, TRUE);
1895 return NULL;
1899 static gboolean autocomplete_doc_word(GeanyEditor *editor, gchar *root, gsize rootlen)
1901 ScintillaObject *sci = editor->sci;
1902 GString *words;
1903 GString *str;
1904 gchar *ptr;
1905 GSList *node, *list = NULL;
1907 words = get_doc_words(sci, root, rootlen);
1908 if (!words)
1910 scintilla_send_message(sci, SCI_AUTOCCANCEL, 0, 0);
1911 autocompletion_mode = AUTOC_CANCELLED;
1912 return FALSE;
1915 /* words are unsorted, make list of words */
1916 foreach_str(ptr, words->str)
1918 if (*ptr == '\n')
1920 list = g_slist_prepend(list, ptr + 1);
1921 /* terminate previous string in list */
1922 ptr[0] = 0x0;
1923 ptr++;
1926 list = g_slist_sort(list, (GCompareFunc)utils_str_casecmp);
1928 str = g_string_sized_new(words->len);
1929 foreach_slist(node, list)
1931 g_string_append(str, node->data);
1932 if (node->next)
1933 g_string_append_c(str, '\n');
1935 if (g_slist_length(list) >= editor_prefs.autocompletion_max_entries)
1936 g_string_append(str, "\n...");
1938 g_slist_free(list);
1939 g_string_free(words, TRUE);
1941 autocompletion_mode = AUTOC_DOC_WORDS;
1942 show_autocomplete(sci, rootlen, str->str);
1943 g_string_free(str, TRUE);
1944 return TRUE;
1948 gboolean editor_start_auto_complete(GeanyEditor *editor, gint pos, gboolean force)
1950 gint line, line_start, line_len, line_pos, current, rootlen, startword, lexer, style;
1951 gchar *linebuf, *root;
1952 ScintillaObject *sci;
1953 gboolean ret = FALSE;
1954 const gchar *wordchars;
1955 GeanyFiletype *ft;
1957 if (! editor_prefs.auto_complete_symbols && ! force)
1958 return FALSE;
1960 g_return_val_if_fail(editor != NULL, FALSE);
1962 /* If we are at the beginning of the document, we skip autocompletion as we can't determine the
1963 * necessary styling information */
1964 if (G_UNLIKELY(pos < 2))
1965 return FALSE;
1967 sci = editor->sci;
1968 ft = editor->document->file_type;
1970 line = sci_get_line_from_position(sci, pos);
1971 line_start = sci_get_position_from_line(sci, line);
1972 line_len = sci_get_line_length(sci, line);
1973 line_pos = pos - line_start - 1;
1974 current = pos - line_start;
1975 startword = current;
1976 lexer = sci_get_lexer(sci);
1977 style = sci_get_style_at(sci, pos - 2);
1979 /* don't autocomplete in comments and strings */
1980 if (!force && !is_code_style(lexer, style))
1981 return FALSE;
1983 autocomplete_scope(editor);
1985 linebuf = sci_get_line(sci, line);
1987 if (ft->id == GEANY_FILETYPES_LATEX)
1988 wordchars = GEANY_WORDCHARS"\\"; /* add \ to word chars if we are in a LaTeX file */
1989 else if (ft->id == GEANY_FILETYPES_HTML || ft->id == GEANY_FILETYPES_PHP)
1990 wordchars = GEANY_WORDCHARS"&"; /* add & to word chars if we are in a PHP or HTML file */
1991 else
1992 wordchars = GEANY_WORDCHARS;
1994 /* find the start of the current word */
1995 while ((startword > 0) && (strchr(wordchars, linebuf[startword - 1])))
1996 startword--;
1997 linebuf[current] = '\0';
1998 root = linebuf + startword;
1999 rootlen = current - startword;
2001 if (rootlen > 0 && autocompletion_mode != AUTOC_SCOPE)
2003 if (autocomplete_check_for_html(ft->id, style))
2005 /* Allow something like "&quot;some text&quot;". The above startword calculation
2006 * only works on words but for HTML entity completion we also want to have completion
2007 * based on '&' within words. */
2008 gchar *tmp = strchr(root, '&');
2009 if (tmp != NULL)
2011 root = tmp;
2012 rootlen = strlen(tmp);
2014 ret = autocomplete_html(sci, root, rootlen);
2016 else
2018 /* force is set when called by keyboard shortcut, otherwise start at the
2019 * editor_prefs.symbolcompletion_min_chars'th char */
2020 if (force || rootlen >= editor_prefs.symbolcompletion_min_chars)
2022 /* complete tags, except if forcing when completion is already visible */
2023 if (!(force && SSM(sci, SCI_AUTOCACTIVE, 0, 0)))
2024 ret = autocomplete_tags(editor, root, rootlen);
2026 /* If forcing and there's nothing else to show, complete from words in document */
2027 if (!ret && (force || editor_prefs.autocomplete_doc_words))
2028 ret = autocomplete_doc_word(editor, root, rootlen);
2032 if (!ret && force)
2033 utils_beep();
2035 g_free(linebuf);
2036 return ret;
2040 static const gchar *snippets_find_completion_by_name(const gchar *type, const gchar *name)
2042 gchar *result = NULL;
2043 GHashTable *tmp;
2045 g_return_val_if_fail(type != NULL && name != NULL, NULL);
2047 tmp = g_hash_table_lookup(snippet_hash, type);
2048 if (tmp != NULL)
2050 result = g_hash_table_lookup(tmp, name);
2052 /* whether nothing is set for the current filetype(tmp is NULL) or
2053 * the particular completion for this filetype is not set (result is NULL) */
2054 if (tmp == NULL || result == NULL)
2056 tmp = g_hash_table_lookup(snippet_hash, "Default");
2057 if (tmp != NULL)
2059 result = g_hash_table_lookup(tmp, name);
2062 /* if result is still NULL here, no completion could be found */
2064 /* result is owned by the hash table and will be freed when the table will destroyed */
2065 return result;
2069 /* This is very ugly but passing the pattern to ac_replace_specials() doesn't work because it is
2070 * modified when replacing a completion but the foreach function still passes the old pointer
2071 * to ac_replace_specials, so we use a global pointer outside of ac_replace_specials and
2072 * ac_complete_constructs. Any hints to improve this are welcome. */
2073 static GString *snippets_global_pattern = NULL;
2075 static void snippets_replace_specials(gpointer key, gpointer value, gpointer user_data)
2077 gchar *needle;
2079 g_return_if_fail(key != NULL);
2080 g_return_if_fail(value != NULL);
2082 needle = g_strconcat("%", (gchar*) key, "%", NULL);
2084 utils_string_replace_all(snippets_global_pattern, needle, (gchar*) value);
2085 g_free(needle);
2089 /* this only works with spaces only indentation on the lines */
2090 static void fix_line_indents(GeanyEditor *editor, gint line_start, gint line_end)
2092 ScintillaObject *sci = editor->sci;
2093 gint line, cur_line, cur_col, pos;
2095 /* get the line, col position as fixing indentation will move cursor to start of line */
2096 pos = sci_get_current_position(sci);
2097 cur_col = sci_get_col_from_position(sci, pos);
2098 cur_line = sci_get_current_line(sci);
2100 for (line = line_start; line <= line_end; line++)
2102 gint size = sci_get_line_indentation(sci, line);
2104 /* set to 0 first to trigger proper indent creation */
2105 sci_set_line_indentation(sci, line, 0);
2106 sci_set_line_indentation(sci, line, size);
2108 pos = scintilla_send_message(sci, SCI_FINDCOLUMN, cur_line, cur_col);
2109 sci_set_current_position(sci, pos, FALSE);
2113 static void replace_leading_tabs(GString *str, const gchar *whitespace)
2115 regex_t regex;
2116 gssize pos;
2117 regmatch_t matches[2];
2118 gchar *ptr;
2120 if (regcomp(&regex, "^ *(\t)", 0) != 0)
2122 g_return_if_fail(FALSE);
2124 ptr = str->str;
2125 while (ptr)
2127 if (regexec(&regex, ptr,
2128 G_N_ELEMENTS(matches), matches, 0) != 0)
2129 break;
2131 pos = matches[1].rm_so;
2132 g_return_if_fail(pos >= 0);
2133 pos += ptr - str->str;
2134 g_string_erase(str, pos, 1);
2135 g_string_insert(str, pos, whitespace);
2136 ptr = str->str + pos + strlen(whitespace);
2138 regfree(&regex);
2142 /** Inserts text, replacing \\t tab chars (@c 0x9) and \\n newline chars (@c 0xA)
2143 * accordingly for the document.
2144 * - Leading tabs are replaced with the correct indentation.
2145 * - Non-leading tabs are replaced with spaces (except when using 'Tabs' indent type).
2146 * - Newline chars are replaced with the correct line ending string.
2147 * This is very useful for inserting code without having to handle the indent
2148 * type yourself (Tabs & Spaces mode can be tricky).
2149 * @param editor Editor.
2150 * @param text Intended as e.g. @c "if (foo)\n\tbar();".
2151 * @param insert_pos Document position to insert text at.
2152 * @param cursor_index If >= 0, the index into @a text to place the cursor.
2153 * @param newline_indent_size Indentation size (in spaces) to insert for each newline; use
2154 * -1 to read the indent size from the line with @a insert_pos on it.
2155 * @param replace_newlines Whether to replace newlines. If
2156 * newlines have been replaced already, this should be false, to avoid errors e.g. on Windows.
2157 * @warning Make sure all \\t tab chars in @a text are intended as indent widths or alignment,
2158 * not hard tabs, as those won't be preserved.
2159 * @note This doesn't scroll the cursor in view afterwards. **/
2160 void editor_insert_text_block(GeanyEditor *editor, const gchar *text, gint insert_pos,
2161 gint cursor_index, gint newline_indent_size, gboolean replace_newlines)
2163 ScintillaObject *sci = editor->sci;
2164 gint line_start = sci_get_line_from_position(sci, insert_pos);
2165 gint line_end;
2166 gchar *whitespace;
2167 GString *buf;
2168 const gchar cur_marker[] = "__GEANY_CURSOR_MARKER__";
2169 const gchar *eol = editor_get_eol_char(editor);
2170 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
2172 g_return_if_fail(text);
2173 g_return_if_fail(editor != NULL);
2174 g_return_if_fail(insert_pos >= 0);
2176 buf = g_string_new(text);
2178 if (cursor_index >= 0)
2179 g_string_insert(buf, cursor_index, cur_marker); /* remember cursor pos */
2181 if (newline_indent_size == -1)
2183 /* count indent size up to insert_pos instead of asking sci
2184 * because there may be spaces after it */
2185 gchar *tmp = sci_get_line(sci, line_start);
2186 gint idx = insert_pos - sci_get_position_from_line(sci, line_start);
2187 tmp[idx] = '\0';
2188 newline_indent_size = count_indent_size(editor, tmp);
2189 g_free(tmp);
2192 /* Add line indents (in spaces) */
2193 if (newline_indent_size > 0)
2195 whitespace = g_strnfill(newline_indent_size, ' ');
2196 setptr(whitespace, g_strconcat(eol, whitespace, NULL));
2197 utils_string_replace_all(buf, eol, whitespace);
2198 g_free(whitespace);
2201 /* transform line endings */
2202 if (replace_newlines)
2203 utils_string_replace_all(buf, "\n", eol);
2205 /* transform leading tabs into indent widths (in spaces) */
2206 whitespace = g_strnfill(iprefs->width, ' ');
2207 replace_leading_tabs(buf, whitespace);
2208 /* remaining tabs are for alignment */
2209 if (iprefs->type != GEANY_INDENT_TYPE_TABS)
2210 utils_string_replace_all(buf, "\t", whitespace);
2211 g_free(whitespace);
2213 sci_start_undo_action(sci);
2215 if (cursor_index >= 0)
2217 gint idx = utils_strpos(buf->str, cur_marker);
2219 g_string_erase(buf, idx, strlen(cur_marker));
2221 sci_insert_text(sci, insert_pos, buf->str);
2222 sci_set_current_position(sci, insert_pos + idx, FALSE);
2224 else
2225 sci_insert_text(sci, insert_pos, buf->str);
2227 /* fixup indentation (very useful for Tabs & Spaces indent type) */
2228 line_end = sci_get_line_from_position(sci, insert_pos + buf->len);
2229 fix_line_indents(editor, line_start, line_end);
2230 snippet_cursor_insert_pos = sci_get_current_position(sci);
2232 sci_end_undo_action(sci);
2233 g_string_free(buf, TRUE);
2237 /* Move the cursor to the next specified cursor position in an inserted snippet.
2238 * Can, and should, be optimized to give better results */
2239 void editor_goto_next_snippet_cursor(GeanyEditor *editor)
2241 ScintillaObject *sci = editor->sci;
2242 gint current_pos = sci_get_current_position(sci);
2244 if (snippet_offsets && !g_queue_is_empty(snippet_offsets))
2246 gint offset;
2248 offset = GPOINTER_TO_INT(g_queue_pop_head(snippet_offsets));
2249 if (current_pos > snippet_cursor_insert_pos)
2250 snippet_cursor_insert_pos = offset + current_pos;
2251 else
2252 snippet_cursor_insert_pos += offset;
2254 sci_set_current_position(sci, snippet_cursor_insert_pos, FALSE);
2256 else
2258 utils_beep();
2263 static gssize snippets_make_replacements(GeanyEditor *editor, GString *pattern,
2264 gsize indent_size)
2266 gssize cur_index = -1;
2267 gchar *whitespace;
2268 gint i, tmp_pos, whitespace_len, nl_count = 0;
2269 GHashTable *specials;
2270 GList *temp_list = NULL;
2271 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
2272 gint cursor_steps, old_cursor = 0;
2274 /* replace 'special' completions */
2275 specials = g_hash_table_lookup(snippet_hash, "Special");
2276 if (G_LIKELY(specials != NULL))
2278 /* ugly hack using global_pattern */
2279 snippets_global_pattern = pattern;
2280 g_hash_table_foreach(specials, snippets_replace_specials, NULL);
2283 /* replace any template {foo} wildcards */
2284 templates_replace_common(pattern, editor->document->file_name, editor->document->file_type, NULL);
2286 /* transform other wildcards */
2287 /* convert to %newlines%, else we get endless loops */
2288 utils_string_replace_all(pattern, "\n", "%newline%");
2290 /* if spaces are used, replaces all tabs with %ws%, which is later replaced
2291 * by real whitespace characters
2292 * otherwise replace all %ws% by \t, which will be replaced later by tab
2293 * characters,
2294 * this makes seperating between tab and spaces intentation pretty easy */
2295 if (iprefs->type == GEANY_INDENT_TYPE_SPACES)
2296 utils_string_replace_all(pattern, "\t", "%ws%");
2297 else
2298 utils_string_replace_all(pattern, "%ws%", "\t");
2300 whitespace = g_strnfill(iprefs->width, ' '); /* use spaces for indentation, will be fixed up */
2301 whitespace_len = strlen(whitespace);
2302 i = 0;
2303 while ((cursor_steps = utils_strpos(pattern->str, "%cursor%")) >= 0)
2305 /* replace every %newline% (up to next %cursor%) with EOL,
2306 * and update cursor_steps after */
2307 while ((tmp_pos = utils_strpos(pattern->str, "%newline%")) < cursor_steps && tmp_pos != -1)
2309 nl_count++;
2310 utils_string_replace_first(pattern, "%newline%", editor_get_eol_char(editor));
2311 cursor_steps = utils_strpos(pattern->str, "%cursor%");
2313 /* replace every %ws% (up to next %cursor%) with whitespaces,
2314 * and update cursor_steps after */
2315 while ((tmp_pos = utils_strpos(pattern->str, "%ws%")) < cursor_steps && tmp_pos != -1)
2317 utils_string_replace_first(pattern, "%ws%", whitespace);
2318 cursor_steps = utils_strpos(pattern->str, "%cursor%");
2320 /* finally replace the next %cursor% */
2321 utils_string_replace_first(pattern, "%cursor%", "");
2323 /* modify cursor_steps to take indentation count and type into account */
2325 /* We're saving the relative offset to each cursor position in a simple
2326 * linked list, including indentations between them. */
2327 if (i++ > 0)
2329 cursor_steps += (nl_count * indent_size);
2330 temp_list = g_list_append(temp_list, GINT_TO_POINTER(cursor_steps - old_cursor));
2332 else
2334 nl_count = 0;
2335 cur_index = cursor_steps;
2337 old_cursor = cursor_steps;
2339 /* replace remaining %ws% and %newline% which may occur after the last %cursor% */
2340 utils_string_replace_all(pattern, "%newline%", editor_get_eol_char(editor));
2341 utils_string_replace_all(pattern, "%ws%", whitespace);
2342 g_free(whitespace);
2344 /* escape % last */
2345 /* Bug: {ob}pc{cb} will be replaced by % too */
2346 templates_replace_valist(pattern, "{pc}", "%", NULL);
2348 /* We put the cursor positions for the most recent
2349 * parsed snippet first, followed by any remaining positions */
2350 i = 0;
2351 if (temp_list)
2353 GList *node;
2355 foreach_list(node, temp_list)
2356 g_queue_push_nth(snippet_offsets, node->data, i++);
2358 /* limit length of queue */
2359 while (g_queue_get_length(snippet_offsets) > 20)
2360 g_queue_pop_tail(snippet_offsets);
2362 g_list_free(temp_list);
2364 if (cur_index < 0)
2365 cur_index = pattern->len;
2367 return cur_index;
2371 static gboolean snippets_complete_constructs(GeanyEditor *editor, gint pos, const gchar *word)
2373 ScintillaObject *sci = editor->sci;
2374 gchar *str;
2375 GString *pattern;
2376 gssize cur_index = -1;
2377 gint str_len;
2378 gint ft_id = FILETYPE_ID(editor->document->file_type);
2380 str = g_strdup(word);
2381 g_strstrip(str);
2382 pattern = g_string_new(snippets_find_completion_by_name(filetypes[ft_id]->name, str));
2383 if (pattern == NULL || pattern->len == 0)
2385 g_free(str);
2386 g_string_free(pattern, TRUE);
2387 return FALSE;
2390 read_indent(editor, pos);
2392 /* remove the typed word, it will be added again by the used auto completion
2393 * (not really necessary but this makes the auto completion more flexible,
2394 * e.g. with a completion like hi=hello, so typing "hi<TAB>" will result in "hello") */
2395 str_len = strlen(str);
2396 sci_set_selection_start(sci, pos - str_len);
2397 sci_set_selection_end(sci, pos);
2398 sci_replace_sel(sci, "");
2399 pos -= str_len; /* pos has changed while deleting */
2401 cur_index = snippets_make_replacements(editor, pattern, strlen(indent));
2403 /* finally insert the text and set the cursor */
2404 editor_insert_text_block(editor, pattern->str, pos, cur_index, -1, FALSE);
2405 sci_scroll_caret(sci);
2407 g_free(str);
2408 g_string_free(pattern, TRUE);
2409 return TRUE;
2413 static gboolean at_eol(ScintillaObject *sci, gint pos)
2415 gint line = sci_get_line_from_position(sci, pos);
2416 gchar c;
2418 /* skip any trailing spaces */
2419 while (TRUE)
2421 c = sci_get_char_at(sci, pos);
2422 if (c == ' ' || c == '\t')
2423 pos++;
2424 else
2425 break;
2428 return (pos == sci_get_line_end_position(sci, line));
2432 gboolean editor_complete_snippet(GeanyEditor *editor, gint pos)
2434 gboolean result = FALSE;
2435 const gchar *wc;
2436 const gchar *word;
2437 ScintillaObject *sci;
2439 g_return_val_if_fail(editor != NULL, FALSE);
2441 sci = editor->sci;
2442 if (sci_has_selection(sci))
2443 return FALSE;
2444 /* return if we are editing an existing line (chars on right of cursor) */
2445 if (keybindings_lookup_item(GEANY_KEY_GROUP_EDITOR,
2446 GEANY_KEYS_EDITOR_COMPLETESNIPPET)->key == GDK_space &&
2447 ! editor_prefs.complete_snippets_whilst_editing && ! at_eol(sci, pos))
2448 return FALSE;
2450 wc = snippets_find_completion_by_name("Special", "wordchars");
2451 word = editor_read_word_stem(editor, pos, wc);
2453 /* prevent completion of "for " */
2454 if (NZV(word) &&
2455 ! isspace(sci_get_char_at(sci, pos - 1))) /* pos points to the line end char so use pos -1 */
2457 sci_start_undo_action(sci); /* needed because we insert a space separately from construct */
2458 result = snippets_complete_constructs(editor, pos, word);
2459 sci_end_undo_action(sci);
2460 if (result)
2461 sci_cancel(sci); /* cancel any autocompletion list, etc */
2463 return result;
2467 void editor_show_macro_list(GeanyEditor *editor)
2469 GString *words;
2471 if (editor == NULL || editor->document->file_type == NULL)
2472 return;
2474 words = symbols_get_macro_list(editor->document->file_type->lang);
2475 if (words == NULL)
2476 return;
2478 SSM(editor->sci, SCI_USERLISTSHOW, 1, (sptr_t) words->str);
2479 g_string_free(words, TRUE);
2483 static void insert_closing_tag(GeanyEditor *editor, gint pos, gchar ch, const gchar *tag_name)
2485 ScintillaObject *sci = editor->sci;
2486 gchar *to_insert = NULL;
2488 if (ch == '/')
2490 const gchar *gt = ">";
2491 /* if there is already a '>' behind the cursor, don't add it */
2492 if (sci_get_char_at(sci, pos) == '>')
2493 gt = "";
2495 to_insert = g_strconcat(tag_name, gt, NULL);
2497 else
2498 to_insert = g_strconcat("</", tag_name, ">", NULL);
2500 sci_start_undo_action(sci);
2501 sci_replace_sel(sci, to_insert);
2502 if (ch == '>')
2504 sci_set_selection(sci, pos, pos);
2505 if (utils_str_equal(tag_name, "table"))
2506 auto_table(editor, pos);
2508 sci_end_undo_action(sci);
2509 g_free(to_insert);
2514 * (stolen from anjuta and heavily modified)
2515 * This routine will auto complete XML or HTML tags that are still open by closing them
2516 * @param ch The character we are dealing with, currently only works with the '>' character
2517 * @return True if handled, false otherwise
2519 static gboolean handle_xml(GeanyEditor *editor, gint pos, gchar ch)
2521 ScintillaObject *sci = editor->sci;
2522 gint lexer = sci_get_lexer(sci);
2523 gint min, style;
2524 gchar *str_found, sel[512];
2525 gboolean result = FALSE;
2527 /* If the user has turned us off, quit now.
2528 * This may make sense only in certain languages */
2529 if (! editor_prefs.auto_close_xml_tags || (lexer != SCLEX_HTML && lexer != SCLEX_XML))
2530 return FALSE;
2532 /* return if we are inside any embedded script */
2533 style = sci_get_style_at(sci, pos);
2534 if (style > SCE_H_XCCOMMENT && ! is_string_style(lexer, style))
2535 return FALSE;
2537 /* if ch is /, check for </, else quit */
2538 if (ch == '/' && sci_get_char_at(sci, pos - 2) != '<')
2539 return FALSE;
2541 /* Grab the last 512 characters or so */
2542 min = pos - (sizeof(sel) - 1);
2543 if (min < 0) min = 0;
2545 if (pos - min < 3)
2546 return FALSE; /* Smallest tag is 3 characters e.g. <p> */
2548 sci_get_text_range(sci, min, pos, sel);
2549 sel[sizeof(sel) - 1] = '\0';
2551 if (ch == '>' && sel[pos - min - 2] == '/')
2552 /* User typed something like "<br/>" */
2553 return FALSE;
2555 str_found = utils_find_open_xml_tag(sel, pos - min, (ch == '/'));
2557 /* when found string is something like br, img or another short tag, quit */
2558 if (utils_str_equal(str_found, "br")
2559 || utils_str_equal(str_found, "hr")
2560 || utils_str_equal(str_found, "img")
2561 || utils_str_equal(str_found, "base")
2562 || utils_str_equal(str_found, "basefont") /* < or not < */
2563 || utils_str_equal(str_found, "frame")
2564 || utils_str_equal(str_found, "input")
2565 || utils_str_equal(str_found, "link")
2566 || utils_str_equal(str_found, "area")
2567 || utils_str_equal(str_found, "meta"))
2569 /* ignore tag */
2571 else if (NZV(str_found))
2573 insert_closing_tag(editor, pos, ch, str_found);
2574 result = TRUE;
2576 g_free(str_found);
2577 return result;
2581 /* like sci_get_line_indentation(), but for a string. */
2582 static gsize count_indent_size(GeanyEditor *editor, const gchar *base_indent)
2584 const gchar *ptr;
2585 gsize tab_size = sci_get_tab_width(editor->sci);
2586 gsize count = 0;
2588 g_return_val_if_fail(base_indent, 0);
2590 for (ptr = base_indent; *ptr != 0; ptr++)
2592 switch (*ptr)
2594 case ' ':
2595 count++;
2596 break;
2597 case '\t':
2598 count += tab_size;
2599 break;
2602 return count;
2606 static void auto_table(GeanyEditor *editor, gint pos)
2608 ScintillaObject *sci = editor->sci;
2609 gchar *table;
2610 gint indent_pos;
2611 const gchar *indent_str;
2613 if (sci_get_lexer(sci) != SCLEX_HTML) return;
2615 read_indent(editor, pos);
2616 indent_pos = sci_get_line_indent_position(sci, sci_get_line_from_position(sci, pos));
2617 if ((pos - 7) != indent_pos) /* 7 == strlen("<table>") */
2619 gint i;
2620 guint x;
2622 x = strlen(indent);
2623 /* find the start of the <table tag */
2624 i = 1;
2625 while (i <= pos && sci_get_char_at(sci, pos - i) != '<') i++;
2626 /* add all non whitespace before the tag to the indent string */
2627 while ((pos - i) != indent_pos && x < sizeof(indent) - 1)
2629 indent[x++] = ' ';
2630 i++;
2632 indent[x] = '\0';
2635 if (! editor->auto_indent)
2636 indent_str = "";
2637 else
2638 indent_str = "\t";
2640 table = g_strconcat("\n", indent_str, "<tr>\n",
2641 indent_str, indent_str, "<td> </td>\n",
2642 indent_str, "</tr>\n",
2643 NULL);
2644 editor_insert_text_block(editor, table, pos, -1,
2645 count_indent_size(editor, indent), TRUE);
2646 g_free(table);
2650 static void real_comment_multiline(GeanyEditor *editor, gint line_start, gint last_line)
2652 const gchar *eol;
2653 gchar *str_begin, *str_end, *co, *cc;
2654 gint line_len;
2656 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2658 eol = editor_get_eol_char(editor);
2659 co = editor->document->file_type->comment_open;
2660 cc = editor->document->file_type->comment_close;
2661 str_begin = g_strdup_printf("%s%s", (co != NULL) ? co : "", eol);
2662 str_end = g_strdup_printf("%s%s", (cc != NULL) ? cc : "", eol);
2664 /* insert the comment strings */
2665 sci_insert_text(editor->sci, line_start, str_begin);
2666 line_len = sci_get_position_from_line(editor->sci, last_line + 2);
2667 sci_insert_text(editor->sci, line_len, str_end);
2669 g_free(str_begin);
2670 g_free(str_end);
2674 static void real_uncomment_multiline(GeanyEditor *editor)
2676 /* find the beginning of the multi line comment */
2677 gint pos, line, len, x;
2678 gchar *linebuf;
2679 GeanyDocument *doc;
2681 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2682 doc = editor->document;
2684 /* remove comment open chars */
2685 pos = document_find_text(doc, doc->file_type->comment_open, 0, TRUE, FALSE, NULL);
2686 SSM(editor->sci, SCI_DELETEBACK, 0, 0);
2688 /* check whether the line is empty and can be deleted */
2689 line = sci_get_line_from_position(editor->sci, pos);
2690 len = sci_get_line_length(editor->sci, line);
2691 linebuf = sci_get_line(editor->sci, line);
2692 x = 0;
2693 while (linebuf[x] != '\0' && isspace(linebuf[x])) x++;
2694 if (x == len) SSM(editor->sci, SCI_LINEDELETE, 0, 0);
2695 g_free(linebuf);
2697 /* remove comment close chars */
2698 pos = document_find_text(doc, doc->file_type->comment_close, 0, FALSE, FALSE, NULL);
2699 SSM(editor->sci, SCI_DELETEBACK, 0, 0);
2701 /* check whether the line is empty and can be deleted */
2702 line = sci_get_line_from_position(editor->sci, pos);
2703 len = sci_get_line_length(editor->sci, line);
2704 linebuf = sci_get_line(editor->sci, line);
2705 x = 0;
2706 while (linebuf[x] != '\0' && isspace(linebuf[x])) x++;
2707 if (x == len) SSM(editor->sci, SCI_LINEDELETE, 0, 0);
2708 g_free(linebuf);
2712 static gint get_multiline_comment_style(GeanyEditor *editor, gint line_start)
2714 gint lexer = sci_get_lexer(editor->sci);
2715 gint style_comment;
2717 /* List only those lexers which support multi line comments */
2718 switch (lexer)
2720 case SCLEX_XML:
2721 case SCLEX_HTML:
2723 if (is_style_php(sci_get_style_at(editor->sci, line_start)))
2724 style_comment = SCE_HPHP_COMMENT;
2725 else
2726 style_comment = SCE_H_COMMENT;
2727 break;
2729 case SCLEX_HASKELL: style_comment = SCE_HA_COMMENTBLOCK; break;
2730 case SCLEX_LUA: style_comment = SCE_LUA_COMMENT; break;
2731 case SCLEX_CSS: style_comment = SCE_CSS_COMMENT; break;
2732 case SCLEX_SQL: style_comment = SCE_SQL_COMMENT; break;
2733 case SCLEX_CAML: style_comment = SCE_CAML_COMMENT; break;
2734 case SCLEX_D: style_comment = SCE_D_COMMENT; break;
2735 case SCLEX_PASCAL: style_comment = SCE_PAS_COMMENT; break;
2736 default: style_comment = SCE_C_COMMENT;
2739 return style_comment;
2743 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise
2744 * returns the amount of uncommented single comment lines, in case of multi line uncomment
2745 * it returns just 1 */
2746 gint editor_do_uncomment(GeanyEditor *editor, gint line, gboolean toggle)
2748 gint first_line, last_line;
2749 gint x, i, line_start, line_len;
2750 gint sel_start, sel_end;
2751 gint count = 0;
2752 gsize co_len;
2753 gchar sel[256], *co, *cc;
2754 gboolean break_loop = FALSE, single_line = FALSE;
2755 GeanyFiletype *ft;
2757 g_return_val_if_fail(editor != NULL && editor->document->file_type != NULL, 0);
2759 if (line < 0)
2760 { /* use selection or current line */
2761 sel_start = sci_get_selection_start(editor->sci);
2762 sel_end = sci_get_selection_end(editor->sci);
2764 first_line = sci_get_line_from_position(editor->sci, sel_start);
2765 /* Find the last line with chars selected (not EOL char) */
2766 last_line = sci_get_line_from_position(editor->sci,
2767 sel_end - editor_get_eol_char_len(editor));
2768 last_line = MAX(first_line, last_line);
2770 else
2772 first_line = last_line = line;
2773 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
2776 ft = editor->document->file_type;
2778 /* detection of HTML vs PHP code, if non-PHP set filetype to XML */
2779 line_start = sci_get_position_from_line(editor->sci, first_line);
2780 if (ft->id == GEANY_FILETYPES_PHP)
2782 if (! is_style_php(sci_get_style_at(editor->sci, line_start)))
2783 ft = filetypes[GEANY_FILETYPES_XML];
2786 co = ft->comment_open;
2787 cc = ft->comment_close;
2788 if (co == NULL)
2789 return 0;
2791 co_len = strlen(co);
2792 if (co_len == 0)
2793 return 0;
2795 sci_start_undo_action(editor->sci);
2797 for (i = first_line; (i <= last_line) && (! break_loop); i++)
2799 gint buf_len;
2801 line_start = sci_get_position_from_line(editor->sci, i);
2802 line_len = sci_get_line_length(editor->sci, i);
2803 x = 0;
2805 buf_len = MIN((gint)sizeof(sel) - 1, line_len - 1);
2806 if (buf_len <= 0)
2807 continue;
2808 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
2809 sel[buf_len] = '\0';
2811 while (isspace(sel[x])) x++;
2813 /* to skip blank lines */
2814 if (x < line_len && sel[x] != '\0')
2816 /* use single line comment */
2817 if (cc == NULL || strlen(cc) == 0)
2819 single_line = TRUE;
2821 if (toggle)
2823 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
2824 if (strncmp(sel + x, co, co_len) != 0 ||
2825 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) != 0)
2826 continue;
2828 co_len += tm_len;
2830 else
2832 if (strncmp(sel + x, co, co_len) != 0)
2833 continue;
2836 sci_set_selection(editor->sci, line_start + x, line_start + x + co_len);
2837 sci_replace_sel(editor->sci, "");
2838 count++;
2840 /* use multi line comment */
2841 else
2843 gint style_comment;
2845 /* skip lines which are already comments */
2846 style_comment = get_multiline_comment_style(editor, line_start);
2847 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
2849 real_uncomment_multiline(editor);
2850 count = 1;
2853 /* break because we are already on the last line */
2854 break_loop = TRUE;
2855 break;
2859 sci_end_undo_action(editor->sci);
2861 /* restore selection if there is one
2862 * but don't touch the selection if caller is editor_do_comment_toggle */
2863 if (! toggle && sel_start < sel_end)
2865 if (single_line)
2867 sci_set_selection_start(editor->sci, sel_start - co_len);
2868 sci_set_selection_end(editor->sci, sel_end - (count * co_len));
2870 else
2872 gint eol_len = editor_get_eol_char_len(editor);
2873 sci_set_selection_start(editor->sci, sel_start - co_len - eol_len);
2874 sci_set_selection_end(editor->sci, sel_end - co_len - eol_len);
2878 return count;
2882 void editor_do_comment_toggle(GeanyEditor *editor)
2884 gint first_line, last_line;
2885 gint x, i, line_start, line_len, first_line_start;
2886 gint sel_start, sel_end;
2887 gint count_commented = 0, count_uncommented = 0;
2888 gchar sel[256], *co, *cc;
2889 gboolean break_loop = FALSE, single_line = FALSE;
2890 gboolean first_line_was_comment = FALSE;
2891 gsize co_len;
2892 gsize tm_len = strlen(editor_prefs.comment_toggle_mark);
2893 GeanyFiletype *ft;
2895 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
2897 sel_start = sci_get_selection_start(editor->sci);
2898 sel_end = sci_get_selection_end(editor->sci);
2900 ft = editor->document->file_type;
2902 first_line = sci_get_line_from_position(editor->sci,
2903 sci_get_selection_start(editor->sci));
2904 /* Find the last line with chars selected (not EOL char) */
2905 last_line = sci_get_line_from_position(editor->sci,
2906 sci_get_selection_end(editor->sci) - editor_get_eol_char_len(editor));
2907 last_line = MAX(first_line, last_line);
2909 /* detection of HTML vs PHP code, if non-PHP set filetype to XML */
2910 first_line_start = sci_get_position_from_line(editor->sci, first_line);
2911 if (ft->id == GEANY_FILETYPES_PHP)
2913 if (! is_style_php(sci_get_style_at(editor->sci, first_line_start)))
2914 ft = filetypes[GEANY_FILETYPES_XML];
2917 co = ft->comment_open;
2918 cc = ft->comment_close;
2919 if (co == NULL)
2920 return;
2922 co_len = strlen(co);
2923 if (co_len == 0)
2924 return;
2926 sci_start_undo_action(editor->sci);
2928 for (i = first_line; (i <= last_line) && (! break_loop); i++)
2930 gint buf_len;
2932 line_start = sci_get_position_from_line(editor->sci, i);
2933 line_len = sci_get_line_length(editor->sci, i);
2934 x = 0;
2936 buf_len = MIN((gint)sizeof(sel) - 1, line_len - 1);
2937 if (buf_len < 0)
2938 continue;
2939 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
2940 sel[buf_len] = '\0';
2942 while (isspace(sel[x])) x++;
2944 /* use single line comment */
2945 if (cc == NULL || strlen(cc) == 0)
2947 gboolean do_continue = FALSE;
2948 single_line = TRUE;
2950 if (strncmp(sel + x, co, co_len) == 0 &&
2951 strncmp(sel + x + co_len, editor_prefs.comment_toggle_mark, tm_len) == 0)
2953 do_continue = TRUE;
2956 if (do_continue && i == first_line)
2957 first_line_was_comment = TRUE;
2959 if (do_continue)
2961 count_uncommented += editor_do_uncomment(editor, i, TRUE);
2962 continue;
2965 /* we are still here, so the above lines were not already comments, so comment it */
2966 editor_do_comment(editor, i, TRUE, TRUE);
2967 count_commented++;
2969 /* use multi line comment */
2970 else
2972 gint style_comment;
2974 /* skip lines which are already comments */
2975 style_comment = get_multiline_comment_style(editor, line_start);
2976 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
2978 real_uncomment_multiline(editor);
2979 count_uncommented++;
2981 else
2983 real_comment_multiline(editor, line_start, last_line);
2984 count_commented++;
2987 /* break because we are already on the last line */
2988 break_loop = TRUE;
2989 break;
2993 sci_end_undo_action(editor->sci);
2995 co_len += tm_len;
2997 /* restore selection if there is one */
2998 if (sel_start < sel_end)
3000 if (single_line)
3002 gint a = (first_line_was_comment) ? - co_len : co_len;
3004 /* don't modify sel_start when the selection starts within indentation */
3005 read_indent(editor, sel_start);
3006 if ((sel_start - first_line_start) <= (gint) strlen(indent))
3007 a = 0;
3009 sci_set_selection_start(editor->sci, sel_start + a);
3010 sci_set_selection_end(editor->sci, sel_end +
3011 (count_commented * co_len) - (count_uncommented * co_len));
3013 else
3015 gint eol_len = editor_get_eol_char_len(editor);
3016 if (count_uncommented > 0)
3018 sci_set_selection_start(editor->sci, sel_start - co_len + eol_len);
3019 sci_set_selection_end(editor->sci, sel_end - co_len + eol_len);
3021 else if (count_commented > 0)
3023 sci_set_selection_start(editor->sci, sel_start + co_len - eol_len);
3024 sci_set_selection_end(editor->sci, sel_end + co_len - eol_len);
3028 else if (count_uncommented > 0)
3030 gint eol_len = single_line ? 0: editor_get_eol_char_len(editor);
3031 sci_set_current_position(editor->sci, sel_start - co_len + eol_len, TRUE);
3033 else if (count_commented > 0)
3035 gint eol_len = single_line ? 0: editor_get_eol_char_len(editor);
3036 sci_set_current_position(editor->sci, sel_start + co_len - eol_len, TRUE);
3041 /* set toggle to TRUE if the caller is the toggle function, FALSE otherwise */
3042 void editor_do_comment(GeanyEditor *editor, gint line, gboolean allow_empty_lines, gboolean toggle)
3044 gint first_line, last_line;
3045 gint x, i, line_start, line_len;
3046 gint sel_start, sel_end, co_len;
3047 gchar sel[256], *co, *cc;
3048 gboolean break_loop = FALSE, single_line = FALSE;
3049 GeanyFiletype *ft;
3051 g_return_if_fail(editor != NULL && editor->document->file_type != NULL);
3053 if (line < 0)
3054 { /* use selection or current line */
3055 sel_start = sci_get_selection_start(editor->sci);
3056 sel_end = sci_get_selection_end(editor->sci);
3058 first_line = sci_get_line_from_position(editor->sci, sel_start);
3059 /* Find the last line with chars selected (not EOL char) */
3060 last_line = sci_get_line_from_position(editor->sci,
3061 sel_end - editor_get_eol_char_len(editor));
3062 last_line = MAX(first_line, last_line);
3064 else
3066 first_line = last_line = line;
3067 sel_start = sel_end = sci_get_position_from_line(editor->sci, line);
3070 ft = editor->document->file_type;
3072 /* detection of HTML vs PHP code, if non-PHP set filetype to XML */
3073 line_start = sci_get_position_from_line(editor->sci, first_line);
3074 if (ft->id == GEANY_FILETYPES_PHP)
3076 if (! is_style_php(sci_get_style_at(editor->sci, line_start)))
3077 ft = filetypes[GEANY_FILETYPES_XML];
3080 co = ft->comment_open;
3081 cc = ft->comment_close;
3082 if (co == NULL)
3083 return;
3085 co_len = strlen(co);
3086 if (co_len == 0)
3087 return;
3089 sci_start_undo_action(editor->sci);
3091 for (i = first_line; (i <= last_line) && (! break_loop); i++)
3093 gint buf_len;
3095 line_start = sci_get_position_from_line(editor->sci, i);
3096 line_len = sci_get_line_length(editor->sci, i);
3097 x = 0;
3099 buf_len = MIN((gint)sizeof(sel) - 1, line_len - 1);
3100 if (buf_len < 0)
3101 continue;
3102 sci_get_text_range(editor->sci, line_start, line_start + buf_len, sel);
3103 sel[buf_len] = '\0';
3105 while (isspace(sel[x])) x++;
3107 /* to skip blank lines */
3108 if (allow_empty_lines || (x < line_len && sel[x] != '\0'))
3110 /* use single line comment */
3111 if (cc == NULL || strlen(cc) == 0)
3113 gint start = line_start;
3114 single_line = TRUE;
3116 if (ft->comment_use_indent)
3117 start = line_start + x;
3119 if (toggle)
3121 gchar *text = g_strconcat(co, editor_prefs.comment_toggle_mark, NULL);
3122 sci_insert_text(editor->sci, start, text);
3123 g_free(text);
3125 else
3126 sci_insert_text(editor->sci, start, co);
3128 /* use multi line comment */
3129 else
3131 gint style_comment;
3133 /* skip lines which are already comments */
3134 style_comment = get_multiline_comment_style(editor, line_start);
3135 if (sci_get_style_at(editor->sci, line_start + x) == style_comment)
3136 continue;
3138 real_comment_multiline(editor, line_start, last_line);
3140 /* break because we are already on the last line */
3141 break_loop = TRUE;
3142 break;
3146 sci_end_undo_action(editor->sci);
3148 /* restore selection if there is one
3149 * but don't touch the selection if caller is editor_do_comment_toggle */
3150 if (! toggle && sel_start < sel_end)
3152 if (single_line)
3154 sci_set_selection_start(editor->sci, sel_start + co_len);
3155 sci_set_selection_end(editor->sci, sel_end + ((i - first_line) * co_len));
3157 else
3159 gint eol_len = editor_get_eol_char_len(editor);
3160 sci_set_selection_start(editor->sci, sel_start + co_len + eol_len);
3161 sci_set_selection_end(editor->sci, sel_end + co_len + eol_len);
3167 static gboolean brace_timeout_active = FALSE;
3169 static gboolean delay_match_brace(G_GNUC_UNUSED gpointer user_data)
3171 GeanyDocument *doc = document_get_current();
3172 GeanyEditor *editor;
3173 gint brace_pos = GPOINTER_TO_INT(user_data);
3174 gint end_pos, cur_pos;
3176 brace_timeout_active = FALSE;
3177 if (!doc)
3178 return FALSE;
3180 editor = doc->editor;
3181 cur_pos = sci_get_current_position(editor->sci) - 1;
3183 if (cur_pos != brace_pos)
3185 cur_pos++;
3186 if (cur_pos != brace_pos)
3188 /* we have moved past the original brace_pos, but after the timeout
3189 * we may now be on a new brace, so check again */
3190 editor_highlight_braces(editor, cur_pos);
3191 return FALSE;
3194 if (!utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3196 editor_highlight_braces(editor, cur_pos);
3197 return FALSE;
3199 end_pos = sci_find_matching_brace(editor->sci, brace_pos);
3201 if (end_pos >= 0)
3203 gint col = MIN(sci_get_col_from_position(editor->sci, brace_pos),
3204 sci_get_col_from_position(editor->sci, end_pos));
3205 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, col, 0);
3206 SSM(editor->sci, SCI_BRACEHIGHLIGHT, brace_pos, end_pos);
3208 else
3210 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3211 SSM(editor->sci, SCI_BRACEBADLIGHT, brace_pos, 0);
3213 return FALSE;
3217 static void editor_highlight_braces(GeanyEditor *editor, gint cur_pos)
3219 gint brace_pos = cur_pos - 1;
3221 SSM(editor->sci, SCI_SETHIGHLIGHTGUIDE, 0, 0);
3222 SSM(editor->sci, SCI_BRACEBADLIGHT, (uptr_t)-1, 0);
3224 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3226 brace_pos++;
3227 if (! utils_isbrace(sci_get_char_at(editor->sci, brace_pos), editor_prefs.brace_match_ltgt))
3229 return;
3232 if (!brace_timeout_active)
3234 brace_timeout_active = TRUE;
3235 /* delaying matching makes scrolling faster e.g. holding down arrow keys */
3236 g_timeout_add(100, delay_match_brace, GINT_TO_POINTER(brace_pos));
3241 static gboolean in_block_comment(gint lexer, gint style)
3243 switch (lexer)
3245 case SCLEX_CPP:
3246 return (style == SCE_C_COMMENT ||
3247 style == SCE_C_COMMENTDOC);
3249 case SCLEX_PASCAL:
3250 return (style == SCE_PAS_COMMENT ||
3251 style == SCE_PAS_COMMENT2);
3253 case SCLEX_D:
3254 return (style == SCE_D_COMMENT ||
3255 style == SCE_D_COMMENTDOC ||
3256 style == SCE_D_COMMENTNESTED);
3258 case SCLEX_HTML:
3259 return (style == SCE_HPHP_COMMENT);
3261 case SCLEX_CSS:
3262 return (style == SCE_CSS_COMMENT);
3264 default:
3265 return FALSE;
3270 static gboolean is_comment_char(gchar c, gint lexer)
3272 if ((c == '*' || c == '+') && lexer == SCLEX_D)
3273 return TRUE;
3274 else
3275 if (c == '*')
3276 return TRUE;
3278 return FALSE;
3282 static void auto_multiline(GeanyEditor *editor, gint cur_line)
3284 ScintillaObject *sci = editor->sci;
3285 gint indent_pos, style;
3286 gint lexer = sci_get_lexer(sci);
3288 /* Use the start of the line enter was pressed on, to avoid any doc keyword styles */
3289 indent_pos = sci_get_line_indent_position(sci, cur_line - 1);
3290 style = sci_get_style_at(sci, indent_pos);
3291 if (!in_block_comment(lexer, style))
3292 return;
3294 /* Check whether the comment block continues on this line */
3295 indent_pos = sci_get_line_indent_position(sci, cur_line);
3296 if (sci_get_style_at(sci, indent_pos) == style)
3298 gchar *previous_line = sci_get_line(sci, cur_line - 1);
3299 /* the type of comment, '*' (C/C++/Java), '+' and the others (D) */
3300 gchar *continuation = "*";
3301 gchar *whitespace = ""; /* to hold whitespace if needed */
3302 gchar *result;
3303 gint len = strlen(previous_line);
3304 gint i;
3306 /* find and stop at end of multi line comment */
3307 i = len - 1;
3308 while (i >= 0 && isspace(previous_line[i])) i--;
3309 if (i >= 1 && is_comment_char(previous_line[i - 1], lexer) && previous_line[i] == '/')
3311 gint indent_len, indent_width;
3313 indent_pos = sci_get_line_indent_position(sci, cur_line);
3314 indent_len = sci_get_col_from_position(sci, indent_pos);
3315 indent_width = editor_get_indent_prefs(editor)->width;
3317 /* if there is one too many spaces, delete the last space,
3318 * to return to the indent used before the multiline comment was started. */
3319 if (indent_len % indent_width == 1)
3320 SSM(sci, SCI_DELETEBACKNOTLINE, 0, 0); /* remove whitespace indent */
3321 g_free(previous_line);
3322 return;
3324 /* check whether we are on the second line of multi line comment */
3325 i = 0;
3326 while (i < len && isspace(previous_line[i])) i++; /* get to start of the line */
3328 if (i + 1 < len &&
3329 previous_line[i] == '/' && is_comment_char(previous_line[i + 1], lexer))
3330 { /* we are on the second line of a multi line comment, so we have to insert white space */
3331 whitespace = " ";
3334 if (G_UNLIKELY(style == SCE_D_COMMENTNESTED))
3335 continuation = "+"; /* for nested comments in D */
3337 result = g_strconcat(whitespace, continuation, " ", NULL);
3338 sci_add_text(sci, result);
3339 g_free(result);
3341 g_free(previous_line);
3346 /* Checks whether the given style is a string for the given lexer.
3347 * It doesn't handle LEX_HTML, this should be done by the caller.
3348 * Returns true if the style is a string, FALSE otherwise.
3350 * Don't forget STRINGEOL, to prevent completion whilst typing a string with no closing char.
3352 static gboolean is_string_style(gint lexer, gint style)
3354 switch (lexer)
3356 case SCLEX_CPP:
3357 return (style == SCE_C_CHARACTER ||
3358 style == SCE_C_STRING ||
3359 style == SCE_C_STRINGEOL);
3361 case SCLEX_PASCAL:
3362 return (style == SCE_PAS_CHARACTER ||
3363 style == SCE_PAS_STRING ||
3364 style == SCE_PAS_STRINGEOL);
3366 case SCLEX_D:
3367 return (style == SCE_D_STRING ||
3368 style == SCE_D_STRINGEOL ||
3369 style == SCE_D_CHARACTER ||
3370 style == SCE_D_STRINGB ||
3371 style == SCE_D_STRINGR);
3373 case SCLEX_PYTHON:
3374 return (style == SCE_P_STRING ||
3375 style == SCE_P_TRIPLE ||
3376 style == SCE_P_TRIPLEDOUBLE ||
3377 style == SCE_P_CHARACTER ||
3378 style == SCE_P_STRINGEOL);
3380 case SCLEX_F77:
3381 case SCLEX_FORTRAN:
3382 return (style == SCE_F_STRING1 ||
3383 style == SCE_F_STRING2 ||
3384 style == SCE_F_STRINGEOL);
3386 case SCLEX_PERL:
3387 return (/*style == SCE_PL_STRING ||*/ /* may want variable autocompletion "$(foo)" */
3388 style == SCE_PL_CHARACTER ||
3389 style == SCE_PL_HERE_DELIM ||
3390 style == SCE_PL_HERE_Q ||
3391 style == SCE_PL_HERE_QQ ||
3392 style == SCE_PL_HERE_QX ||
3393 style == SCE_PL_POD ||
3394 style == SCE_PL_STRING_Q ||
3395 style == SCE_PL_STRING_QQ ||
3396 style == SCE_PL_STRING_QX ||
3397 style == SCE_PL_STRING_QR ||
3398 style == SCE_PL_STRING_QW ||
3399 style == SCE_PL_POD_VERB);
3401 case SCLEX_R:
3402 return (style == SCE_R_STRING);
3404 case SCLEX_RUBY:
3405 return (style == SCE_RB_CHARACTER ||
3406 style == SCE_RB_STRING ||
3407 style == SCE_RB_HERE_DELIM ||
3408 style == SCE_RB_HERE_Q ||
3409 style == SCE_RB_HERE_QQ ||
3410 style == SCE_RB_HERE_QX ||
3411 style == SCE_RB_POD);
3413 case SCLEX_BASH:
3414 return (style == SCE_SH_STRING);
3416 case SCLEX_SQL:
3417 return (style == SCE_SQL_STRING);
3419 case SCLEX_TCL:
3420 return (style == SCE_TCL_IN_QUOTE);
3422 case SCLEX_LUA:
3423 return (style == SCE_LUA_LITERALSTRING ||
3424 style == SCE_LUA_CHARACTER ||
3425 style == SCE_LUA_STRINGEOL ||
3426 style == SCE_LUA_STRING);
3428 case SCLEX_HASKELL:
3429 return (style == SCE_HA_CHARACTER ||
3430 style == SCE_HA_STRING);
3432 case SCLEX_FREEBASIC:
3433 return (style == SCE_B_STRING ||
3434 style == SCE_B_STRINGEOL);
3436 case SCLEX_MATLAB:
3437 return (style == SCE_MATLAB_STRING ||
3438 style == SCE_MATLAB_DOUBLEQUOTESTRING);
3440 case SCLEX_HTML:
3441 return (
3442 style == SCE_HBA_STRING ||
3443 style == SCE_HBA_STRINGEOL ||
3444 style == SCE_HB_STRING ||
3445 style == SCE_HB_STRINGEOL ||
3446 style == SCE_H_CDATA ||
3447 style == SCE_H_DOUBLESTRING ||
3448 style == SCE_HJA_DOUBLESTRING ||
3449 style == SCE_HJA_SINGLESTRING ||
3450 style == SCE_HJA_STRINGEOL ||
3451 style == SCE_HJ_DOUBLESTRING ||
3452 style == SCE_HJ_SINGLESTRING ||
3453 style == SCE_HJ_STRINGEOL ||
3454 style == SCE_HPA_CHARACTER ||
3455 style == SCE_HPA_STRING ||
3456 style == SCE_HPA_TRIPLE ||
3457 style == SCE_HPA_TRIPLEDOUBLE ||
3458 style == SCE_HP_CHARACTER ||
3459 style == SCE_HPHP_HSTRING ||
3460 style == SCE_HPHP_HSTRING || /* HSTRING is a heredoc */
3461 style == SCE_HPHP_HSTRING_VARIABLE ||
3462 style == SCE_HPHP_SIMPLESTRING ||
3463 style == SCE_HPHP_SIMPLESTRING ||
3464 style == SCE_HP_STRING ||
3465 style == SCE_HP_TRIPLE ||
3466 style == SCE_HP_TRIPLEDOUBLE ||
3467 style == SCE_H_SGML_DOUBLESTRING ||
3468 style == SCE_H_SGML_SIMPLESTRING ||
3469 style == SCE_H_SINGLESTRING);
3471 case SCLEX_CMAKE:
3472 return (style == SCE_CMAKE_STRINGDQ ||
3473 style == SCE_CMAKE_STRINGLQ ||
3474 style == SCE_CMAKE_STRINGRQ ||
3475 style == SCE_CMAKE_STRINGVAR);
3477 case SCLEX_NSIS:
3478 return (style == SCE_NSIS_STRINGDQ ||
3479 style == SCE_NSIS_STRINGLQ ||
3480 style == SCE_NSIS_STRINGRQ ||
3481 style == SCE_NSIS_STRINGVAR);
3483 case SCLEX_ADA:
3484 return (style == SCE_ADA_CHARACTER ||
3485 style == SCE_ADA_STRING ||
3486 style == SCE_ADA_CHARACTEREOL ||
3487 style == SCE_ADA_STRINGEOL);
3489 return FALSE;
3493 /* Checks whether the given style is a comment for the given lexer.
3494 * It doesn't handle LEX_HTML, this should be done by the caller.
3495 * Returns true if the style is a comment, FALSE otherwise.
3497 static gboolean is_comment_style(gint lexer, gint style)
3499 switch (lexer)
3501 case SCLEX_CPP:
3502 return (style == SCE_C_COMMENT ||
3503 style == SCE_C_COMMENTLINE ||
3504 style == SCE_C_COMMENTDOC ||
3505 style == SCE_C_COMMENTLINEDOC ||
3506 style == SCE_C_COMMENTDOCKEYWORD ||
3507 style == SCE_C_COMMENTDOCKEYWORDERROR);
3509 case SCLEX_PASCAL:
3510 return (style == SCE_PAS_COMMENT ||
3511 style == SCE_PAS_COMMENT2 ||
3512 style == SCE_PAS_COMMENTLINE);
3514 case SCLEX_D:
3515 return (style == SCE_D_COMMENT ||
3516 style == SCE_D_COMMENTLINE ||
3517 style == SCE_D_COMMENTDOC ||
3518 style == SCE_D_COMMENTNESTED ||
3519 style == SCE_D_COMMENTLINEDOC ||
3520 style == SCE_D_COMMENTDOCKEYWORD ||
3521 style == SCE_D_COMMENTDOCKEYWORDERROR);
3523 case SCLEX_PYTHON:
3524 return (style == SCE_P_COMMENTLINE ||
3525 style == SCE_P_COMMENTBLOCK);
3527 case SCLEX_F77:
3528 case SCLEX_FORTRAN:
3529 return (style == SCE_F_COMMENT);
3531 case SCLEX_PERL:
3532 return (style == SCE_PL_COMMENTLINE);
3534 case SCLEX_PROPERTIES:
3535 return (style == SCE_PROPS_COMMENT);
3537 case SCLEX_PO:
3538 return (style == SCE_PO_COMMENT);
3540 case SCLEX_LATEX:
3541 return (style == SCE_L_COMMENT);
3543 case SCLEX_MAKEFILE:
3544 return (style == SCE_MAKE_COMMENT);
3546 case SCLEX_RUBY:
3547 return (style == SCE_RB_COMMENTLINE);
3549 case SCLEX_BASH:
3550 return (style == SCE_SH_COMMENTLINE);
3552 case SCLEX_R:
3553 return (style == SCE_R_COMMENT);
3555 case SCLEX_SQL:
3556 return (style == SCE_SQL_COMMENT ||
3557 style == SCE_SQL_COMMENTLINE ||
3558 style == SCE_SQL_COMMENTDOC);
3560 case SCLEX_TCL:
3561 return (style == SCE_TCL_COMMENT ||
3562 style == SCE_TCL_COMMENTLINE ||
3563 style == SCE_TCL_COMMENT_BOX ||
3564 style == SCE_TCL_BLOCK_COMMENT);
3566 case SCLEX_MATLAB:
3567 return (style == SCE_MATLAB_COMMENT);
3569 case SCLEX_LUA:
3570 return (style == SCE_LUA_COMMENT ||
3571 style == SCE_LUA_COMMENTLINE ||
3572 style == SCE_LUA_COMMENTDOC);
3574 case SCLEX_HASKELL:
3575 return (style == SCE_HA_COMMENTLINE ||
3576 style == SCE_HA_COMMENTBLOCK ||
3577 style == SCE_HA_COMMENTBLOCK2 ||
3578 style == SCE_HA_COMMENTBLOCK3);
3580 case SCLEX_FREEBASIC:
3581 return (style == SCE_B_COMMENT);
3583 case SCLEX_YAML:
3584 return (style == SCE_YAML_COMMENT);
3586 case SCLEX_HTML:
3587 return (
3588 style == SCE_HBA_COMMENTLINE ||
3589 style == SCE_HB_COMMENTLINE ||
3590 style == SCE_H_COMMENT ||
3591 style == SCE_HJA_COMMENT ||
3592 style == SCE_HJA_COMMENTDOC ||
3593 style == SCE_HJA_COMMENTLINE ||
3594 style == SCE_HJ_COMMENT ||
3595 style == SCE_HJ_COMMENTDOC ||
3596 style == SCE_HJ_COMMENTLINE ||
3597 style == SCE_HPA_COMMENTLINE ||
3598 style == SCE_HP_COMMENTLINE ||
3599 style == SCE_HPHP_COMMENT ||
3600 style == SCE_HPHP_COMMENTLINE ||
3601 style == SCE_H_SGML_COMMENT);
3603 case SCLEX_CMAKE:
3604 return (style == SCE_CMAKE_COMMENT);
3606 case SCLEX_NSIS:
3607 return (style == SCE_NSIS_COMMENT ||
3608 style == SCE_NSIS_COMMENTBOX);
3610 case SCLEX_ADA:
3611 return (style == SCE_ADA_COMMENTLINE ||
3612 style == SCE_NSIS_COMMENTBOX);
3614 return FALSE;
3618 /* Checks whether the given style is normal code (not string, comment, preprocessor, etc).
3619 * It doesn't handle LEX_HTML, this should be done by the caller.
3621 static gboolean is_code_style(gint lexer, gint style)
3623 switch (lexer)
3625 case SCLEX_CPP:
3626 if (style == SCE_C_PREPROCESSOR)
3627 return FALSE;
3628 break;
3630 return !(is_comment_style(lexer, style) ||
3631 is_string_style(lexer, style));
3635 #if 0
3636 static gboolean editor_lexer_is_c_like(gint lexer)
3638 switch (lexer)
3640 case SCLEX_CPP:
3641 case SCLEX_D:
3642 return TRUE;
3644 default:
3645 return FALSE;
3648 #endif
3651 /* Returns: -1 if lexer doesn't support type keywords */
3652 gint editor_lexer_get_type_keyword_idx(gint lexer)
3654 switch (lexer)
3656 case SCLEX_CPP:
3657 case SCLEX_D:
3658 return 3;
3660 default:
3661 return -1;
3666 /* inserts a three-line comment at one line above current cursor position */
3667 void editor_insert_multiline_comment(GeanyEditor *editor)
3669 gchar *text;
3670 gint text_len;
3671 gint line;
3672 gint pos;
3673 gboolean have_multiline_comment = FALSE;
3674 GeanyDocument *doc;
3676 g_return_if_fail(editor != NULL &&
3677 editor->document->file_type != NULL && editor->document->file_type->comment_open != NULL);
3679 doc = editor->document;
3681 if (doc->file_type->comment_close != NULL && strlen(doc->file_type->comment_close) > 0)
3682 have_multiline_comment = TRUE;
3684 /* insert three lines one line above of the current position */
3685 line = sci_get_line_from_position(editor->sci, editor_info.click_pos);
3686 pos = sci_get_position_from_line(editor->sci, line);
3688 /* use the indent on the current line but only when comment indentation is used
3689 * and we don't have multi line comment characters */
3690 if (editor->auto_indent &&
3691 ! have_multiline_comment && doc->file_type->comment_use_indent)
3693 read_indent(editor, editor_info.click_pos);
3694 text = g_strdup_printf("%s\n%s\n%s\n", indent, indent, indent);
3695 text_len = strlen(text);
3697 else
3699 text = g_strdup("\n\n\n");
3700 text_len = 3;
3702 sci_insert_text(editor->sci, pos, text);
3703 g_free(text);
3706 /* select the inserted lines for commenting */
3707 sci_set_selection_start(editor->sci, pos);
3708 sci_set_selection_end(editor->sci, pos + text_len);
3710 editor_do_comment(editor, -1, TRUE, FALSE);
3712 /* set the current position to the start of the first inserted line */
3713 pos += strlen(doc->file_type->comment_open);
3715 /* on multi line comment jump to the next line, otherwise add the length of added indentation */
3716 if (have_multiline_comment)
3717 pos += 1;
3718 else
3719 pos += strlen(indent);
3721 sci_set_current_position(editor->sci, pos, TRUE);
3722 /* reset the selection */
3723 sci_set_anchor(editor->sci, pos);
3727 /* Note: If the editor is pending a redraw, set document::scroll_percent instead.
3728 * Scroll the view to make line appear at percent_of_view.
3729 * line can be -1 to use the current position. */
3730 void editor_scroll_to_line(GeanyEditor *editor, gint line, gfloat percent_of_view)
3732 gint vis1, los, delta;
3733 GtkWidget *wid;
3735 g_return_if_fail(editor != NULL);
3737 wid = GTK_WIDGET(editor->sci);
3739 if (! wid->window || ! gdk_window_is_viewable(wid->window))
3740 return; /* prevent gdk_window_scroll warning */
3742 if (line == -1)
3743 line = sci_get_current_line(editor->sci);
3745 /* sci 'visible line' != doc line number because of folding and line wrapping */
3746 /* calling SCI_VISIBLEFROMDOCLINE for line is more accurate than calling
3747 * SCI_DOCLINEFROMVISIBLE for vis1. */
3748 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0);
3749 vis1 = SSM(editor->sci, SCI_GETFIRSTVISIBLELINE, 0, 0);
3750 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
3751 delta = (line - vis1) - los * percent_of_view;
3752 sci_scroll_lines(editor->sci, delta);
3753 sci_scroll_caret(editor->sci); /* needed for horizontal scrolling */
3757 /* creates and inserts one tab or whitespace of the amount of the tab width */
3758 void editor_insert_alternative_whitespace(GeanyEditor *editor)
3760 gchar *text;
3761 GeanyIndentPrefs iprefs = *editor_get_indent_prefs(editor);
3763 g_return_if_fail(editor != NULL);
3765 switch (iprefs.type)
3767 case GEANY_INDENT_TYPE_TABS:
3768 iprefs.type = GEANY_INDENT_TYPE_SPACES;
3769 break;
3770 case GEANY_INDENT_TYPE_SPACES:
3771 case GEANY_INDENT_TYPE_BOTH: /* most likely we want a tab */
3772 iprefs.type = GEANY_INDENT_TYPE_TABS;
3773 break;
3775 text = get_whitespace(&iprefs, iprefs.width);
3776 sci_add_text(editor->sci, text);
3777 g_free(text);
3781 void editor_select_word(GeanyEditor *editor)
3783 gint pos;
3784 gint start;
3785 gint end;
3787 g_return_if_fail(editor != NULL);
3789 pos = SSM(editor->sci, SCI_GETCURRENTPOS, 0, 0);
3790 start = SSM(editor->sci, SCI_WORDSTARTPOSITION, pos, TRUE);
3791 end = SSM(editor->sci, SCI_WORDENDPOSITION, pos, TRUE);
3793 if (start == end) /* caret in whitespaces sequence */
3795 /* look forward but reverse the selection direction,
3796 * so the caret end up stay as near as the original position. */
3797 end = SSM(editor->sci, SCI_WORDENDPOSITION, pos, FALSE);
3798 start = SSM(editor->sci, SCI_WORDENDPOSITION, end, TRUE);
3799 if (start == end)
3800 return;
3803 sci_set_selection(editor->sci, start, end);
3807 /* extra_line is for selecting the cursor line (or anchor line) at the bottom of a selection,
3808 * when those lines have no selection (cursor at start of line). */
3809 void editor_select_lines(GeanyEditor *editor, gboolean extra_line)
3811 gint start, end, line;
3813 g_return_if_fail(editor != NULL);
3815 start = sci_get_selection_start(editor->sci);
3816 end = sci_get_selection_end(editor->sci);
3818 /* check if whole lines are already selected */
3819 if (! extra_line && start != end &&
3820 sci_get_col_from_position(editor->sci, start) == 0 &&
3821 sci_get_col_from_position(editor->sci, end) == 0)
3822 return;
3824 line = sci_get_line_from_position(editor->sci, start);
3825 start = sci_get_position_from_line(editor->sci, line);
3827 line = sci_get_line_from_position(editor->sci, end);
3828 end = sci_get_position_from_line(editor->sci, line + 1);
3830 sci_set_selection(editor->sci, start, end);
3834 /* find the start or end of a paragraph by searching all lines in direction (UP or DOWN)
3835 * starting at the given line and return the found line or return -1 if called on an empty line */
3836 static gint find_paragraph_stop(GeanyEditor *editor, gint line, gint direction)
3838 gboolean found_end = FALSE;
3839 gint step;
3840 gchar *line_buf, *x;
3841 ScintillaObject *sci = editor->sci;
3843 /* first check current line and return -1 if it is empty to skip creating of a selection */
3844 line_buf = x = sci_get_line(sci, line);
3845 while (isspace(*x))
3846 x++;
3847 if (*x == '\0')
3849 g_free(line_buf);
3850 return -1;
3853 if (direction == GTK_DIR_UP)
3854 step = -1;
3855 else
3856 step = 1;
3858 while (! found_end)
3860 line += step;
3862 /* sci_get_line checks for sanity of the given line, sci_get_line always return a string
3863 * containing at least '\0' so no need to check for NULL */
3864 line_buf = x = sci_get_line(sci, line);
3866 /* check whether after skipping all whitespace we are at end of line and if so, assume
3867 * this line as end of paragraph */
3868 while (isspace(*x))
3869 x++;
3870 if (*x == '\0')
3872 found_end = TRUE;
3873 if (line == -1)
3874 /* called on the first line but there is no previous line so return line 0 */
3875 line = 0;
3877 g_free(line_buf);
3879 return line;
3883 void editor_select_paragraph(GeanyEditor *editor)
3885 gint pos_start, pos_end, line_start, line_found;
3887 g_return_if_fail(editor != NULL);
3889 line_start = SSM(editor->sci, SCI_LINEFROMPOSITION,
3890 SSM(editor->sci, SCI_GETCURRENTPOS, 0, 0), 0);
3892 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_UP);
3893 if (line_found == -1)
3894 return;
3896 /* find_paragraph_stop returns the emtpy line(previous to the real start of the paragraph),
3897 * so use the next line for selection start */
3898 if (line_found > 0)
3899 line_found++;
3901 pos_start = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3903 line_found = find_paragraph_stop(editor, line_start, GTK_DIR_DOWN);
3904 pos_end = SSM(editor->sci, SCI_POSITIONFROMLINE, line_found, 0);
3906 sci_set_selection(editor->sci, pos_start, pos_end);
3910 /* simple indentation to indent the current line with the same indent as the previous one */
3911 static void smart_line_indentation(GeanyEditor *editor, gint first_line, gint last_line)
3913 gint i, sel_start = 0, sel_end = 0;
3915 /* get previous line and use it for read_indent to use that line
3916 * (otherwise it would fail on a line only containing "{" in advanced indentation mode) */
3917 read_indent(editor, sci_get_position_from_line(editor->sci, first_line - 1));
3919 for (i = first_line; i <= last_line; i++)
3921 /* skip the first line or if the indentation of the previous and current line are equal */
3922 if (i == 0 ||
3923 SSM(editor->sci, SCI_GETLINEINDENTATION, i - 1, 0) ==
3924 SSM(editor->sci, SCI_GETLINEINDENTATION, i, 0))
3925 continue;
3927 sel_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
3928 sel_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
3929 if (sel_start < sel_end)
3931 sci_set_selection(editor->sci, sel_start, sel_end);
3932 sci_replace_sel(editor->sci, "");
3934 sci_insert_text(editor->sci, sel_start, indent);
3939 /* simple indentation to indent the current line with the same indent as the previous one */
3940 void editor_smart_line_indentation(GeanyEditor *editor, gint pos)
3942 gint first_line, last_line;
3943 gint first_sel_start, first_sel_end;
3944 ScintillaObject *sci;
3946 g_return_if_fail(editor != NULL);
3948 sci = editor->sci;
3950 first_sel_start = sci_get_selection_start(sci);
3951 first_sel_end = sci_get_selection_end(sci);
3953 first_line = sci_get_line_from_position(sci, first_sel_start);
3954 /* Find the last line with chars selected (not EOL char) */
3955 last_line = sci_get_line_from_position(sci, first_sel_end - editor_get_eol_char_len(editor));
3956 last_line = MAX(first_line, last_line);
3958 if (pos == -1)
3959 pos = first_sel_start;
3961 sci_start_undo_action(sci);
3963 smart_line_indentation(editor, first_line, last_line);
3965 /* set cursor position if there was no selection */
3966 if (first_sel_start == first_sel_end)
3968 gint indent_pos = SSM(sci, SCI_GETLINEINDENTPOSITION, first_line, 0);
3970 /* use indent position as user may wish to change indentation afterwards */
3971 sci_set_current_position(sci, indent_pos, FALSE);
3973 else
3975 /* fully select all the lines affected */
3976 sci_set_selection_start(sci, sci_get_position_from_line(sci, first_line));
3977 sci_set_selection_end(sci, sci_get_position_from_line(sci, last_line + 1));
3980 sci_end_undo_action(sci);
3984 /* increase / decrease current line or selection by one space */
3985 void editor_indentation_by_one_space(GeanyEditor *editor, gint pos, gboolean decrease)
3987 gint i, first_line, last_line, line_start, indentation_end, count = 0;
3988 gint sel_start, sel_end, first_line_offset = 0;
3990 g_return_if_fail(editor != NULL);
3992 sel_start = sci_get_selection_start(editor->sci);
3993 sel_end = sci_get_selection_end(editor->sci);
3995 first_line = sci_get_line_from_position(editor->sci, sel_start);
3996 /* Find the last line with chars selected (not EOL char) */
3997 last_line = sci_get_line_from_position(editor->sci, sel_end - editor_get_eol_char_len(editor));
3998 last_line = MAX(first_line, last_line);
4000 if (pos == -1)
4001 pos = sel_start;
4003 sci_start_undo_action(editor->sci);
4005 for (i = first_line; i <= last_line; i++)
4007 indentation_end = SSM(editor->sci, SCI_GETLINEINDENTPOSITION, i, 0);
4008 if (decrease)
4010 line_start = SSM(editor->sci, SCI_POSITIONFROMLINE, i, 0);
4011 /* searching backwards for a space to remove */
4012 while (sci_get_char_at(editor->sci, indentation_end) != ' ' && indentation_end > line_start)
4013 indentation_end--;
4015 if (sci_get_char_at(editor->sci, indentation_end) == ' ')
4017 sci_set_selection(editor->sci, indentation_end, indentation_end + 1);
4018 sci_replace_sel(editor->sci, "");
4019 count--;
4020 if (i == first_line)
4021 first_line_offset = -1;
4024 else
4026 sci_insert_text(editor->sci, indentation_end, " ");
4027 count++;
4028 if (i == first_line)
4029 first_line_offset = 1;
4033 /* set cursor position */
4034 if (sel_start < sel_end)
4036 gint start = sel_start + first_line_offset;
4037 if (first_line_offset < 0)
4038 start = MAX(sel_start + first_line_offset,
4039 SSM(editor->sci, SCI_POSITIONFROMLINE, first_line, 0));
4041 sci_set_selection_start(editor->sci, start);
4042 sci_set_selection_end(editor->sci, sel_end + count);
4044 else
4045 sci_set_current_position(editor->sci, pos + count, FALSE);
4047 sci_end_undo_action(editor->sci);
4051 void editor_finalize()
4053 scintilla_release_resources();
4057 /* wordchars: NULL or a string containing characters to match a word.
4058 * Returns: the current selection or the current word. */
4059 gchar *editor_get_default_selection(GeanyEditor *editor, gboolean use_current_word,
4060 const gchar *wordchars)
4062 gchar *s = NULL;
4064 g_return_val_if_fail(editor != NULL, NULL);
4066 if (sci_get_lines_selected(editor->sci) == 1)
4068 gint len = sci_get_selected_text_length(editor->sci);
4070 s = g_malloc(len + 1);
4071 sci_get_selected_text(editor->sci, s);
4073 else if (sci_get_lines_selected(editor->sci) == 0 && use_current_word)
4074 { /* use the word at current cursor position */
4075 gchar word[GEANY_MAX_WORD_LENGTH];
4077 editor_find_current_word(editor, -1, word, sizeof(word), wordchars);
4078 if (word[0] != '\0')
4079 s = g_strdup(word);
4081 return s;
4085 /* Note: Usually the line should be made visible (not folded) before calling this.
4086 * Returns: TRUE if line is/will be displayed to the user, or FALSE if it is
4087 * outside the *vertical* view.
4088 * Warning: You may need horizontal scrolling to make the cursor visible - so always call
4089 * sci_scroll_caret() when this returns TRUE. */
4090 gboolean editor_line_in_view(GeanyEditor *editor, gint line)
4092 gint vis1, los;
4094 g_return_val_if_fail(editor != NULL, FALSE);
4096 /* If line is wrapped the result may occur on another virtual line than the first and may be
4097 * still hidden, so increase the line number to check for the next document line */
4098 if (SSM(editor->sci, SCI_WRAPCOUNT, line, 0) > 1)
4099 line++;
4101 line = SSM(editor->sci, SCI_VISIBLEFROMDOCLINE, line, 0); /* convert to visible line number */
4102 vis1 = SSM(editor->sci, SCI_GETFIRSTVISIBLELINE, 0, 0);
4103 los = SSM(editor->sci, SCI_LINESONSCREEN, 0, 0);
4105 return (line >= vis1 && line < vis1 + los);
4109 /* If the current line is outside the current view window, scroll the line
4110 * so it appears at percent_of_view. */
4111 void editor_display_current_line(GeanyEditor *editor, gfloat percent_of_view)
4113 gint line;
4115 g_return_if_fail(editor != NULL);
4117 line = sci_get_current_line(editor->sci);
4119 /* unfold maybe folded results */
4120 sci_ensure_line_is_visible(editor->sci, line);
4122 /* scroll the line if it's off screen */
4123 if (! editor_line_in_view(editor, line))
4124 editor->scroll_percent = percent_of_view;
4125 else
4126 sci_scroll_caret(editor->sci); /* may need horizontal scrolling */
4131 * Deletes all currently set indicators in the @a editor window.
4132 * Error indicators (red squiggly underlines) and usual line markers are removed.
4134 * @param editor The editor to operate on.
4136 void editor_indicator_clear_errors(GeanyEditor *editor)
4138 editor_indicator_clear(editor, GEANY_INDICATOR_ERROR);
4139 sci_marker_delete_all(editor->sci, 0); /* remove the yellow error line marker */
4144 * Deletes all currently set indicators matching @a indic in the @a editor window.
4146 * @param editor The editor to operate on.
4147 * @param indic The indicator number to clear, this is a value of @ref GeanyIndicator.
4149 * @since 0.16
4151 void editor_indicator_clear(GeanyEditor *editor, gint indic)
4153 glong last_pos;
4155 g_return_if_fail(editor != NULL);
4157 last_pos = sci_get_length(editor->sci);
4158 if (last_pos > 0)
4160 sci_indicator_set(editor->sci, indic);
4161 sci_indicator_clear(editor->sci, 0, last_pos);
4167 * Sets an indicator @a indic on @a line.
4168 * Whitespace at the start and the end of the line is not marked.
4170 * @param editor The editor to operate on.
4171 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4172 * @param line The line number which should be marked.
4174 * @since 0.16
4176 void editor_indicator_set_on_line(GeanyEditor *editor, gint indic, gint line)
4178 gint start, end;
4179 guint i = 0, len;
4180 gchar *linebuf;
4182 g_return_if_fail(editor != NULL);
4183 g_return_if_fail(line >= 0);
4185 start = sci_get_position_from_line(editor->sci, line);
4186 end = sci_get_position_from_line(editor->sci, line + 1);
4188 /* skip blank lines */
4189 if ((start + 1) == end ||
4190 start > end ||
4191 sci_get_line_length(editor->sci, line) == editor_get_eol_char_len(editor))
4193 return;
4196 len = end - start;
4197 linebuf = sci_get_line(editor->sci, line);
4199 /* don't set the indicator on whitespace */
4200 while (isspace(linebuf[i]))
4201 i++;
4202 while (len > 1 && len > i && isspace(linebuf[len - 1]))
4204 len--;
4205 end--;
4207 g_free(linebuf);
4209 editor_indicator_set_on_range(editor, indic, start + i, end);
4214 * Sets an indicator on the range specified by @a start and @a end.
4215 * No error checking or whitespace removal is performed, this should be done by the calling
4216 * function if necessary.
4218 * @param editor The editor to operate on.
4219 * @param indic The indicator number to use, this is a value of @ref GeanyIndicator.
4220 * @param start The starting position for the marker.
4221 * @param end The ending position for the marker.
4223 * @since 0.16
4225 void editor_indicator_set_on_range(GeanyEditor *editor, gint indic, gint start, gint end)
4227 g_return_if_fail(editor != NULL);
4228 if (start >= end)
4229 return;
4231 sci_indicator_set(editor->sci, indic);
4232 sci_indicator_fill(editor->sci, start, end - start);
4236 /* Inserts the given colour (format should be #...), if there is a selection starting with 0x...
4237 * the replacement will also start with 0x... */
4238 void editor_insert_color(GeanyEditor *editor, const gchar *colour)
4240 g_return_if_fail(editor != NULL);
4242 if (sci_has_selection(editor->sci))
4244 gint start = sci_get_selection_start(editor->sci);
4245 const gchar *replacement = colour;
4247 if (sci_get_char_at(editor->sci, start) == '0' &&
4248 sci_get_char_at(editor->sci, start + 1) == 'x')
4250 sci_set_selection_start(editor->sci, start + 2);
4251 sci_set_selection_end(editor->sci, start + 8);
4252 replacement++; /* skip the leading "0x" */
4254 else if (sci_get_char_at(editor->sci, start - 1) == '#')
4255 { /* double clicking something like #00ffff may only select 00ffff because of wordchars */
4256 replacement++; /* so skip the '#' to only replace the colour value */
4258 sci_replace_sel(editor->sci, replacement);
4260 else
4261 sci_add_text(editor->sci, colour);
4266 * Retrieves the localized name (for displaying) of the used end of line characters
4267 * (LF, CR/LF, CR) in the given editor.
4268 * If @a editor is @c NULL, the default end of line characters are used.
4270 * @param editor The editor to operate on, or @c NULL to query the default value.
4271 * @return The name of the end of line characters.
4273 * @since 0.19
4275 const gchar *editor_get_eol_char_name(GeanyEditor *editor)
4277 gint mode = file_prefs.default_eol_character;
4279 if (editor != NULL)
4280 mode = sci_get_eol_mode(editor->sci);
4282 return utils_get_eol_name(mode);
4287 * Retrieves the length of the used end of line characters (LF, CR/LF, CR) in the given editor.
4288 * If @a editor is @c NULL, the default end of line characters are used.
4289 * The returned value is 1 for CR and LF and 2 for CR/LF.
4291 * @param editor The editor to operate on, or @c NULL to query the default value.
4292 * @return The length of the end of line characters.
4294 * @since 0.19
4296 gint editor_get_eol_char_len(GeanyEditor *editor)
4298 gint mode = file_prefs.default_eol_character;
4300 if (editor != NULL)
4301 mode = sci_get_eol_mode(editor->sci);
4303 switch (mode)
4305 case SC_EOL_CRLF: return 2; break;
4306 default: return 1; break;
4312 * Retrieves the used end of line characters (LF, CR/LF, CR) in the given editor.
4313 * If @a editor is @c NULL, the default end of line characters are used.
4314 * The returned value is either "\n", "\r\n" or "\r".
4316 * @param editor The editor to operate on, or @c NULL to query the default value.
4317 * @return The end of line characters.
4319 * @since 0.19
4321 const gchar *editor_get_eol_char(GeanyEditor *editor)
4323 gint mode = file_prefs.default_eol_character;
4325 if (editor != NULL)
4326 mode = sci_get_eol_mode(editor->sci);
4328 switch (mode)
4330 case SC_EOL_CRLF: return "\r\n"; break;
4331 case SC_EOL_CR: return "\r"; break;
4332 default: return "\n"; break;
4337 static void fold_all(GeanyEditor *editor, gboolean want_fold)
4339 gint lines, first, i;
4341 if (editor == NULL || ! editor_prefs.folding)
4342 return;
4344 lines = sci_get_line_count(editor->sci);
4345 first = sci_get_first_visible_line(editor->sci);
4347 for (i = 0; i < lines; i++)
4349 gint level = sci_get_fold_level(editor->sci, i);
4351 if (level & SC_FOLDLEVELHEADERFLAG)
4353 if (sci_get_fold_expanded(editor->sci, i) == want_fold)
4354 sci_toggle_fold(editor->sci, i);
4357 editor_scroll_to_line(editor, first, 0.0F);
4361 void editor_unfold_all(GeanyEditor *editor)
4363 fold_all(editor, FALSE);
4367 void editor_fold_all(GeanyEditor *editor)
4369 fold_all(editor, TRUE);
4373 void editor_replace_tabs(GeanyEditor *editor)
4375 gint search_pos, pos_in_line, current_tab_true_length;
4376 gint tab_len;
4377 gchar *tab_str;
4378 struct Sci_TextToFind ttf;
4380 g_return_if_fail(editor != NULL);
4382 sci_start_undo_action(editor->sci);
4383 tab_len = sci_get_tab_width(editor->sci);
4384 ttf.chrg.cpMin = 0;
4385 ttf.chrg.cpMax = sci_get_length(editor->sci);
4386 ttf.lpstrText = (gchar*) "\t";
4388 while (TRUE)
4390 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4391 if (search_pos == -1)
4392 break;
4394 pos_in_line = sci_get_col_from_position(editor->sci, search_pos);
4395 current_tab_true_length = tab_len - (pos_in_line % tab_len);
4396 tab_str = g_strnfill(current_tab_true_length, ' ');
4397 sci_set_target_start(editor->sci, search_pos);
4398 sci_set_target_end(editor->sci, search_pos + 1);
4399 sci_replace_target(editor->sci, tab_str, FALSE);
4400 /* next search starts after replacement */
4401 ttf.chrg.cpMin = search_pos + current_tab_true_length - 1;
4402 /* update end of range now text has changed */
4403 ttf.chrg.cpMax += current_tab_true_length - 1;
4404 g_free(tab_str);
4406 sci_end_undo_action(editor->sci);
4410 /* Replaces all occurrences all spaces of the length of a given tab_width. */
4411 void editor_replace_spaces(GeanyEditor *editor)
4413 gint search_pos;
4414 static gdouble tab_len_f = -1.0; /* keep the last used value */
4415 gint tab_len;
4416 struct Sci_TextToFind ttf;
4418 g_return_if_fail(editor != NULL);
4420 if (tab_len_f < 0.0)
4421 tab_len_f = sci_get_tab_width(editor->sci);
4423 if (! dialogs_show_input_numeric(
4424 _("Enter Tab Width"),
4425 _("Enter the amount of spaces which should be replaced by a tab character."),
4426 &tab_len_f, 1, 100, 1))
4428 return;
4430 tab_len = (gint) tab_len_f;
4432 sci_start_undo_action(editor->sci);
4433 ttf.chrg.cpMin = 0;
4434 ttf.chrg.cpMax = sci_get_length(editor->sci);
4435 ttf.lpstrText = g_strnfill(tab_len, ' ');
4437 while (TRUE)
4439 search_pos = sci_find_text(editor->sci, SCFIND_MATCHCASE, &ttf);
4440 if (search_pos == -1)
4441 break;
4443 sci_set_target_start(editor->sci, search_pos);
4444 sci_set_target_end(editor->sci, search_pos + tab_len);
4445 sci_replace_target(editor->sci, "\t", FALSE);
4446 ttf.chrg.cpMin = search_pos;
4447 /* update end of range now text has changed */
4448 ttf.chrg.cpMax -= tab_len - 1;
4450 sci_end_undo_action(editor->sci);
4451 g_free(ttf.lpstrText);
4455 void editor_strip_line_trailing_spaces(GeanyEditor *editor, gint line)
4457 gint line_start = sci_get_position_from_line(editor->sci, line);
4458 gint line_end = sci_get_line_end_position(editor->sci, line);
4459 gint i = line_end - 1;
4460 gchar ch = sci_get_char_at(editor->sci, i);
4462 while ((i >= line_start) && ((ch == ' ') || (ch == '\t')))
4464 i--;
4465 ch = sci_get_char_at(editor->sci, i);
4467 if (i < (line_end - 1))
4469 sci_set_target_start(editor->sci, i + 1);
4470 sci_set_target_end(editor->sci, line_end);
4471 sci_replace_target(editor->sci, "", FALSE);
4476 void editor_strip_trailing_spaces(GeanyEditor *editor)
4478 gint max_lines = sci_get_line_count(editor->sci);
4479 gint line;
4481 sci_start_undo_action(editor->sci);
4483 for (line = 0; line < max_lines; line++)
4485 editor_strip_line_trailing_spaces(editor, line);
4487 sci_end_undo_action(editor->sci);
4491 void editor_ensure_final_newline(GeanyEditor *editor)
4493 gint max_lines = sci_get_line_count(editor->sci);
4494 gboolean append_newline = (max_lines == 1);
4495 gint end_document = sci_get_position_from_line(editor->sci, max_lines);
4497 if (max_lines > 1)
4499 append_newline = end_document > sci_get_position_from_line(editor->sci, max_lines - 1);
4501 if (append_newline)
4503 const gchar *eol = "\n";
4504 switch (sci_get_eol_mode(editor->sci))
4506 case SC_EOL_CRLF:
4507 eol = "\r\n";
4508 break;
4509 case SC_EOL_CR:
4510 eol = "\r";
4511 break;
4513 sci_insert_text(editor->sci, end_document, eol);
4518 void editor_set_font(GeanyEditor *editor, const gchar *font)
4520 gint style, size;
4521 gchar *font_name;
4522 PangoFontDescription *pfd;
4524 g_return_if_fail(editor);
4526 pfd = pango_font_description_from_string(font);
4527 size = pango_font_description_get_size(pfd) / PANGO_SCALE;
4528 font_name = g_strdup_printf("!%s", pango_font_description_get_family(pfd));
4529 pango_font_description_free(pfd);
4531 for (style = 0; style <= 127; style++)
4532 sci_set_font(editor->sci, style, font_name, size);
4534 /* line number and braces */
4535 sci_set_font(editor->sci, STYLE_LINENUMBER, font_name, size);
4536 sci_set_font(editor->sci, STYLE_BRACELIGHT, font_name, size);
4537 sci_set_font(editor->sci, STYLE_BRACEBAD, font_name, size);
4538 g_free(font_name);
4540 /* zoom to 100% to prevent confusion */
4541 sci_zoom_off(editor->sci);
4545 void editor_set_line_wrapping(GeanyEditor *editor, gboolean wrap)
4547 g_return_if_fail(editor != NULL);
4549 editor->line_wrapping = wrap;
4550 sci_set_lines_wrapped(editor->sci, wrap);
4554 /** Sets the indent type for @a editor.
4555 * @param editor Editor.
4556 * @param type Indent type.
4558 * @since 0.16
4560 void editor_set_indent_type(GeanyEditor *editor, GeanyIndentType type)
4562 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
4563 ScintillaObject *sci = editor->sci;
4564 gboolean use_tabs = type != GEANY_INDENT_TYPE_SPACES;
4566 editor->indent_type = type;
4567 sci_set_use_tabs(sci, use_tabs);
4569 if (type == GEANY_INDENT_TYPE_BOTH)
4571 sci_set_tab_width(sci, iprefs->hard_tab_width);
4572 if (iprefs->hard_tab_width != 8)
4574 static gboolean warn = TRUE;
4575 if (warn)
4576 ui_set_statusbar(TRUE, _("Warning: non-standard hard tab width: %d != 8!"),
4577 iprefs->hard_tab_width);
4578 warn = FALSE;
4581 else
4582 sci_set_tab_width(sci, iprefs->width);
4584 SSM(sci, SCI_SETINDENT, iprefs->width, 0);
4586 /* remove indent spaces on backspace, if using any spaces to indent */
4587 SSM(sci, SCI_SETBACKSPACEUNINDENTS, type != GEANY_INDENT_TYPE_TABS, 0);
4591 /* Convenience function for editor_goto_pos() to pass in a line number. */
4592 gboolean editor_goto_line(GeanyEditor *editor, gint line_no, gint offset)
4594 gint pos;
4596 g_return_val_if_fail(editor, FALSE);
4597 if (line_no < 0 || line_no >= sci_get_line_count(editor->sci))
4598 return FALSE;
4600 if (offset != 0)
4602 gint current_line = sci_get_current_line(editor->sci);
4603 line_no *= offset;
4604 line_no = current_line + line_no;
4607 pos = sci_get_position_from_line(editor->sci, line_no);
4608 return editor_goto_pos(editor, pos, TRUE);
4612 /* Move to position @a pos, switching to the document if necessary,
4613 * setting a marker if @a mark is set. */
4614 gboolean editor_goto_pos(GeanyEditor *editor, gint pos, gboolean mark)
4616 gint page_num;
4618 g_return_val_if_fail(editor, FALSE);
4619 if (G_UNLIKELY(pos < 0))
4620 return FALSE;
4622 if (mark)
4624 gint line = sci_get_line_from_position(editor->sci, pos);
4626 /* mark the tag with the yellow arrow */
4627 sci_marker_delete_all(editor->sci, 0);
4628 sci_set_marker_at_line(editor->sci, line, 0);
4631 sci_goto_pos(editor->sci, pos, TRUE);
4632 editor->scroll_percent = 0.25F;
4634 /* finally switch to the page */
4635 page_num = gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook), GTK_WIDGET(editor->sci));
4636 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
4638 return TRUE;
4642 static gboolean
4643 on_editor_scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer user_data)
4645 GeanyEditor *editor = user_data;
4647 /* Handle scroll events if Alt is pressed and scroll whole pages instead of a
4648 * few lines only, maybe this could/should be done in Scintilla directly */
4649 if (event->state & GDK_MOD1_MASK)
4651 sci_send_command(editor->sci, (event->direction == GDK_SCROLL_DOWN) ? SCI_PAGEDOWN : SCI_PAGEUP);
4652 return TRUE;
4654 else if (event->state & GDK_SHIFT_MASK)
4656 gint amount = (event->direction == GDK_SCROLL_DOWN) ? 8 : -8;
4658 sci_scroll_columns(editor->sci, amount);
4659 return TRUE;
4662 return FALSE; /* let Scintilla handle all other cases */
4666 static gboolean editor_check_colourise(GeanyEditor *editor)
4668 GeanyDocument *doc = editor->document;
4670 if (!doc->priv->colourise_needed)
4671 return FALSE;
4673 doc->priv->colourise_needed = FALSE;
4674 sci_colourise(editor->sci, 0, -1);
4676 /* now that the current document is colourised, fold points are now accurate,
4677 * so force an update of the current function/tag. */
4678 symbols_get_current_function(NULL, NULL);
4679 ui_update_statusbar(NULL, -1);
4681 return TRUE;
4685 /* We only want to colourise just before drawing, to save startup time and
4686 * prevent unnecessary recolouring other documents after one is saved.
4687 * Really we want a "draw" signal but there doesn't seem to be one (expose is too late,
4688 * and "show" doesn't work). */
4689 static gboolean on_editor_focus_in(GtkWidget *widget, GdkEventFocus *event, gpointer user_data)
4691 GeanyEditor *editor = user_data;
4693 editor_check_colourise(editor);
4694 return FALSE;
4698 /* This is just to catch any uncolourised documents being drawn that didn't receive focus
4699 * for some reason, maybe it's not necessary but just in case. */
4700 static gboolean on_editor_expose_event(GtkWidget *widget, GdkEventExpose *event,
4701 gpointer user_data)
4703 GeanyEditor *editor = user_data;
4705 editor_check_colourise(editor);
4706 return FALSE;
4710 static void setup_sci_keys(ScintillaObject *sci)
4712 /* disable some Scintilla keybindings to be able to redefine them cleanly */
4713 sci_clear_cmdkey(sci, 'A' | (SCMOD_CTRL << 16)); /* select all */
4714 sci_clear_cmdkey(sci, 'D' | (SCMOD_CTRL << 16)); /* duplicate */
4715 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16)); /* line transpose */
4716 sci_clear_cmdkey(sci, 'T' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line copy */
4717 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16)); /* line cut */
4718 sci_clear_cmdkey(sci, 'L' | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line delete */
4719 sci_clear_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16)); /* line to end delete */
4720 sci_clear_cmdkey(sci, '/' | (SCMOD_CTRL << 16)); /* Previous word part */
4721 sci_clear_cmdkey(sci, '\\' | (SCMOD_CTRL << 16)); /* Next word part */
4722 sci_clear_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16)); /* scroll line up */
4723 sci_clear_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16)); /* scroll line down */
4724 sci_clear_cmdkey(sci, SCK_HOME); /* line start */
4725 sci_clear_cmdkey(sci, SCK_END); /* line end */
4726 sci_clear_cmdkey(sci, SCK_END | (SCMOD_ALT << 16)); /* visual line end */
4728 if (editor_prefs.use_gtk_word_boundaries)
4730 /* use GtkEntry-like word boundaries */
4731 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16), SCI_WORDRIGHTEND);
4732 sci_assign_cmdkey(sci, SCK_RIGHT | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_WORDRIGHTENDEXTEND);
4733 sci_assign_cmdkey(sci, SCK_DELETE | (SCMOD_CTRL << 16), SCI_DELWORDRIGHTEND);
4735 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_ALT << 16), SCI_LINESCROLLUP);
4736 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_ALT << 16), SCI_LINESCROLLDOWN);
4737 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16), SCI_PARAUP);
4738 sci_assign_cmdkey(sci, SCK_UP | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARAUPEXTEND);
4739 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16), SCI_PARADOWN);
4740 sci_assign_cmdkey(sci, SCK_DOWN | (SCMOD_CTRL << 16) | (SCMOD_SHIFT << 16), SCI_PARADOWNEXTEND);
4742 sci_clear_cmdkey(sci, SCK_BACK | (SCMOD_ALT << 16)); /* clear Alt-Backspace (Undo) */
4746 #include "icons/16x16/classviewer-var.xpm"
4747 #include "icons/16x16/classviewer-method.xpm"
4749 /* Create new editor widget (scintilla).
4750 * @note The @c "sci-notify" signal is connected separately. */
4751 static ScintillaObject *create_new_sci(GeanyEditor *editor)
4753 ScintillaObject *sci;
4755 sci = SCINTILLA(scintilla_new());
4757 gtk_widget_show(GTK_WIDGET(sci));
4759 sci_set_codepage(sci, SC_CP_UTF8);
4760 /*SSM(sci, SCI_SETWRAPSTARTINDENT, 4, 0);*/
4761 /* disable scintilla provided popup menu */
4762 sci_use_popup(sci, FALSE);
4764 setup_sci_keys(sci);
4766 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
4767 sci_set_lines_wrapped(sci, editor_prefs.line_wrapping);
4768 sci_set_scrollbar_mode(sci, editor_prefs.show_scrollbars);
4769 sci_set_caret_policy_x(sci, CARET_JUMPS | CARET_EVEN, 0);
4770 /*sci_set_caret_policy_y(sci, CARET_JUMPS | CARET_EVEN, 0);*/
4771 SSM(sci, SCI_AUTOCSETSEPARATOR, '\n', 0);
4772 SSM(sci, SCI_SETSCROLLWIDTHTRACKING, 1, 0);
4774 /* tag autocompletion images */
4775 SSM(sci, SCI_REGISTERIMAGE, 1, (sptr_t)classviewer_var);
4776 SSM(sci, SCI_REGISTERIMAGE, 2, (sptr_t)classviewer_method);
4778 /* necessary for column mode editing, implemented in Scintilla since 2.0 */
4779 SSM(sci, SCI_SETADDITIONALSELECTIONTYPING, 1, 0);
4781 /* virtual space */
4782 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
4784 /* only connect signals if this is for the document notebook, not split window */
4785 if (editor->sci == NULL)
4787 g_signal_connect(sci, "button-press-event", G_CALLBACK(on_editor_button_press_event), editor);
4788 g_signal_connect(sci, "scroll-event", G_CALLBACK(on_editor_scroll_event), editor);
4789 g_signal_connect(sci, "motion-notify-event", G_CALLBACK(on_motion_event), NULL);
4790 g_signal_connect(sci, "focus-in-event", G_CALLBACK(on_editor_focus_in), editor);
4791 g_signal_connect(sci, "expose-event", G_CALLBACK(on_editor_expose_event), editor);
4793 return sci;
4797 /** Creates a new Scintilla @c GtkWidget based on the settings for @a editor.
4798 * @param editor Editor settings.
4799 * @return The new widget.
4801 * @since 0.15
4803 ScintillaObject *editor_create_widget(GeanyEditor *editor)
4805 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4806 ScintillaObject *old, *sci;
4808 /* temporarily change editor to use the new sci widget */
4809 old = editor->sci;
4810 sci = create_new_sci(editor);
4811 editor->sci = sci;
4813 editor_set_indent_type(editor, iprefs->type);
4814 editor_set_font(editor, interface_prefs.editor_font);
4815 editor_apply_update_prefs(editor);
4817 /* if editor already had a widget, restore it */
4818 if (old)
4819 editor->sci = old;
4820 return sci;
4824 GeanyEditor *editor_create(GeanyDocument *doc)
4826 const GeanyIndentPrefs *iprefs = get_default_indent_prefs();
4827 GeanyEditor *editor = g_new0(GeanyEditor, 1);
4829 editor->document = doc;
4830 doc->editor = editor; /* needed in case some editor functions/callbacks expect it */
4832 editor->auto_indent = (iprefs->auto_indent_mode != GEANY_AUTOINDENT_NONE);
4833 editor->line_wrapping = editor_prefs.line_wrapping;
4834 editor->scroll_percent = -1.0F;
4835 editor->line_breaking = FALSE;
4837 editor->sci = editor_create_widget(editor);
4838 return editor;
4842 /* in case we need to free some fields in future */
4843 void editor_destroy(GeanyEditor *editor)
4845 g_free(editor);
4849 static void on_document_save(GObject *obj, GeanyDocument *doc)
4851 g_return_if_fail(NZV(doc->real_path));
4853 if (utils_str_equal(doc->real_path,
4854 utils_build_path(app->configdir, "snippets.conf", NULL)))
4856 /* reload snippets */
4857 editor_snippets_free();
4858 editor_snippets_init();
4863 gboolean editor_complete_word_part(GeanyEditor *editor)
4865 gchar *entry;
4867 g_return_val_if_fail(editor, FALSE);
4869 if (!SSM(editor->sci, SCI_AUTOCACTIVE, 0, 0))
4870 return FALSE;
4872 entry = sci_get_string(editor->sci, SCI_AUTOCGETCURRENTTEXT, 0);
4874 /* if no word part, complete normally */
4875 if (!check_partial_completion(editor, entry))
4876 SSM(editor->sci, SCI_AUTOCCOMPLETE, 0, 0);
4878 g_free(entry);
4879 return TRUE;
4883 void editor_init(void)
4885 static GeanyIndentPrefs indent_prefs;
4887 memset(&editor_prefs, 0, sizeof(GeanyEditorPrefs));
4888 memset(&indent_prefs, 0, sizeof(GeanyIndentPrefs));
4889 editor_prefs.indentation = &indent_prefs;
4891 /* use g_signal_connect_after() to allow plugins connecting to the signal before the default
4892 * handler (on_editor_notify) is called */
4893 g_signal_connect_after(geany_object, "editor-notify", G_CALLBACK(on_editor_notify), NULL);
4895 ui_add_config_file_menu_item(utils_build_path(app->configdir, "snippets.conf", NULL),
4896 NULL, NULL);
4897 g_signal_connect(geany_object, "document-save", G_CALLBACK(on_document_save), NULL);
4901 /* TODO: Should these be user-defined instead of hard-coded? */
4902 void editor_set_indentation_guides(GeanyEditor *editor)
4904 gint mode;
4905 gint lexer;
4907 g_return_if_fail(editor != NULL);
4909 if (! editor_prefs.show_indent_guide)
4911 sci_set_indentation_guides(editor->sci, SC_IV_NONE);
4912 return;
4915 lexer = sci_get_lexer(editor->sci);
4916 switch (lexer)
4918 /* Lines added/removed are prefixed with +/- characters, so
4919 * those lines will not be shown with any indentation guides.
4920 * It can be distracting that only a few of lines in a diff/patch
4921 * file will show the guides. */
4922 case SCLEX_DIFF:
4923 mode = SC_IV_NONE;
4924 break;
4926 /* These languages use indentation for control blocks; the "look forward" method works
4927 * best here */
4928 case SCLEX_PYTHON:
4929 case SCLEX_HASKELL:
4930 case SCLEX_MAKEFILE:
4931 case SCLEX_ASM:
4932 case SCLEX_SQL:
4933 case SCLEX_PROPERTIES:
4934 case SCLEX_FORTRAN: /* Is this the best option for Fortran? */
4935 case SCLEX_CAML:
4936 mode = SC_IV_LOOKFORWARD;
4937 break;
4939 /* C-like (structured) languages benefit from the "look both" method */
4940 case SCLEX_CPP:
4941 case SCLEX_HTML:
4942 case SCLEX_XML:
4943 case SCLEX_PERL:
4944 case SCLEX_LATEX:
4945 case SCLEX_LUA:
4946 case SCLEX_PASCAL:
4947 case SCLEX_RUBY:
4948 case SCLEX_TCL:
4949 case SCLEX_F77:
4950 case SCLEX_CSS:
4951 case SCLEX_BASH:
4952 case SCLEX_VHDL:
4953 case SCLEX_FREEBASIC:
4954 case SCLEX_D:
4955 case SCLEX_MATLAB:
4956 mode = SC_IV_LOOKBOTH;
4957 break;
4959 default:
4960 mode = SC_IV_REAL;
4961 break;
4964 sci_set_indentation_guides(editor->sci, mode);
4968 /* Apply just the prefs that can change in the Preferences dialog */
4969 void editor_apply_update_prefs(GeanyEditor *editor)
4971 ScintillaObject *sci;
4973 g_return_if_fail(editor != NULL);
4975 sci = editor->sci;
4977 sci_set_mark_long_lines(sci, editor_get_long_line_type(),
4978 editor_get_long_line_column(), editor_prefs.long_line_color);
4980 /* update indent width, tab width */
4981 editor_set_indent_type(editor, editor->indent_type);
4982 sci_set_tab_indents(sci, editor_prefs.use_tab_to_indent);
4984 sci_set_autoc_max_height(sci, editor_prefs.symbolcompletion_max_height);
4985 SSM(sci, SCI_AUTOCSETDROPRESTOFWORD, editor_prefs.completion_drops_rest_of_word, 0);
4987 editor_set_indentation_guides(editor);
4989 sci_set_visible_white_spaces(sci, editor_prefs.show_white_space);
4990 sci_set_visible_eols(sci, editor_prefs.show_line_endings);
4991 sci_set_symbol_margin(sci, editor_prefs.show_markers_margin);
4992 sci_set_line_numbers(sci, editor_prefs.show_linenumber_margin, 0);
4994 sci_set_folding_margin_visible(sci, editor_prefs.folding);
4996 /* virtual space */
4997 SSM(sci, SCI_SETVIRTUALSPACEOPTIONS, editor_prefs.show_virtual_space, 0);
4999 /* (dis)allow scrolling past end of document */
5000 sci_set_scroll_stop_at_last_line(sci, editor_prefs.scroll_stop_at_last_line);
5004 /* This is for tab-indents, space aligns formatted code. Spaces should be preserved. */
5005 static void change_tab_indentation(GeanyEditor *editor, gint line, gboolean increase)
5007 ScintillaObject *sci = editor->sci;
5008 gint pos = sci_get_position_from_line(sci, line);
5010 if (increase)
5012 sci_insert_text(sci, pos, "\t");
5014 else
5016 if (sci_get_char_at(sci, pos) == '\t')
5018 sci_set_selection(sci, pos, pos + 1);
5019 sci_replace_sel(sci, "");
5021 else /* remove spaces only if no tabs */
5023 gint width = sci_get_line_indentation(sci, line);
5025 width -= editor_get_indent_prefs(editor)->width;
5026 sci_set_line_indentation(sci, line, width);
5032 static void editor_change_line_indent(GeanyEditor *editor, gint line, gboolean increase)
5034 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
5035 ScintillaObject *sci = editor->sci;
5037 if (iprefs->type == GEANY_INDENT_TYPE_TABS)
5038 change_tab_indentation(editor, line, increase);
5039 else
5041 gint width = sci_get_line_indentation(sci, line);
5043 width += increase ? iprefs->width : -iprefs->width;
5044 sci_set_line_indentation(sci, line, width);
5049 void editor_indent(GeanyEditor *editor, gboolean increase)
5051 ScintillaObject *sci = editor->sci;
5052 gint start, end;
5053 gint line, lstart, lend;
5055 if (sci_get_lines_selected(sci) <= 1)
5057 line = sci_get_current_line(sci);
5058 editor_change_line_indent(editor, line, increase);
5059 return;
5061 editor_select_lines(editor, FALSE);
5062 start = sci_get_selection_start(sci);
5063 end = sci_get_selection_end(sci);
5064 lstart = sci_get_line_from_position(sci, start);
5065 lend = sci_get_line_from_position(sci, end);
5066 if (end == sci_get_length(sci))
5067 lend++; /* for last line with text on it */
5069 sci_start_undo_action(sci);
5070 for (line = lstart; line < lend; line++)
5072 editor_change_line_indent(editor, line, increase);
5074 sci_end_undo_action(sci);
5076 /* set cursor/selection */
5077 if (lend > lstart)
5079 sci_set_selection_start(sci, start);
5080 end = sci_get_position_from_line(sci, lend);
5081 sci_set_selection_end(sci, end);
5082 editor_select_lines(editor, FALSE);
5084 else
5086 sci_set_current_line(sci, lstart);