1 /*
2  *      symbols.c - this file is part of Geany, a fast and lightweight IDE
3  *
4  *      Copyright 2006 The Geany contributors
5  *
6  *      This program is free software; you can redistribute it and/or modify
7  *      it under the terms of the GNU General Public License as published by
8  *      the Free Software Foundation; either version 2 of the License, or
9  *      (at your option) any later version.
10  *
11  *      This program is distributed in the hope that it will be useful,
12  *      but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *      GNU General Public License for more details.
15  *
16  *      You should have received a copy of the GNU General Public License along
17  *      with this program; if not, write to the Free Software Foundation, Inc.,
18  *      51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  */
20 
21 /**
22  * @file symbols.h
23  * Tag-related functions.
24  **/
25 
26 /*
27  * Symbol Tree and TagManager-related convenience functions.
28  * TagManager parses tags for each document, and also adds them to the workspace (session).
29  * Global tags are lists of tags for each filetype, loaded when a document with a
30  * matching filetype is first loaded.
31  */
32 
33 #ifdef HAVE_CONFIG_H
34 # include "config.h"
35 #endif
36 
37 #include "symbols.h"
38 
39 #include "app.h"
40 #include "callbacks.h" /* FIXME: for ignore_callback */
41 #include "documentprivate.h"
42 #include "editor.h"
43 #include "encodings.h"
44 #include "filetypesprivate.h"
45 #include "geanyobject.h"
46 #include "highlighting.h"
47 #include "main.h"
48 #include "navqueue.h"
49 #include "sciwrappers.h"
50 #include "sidebar.h"
51 #include "support.h"
52 #include "tm_parser.h"
53 #include "tm_tag.h"
54 #include "ui_utils.h"
55 #include "utils.h"
56 
57 #include "SciLexer.h"
58 
59 #include "gtkcompat.h"
60 
61 #include <ctype.h>
62 #include <string.h>
63 #include <stdlib.h>
64 
65 
66 typedef struct
67 {
68 	gint found_line; /* return: the nearest line found */
69 	gint line;       /* input: the line to look for */
70 	gboolean lower   /* input: search only for lines with lower number than @line */;
71 } TreeSearchData;
72 
73 
74 static GPtrArray *top_level_iter_names = NULL;
75 
76 enum
77 {
78 	ICON_CLASS,
79 	ICON_MACRO,
80 	ICON_MEMBER,
81 	ICON_METHOD,
82 	ICON_NAMESPACE,
83 	ICON_OTHER,
84 	ICON_STRUCT,
85 	ICON_VAR,
86 	ICON_NONE,
87 	N_ICONS = ICON_NONE
88 };
89 
90 static struct
91 {
92 	const gchar *icon_name;
93 	GdkPixbuf *pixbuf;
94 }
95 symbols_icons[N_ICONS] = {
96 	[ICON_CLASS]		= { "classviewer-class", NULL },
97 	[ICON_MACRO]		= { "classviewer-macro", NULL },
98 	[ICON_MEMBER]		= { "classviewer-member", NULL },
99 	[ICON_METHOD]		= { "classviewer-method", NULL },
100 	[ICON_NAMESPACE]	= { "classviewer-namespace", NULL },
101 	[ICON_OTHER]		= { "classviewer-other", NULL },
102 	[ICON_STRUCT]		= { "classviewer-struct", NULL },
103 	[ICON_VAR]			= { "classviewer-var", NULL },
104 };
105 
106 static struct
107 {
108 	GtkWidget *expand_all;
109 	GtkWidget *collapse_all;
110 	GtkWidget *sort_by_name;
111 	GtkWidget *sort_by_appearance;
112 	GtkWidget *find_usage;
113 	GtkWidget *find_doc_usage;
114 	GtkWidget *find_in_files;
115 }
116 symbol_menu;
117 
118 static void load_user_tags(GeanyFiletypeID ft_id);
119 
120 /* get the tags_ignore list, exported by tagmanager's geany.c */
121 extern gchar **c_tags_ignore;
122 
123 /* ignore certain tokens when parsing C-like syntax.
124  * Also works for reloading. */
load_c_ignore_tags(void)125 static void load_c_ignore_tags(void)
126 {
127 	gchar *path = g_build_filename(app->configdir, "ignore.tags", NULL);
128 	gchar *content;
129 
130 	if (g_file_get_contents(path, &content, NULL, NULL))
131 	{
132 		/* historically we ignore the glib _DECLS for tag generation */
133 		SETPTR(content, g_strconcat("G_BEGIN_DECLS G_END_DECLS\n", content, NULL));
134 
135 		g_strfreev(c_tags_ignore);
136 		c_tags_ignore = g_strsplit_set(content, " \n\r", -1);
137 		g_free(content);
138 	}
139 	g_free(path);
140 }
141 
142 
symbols_reload_config_files(void)143 void symbols_reload_config_files(void)
144 {
145 	load_c_ignore_tags();
146 }
147 
148 
get_tag_count(void)149 static gsize get_tag_count(void)
150 {
151 	GPtrArray *tags = tm_get_workspace()->global_tags;
152 	gsize count = tags ? tags->len : 0;
153 
154 	return count;
155 }
156 
157 
158 /* wrapper for tm_workspace_load_global_tags().
159  * note that the tag count only counts new global tags added - if a tag has the same name,
160  * currently it replaces the existing tag, so loading a file twice will say 0 tags the 2nd time. */
symbols_load_global_tags(const gchar * tags_file,GeanyFiletype * ft)161 static gboolean symbols_load_global_tags(const gchar *tags_file, GeanyFiletype *ft)
162 {
163 	gboolean result;
164 	gsize old_tag_count = get_tag_count();
165 
166 	result = tm_workspace_load_global_tags(tags_file, ft->lang);
167 	if (result)
168 	{
169 		geany_debug("Loaded %s (%s), %u symbol(s).", tags_file, ft->name,
170 			(guint) (get_tag_count() - old_tag_count));
171 	}
172 	return result;
173 }
174 
175 
176 /* Ensure that the global tags file(s) for the file_type_idx filetype is loaded.
177  * This provides autocompletion, calltips, etc. */
symbols_global_tags_loaded(guint file_type_idx)178 void symbols_global_tags_loaded(guint file_type_idx)
179 {
180 	/* load ignore list for C/C++ parser */
181 	if ((file_type_idx == GEANY_FILETYPES_C || file_type_idx == GEANY_FILETYPES_CPP) &&
182 		c_tags_ignore == NULL)
183 	{
184 		load_c_ignore_tags();
185 	}
186 
187 	if (cl_options.ignore_global_tags || app->tm_workspace == NULL)
188 		return;
189 
190 	/* load config in case of custom filetypes */
191 	filetypes_load_config(file_type_idx, FALSE);
192 
193 	load_user_tags(file_type_idx);
194 
195 	switch (file_type_idx)
196 	{
197 		case GEANY_FILETYPES_CPP:
198 			symbols_global_tags_loaded(GEANY_FILETYPES_C);	/* load C global tags */
199 			break;
200 		case GEANY_FILETYPES_PHP:
201 			symbols_global_tags_loaded(GEANY_FILETYPES_HTML);	/* load HTML global tags */
202 			break;
203 	}
204 }
205 
206 
symbols_find_typenames_as_string(TMParserType lang,gboolean global)207 GString *symbols_find_typenames_as_string(TMParserType lang, gboolean global)
208 {
209 	guint j;
210 	TMTag *tag;
211 	GString *s = NULL;
212 	GPtrArray *typedefs;
213 	TMParserType tag_lang;
214 
215 	if (global)
216 		typedefs = app->tm_workspace->global_typename_array;
217 	else
218 		typedefs = app->tm_workspace->typename_array;
219 
220 	if ((typedefs) && (typedefs->len > 0))
221 	{
222 		const gchar *last_name = "";
223 
224 		s = g_string_sized_new(typedefs->len * 10);
225 		for (j = 0; j < typedefs->len; ++j)
226 		{
227 			tag = TM_TAG(typedefs->pdata[j]);
228 			tag_lang = tag->lang;
229 
230 			if (tag->name && tm_parser_langs_compatible(lang, tag_lang) &&
231 				strcmp(tag->name, last_name) != 0)
232 			{
233 				if (j != 0)
234 					g_string_append_c(s, ' ');
235 				g_string_append(s, tag->name);
236 				last_name = tag->name;
237 			}
238 		}
239 	}
240 	return s;
241 }
242 
243 
244 /** Gets the context separator used by the tag manager for a particular file
245  * type.
246  * @param ft_id File type identifier.
247  * @return The context separator string.
248  *
249  * Returns non-printing sequence "\x03" ie ETX (end of text) for filetypes
250  * without a context separator.
251  *
252  * @since 0.19
253  */
254 GEANY_API_SYMBOL
symbols_get_context_separator(gint ft_id)255 const gchar *symbols_get_context_separator(gint ft_id)
256 {
257 	return tm_parser_context_separator(filetypes[ft_id]->lang);
258 }
259 
260 
261 /* sort by name, then line */
compare_symbol(const TMTag * tag_a,const TMTag * tag_b)262 static gint compare_symbol(const TMTag *tag_a, const TMTag *tag_b)
263 {
264 	gint ret;
265 
266 	if (tag_a == NULL || tag_b == NULL)
267 		return 0;
268 
269 	if (tag_a->name == NULL)
270 		return -(tag_a->name != tag_b->name);
271 
272 	if (tag_b->name == NULL)
273 		return tag_a->name != tag_b->name;
274 
275 	ret = strcmp(tag_a->name, tag_b->name);
276 	if (ret == 0)
277 	{
278 		return tag_a->line - tag_b->line;
279 	}
280 	return ret;
281 }
282 
283 
284 /* sort by line, then scope */
compare_symbol_lines(gconstpointer a,gconstpointer b)285 static gint compare_symbol_lines(gconstpointer a, gconstpointer b)
286 {
287 	const TMTag *tag_a = TM_TAG(a);
288 	const TMTag *tag_b = TM_TAG(b);
289 	gint ret;
290 
291 	if (a == NULL || b == NULL)
292 		return 0;
293 
294 	ret = tag_a->line - tag_b->line;
295 	if (ret == 0)
296 	{
297 		if (tag_a->scope == NULL)
298 			return -(tag_a->scope != tag_b->scope);
299 		if (tag_b->scope == NULL)
300 			return tag_a->scope != tag_b->scope;
301 		else
302 			return strcmp(tag_a->scope, tag_b->scope);
303 	}
304 	return ret;
305 }
306 
307 
get_tag_list(GeanyDocument * doc,TMTagType tag_types)308 static GList *get_tag_list(GeanyDocument *doc, TMTagType tag_types)
309 {
310 	GList *tag_names = NULL;
311 	guint i;
312 
313 	g_return_val_if_fail(doc, NULL);
314 
315 	if (! doc->tm_file || ! doc->tm_file->tags_array)
316 		return NULL;
317 
318 	for (i = 0; i < doc->tm_file->tags_array->len; ++i)
319 	{
320 		TMTag *tag = TM_TAG(doc->tm_file->tags_array->pdata[i]);
321 
322 		if (G_UNLIKELY(tag == NULL))
323 			return NULL;
324 
325 		if (tag->type & tag_types)
326 		{
327 			tag_names = g_list_prepend(tag_names, tag);
328 		}
329 	}
330 	tag_names = g_list_sort(tag_names, compare_symbol_lines);
331 	return tag_names;
332 }
333 
334 
335 /* amount of types in the symbol list (currently max. 8 are used) */
336 #define MAX_SYMBOL_TYPES	(sizeof(tv_iters) / sizeof(GtkTreeIter))
337 
338 struct TreeviewSymbols
339 {
340 	GtkTreeIter		 tag_function;
341 	GtkTreeIter		 tag_class;
342 	GtkTreeIter		 tag_macro;
343 	GtkTreeIter		 tag_member;
344 	GtkTreeIter		 tag_variable;
345 	GtkTreeIter		 tag_externvar;
346 	GtkTreeIter		 tag_namespace;
347 	GtkTreeIter		 tag_struct;
348 	GtkTreeIter		 tag_interface;
349 	GtkTreeIter		 tag_type;
350 	GtkTreeIter		 tag_other;
351 } tv_iters;
352 
353 
init_tag_iters(void)354 static void init_tag_iters(void)
355 {
356 	/* init all GtkTreeIters with -1 to make them invalid to avoid crashes when switching between
357 	 * filetypes(e.g. config file to Python crashes Geany without this) */
358 	tv_iters.tag_function.stamp = -1;
359 	tv_iters.tag_class.stamp = -1;
360 	tv_iters.tag_member.stamp = -1;
361 	tv_iters.tag_macro.stamp = -1;
362 	tv_iters.tag_variable.stamp = -1;
363 	tv_iters.tag_externvar.stamp = -1;
364 	tv_iters.tag_namespace.stamp = -1;
365 	tv_iters.tag_struct.stamp = -1;
366 	tv_iters.tag_interface.stamp = -1;
367 	tv_iters.tag_type.stamp = -1;
368 	tv_iters.tag_other.stamp = -1;
369 }
370 
371 
get_tag_icon(const gchar * icon_name)372 static GdkPixbuf *get_tag_icon(const gchar *icon_name)
373 {
374 	static GtkIconTheme *icon_theme = NULL;
375 	static gint x = -1;
376 
377 	if (G_UNLIKELY(x < 0))
378 	{
379 		gint dummy;
380 		icon_theme = gtk_icon_theme_get_default();
381 		gtk_icon_size_lookup(GTK_ICON_SIZE_MENU, &x, &dummy);
382 	}
383 	return gtk_icon_theme_load_icon(icon_theme, icon_name, x, 0, NULL);
384 }
385 
386 
find_toplevel_iter(GtkTreeStore * store,GtkTreeIter * iter,const gchar * title)387 static gboolean find_toplevel_iter(GtkTreeStore *store, GtkTreeIter *iter, const gchar *title)
388 {
389 	GtkTreeModel *model = GTK_TREE_MODEL(store);
390 
391 	if (!gtk_tree_model_get_iter_first(model, iter))
392 		return FALSE;
393 	do
394 	{
395 		gchar *candidate;
396 
397 		gtk_tree_model_get(model, iter, SYMBOLS_COLUMN_NAME, &candidate, -1);
398 		/* FIXME: what if 2 different items have the same name?
399 		 * this should never happen, but might be caused by a typo in a translation */
400 		if (utils_str_equal(candidate, title))
401 		{
402 			g_free(candidate);
403 			return TRUE;
404 		}
405 		else
406 			g_free(candidate);
407 	}
408 	while (gtk_tree_model_iter_next(model, iter));
409 
410 	return FALSE;
411 }
412 
413 
414 /* Adds symbol list groups in (iter*, title) pairs.
415  * The list must be ended with NULL. */
416 static void G_GNUC_NULL_TERMINATED
tag_list_add_groups(GtkTreeStore * tree_store,...)417 tag_list_add_groups(GtkTreeStore *tree_store, ...)
418 {
419 	va_list args;
420 	GtkTreeIter *iter;
421 
422 	g_return_if_fail(top_level_iter_names);
423 
424 	va_start(args, tree_store);
425 	for (; iter = va_arg(args, GtkTreeIter*), iter != NULL;)
426 	{
427 		gchar *title = va_arg(args, gchar*);
428 		guint icon_id = va_arg(args, guint);
429 		GdkPixbuf *icon = NULL;
430 
431 		if (icon_id < N_ICONS)
432 			icon = symbols_icons[icon_id].pixbuf;
433 
434 		g_assert(title != NULL);
435 		g_ptr_array_add(top_level_iter_names, title);
436 
437 		if (!find_toplevel_iter(tree_store, iter, title))
438 			gtk_tree_store_append(tree_store, iter, NULL);
439 
440 		if (icon)
441 			gtk_tree_store_set(tree_store, iter, SYMBOLS_COLUMN_ICON, icon, -1);
442 		gtk_tree_store_set(tree_store, iter, SYMBOLS_COLUMN_NAME, title, -1);
443 	}
444 	va_end(args);
445 }
446 
447 
add_top_level_items(GeanyDocument * doc)448 static void add_top_level_items(GeanyDocument *doc)
449 {
450 	GeanyFiletypeID ft_id = doc->file_type->id;
451 	GtkTreeStore *tag_store = doc->priv->tag_store;
452 
453 	if (top_level_iter_names == NULL)
454 		top_level_iter_names = g_ptr_array_new();
455 	else
456 		g_ptr_array_set_size(top_level_iter_names, 0);
457 
458 	init_tag_iters();
459 
460 	switch (ft_id)
461 	{
462 		case GEANY_FILETYPES_DIFF:
463 		{
464 			tag_list_add_groups(tag_store,
465 				&(tv_iters.tag_function), _("Files"), ICON_NONE, NULL);
466 			break;
467 		}
468 		case GEANY_FILETYPES_DOCBOOK:
469 		{
470 			tag_list_add_groups(tag_store,
471 				&(tv_iters.tag_function), _("Chapter"), ICON_NONE,
472 				&(tv_iters.tag_class), _("Section"), ICON_NONE,
473 				&(tv_iters.tag_member), _("Sect1"), ICON_NONE,
474 				&(tv_iters.tag_macro), _("Sect2"), ICON_NONE,
475 				&(tv_iters.tag_variable), _("Sect3"), ICON_NONE,
476 				&(tv_iters.tag_struct), _("Appendix"), ICON_NONE,
477 				&(tv_iters.tag_other), _("Other"), ICON_NONE,
478 				NULL);
479 			break;
480 		}
481 		case GEANY_FILETYPES_HASKELL:
482 			tag_list_add_groups(tag_store,
483 				&tv_iters.tag_namespace, _("Module"), ICON_NONE,
484 				&tv_iters.tag_type, _("Types"), ICON_NONE,
485 				&tv_iters.tag_macro, _("Type constructors"), ICON_NONE,
486 				&tv_iters.tag_function, _("Functions"), ICON_METHOD,
487 				NULL);
488 			break;
489 		case GEANY_FILETYPES_COBOL:
490 			tag_list_add_groups(tag_store,
491 				&tv_iters.tag_class, _("Program"), ICON_CLASS,
492 				&tv_iters.tag_function, _("File"), ICON_METHOD,
493 				&tv_iters.tag_interface, _("Divisions"), ICON_NAMESPACE,
494 				&tv_iters.tag_namespace, _("Sections"), ICON_NAMESPACE,
495 				&tv_iters.tag_macro, _("Paragraph"), ICON_OTHER,
496 				&tv_iters.tag_struct, _("Group"), ICON_STRUCT,
497 				&tv_iters.tag_variable, _("Data"), ICON_VAR,
498 				&tv_iters.tag_externvar, _("Copies"), ICON_NAMESPACE,
499 				NULL);
500 			break;
501 		case GEANY_FILETYPES_CONF:
502 			tag_list_add_groups(tag_store,
503 				&tv_iters.tag_namespace, _("Sections"), ICON_OTHER,
504 				&tv_iters.tag_macro, _("Keys"), ICON_VAR,
505 				NULL);
506 			break;
507 		case GEANY_FILETYPES_NSIS:
508 			tag_list_add_groups(tag_store,
509 				&tv_iters.tag_namespace, _("Sections"), ICON_OTHER,
510 				&tv_iters.tag_function, _("Functions"), ICON_METHOD,
511 				&(tv_iters.tag_variable), _("Variables"), ICON_VAR,
512 				NULL);
513 			break;
514 		case GEANY_FILETYPES_LATEX:
515 		{
516 			tag_list_add_groups(tag_store,
517 				&(tv_iters.tag_function), _("Command"), ICON_NONE,
518 				&(tv_iters.tag_class), _("Environment"), ICON_NONE,
519 				&(tv_iters.tag_member), _("Section"), ICON_NONE,
520 				&(tv_iters.tag_macro), _("Subsection"), ICON_NONE,
521 				&(tv_iters.tag_variable), _("Subsubsection"), ICON_NONE,
522 				&(tv_iters.tag_struct), _("Label"), ICON_NONE,
523 				&(tv_iters.tag_namespace), _("Chapter"), ICON_NONE,
524 				&(tv_iters.tag_other), _("Other"), ICON_NONE,
525 				NULL);
526 			break;
527 		}
528 		case GEANY_FILETYPES_BIBTEX:
529 		{
530 			tag_list_add_groups(tag_store,
531 				&(tv_iters.tag_function), _("Articles"), ICON_NONE,
532 				&(tv_iters.tag_macro), _("Book Chapters"), ICON_NONE,
533 				&(tv_iters.tag_class), _("Books & Conference Proceedings"), ICON_NONE,
534 				&(tv_iters.tag_member), _("Conference Papers"), ICON_NONE,
535 				&(tv_iters.tag_variable), _("Theses"), ICON_NONE,
536 				&(tv_iters.tag_namespace), _("Strings"), ICON_NONE,
537 				&(tv_iters.tag_externvar), _("Unpublished"), ICON_NONE,
538 				&(tv_iters.tag_other), _("Other"), ICON_NONE,
539 				NULL);
540 			break;
541 		}
542 		case GEANY_FILETYPES_MATLAB:
543 		{
544 			tag_list_add_groups(tag_store,
545 				&(tv_iters.tag_function), _("Functions"), ICON_METHOD,
546 				&(tv_iters.tag_struct), _("Structures"), ICON_STRUCT,
547 				NULL);
548 			break;
549 		}
550 		case GEANY_FILETYPES_ABAQUS:
551 		{
552 			tag_list_add_groups(tag_store,
553 				&(tv_iters.tag_class), _("Parts"), ICON_NONE,
554 				&(tv_iters.tag_member), _("Assembly"), ICON_NONE,
555 				&(tv_iters.tag_namespace), _("Steps"), ICON_NONE,
556 				NULL);
557 			break;
558 		}
559 		case GEANY_FILETYPES_R:
560 		{
561 			tag_list_add_groups(tag_store,
562 				&(tv_iters.tag_function), _("Functions"), ICON_METHOD,
563 				&(tv_iters.tag_other), _("Other"), ICON_NONE,
564 				NULL);
565 			break;
566 		}
567 		case GEANY_FILETYPES_RUST:
568 		{
569 			tag_list_add_groups(tag_store,
570 				&(tv_iters.tag_namespace), _("Modules"), ICON_NAMESPACE,
571 				&(tv_iters.tag_struct), _("Structures"), ICON_STRUCT,
572 				&(tv_iters.tag_interface), _("Traits"), ICON_CLASS,
573 				&(tv_iters.tag_class), _("Implementations"), ICON_CLASS,
574 				&(tv_iters.tag_function), _("Functions"), ICON_METHOD,
575 				&(tv_iters.tag_type), _("Typedefs / Enums"), ICON_STRUCT,
576 				&(tv_iters.tag_variable), _("Variables"), ICON_VAR,
577 				&(tv_iters.tag_macro), _("Macros"), ICON_MACRO,
578 				&(tv_iters.tag_member), _("Methods"), ICON_MEMBER,
579 				&(tv_iters.tag_other), _("Other"), ICON_OTHER,
580 				NULL);
581 			break;
582 		}
583 		case GEANY_FILETYPES_GO:
584 		{
585 			tag_list_add_groups(tag_store,
586 				&(tv_iters.tag_namespace), _("Package"), ICON_NAMESPACE,
587 				&(tv_iters.tag_function), _("Functions"), ICON_METHOD,
588 				&(tv_iters.tag_interface), _("Interfaces"), ICON_STRUCT,
589 				&(tv_iters.tag_struct), _("Structs"), ICON_STRUCT,
590 				&(tv_iters.tag_type), _("Types"), ICON_STRUCT,
591 				&(tv_iters.tag_macro), _("Constants"), ICON_MACRO,
592 				&(tv_iters.tag_variable), _("Variables"), ICON_VAR,
593 				&(tv_iters.tag_member), _("Members"), ICON_MEMBER,
594 				&(tv_iters.tag_other), _("Other"), ICON_OTHER,
595 				NULL);
596 			break;
597 		}
598 		case GEANY_FILETYPES_PERL:
599 		{
600 			tag_list_add_groups(tag_store,
601 				&(tv_iters.tag_namespace), _("Package"), ICON_NAMESPACE,
602 				&(tv_iters.tag_function), _("Functions"), ICON_METHOD,
603 				&(tv_iters.tag_macro), _("Labels"), ICON_NONE,
604 				&(tv_iters.tag_type), _("Constants"), ICON_NONE,
605 				&(tv_iters.tag_other), _("Other"), ICON_OTHER,
606 				NULL);
607 			break;
608 		}
609 		case GEANY_FILETYPES_PHP:
610 		case GEANY_FILETYPES_ZEPHIR:
611 		{
612 			tag_list_add_groups(tag_store,
613 				&(tv_iters.tag_namespace), _("Namespaces"), ICON_NAMESPACE,
614 				&(tv_iters.tag_interface), _("Interfaces"), ICON_STRUCT,
615 				&(tv_iters.tag_class), _("Classes"), ICON_CLASS,
616 				&(tv_iters.tag_function), _("Functions"), ICON_METHOD,
617 				&(tv_iters.tag_macro), _("Constants"), ICON_MACRO,
618 				&(tv_iters.tag_variable), _("Variables"), ICON_VAR,
619 				&(tv_iters.tag_struct), _("Traits"), ICON_STRUCT,
620 				NULL);
621 			break;
622 		}
623 		case GEANY_FILETYPES_HTML:
624 		{
625 			tag_list_add_groups(tag_store,
626 				&(tv_iters.tag_function), _("Functions"), ICON_NONE,
627 				&(tv_iters.tag_member), _("Anchors"), ICON_NONE,
628 				&(tv_iters.tag_namespace), _("H1 Headings"), ICON_NONE,
629 				&(tv_iters.tag_class), _("H2 Headings"), ICON_NONE,
630 				&(tv_iters.tag_variable), _("H3 Headings"), ICON_NONE,
631 				NULL);
632 			break;
633 		}
634 		case GEANY_FILETYPES_CSS:
635 		{
636 			tag_list_add_groups(tag_store,
637 				&(tv_iters.tag_class), _("Classes"), ICON_CLASS,
638 				&(tv_iters.tag_variable), _("ID Selectors"), ICON_VAR,
639 				&(tv_iters.tag_struct), _("Type Selectors"), ICON_STRUCT, NULL);
640 			break;
641 		}
642 		case GEANY_FILETYPES_REST:
643 		case GEANY_FILETYPES_TXT2TAGS:
644 		case GEANY_FILETYPES_ABC:
645 		{
646 			tag_list_add_groups(tag_store,
647 				&(tv_iters.tag_namespace), _("Chapter"), ICON_NONE,
648 				&(tv_iters.tag_member), _("Section"), ICON_NONE,
649 				&(tv_iters.tag_macro), _("Subsection"), ICON_NONE,
650 				&(tv_iters.tag_variable), _("Subsubsection"), ICON_NONE,
651 				NULL);
652 			break;
653 		}
654 		case GEANY_FILETYPES_ASCIIDOC:
655 		{
656 			tag_list_add_groups(tag_store,
657 				&(tv_iters.tag_namespace), _("Document"), ICON_NONE,
658 				&(tv_iters.tag_member), _("Section Level 1"), ICON_NONE,
659 				&(tv_iters.tag_macro), _("Section Level 2"), ICON_NONE,
660 				&(tv_iters.tag_variable), _("Section Level 3"), ICON_NONE,
661 				&(tv_iters.tag_struct), _("Section Level 4"), ICON_NONE,
662 				NULL);
663 			break;
664 		}
665 		case GEANY_FILETYPES_RUBY:
666 		{
667 			tag_list_add_groups(tag_store,
668 				&(tv_iters.tag_namespace), _("Modules"), ICON_NAMESPACE,
669 				&(tv_iters.tag_class), _("Classes"), ICON_CLASS,
670 				&(tv_iters.tag_member), _("Singletons"), ICON_STRUCT,
671 				&(tv_iters.tag_function), _("Methods"), ICON_METHOD,
672 				NULL);
673 			break;
674 		}
675 		case GEANY_FILETYPES_TCL:
676 		{
677 			tag_list_add_groups(tag_store,
678 				&(tv_iters.tag_namespace), _("Namespaces"), ICON_NAMESPACE,
679 				&(tv_iters.tag_class), _("Classes"), ICON_CLASS,
680 				&(tv_iters.tag_member), _("Methods"), ICON_METHOD,
681 				&(tv_iters.tag_function), _("Procedures"), ICON_OTHER,
682 				NULL);
683 			break;
684 		}
685 		case GEANY_FILETYPES_PYTHON:
686 		{
687 			tag_list_add_groups(tag_store,
688 				&(tv_iters.tag_class), _("Classes"), ICON_CLASS,
689 				&(tv_iters.tag_member), _("Methods"), ICON_MACRO,
690 				&(tv_iters.tag_function), _("Functions"), ICON_METHOD,
691 				&(tv_iters.tag_variable), _("Variables"), ICON_VAR,
692 				&(tv_iters.tag_externvar), _("Imports"), ICON_NAMESPACE,
693 				NULL);
694 			break;
695 		}
696 		case GEANY_FILETYPES_VHDL:
697 		{
698 			tag_list_add_groups(tag_store,
699 				&(tv_iters.tag_namespace), _("Package"), ICON_NAMESPACE,
700 				&(tv_iters.tag_class), _("Entities"), ICON_CLASS,
701 				&(tv_iters.tag_struct), _("Architectures"), ICON_STRUCT,
702 				&(tv_iters.tag_type), _("Types"), ICON_OTHER,
703 				&(tv_iters.tag_function), _("Functions / Procedures"), ICON_METHOD,
704 				&(tv_iters.tag_variable), _("Variables / Signals"), ICON_VAR,
705 				&(tv_iters.tag_member), _("Processes / Blocks / Components"), ICON_MEMBER,
706 				&(tv_iters.tag_other), _("Other"), ICON_OTHER,
707 				NULL);
708 			break;
709 		}
710 		case GEANY_FILETYPES_VERILOG:
711 		{
712 			tag_list_add_groups(tag_store,
713 				&(tv_iters.tag_type), _("Events"), ICON_MACRO,
714 				&(tv_iters.tag_class), _("Modules"), ICON_CLASS,
715 				&(tv_iters.tag_function), _("Functions / Tasks"), ICON_METHOD,
716 				&(tv_iters.tag_variable), _("Variables"), ICON_VAR,
717 				&(tv_iters.tag_other), _("Other"), ICON_OTHER,
718 				NULL);
719 			break;
720 		}
721 		case GEANY_FILETYPES_JAVA:
722 		{
723 			tag_list_add_groups(tag_store,
724 				&(tv_iters.tag_namespace), _("Package"), ICON_NAMESPACE,
725 				&(tv_iters.tag_interface), _("Interfaces"), ICON_STRUCT,
726 				&(tv_iters.tag_class), _("Classes"), ICON_CLASS,
727 				&(tv_iters.tag_function), _("Methods"), ICON_METHOD,
728 				&(tv_iters.tag_member), _("Members"), ICON_MEMBER,
729 				&(tv_iters.tag_type), _("Enums"), ICON_STRUCT,
730 				&(tv_iters.tag_other), _("Other"), ICON_OTHER,
731 				NULL);
732 			break;
733 		}
734 		case GEANY_FILETYPES_AS:
735 		{
736 			tag_list_add_groups(tag_store,
737 				&(tv_iters.tag_externvar), _("Imports"), ICON_NAMESPACE,
738 				&(tv_iters.tag_namespace), _("Package"), ICON_NAMESPACE,
739 				&(tv_iters.tag_interface), _("Interfaces"), ICON_STRUCT,
740 				&(tv_iters.tag_class), _("Classes"), ICON_CLASS,
741 				&(tv_iters.tag_function), _("Functions"), ICON_METHOD,
742 				&(tv_iters.tag_member), _("Properties"), ICON_MEMBER,
743 				&(tv_iters.tag_variable), _("Variables"), ICON_VAR,
744 				&(tv_iters.tag_macro), _("Constants"), ICON_MACRO,
745 				&(tv_iters.tag_other), _("Other"), ICON_OTHER,
746 				NULL);
747 			break;
748 		}
749 		case GEANY_FILETYPES_HAXE:
750 		{
751 			tag_list_add_groups(tag_store,
752 				&(tv_iters.tag_interface), _("Interfaces"), ICON_STRUCT,
753 				&(tv_iters.tag_class), _("Classes"), ICON_CLASS,
754 				&(tv_iters.tag_function), _("Methods"), ICON_METHOD,
755 				&(tv_iters.tag_type), _("Types"), ICON_MACRO,
756 				&(tv_iters.tag_variable), _("Variables"), ICON_VAR,
757 				&(tv_iters.tag_other), _("Other"), ICON_OTHER,
758 				NULL);
759 			break;
760 		}
761 		case GEANY_FILETYPES_BASIC:
762 		{
763 			tag_list_add_groups(tag_store,
764 				&(tv_iters.tag_function), _("Functions"), ICON_METHOD,
765 				&(tv_iters.tag_variable), _("Variables"), ICON_VAR,
766 				&(tv_iters.tag_macro), _("Constants"), ICON_MACRO,
767 				&(tv_iters.tag_struct), _("Types"), ICON_NAMESPACE,
768 				&(tv_iters.tag_namespace), _("Labels"), ICON_MEMBER,
769 				&(tv_iters.tag_other), _("Other"), ICON_OTHER,
770 				NULL);
771 			break;
772 		}
773 		case GEANY_FILETYPES_F77:
774 		case GEANY_FILETYPES_FORTRAN:
775 		{
776 			tag_list_add_groups(tag_store,
777 				&(tv_iters.tag_namespace), _("Module"), ICON_CLASS,
778 				&(tv_iters.tag_struct), _("Programs"), ICON_CLASS,
779 				&(tv_iters.tag_interface), _("Interfaces"), ICON_STRUCT,
780 				&(tv_iters.tag_function), _("Functions / Subroutines"), ICON_METHOD,
781 				&(tv_iters.tag_variable), _("Variables"), ICON_VAR,
782 				&(tv_iters.tag_class), _("Types"), ICON_CLASS,
783 				&(tv_iters.tag_member), _("Components"), ICON_MEMBER,
784 				&(tv_iters.tag_macro), _("Blocks"), ICON_MEMBER,
785 				&(tv_iters.tag_type), _("Enums"), ICON_STRUCT,
786 				&(tv_iters.tag_other), _("Other"), ICON_OTHER,
787 				NULL);
788 			break;
789 		}
790 		case GEANY_FILETYPES_ASM:
791 		{
792 			tag_list_add_groups(tag_store,
793 				&(tv_iters.tag_namespace), _("Labels"), ICON_NAMESPACE,
794 				&(tv_iters.tag_function), _("Macros"), ICON_METHOD,
795 				&(tv_iters.tag_macro), _("Defines"), ICON_MACRO,
796 				&(tv_iters.tag_struct), _("Types"), ICON_STRUCT,
797 				NULL);
798 			break;
799 		}
800 		case GEANY_FILETYPES_MAKE:
801 			tag_list_add_groups(tag_store,
802 				&tv_iters.tag_function, _("Targets"), ICON_METHOD,
803 				&tv_iters.tag_macro, _("Macros"), ICON_MACRO,
804 				NULL);
805 			break;
806 		case GEANY_FILETYPES_SQL:
807 		{
808 			tag_list_add_groups(tag_store,
809 				&(tv_iters.tag_function), _("Functions"), ICON_METHOD,
810 				&(tv_iters.tag_namespace), _("Procedures"), ICON_NAMESPACE,
811 				&(tv_iters.tag_struct), _("Indexes"), ICON_STRUCT,
812 				&(tv_iters.tag_class), _("Tables"), ICON_CLASS,
813 				&(tv_iters.tag_macro), _("Triggers"), ICON_MACRO,
814 				&(tv_iters.tag_member), _("Views"), ICON_VAR,
815 				&(tv_iters.tag_other), _("Other"), ICON_OTHER,
816 				&(tv_iters.tag_variable), _("Variables"), ICON_VAR,
817 				NULL);
818 			break;
819 		}
820 		case GEANY_FILETYPES_D:
821 		default:
822 		{
823 			if (ft_id == GEANY_FILETYPES_D)
824 				tag_list_add_groups(tag_store,
825 					&(tv_iters.tag_namespace), _("Module"), ICON_NONE, NULL);
826 			else
827 				tag_list_add_groups(tag_store,
828 					&(tv_iters.tag_namespace), _("Namespaces"), ICON_NAMESPACE, NULL);
829 
830 			tag_list_add_groups(tag_store,
831 				&(tv_iters.tag_class), _("Classes"), ICON_CLASS,
832 				&(tv_iters.tag_interface), _("Interfaces"), ICON_STRUCT,
833 				&(tv_iters.tag_function), _("Functions"), ICON_METHOD,
834 				&(tv_iters.tag_member), _("Members"), ICON_MEMBER,
835 				&(tv_iters.tag_struct), _("Structs"), ICON_STRUCT,
836 				&(tv_iters.tag_type), _("Typedefs / Enums"), ICON_STRUCT,
837 				NULL);
838 
839 			if (ft_id != GEANY_FILETYPES_D)
840 			{
841 				tag_list_add_groups(tag_store,
842 					&(tv_iters.tag_macro), _("Macros"), ICON_MACRO, NULL);
843 			}
844 			tag_list_add_groups(tag_store,
845 				&(tv_iters.tag_variable), _("Variables"), ICON_VAR,
846 				&(tv_iters.tag_externvar), _("Extern Variables"), ICON_VAR,
847 				&(tv_iters.tag_other), _("Other"), ICON_OTHER, NULL);
848 		}
849 	}
850 }
851 
852 
853 /* removes toplevel items that have no children */
hide_empty_rows(GtkTreeStore * store)854 static void hide_empty_rows(GtkTreeStore *store)
855 {
856 	GtkTreeIter iter;
857 	gboolean cont = TRUE;
858 
859 	if (! gtk_tree_model_get_iter_first(GTK_TREE_MODEL(store), &iter))
860 		return; /* stop when first iter is invalid, i.e. no elements */
861 
862 	while (cont)
863 	{
864 		if (! gtk_tree_model_iter_has_child(GTK_TREE_MODEL(store), &iter))
865 			cont = gtk_tree_store_remove(store, &iter);
866 		else
867 			cont = gtk_tree_model_iter_next(GTK_TREE_MODEL(store), &iter);
868 	}
869 }
870 
871 
get_symbol_name(GeanyDocument * doc,const TMTag * tag,gboolean found_parent)872 static const gchar *get_symbol_name(GeanyDocument *doc, const TMTag *tag, gboolean found_parent)
873 {
874 	gchar *utf8_name;
875 	const gchar *scope = tag->scope;
876 	static GString *buffer = NULL;	/* buffer will be small so we can keep it for reuse */
877 	gboolean doc_is_utf8 = FALSE;
878 
879 	/* encodings_convert_to_utf8_from_charset() fails with charset "None", so skip conversion
880 	 * for None at this point completely */
881 	if (utils_str_equal(doc->encoding, "UTF-8") ||
882 		utils_str_equal(doc->encoding, "None"))
883 		doc_is_utf8 = TRUE;
884 	else /* normally the tags will always be in UTF-8 since we parse from our buffer, but a
885 		  * plugin might have called tm_source_file_update(), so check to be sure */
886 		doc_is_utf8 = g_utf8_validate(tag->name, -1, NULL);
887 
888 	if (! doc_is_utf8)
889 		utf8_name = encodings_convert_to_utf8_from_charset(tag->name,
890 			-1, doc->encoding, TRUE);
891 	else
892 		utf8_name = tag->name;
893 
894 	if (utf8_name == NULL)
895 		return NULL;
896 
897 	if (! buffer)
898 		buffer = g_string_new(NULL);
899 	else
900 		g_string_truncate(buffer, 0);
901 
902 	/* check first char of scope is a wordchar */
903 	if (!found_parent && scope &&
904 		strpbrk(scope, GEANY_WORDCHARS) == scope)
905 	{
906 		const gchar *sep = symbols_get_context_separator(doc->file_type->id);
907 
908 		g_string_append(buffer, scope);
909 		g_string_append(buffer, sep);
910 	}
911 	g_string_append(buffer, utf8_name);
912 
913 	if (! doc_is_utf8)
914 		g_free(utf8_name);
915 
916 	g_string_append_printf(buffer, " [%lu]", tag->line);
917 
918 	return buffer->str;
919 }
920 
921 
get_symbol_tooltip(GeanyDocument * doc,const TMTag * tag)922 static gchar *get_symbol_tooltip(GeanyDocument *doc, const TMTag *tag)
923 {
924 	gchar *utf8_name = editor_get_calltip_text(doc->editor, tag);
925 
926 	if (!utf8_name && tag->var_type &&
927 		tag->type & (tm_tag_field_t | tm_tag_member_t | tm_tag_variable_t | tm_tag_externvar_t))
928 	{
929 		if (tag->lang != TM_PARSER_PASCAL && tag->lang != TM_PARSER_GO)
930 			utf8_name = g_strconcat(tag->var_type, " ", tag->name, NULL);
931 		else
932 		{
933 			const gchar *sep = tag->lang == TM_PARSER_PASCAL ? " : " : " ";
934 			utf8_name = g_strconcat(tag->name, sep, tag->var_type, NULL);
935 		}
936 	}
937 
938 	/* encodings_convert_to_utf8_from_charset() fails with charset "None", so skip conversion
939 	 * for None at this point completely */
940 	if (utf8_name != NULL &&
941 		! utils_str_equal(doc->encoding, "UTF-8") &&
942 		! utils_str_equal(doc->encoding, "None"))
943 	{
944 		SETPTR(utf8_name,
945 			encodings_convert_to_utf8_from_charset(utf8_name, -1, doc->encoding, TRUE));
946 	}
947 
948 	return utf8_name;
949 }
950 
951 
get_parent_name(const TMTag * tag)952 static const gchar *get_parent_name(const TMTag *tag)
953 {
954 	return !EMPTY(tag->scope) ? tag->scope : NULL;
955 }
956 
957 
get_tag_type_iter(TMTagType tag_type)958 static GtkTreeIter *get_tag_type_iter(TMTagType tag_type)
959 {
960 	GtkTreeIter *iter = NULL;
961 
962 	switch (tag_type)
963 	{
964 		case tm_tag_prototype_t:
965 		case tm_tag_method_t:
966 		case tm_tag_function_t:
967 		{
968 			iter = &tv_iters.tag_function;
969 			break;
970 		}
971 		case tm_tag_externvar_t:
972 		{
973 			iter = &tv_iters.tag_externvar;
974 			break;
975 		}
976 		case tm_tag_macro_t:
977 		case tm_tag_macro_with_arg_t:
978 		{
979 			iter = &tv_iters.tag_macro;
980 			break;
981 		}
982 		case tm_tag_class_t:
983 		{
984 			iter = &tv_iters.tag_class;
985 			break;
986 		}
987 		case tm_tag_member_t:
988 		case tm_tag_field_t:
989 		{
990 			iter = &tv_iters.tag_member;
991 			break;
992 		}
993 		case tm_tag_typedef_t:
994 		case tm_tag_enum_t:
995 		{
996 			iter = &tv_iters.tag_type;
997 			break;
998 		}
999 		case tm_tag_union_t:
1000 		case tm_tag_struct_t:
1001 		{
1002 			iter = &tv_iters.tag_struct;
1003 			break;
1004 		}
1005 		case tm_tag_interface_t:
1006 			iter = &tv_iters.tag_interface;
1007 			break;
1008 		case tm_tag_variable_t:
1009 		{
1010 			iter = &tv_iters.tag_variable;
1011 			break;
1012 		}
1013 		case tm_tag_namespace_t:
1014 		case tm_tag_package_t:
1015 		{
1016 			iter = &tv_iters.tag_namespace;
1017 			break;
1018 		}
1019 		default:
1020 		{
1021 			iter = &tv_iters.tag_other;
1022 		}
1023 	}
1024 	if (G_LIKELY(iter->stamp != -1))
1025 		return iter;
1026 	else
1027 		return NULL;
1028 }
1029 
1030 
get_child_icon(GtkTreeStore * tree_store,GtkTreeIter * parent)1031 static GdkPixbuf *get_child_icon(GtkTreeStore *tree_store, GtkTreeIter *parent)
1032 {
1033 	GdkPixbuf *icon = NULL;
1034 
1035 	if (parent == &tv_iters.tag_other)
1036 	{
1037 		return g_object_ref(symbols_icons[ICON_VAR].pixbuf);
1038 	}
1039 	/* copy parent icon */
1040 	gtk_tree_model_get(GTK_TREE_MODEL(tree_store), parent,
1041 		SYMBOLS_COLUMN_ICON, &icon, -1);
1042 	return icon;
1043 }
1044 
1045 
tag_equal(gconstpointer v1,gconstpointer v2)1046 static gboolean tag_equal(gconstpointer v1, gconstpointer v2)
1047 {
1048 	const TMTag *t1 = v1;
1049 	const TMTag *t2 = v2;
1050 
1051 	return (t1->type == t2->type && strcmp(t1->name, t2->name) == 0 &&
1052 			utils_str_equal(t1->scope, t2->scope) &&
1053 			/* include arglist in match to support e.g. C++ overloading */
1054 			utils_str_equal(t1->arglist, t2->arglist));
1055 }
1056 
1057 
1058 /* inspired from g_str_hash() */
tag_hash(gconstpointer v)1059 static guint tag_hash(gconstpointer v)
1060 {
1061 	const TMTag *tag = v;
1062 	const gchar *p;
1063 	guint32 h = 5381;
1064 
1065 	h = (h << 5) + h + tag->type;
1066 	for (p = tag->name; *p != '\0'; p++)
1067 		h = (h << 5) + h + *p;
1068 	if (tag->scope)
1069 	{
1070 		for (p = tag->scope; *p != '\0'; p++)
1071 			h = (h << 5) + h + *p;
1072 	}
1073 	/* for e.g. C++ overloading */
1074 	if (tag->arglist)
1075 	{
1076 		for (p = tag->arglist; *p != '\0'; p++)
1077 			h = (h << 5) + h + *p;
1078 	}
1079 
1080 	return h;
1081 }
1082 
1083 
1084 /* like gtk_tree_view_expand_to_path() but with an iter */
tree_view_expand_to_iter(GtkTreeView * view,GtkTreeIter * iter)1085 static void tree_view_expand_to_iter(GtkTreeView *view, GtkTreeIter *iter)
1086 {
1087 	GtkTreeModel *model = gtk_tree_view_get_model(view);
1088 	GtkTreePath *path = gtk_tree_model_get_path(model, iter);
1089 
1090 	gtk_tree_view_expand_to_path(view, path);
1091 	gtk_tree_path_free(path);
1092 }
1093 
1094 
1095 /* like gtk_tree_store_remove() but finds the next iter at any level */
tree_store_remove_row(GtkTreeStore * store,GtkTreeIter * iter)1096 static gboolean tree_store_remove_row(GtkTreeStore *store, GtkTreeIter *iter)
1097 {
1098 	GtkTreeIter parent;
1099 	gboolean has_parent;
1100 	gboolean cont;
1101 
1102 	has_parent = gtk_tree_model_iter_parent(GTK_TREE_MODEL(store), &parent, iter);
1103 	cont = gtk_tree_store_remove(store, iter);
1104 	/* if there is no next at this level but there is a parent iter, continue from it */
1105 	if (! cont && has_parent)
1106 	{
1107 		*iter = parent;
1108 		cont = ui_tree_model_iter_any_next(GTK_TREE_MODEL(store), iter, FALSE);
1109 	}
1110 
1111 	return cont;
1112 }
1113 
1114 
tree_search_func(gconstpointer key,gpointer user_data)1115 static gint tree_search_func(gconstpointer key, gpointer user_data)
1116 {
1117 	TreeSearchData *data = user_data;
1118 	gint parent_line = GPOINTER_TO_INT(key);
1119 	gboolean new_nearest;
1120 
1121 	if (data->found_line == -1)
1122 		data->found_line = parent_line; /* initial value */
1123 
1124 	new_nearest = ABS(data->line - parent_line) < ABS(data->line - data->found_line);
1125 
1126 	if (parent_line > data->line)
1127 	{
1128 		if (new_nearest && !data->lower)
1129 			data->found_line = parent_line;
1130 		return -1;
1131 	}
1132 
1133 	if (new_nearest)
1134 		data->found_line = parent_line;
1135 
1136 	if (parent_line < data->line)
1137 		return 1;
1138 
1139 	return 0;
1140 }
1141 
1142 
tree_cmp(gconstpointer a,gconstpointer b,gpointer user_data)1143 static gint tree_cmp(gconstpointer a, gconstpointer b, gpointer user_data)
1144 {
1145 	return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
1146 }
1147 
1148 
parents_table_tree_value_free(gpointer data)1149 static void parents_table_tree_value_free(gpointer data)
1150 {
1151 	g_slice_free(GtkTreeIter, data);
1152 }
1153 
1154 
1155 /* adds a new element in the parent table if its key is known. */
update_parents_table(GHashTable * table,const TMTag * tag,const GtkTreeIter * iter)1156 static void update_parents_table(GHashTable *table, const TMTag *tag, const GtkTreeIter *iter)
1157 {
1158 	const gchar *name;
1159 	gchar *name_free = NULL;
1160 	GTree *tree;
1161 
1162 	if (EMPTY(tag->scope))
1163 	{
1164 		/* simple case, just use the tag name */
1165 		name = tag->name;
1166 	}
1167 	else if (! tm_parser_has_full_context(tag->lang))
1168 	{
1169 		/* if the parser doesn't use fully qualified scope, use the name alone but
1170 		 * prevent Foo::Foo from making parent = child */
1171 		if (utils_str_equal(tag->scope, tag->name))
1172 			name = NULL;
1173 		else
1174 			name = tag->name;
1175 	}
1176 	else
1177 	{
1178 		/* build the fully qualified scope as get_parent_name() would return it for a child tag */
1179 		name_free = g_strconcat(tag->scope, tm_parser_context_separator(tag->lang), tag->name, NULL);
1180 		name = name_free;
1181 	}
1182 
1183 	if (name && g_hash_table_lookup_extended(table, name, NULL, (gpointer *) &tree))
1184 	{
1185 		if (!tree)
1186 		{
1187 			tree = g_tree_new_full(tree_cmp, NULL, NULL, parents_table_tree_value_free);
1188 			g_hash_table_insert(table, name_free ? name_free : g_strdup(name), tree);
1189 			name_free = NULL;
1190 		}
1191 
1192 		g_tree_insert(tree, GINT_TO_POINTER(tag->line), g_slice_dup(GtkTreeIter, iter));
1193 	}
1194 
1195 	g_free(name_free);
1196 }
1197 
1198 
parents_table_lookup(GHashTable * table,const gchar * name,guint line)1199 static GtkTreeIter *parents_table_lookup(GHashTable *table, const gchar *name, guint line)
1200 {
1201 	GtkTreeIter *parent_search = NULL;
1202 	GTree *tree;
1203 
1204 	tree = g_hash_table_lookup(table, name);
1205 	if (tree)
1206 	{
1207 		TreeSearchData user_data = {-1, line, TRUE};
1208 
1209 		/* search parent candidates for the one with the nearest
1210 		 * line number which is lower than the tag's line number */
1211 		g_tree_search(tree, (GCompareFunc)tree_search_func, &user_data);
1212 		parent_search = g_tree_lookup(tree, GINT_TO_POINTER(user_data.found_line));
1213 	}
1214 
1215 	return parent_search;
1216 }
1217 
1218 
parents_table_value_free(gpointer data)1219 static void parents_table_value_free(gpointer data)
1220 {
1221 	GTree *tree = data;
1222 	if (tree)
1223 		g_tree_destroy(tree);
1224 }
1225 
1226 
1227 /* inserts a @data in @table on key @tag.
1228  * previous data is not overwritten if the key is duplicated, but rather the
1229  * two values are kept in a list
1230  *
1231  * table is: GHashTable<TMTag, GTree<line_num, GList<GList<TMTag>>>> */
tags_table_insert(GHashTable * table,TMTag * tag,GList * data)1232 static void tags_table_insert(GHashTable *table, TMTag *tag, GList *data)
1233 {
1234 	GTree *tree = g_hash_table_lookup(table, tag);
1235 	if (!tree)
1236 	{
1237 		tree = g_tree_new_full(tree_cmp, NULL, NULL, NULL);
1238 		g_hash_table_insert(table, tag, tree);
1239 	}
1240 	GList *list = g_tree_lookup(tree, GINT_TO_POINTER(tag->line));
1241 	list = g_list_prepend(list, data);
1242 	g_tree_insert(tree, GINT_TO_POINTER(tag->line), list);
1243 }
1244 
1245 
1246 /* looks up the entry in @table that best matches @tag.
1247  * if there is more than one candidate, the one that has closest line position to @tag is chosen */
tags_table_lookup(GHashTable * table,TMTag * tag)1248 static GList *tags_table_lookup(GHashTable *table, TMTag *tag)
1249 {
1250 	TreeSearchData user_data = {-1, tag->line, FALSE};
1251 	GTree *tree = g_hash_table_lookup(table, tag);
1252 
1253 	if (tree)
1254 	{
1255 		GList *list;
1256 
1257 		g_tree_search(tree, (GCompareFunc)tree_search_func, &user_data);
1258 		list = g_tree_lookup(tree, GINT_TO_POINTER(user_data.found_line));
1259 		/* return the first value in the list - we don't care which of the
1260 		 * tags with identical names defined on the same line we get */
1261 		if (list)
1262 			return list->data;
1263 	}
1264 	return NULL;
1265 }
1266 
1267 
1268 /* removes the element at @tag from @table.
1269  * @tag must be the exact pointer used at insertion time */
tags_table_remove(GHashTable * table,TMTag * tag)1270 static void tags_table_remove(GHashTable *table, TMTag *tag)
1271 {
1272 	GTree *tree = g_hash_table_lookup(table, tag);
1273 	if (tree)
1274 	{
1275 		GList *list = g_tree_lookup(tree, GINT_TO_POINTER(tag->line));
1276 		if (list)
1277 		{
1278 			GList *node;
1279 			/* should always be the first element as we returned the first one in
1280 			 * tags_table_lookup() */
1281 			foreach_list(node, list)
1282 			{
1283 				if (((GList *) node->data)->data == tag)
1284 					break;
1285 			}
1286 			list = g_list_delete_link(list, node);
1287 			if (!list)
1288 				g_tree_remove(tree, GINT_TO_POINTER(tag->line));
1289 			else
1290 				g_tree_insert(tree, GINT_TO_POINTER(tag->line), list);
1291 		}
1292 	}
1293 }
1294 
1295 
tags_table_tree_value_free(gpointer key,gpointer value,gpointer data)1296 static gboolean tags_table_tree_value_free(gpointer key, gpointer value, gpointer data)
1297 {
1298 	GList *list = value;
1299 	g_list_free(list);
1300 	return FALSE;
1301 }
1302 
1303 
tags_table_value_free(gpointer data)1304 static void tags_table_value_free(gpointer data)
1305 {
1306 	GTree *tree = data;
1307 	if (tree)
1308 	{
1309 		/* free any leftover elements.  note that we can't register a value_free_func when
1310 		 * creating the tree because we only want to free it when destroying the tree,
1311 		 * not when inserting a duplicate (we handle this manually) */
1312 		g_tree_foreach(tree, tags_table_tree_value_free, NULL);
1313 		g_tree_destroy(tree);
1314 	}
1315 }
1316 
1317 
1318 /*
1319  * Updates the tag tree for a document with the tags in *list.
1320  * @param doc a document
1321  * @param tags a pointer to a GList* holding the tags to add/update.  This
1322  *             list may be updated, removing updated elements.
1323  *
1324  * The update is done in two passes:
1325  * 1) walking the current tree, update tags that still exist and remove the
1326  *    obsolescent ones;
1327  * 2) walking the remaining (non updated) tags, adds them in the list.
1328  *
1329  * For better performances, we use 2 hash tables:
1330  * - one containing all the tags for lookup in the first pass (actually stores a
1331  *   reference in the tags list for removing it efficiently), avoiding list search
1332  *   on each tag;
1333  * - the other holding "tag-name":row references for tags having children, used to
1334  *   lookup for a parent in both passes, avoiding tree traversal.
1335  */
update_tree_tags(GeanyDocument * doc,GList ** tags)1336 static void update_tree_tags(GeanyDocument *doc, GList **tags)
1337 {
1338 	GtkTreeStore *store = doc->priv->tag_store;
1339 	GtkTreeModel *model = GTK_TREE_MODEL(store);
1340 	GHashTable *parents_table;
1341 	GHashTable *tags_table;
1342 	GtkTreeIter iter;
1343 	gboolean cont;
1344 	GList *item;
1345 
1346 	/* Build hash tables holding tags and parents */
1347 	/* parent table is GHashTable<tag_name, GTree<line_num, GtkTreeIter>>
1348 	 * where tag_name might be a fully qualified name (with scope) if the language
1349 	 * parser reports scope properly (see tm_parser_has_full_context()). */
1350 	parents_table = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, parents_table_value_free);
1351 	/* tags table is another representation of the @tags list,
1352 	 * GHashTable<TMTag, GTree<line_num, GList<GList<TMTag>>>> */
1353 	tags_table = g_hash_table_new_full(tag_hash, tag_equal, NULL, tags_table_value_free);
1354 	foreach_list(item, *tags)
1355 	{
1356 		TMTag *tag = item->data;
1357 		const gchar *parent_name;
1358 
1359 		tags_table_insert(tags_table, tag, item);
1360 
1361 		parent_name = get_parent_name(tag);
1362 		if (parent_name)
1363 			g_hash_table_insert(parents_table, g_strdup(parent_name), NULL);
1364 	}
1365 
1366 	/* First pass, update existing rows or delete them.
1367 	 * It is OK to delete them since we walk top down so we would remove
1368 	 * parents before checking for their children, thus never implicitly
1369 	 * deleting an updated child */
1370 	cont = gtk_tree_model_get_iter_first(model, &iter);
1371 	while (cont)
1372 	{
1373 		TMTag *tag;
1374 
1375 		gtk_tree_model_get(model, &iter, SYMBOLS_COLUMN_TAG, &tag, -1);
1376 		if (! tag) /* most probably a toplevel, skip it */
1377 			cont = ui_tree_model_iter_any_next(model, &iter, TRUE);
1378 		else
1379 		{
1380 			GList *found_item;
1381 
1382 			found_item = tags_table_lookup(tags_table, tag);
1383 			if (! found_item) /* tag doesn't exist, remove it */
1384 				cont = tree_store_remove_row(store, &iter);
1385 			else /* tag still exist, update it */
1386 			{
1387 				const gchar *parent_name;
1388 				TMTag *found = found_item->data;
1389 
1390 				parent_name = get_parent_name(found);
1391 				/* if parent is unknown, ignore it */
1392 				if (parent_name && ! g_hash_table_lookup(parents_table, parent_name))
1393 					parent_name = NULL;
1394 
1395 				if (!tm_tags_equal(tag, found))
1396 				{
1397 					const gchar *name;
1398 					gchar *tooltip;
1399 
1400 					/* only update fields that (can) have changed (name that holds line
1401 					 * number, tooltip, and the tag itself) */
1402 					name = get_symbol_name(doc, found, parent_name != NULL);
1403 					tooltip = get_symbol_tooltip(doc, found);
1404 					gtk_tree_store_set(store, &iter,
1405 							SYMBOLS_COLUMN_NAME, name,
1406 							SYMBOLS_COLUMN_TOOLTIP, tooltip,
1407 							SYMBOLS_COLUMN_TAG, found,
1408 							-1);
1409 					g_free(tooltip);
1410 				}
1411 
1412 				update_parents_table(parents_table, found, &iter);
1413 
1414 				/* remove the updated tag from the table and list */
1415 				tags_table_remove(tags_table, found);
1416 				*tags = g_list_delete_link(*tags, found_item);
1417 
1418 				cont = ui_tree_model_iter_any_next(model, &iter, TRUE);
1419 			}
1420 
1421 			tm_tag_unref(tag);
1422 		}
1423 	}
1424 
1425 	/* Second pass, now we have a tree cleaned up from invalid rows,
1426 	 * we simply add new ones */
1427 	foreach_list (item, *tags)
1428 	{
1429 		TMTag *tag = item->data;
1430 		GtkTreeIter *parent;
1431 
1432 		parent = get_tag_type_iter(tag->type);
1433 		if (G_UNLIKELY(! parent))
1434 			geany_debug("Missing symbol-tree parent iter for type %d!", tag->type);
1435 		else
1436 		{
1437 			gboolean expand;
1438 			const gchar *name;
1439 			const gchar *parent_name;
1440 			gchar *tooltip;
1441 			GdkPixbuf *icon = get_child_icon(store, parent);
1442 
1443 			parent_name = get_parent_name(tag);
1444 			if (parent_name)
1445 			{
1446 				GtkTreeIter *parent_search = parents_table_lookup(parents_table, parent_name, tag->line);
1447 
1448 				if (parent_search)
1449 					parent = parent_search;
1450 				else
1451 					parent_name = NULL;
1452 			}
1453 
1454 			/* only expand to the iter if the parent was empty, otherwise we let the
1455 			 * folding as it was before (already expanded, or closed by the user) */
1456 			expand = ! gtk_tree_model_iter_has_child(model, parent);
1457 
1458 			/* insert the new element */
1459 			name = get_symbol_name(doc, tag, parent_name != NULL);
1460 			tooltip = get_symbol_tooltip(doc, tag);
1461 			gtk_tree_store_insert_with_values(store, &iter, parent, 0,
1462 					SYMBOLS_COLUMN_NAME, name,
1463 					SYMBOLS_COLUMN_TOOLTIP, tooltip,
1464 					SYMBOLS_COLUMN_ICON, icon,
1465 					SYMBOLS_COLUMN_TAG, tag,
1466 					-1);
1467 			g_free(tooltip);
1468 			if (G_LIKELY(icon))
1469 				g_object_unref(icon);
1470 
1471 			update_parents_table(parents_table, tag, &iter);
1472 
1473 			if (expand)
1474 				tree_view_expand_to_iter(GTK_TREE_VIEW(doc->priv->tag_tree), &iter);
1475 		}
1476 	}
1477 
1478 	g_hash_table_destroy(parents_table);
1479 	g_hash_table_destroy(tags_table);
1480 }
1481 
1482 
1483 /* we don't want to sort 1st-level nodes, but we can't return 0 because the tree sort
1484  * is not stable, so the order is already lost. */
compare_top_level_names(const gchar * a,const gchar * b)1485 static gint compare_top_level_names(const gchar *a, const gchar *b)
1486 {
1487 	guint i;
1488 	const gchar *name;
1489 
1490 	/* This should never happen as it would mean that two or more top
1491 	 * level items have the same name but it can happen by typos in the translations. */
1492 	if (utils_str_equal(a, b))
1493 		return 1;
1494 
1495 	foreach_ptr_array(name, i, top_level_iter_names)
1496 	{
1497 		if (utils_str_equal(name, a))
1498 			return -1;
1499 		if (utils_str_equal(name, b))
1500 			return 1;
1501 	}
1502 	g_warning("Couldn't find top level node '%s' or '%s'!", a, b);
1503 	return 0;
1504 }
1505 
1506 
tag_has_missing_parent(const TMTag * tag,GtkTreeStore * store,GtkTreeIter * iter)1507 static gboolean tag_has_missing_parent(const TMTag *tag, GtkTreeStore *store,
1508 		GtkTreeIter *iter)
1509 {
1510 	/* if the tag has a parent tag, it should be at depth >= 2 */
1511 	return !EMPTY(tag->scope) &&
1512 		gtk_tree_store_iter_depth(store, iter) == 1;
1513 }
1514 
1515 
tree_sort_func(GtkTreeModel * model,GtkTreeIter * a,GtkTreeIter * b,gpointer user_data)1516 static gint tree_sort_func(GtkTreeModel *model, GtkTreeIter *a, GtkTreeIter *b,
1517 		gpointer user_data)
1518 {
1519 	gboolean sort_by_name = GPOINTER_TO_INT(user_data);
1520 	TMTag *tag_a, *tag_b;
1521 	gint cmp;
1522 
1523 	gtk_tree_model_get(model, a, SYMBOLS_COLUMN_TAG, &tag_a, -1);
1524 	gtk_tree_model_get(model, b, SYMBOLS_COLUMN_TAG, &tag_b, -1);
1525 
1526 	/* Check if the iters can be sorted based on tag name and line, not tree item name.
1527 	 * Sort by tree name if the scope was prepended, e.g. 'ScopeNameWithNoTag::TagName'. */
1528 	if (tag_a && !tag_has_missing_parent(tag_a, GTK_TREE_STORE(model), a) &&
1529 		tag_b && !tag_has_missing_parent(tag_b, GTK_TREE_STORE(model), b))
1530 	{
1531 		cmp = sort_by_name ? compare_symbol(tag_a, tag_b) :
1532 			compare_symbol_lines(tag_a, tag_b);
1533 	}
1534 	else
1535 	{
1536 		gchar *astr, *bstr;
1537 
1538 		gtk_tree_model_get(model, a, SYMBOLS_COLUMN_NAME, &astr, -1);
1539 		gtk_tree_model_get(model, b, SYMBOLS_COLUMN_NAME, &bstr, -1);
1540 
1541 		/* if a is toplevel, b must be also */
1542 		if (gtk_tree_store_iter_depth(GTK_TREE_STORE(model), a) == 0)
1543 		{
1544 			cmp = compare_top_level_names(astr, bstr);
1545 		}
1546 		else
1547 		{
1548 			/* this is what g_strcmp0() does */
1549 			if (! astr)
1550 				cmp = -(astr != bstr);
1551 			else if (! bstr)
1552 				cmp = astr != bstr;
1553 			else
1554 			{
1555 				cmp = strcmp(astr, bstr);
1556 
1557 				/* sort duplicate 'ScopeName::OverloadedTagName' items by line as well */
1558 				if (tag_a && tag_b)
1559 					if (!sort_by_name ||
1560 						(utils_str_equal(tag_a->name, tag_b->name) &&
1561 							utils_str_equal(tag_a->scope, tag_b->scope)))
1562 						cmp = compare_symbol_lines(tag_a, tag_b);
1563 			}
1564 		}
1565 		g_free(astr);
1566 		g_free(bstr);
1567 	}
1568 	tm_tag_unref(tag_a);
1569 	tm_tag_unref(tag_b);
1570 
1571 	return cmp;
1572 }
1573 
1574 
sort_tree(GtkTreeStore * store,gboolean sort_by_name)1575 static void sort_tree(GtkTreeStore *store, gboolean sort_by_name)
1576 {
1577 	gtk_tree_sortable_set_sort_func(GTK_TREE_SORTABLE(store), SYMBOLS_COLUMN_NAME, tree_sort_func,
1578 		GINT_TO_POINTER(sort_by_name), NULL);
1579 
1580 	gtk_tree_sortable_set_sort_column_id(GTK_TREE_SORTABLE(store), SYMBOLS_COLUMN_NAME, GTK_SORT_ASCENDING);
1581 }
1582 
1583 
symbols_recreate_tag_list(GeanyDocument * doc,gint sort_mode)1584 gboolean symbols_recreate_tag_list(GeanyDocument *doc, gint sort_mode)
1585 {
1586 	GList *tags;
1587 
1588 	g_return_val_if_fail(DOC_VALID(doc), FALSE);
1589 
1590 	tags = get_tag_list(doc, tm_tag_max_t);
1591 	if (tags == NULL)
1592 		return FALSE;
1593 
1594 	/* FIXME: Not sure why we detached the model here? */
1595 
1596 	/* disable sorting during update because the code doesn't support correctly
1597 	 * models that are currently being built */
1598 	gtk_tree_sortable_set_sort_column_id(GTK_TREE_SORTABLE(doc->priv->tag_store), GTK_TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID, 0);
1599 
1600 	/* add grandparent type iters */
1601 	add_top_level_items(doc);
1602 
1603 	update_tree_tags(doc, &tags);
1604 	g_list_free(tags);
1605 
1606 	hide_empty_rows(doc->priv->tag_store);
1607 
1608 	if (sort_mode == SYMBOLS_SORT_USE_PREVIOUS)
1609 		sort_mode = doc->priv->symbol_list_sort_mode;
1610 
1611 	sort_tree(doc->priv->tag_store, sort_mode == SYMBOLS_SORT_BY_NAME);
1612 	doc->priv->symbol_list_sort_mode = sort_mode;
1613 
1614 	return TRUE;
1615 }
1616 
1617 
1618 /* Detects a global tags filetype from the *.lang.* language extension.
1619  * Returns NULL if there was no matching TM language. */
detect_global_tags_filetype(const gchar * utf8_filename)1620 static GeanyFiletype *detect_global_tags_filetype(const gchar *utf8_filename)
1621 {
1622 	gchar *tags_ext;
1623 	gchar *shortname = utils_strdupa(utf8_filename);
1624 	GeanyFiletype *ft = NULL;
1625 
1626 	tags_ext = g_strrstr(shortname, ".tags");
1627 	if (tags_ext)
1628 	{
1629 		*tags_ext = '\0';	/* remove .tags extension */
1630 		ft = filetypes_detect_from_extension(shortname);
1631 		if (ft->id != GEANY_FILETYPES_NONE)
1632 			return ft;
1633 	}
1634 	return NULL;
1635 }
1636 
1637 
1638 /* Adapted from anjuta-2.0.2/global-tags/tm_global_tags.c, thanks.
1639  * Needs full paths for filenames, except for C/C++ tag files, when CFLAGS includes
1640  * the relevant path.
1641  * Example:
1642  * CFLAGS=-I/home/user/libname-1.x geany -g libname.d.tags libname.h */
symbols_generate_global_tags(int argc,char ** argv,gboolean want_preprocess)1643 int symbols_generate_global_tags(int argc, char **argv, gboolean want_preprocess)
1644 {
1645 	/* -E pre-process, -dD output user macros, -p prof info (?) */
1646 	const char pre_process[] = "gcc -E -dD -p -I.";
1647 
1648 	if (argc > 2)
1649 	{
1650 		/* Create global taglist */
1651 		int status;
1652 		char *command;
1653 		const char *tags_file = argv[1];
1654 		char *utf8_fname;
1655 		GeanyFiletype *ft;
1656 
1657 		utf8_fname = utils_get_utf8_from_locale(tags_file);
1658 		ft = detect_global_tags_filetype(utf8_fname);
1659 		g_free(utf8_fname);
1660 
1661 		if (ft == NULL)
1662 		{
1663 			g_printerr(_("Unknown filetype extension for \"%s\".\n"), tags_file);
1664 			return 1;
1665 		}
1666 		/* load config in case of custom filetypes */
1667 		filetypes_load_config(ft->id, FALSE);
1668 
1669 		/* load ignore list for C/C++ parser */
1670 		if (ft->id == GEANY_FILETYPES_C || ft->id == GEANY_FILETYPES_CPP)
1671 			load_c_ignore_tags();
1672 
1673 		if (want_preprocess && (ft->id == GEANY_FILETYPES_C || ft->id == GEANY_FILETYPES_CPP))
1674 		{
1675 			const gchar *cflags = getenv("CFLAGS");
1676 			command = g_strdup_printf("%s %s", pre_process, FALLBACK(cflags, ""));
1677 		}
1678 		else
1679 			command = NULL;	/* don't preprocess */
1680 
1681 		geany_debug("Generating %s tags file.", ft->name);
1682 		tm_get_workspace();
1683 		status = tm_workspace_create_global_tags(command, (const char **) (argv + 2),
1684 												 argc - 2, tags_file, ft->lang);
1685 		g_free(command);
1686 		symbols_finalize(); /* free c_tags_ignore data */
1687 		if (! status)
1688 		{
1689 			g_printerr(_("Failed to create tags file, perhaps because no symbols "
1690 				"were found.\n"));
1691 			return 1;
1692 		}
1693 	}
1694 	else
1695 	{
1696 		g_printerr(_("Usage: %s -g <Tags File> <File list>\n\n"), argv[0]);
1697 		g_printerr(_("Example:\n"
1698 			"CFLAGS=`pkg-config gtk+-2.0 --cflags` %s -g gtk2.c.tags"
1699 			" /usr/include/gtk-2.0/gtk/gtk.h\n"), argv[0]);
1700 		return 1;
1701 	}
1702 	return 0;
1703 }
1704 
1705 
symbols_show_load_tags_dialog(void)1706 void symbols_show_load_tags_dialog(void)
1707 {
1708 	GtkWidget *dialog;
1709 	GtkFileFilter *filter;
1710 
1711 	dialog = gtk_file_chooser_dialog_new(_("Load Tags File"), GTK_WINDOW(main_widgets.window),
1712 		GTK_FILE_CHOOSER_ACTION_OPEN,
1713 		GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
1714 		GTK_STOCK_OPEN, GTK_RESPONSE_OK,
1715 		NULL);
1716 	gtk_widget_set_name(dialog, "GeanyDialog");
1717 	filter = gtk_file_filter_new();
1718 	gtk_file_filter_set_name(filter, _("Geany tags file (*.*.tags)"));
1719 	gtk_file_filter_add_pattern(filter, "*.*.tags");
1720 	gtk_file_chooser_add_filter(GTK_FILE_CHOOSER(dialog), filter);
1721 
1722 	if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK)
1723 	{
1724 		GSList *flist = gtk_file_chooser_get_filenames(GTK_FILE_CHOOSER(dialog));
1725 		GSList *item;
1726 
1727 		for (item = flist; item != NULL; item = g_slist_next(item))
1728 		{
1729 			gchar *fname = item->data;
1730 			gchar *utf8_fname;
1731 			GeanyFiletype *ft;
1732 
1733 			utf8_fname = utils_get_utf8_from_locale(fname);
1734 			ft = detect_global_tags_filetype(utf8_fname);
1735 
1736 			if (ft != NULL && symbols_load_global_tags(fname, ft))
1737 				/* For translators: the first wildcard is the filetype, the second the filename */
1738 				ui_set_statusbar(TRUE, _("Loaded %s tags file '%s'."),
1739 					filetypes_get_display_name(ft), utf8_fname);
1740 			else
1741 				ui_set_statusbar(TRUE, _("Could not load tags file '%s'."), utf8_fname);
1742 
1743 			g_free(utf8_fname);
1744 			g_free(fname);
1745 		}
1746 		g_slist_free(flist);
1747 	}
1748 	gtk_widget_destroy(dialog);
1749 }
1750 
1751 
init_user_tags(void)1752 static void init_user_tags(void)
1753 {
1754 	GSList *file_list = NULL, *list = NULL;
1755 	const GSList *node;
1756 	gchar *dir;
1757 
1758 	dir = g_build_filename(app->configdir, GEANY_TAGS_SUBDIR, NULL);
1759 	/* create the user tags dir for next time if it doesn't exist */
1760 	if (! g_file_test(dir, G_FILE_TEST_IS_DIR))
1761 		utils_mkdir(dir, FALSE);
1762 	file_list = utils_get_file_list_full(dir, TRUE, FALSE, NULL);
1763 
1764 	SETPTR(dir, g_build_filename(app->datadir, GEANY_TAGS_SUBDIR, NULL));
1765 	list = utils_get_file_list_full(dir, TRUE, FALSE, NULL);
1766 	g_free(dir);
1767 
1768 	file_list = g_slist_concat(file_list, list);
1769 
1770 	/* populate the filetype-specific tag files lists */
1771 	for (node = file_list; node != NULL; node = node->next)
1772 	{
1773 		gchar *fname = node->data;
1774 		gchar *utf8_fname = utils_get_utf8_from_locale(fname);
1775 		GeanyFiletype *ft = detect_global_tags_filetype(utf8_fname);
1776 
1777 		g_free(utf8_fname);
1778 
1779 		if (FILETYPE_ID(ft) != GEANY_FILETYPES_NONE)
1780 			ft->priv->tag_files = g_slist_prepend(ft->priv->tag_files, fname);
1781 		else
1782 		{
1783 			geany_debug("Unknown filetype for file '%s'.", fname);
1784 			g_free(fname);
1785 		}
1786 	}
1787 
1788 	/* don't need to delete list contents because they are now stored in
1789 	 * ft->priv->tag_files */
1790 	g_slist_free(file_list);
1791 }
1792 
1793 
load_user_tags(GeanyFiletypeID ft_id)1794 static void load_user_tags(GeanyFiletypeID ft_id)
1795 {
1796 	static guchar *tags_loaded = NULL;
1797 	static gboolean init_tags = FALSE;
1798 	const GSList *node;
1799 	GeanyFiletype *ft = filetypes[ft_id];
1800 
1801 	g_return_if_fail(ft_id > 0);
1802 
1803 	if (!tags_loaded)
1804 		tags_loaded = g_new0(guchar, filetypes_array->len);
1805 	if (tags_loaded[ft_id])
1806 		return;
1807 	tags_loaded[ft_id] = TRUE;	/* prevent reloading */
1808 
1809 	if (!init_tags)
1810 	{
1811 		init_user_tags();
1812 		init_tags = TRUE;
1813 	}
1814 
1815 	for (node = ft->priv->tag_files; node != NULL; node = g_slist_next(node))
1816 	{
1817 		const gchar *fname = node->data;
1818 
1819 		symbols_load_global_tags(fname, ft);
1820 	}
1821 }
1822 
1823 
on_goto_popup_item_activate(GtkMenuItem * item,TMTag * tag)1824 static void on_goto_popup_item_activate(GtkMenuItem *item, TMTag *tag)
1825 {
1826 	GeanyDocument *new_doc, *old_doc;
1827 
1828 	g_return_if_fail(tag);
1829 
1830 	old_doc = document_get_current();
1831 	new_doc = document_open_file(tag->file->file_name, FALSE, NULL, NULL);
1832 
1833 	if (new_doc)
1834 		navqueue_goto_line(old_doc, new_doc, tag->line);
1835 }
1836 
1837 
1838 /* FIXME: use the same icons as in the symbols tree defined in add_top_level_items() */
get_tag_class(const TMTag * tag)1839 static guint get_tag_class(const TMTag *tag)
1840 {
1841 	switch (tag->type)
1842 	{
1843 		case tm_tag_prototype_t:
1844 		case tm_tag_method_t:
1845 		case tm_tag_function_t:
1846 			return ICON_METHOD;
1847 		case tm_tag_variable_t:
1848 		case tm_tag_externvar_t:
1849 			return ICON_VAR;
1850 		case tm_tag_macro_t:
1851 		case tm_tag_macro_with_arg_t:
1852 			return ICON_MACRO;
1853 		case tm_tag_class_t:
1854 			return ICON_CLASS;
1855 		case tm_tag_member_t:
1856 		case tm_tag_field_t:
1857 			return ICON_MEMBER;
1858 		case tm_tag_typedef_t:
1859 		case tm_tag_enum_t:
1860 		case tm_tag_union_t:
1861 		case tm_tag_struct_t:
1862 			return ICON_STRUCT;
1863 		case tm_tag_namespace_t:
1864 		case tm_tag_package_t:
1865 			return ICON_NAMESPACE;
1866 		default:
1867 			break;
1868 	}
1869 	return ICON_STRUCT;
1870 }
1871 
1872 
1873 /* positions a popup at the caret from the ScintillaObject in @p data */
goto_popup_position_func(GtkMenu * menu,gint * x,gint * y,gboolean * push_in,gpointer data)1874 static void goto_popup_position_func(GtkMenu *menu, gint *x, gint *y, gboolean *push_in, gpointer data)
1875 {
1876 	gint line_height;
1877 	GdkScreen *screen = gtk_widget_get_screen(GTK_WIDGET(menu));
1878 	gint monitor_num;
1879 	GdkRectangle monitor;
1880 	GtkRequisition req;
1881 	GdkEventButton *event_button = g_object_get_data(G_OBJECT(menu), "geany-button-event");
1882 
1883 	if (event_button)
1884 	{
1885 		/* if we got a mouse click, popup at that position */
1886 		*x = (gint) event_button->x_root;
1887 		*y = (gint) event_button->y_root;
1888 		line_height = 0; /* we don't want to offset below the line or anything */
1889 	}
1890 	else /* keyboard positioning */
1891 	{
1892 		ScintillaObject *sci = data;
1893 		GdkWindow *window = gtk_widget_get_window(GTK_WIDGET(sci));
1894 		gint pos = sci_get_current_position(sci);
1895 		gint line = sci_get_line_from_position(sci, pos);
1896 		gint pos_x = SSM(sci, SCI_POINTXFROMPOSITION, 0, pos);
1897 		gint pos_y = SSM(sci, SCI_POINTYFROMPOSITION, 0, pos);
1898 
1899 		line_height = SSM(sci, SCI_TEXTHEIGHT, line, 0);
1900 
1901 		gdk_window_get_origin(window, x, y);
1902 		*x += pos_x;
1903 		*y += pos_y;
1904 	}
1905 
1906 	monitor_num = gdk_screen_get_monitor_at_point(screen, *x, *y);
1907 
1908 #if GTK_CHECK_VERSION(3, 0, 0)
1909 	gtk_widget_get_preferred_size(GTK_WIDGET(menu), NULL, &req);
1910 #else
1911 	gtk_widget_size_request(GTK_WIDGET(menu), &req);
1912 #endif
1913 
1914 #if GTK_CHECK_VERSION(3, 4, 0)
1915 	gdk_screen_get_monitor_workarea(screen, monitor_num, &monitor);
1916 #else
1917 	gdk_screen_get_monitor_geometry(screen, monitor_num, &monitor);
1918 #endif
1919 
1920 	/* put on one size of the X position, but within the monitor */
1921 	if (gtk_widget_get_direction(GTK_WIDGET(menu)) == GTK_TEXT_DIR_RTL)
1922 	{
1923 		if (*x - req.width - 1 >= monitor.x)
1924 			*x -= req.width + 1;
1925 		else if (*x + req.width > monitor.x + monitor.width)
1926 			*x = monitor.x;
1927 		else
1928 			*x += 1;
1929 	}
1930 	else
1931 	{
1932 		if (*x + req.width + 1 <= monitor.x + monitor.width)
1933 			*x = MAX(monitor.x, *x + 1);
1934 		else if (*x - req.width - 1 >= monitor.x)
1935 			*x -= req.width + 1;
1936 		else
1937 			*x = monitor.x + MAX(0, monitor.width - req.width);
1938 	}
1939 
1940 	/* try to put, in order:
1941 	 * 1. below the Y position, under the line
1942 	 * 2. above the Y position
1943 	 * 3. within the monitor */
1944 	if (*y + line_height + req.height <= monitor.y + monitor.height)
1945 		*y = MAX(monitor.y, *y + line_height);
1946 	else if (*y - req.height >= monitor.y)
1947 		*y = *y - req.height;
1948 	else
1949 		*y = monitor.y + MAX(0, monitor.height - req.height);
1950 
1951 	*push_in = FALSE;
1952 }
1953 
1954 
show_goto_popup(GeanyDocument * doc,GPtrArray * tags,gboolean have_best)1955 static void show_goto_popup(GeanyDocument *doc, GPtrArray *tags, gboolean have_best)
1956 {
1957 	GtkWidget *first = NULL;
1958 	GtkWidget *menu;
1959 	GdkEvent *event;
1960 	GdkEventButton *button_event = NULL;
1961 	TMTag *tmtag;
1962 	guint i;
1963 	gchar **short_names, **file_names;
1964 	menu = gtk_menu_new();
1965 
1966 	/* If popup would show multiple files present a smart file list that allows
1967 	 * to easily distinguish the files while avoiding the file paths in their entirety */
1968 	file_names = g_new(gchar *, tags->len);
1969 	foreach_ptr_array(tmtag, i, tags)
1970 		file_names[i] = tmtag->file->file_name;
1971 	short_names = utils_strv_shorten_file_list(file_names, tags->len);
1972 	g_free(file_names);
1973 
1974 	foreach_ptr_array(tmtag, i, tags)
1975 	{
1976 		GtkWidget *item;
1977 		GtkWidget *label;
1978 		GtkWidget *image;
1979 		gchar *fname = short_names[i];
1980 		gchar *text;
1981 
1982 		if (! first && have_best)
1983 			/* For translators: it's the filename and line number of a symbol in the goto-symbol popup menu */
1984 			text = g_markup_printf_escaped(_("<b>%s: %lu</b>"), fname, tmtag->line);
1985 		else
1986 			/* For translators: it's the filename and line number of a symbol in the goto-symbol popup menu */
1987 			text = g_markup_printf_escaped(_("%s: %lu"), fname, tmtag->line);
1988 
1989 		image = gtk_image_new_from_pixbuf(symbols_icons[get_tag_class(tmtag)].pixbuf);
1990 		label = g_object_new(GTK_TYPE_LABEL, "label", text, "use-markup", TRUE, "xalign", 0.0, NULL);
1991 		item = g_object_new(GTK_TYPE_IMAGE_MENU_ITEM, "image", image, "child", label, "always-show-image", TRUE, NULL);
1992 		g_signal_connect_data(item, "activate", G_CALLBACK(on_goto_popup_item_activate),
1993 		                      tm_tag_ref(tmtag), (GClosureNotify) tm_tag_unref, 0);
1994 		gtk_menu_shell_append(GTK_MENU_SHELL(menu), item);
1995 
1996 		if (! first)
1997 			first = item;
1998 
1999 		g_free(text);
2000 		g_free(fname);
2001 	}
2002 	g_free(short_names);
2003 
2004 	gtk_widget_show_all(menu);
2005 
2006 	if (first) /* always select the first item for better keyboard navigation */
2007 		g_signal_connect(menu, "realize", G_CALLBACK(gtk_menu_shell_select_item), first);
2008 
2009 	event = gtk_get_current_event();
2010 	if (event && event->type == GDK_BUTTON_PRESS)
2011 		button_event = (GdkEventButton *) event;
2012 	else
2013 		gdk_event_free(event);
2014 
2015 	g_object_set_data_full(G_OBJECT(menu), "geany-button-event", button_event,
2016 	                       button_event ? (GDestroyNotify) gdk_event_free : NULL);
2017 	gtk_menu_popup(GTK_MENU(menu), NULL, NULL, goto_popup_position_func, doc->editor->sci,
2018 				   button_event ? button_event->button : 0, gtk_get_current_event_time ());
2019 }
2020 
2021 
compare_tags_by_name_line(gconstpointer ptr1,gconstpointer ptr2)2022 static gint compare_tags_by_name_line(gconstpointer ptr1, gconstpointer ptr2)
2023 {
2024 	gint res;
2025 	TMTag *t1 = *((TMTag **) ptr1);
2026 	TMTag *t2 = *((TMTag **) ptr2);
2027 
2028 	res = g_strcmp0(t1->file->short_name, t2->file->short_name);
2029 	if (res != 0)
2030 		return res;
2031 	return t1->line - t2->line;
2032 }
2033 
2034 
find_best_goto_tag(GeanyDocument * doc,GPtrArray * tags)2035 static TMTag *find_best_goto_tag(GeanyDocument *doc, GPtrArray *tags)
2036 {
2037 	TMTag *tag;
2038 	guint i;
2039 
2040 	/* first check if we have a tag in the current file */
2041 	foreach_ptr_array(tag, i, tags)
2042 	{
2043 		if (g_strcmp0(doc->real_path, tag->file->file_name) == 0)
2044 			return tag;
2045 	}
2046 
2047 	/* next check if we have a tag for some of the open documents */
2048 	foreach_ptr_array(tag, i, tags)
2049 	{
2050 		guint j;
2051 
2052 		foreach_document(j)
2053 		{
2054 			if (g_strcmp0(documents[j]->real_path, tag->file->file_name) == 0)
2055 				return tag;
2056 		}
2057 	}
2058 
2059 	/* next check if we have a tag for a file inside the current document's directory */
2060 	foreach_ptr_array(tag, i, tags)
2061 	{
2062 		gchar *dir = g_path_get_dirname(doc->real_path);
2063 
2064 		if (g_str_has_prefix(tag->file->file_name, dir))
2065 		{
2066 			g_free(dir);
2067 			return tag;
2068 		}
2069 		g_free(dir);
2070 	}
2071 
2072 	return NULL;
2073 }
2074 
2075 
filter_tags(GPtrArray * tags,TMTag * current_tag,gboolean definition)2076 static GPtrArray *filter_tags(GPtrArray *tags, TMTag *current_tag, gboolean definition)
2077 {
2078 	const TMTagType forward_types = tm_tag_prototype_t | tm_tag_externvar_t;
2079 	TMTag *tmtag, *last_tag = NULL;
2080 	GPtrArray *filtered_tags = g_ptr_array_new();
2081 	guint i;
2082 
2083 	foreach_ptr_array(tmtag, i, tags)
2084 	{
2085 		if ((definition && !(tmtag->type & forward_types)) ||
2086 			(!definition && (tmtag->type & forward_types)))
2087 		{
2088 			/* If there are typedefs of e.g. a struct such as
2089 			 * "typedef struct Foo {} Foo;", filter out the typedef unless
2090 			 * cursor is at the struct name. */
2091 			if (last_tag != NULL && last_tag->file == tmtag->file &&
2092 				last_tag->type != tm_tag_typedef_t && tmtag->type == tm_tag_typedef_t)
2093 			{
2094 				if (last_tag == current_tag)
2095 					g_ptr_array_add(filtered_tags, tmtag);
2096 			}
2097 			else if (tmtag != current_tag)
2098 				g_ptr_array_add(filtered_tags, tmtag);
2099 
2100 			last_tag = tmtag;
2101 		}
2102 	}
2103 
2104 	return filtered_tags;
2105 }
2106 
2107 
goto_tag(const gchar * name,gboolean definition)2108 static gboolean goto_tag(const gchar *name, gboolean definition)
2109 {
2110 	const TMTagType forward_types = tm_tag_prototype_t | tm_tag_externvar_t;
2111 	TMTag *tmtag, *current_tag = NULL;
2112 	GeanyDocument *old_doc = document_get_current();
2113 	gboolean found = FALSE;
2114 	const GPtrArray *all_tags;
2115 	GPtrArray *tags, *filtered_tags;
2116 	guint i;
2117 	guint current_line = sci_get_current_line(old_doc->editor->sci) + 1;
2118 
2119 	all_tags = tm_workspace_find(name, NULL, tm_tag_max_t, NULL, old_doc->file_type->lang);
2120 
2121 	/* get rid of global tags and find tag at current line */
2122 	tags = g_ptr_array_new();
2123 	foreach_ptr_array(tmtag, i, all_tags)
2124 	{
2125 		if (tmtag->file)
2126 		{
2127 			g_ptr_array_add(tags, tmtag);
2128 			if (tmtag->file == old_doc->tm_file && tmtag->line == current_line)
2129 				current_tag = tmtag;
2130 		}
2131 	}
2132 
2133 	if (current_tag)
2134 		/* swap definition/declaration search */
2135 		definition = current_tag->type & forward_types;
2136 
2137 	filtered_tags = filter_tags(tags, current_tag, definition);
2138 	if (filtered_tags->len == 0)
2139 	{
2140 		/* if we didn't find anything, try again with the opposite type */
2141 		g_ptr_array_free(filtered_tags, TRUE);
2142 		filtered_tags = filter_tags(tags, current_tag, !definition);
2143 	}
2144 	g_ptr_array_free(tags, TRUE);
2145 	tags = filtered_tags;
2146 
2147 	if (tags->len == 1)
2148 	{
2149 		GeanyDocument *new_doc;
2150 
2151 		tmtag = tags->pdata[0];
2152 		new_doc = document_find_by_real_path(tmtag->file->file_name);
2153 
2154 		if (!new_doc)
2155 			/* not found in opened document, should open */
2156 			new_doc = document_open_file(tmtag->file->file_name, FALSE, NULL, NULL);
2157 
2158 		navqueue_goto_line(old_doc, new_doc, tmtag->line);
2159 	}
2160 	else if (tags->len > 1)
2161 	{
2162 		GPtrArray *tag_list;
2163 		TMTag *tag, *best_tag;
2164 
2165 		g_ptr_array_sort(tags, compare_tags_by_name_line);
2166 		best_tag = find_best_goto_tag(old_doc, tags);
2167 
2168 		tag_list = g_ptr_array_new();
2169 		if (best_tag)
2170 			g_ptr_array_add(tag_list, best_tag);
2171 		foreach_ptr_array(tag, i, tags)
2172 		{
2173 			if (tag != best_tag)
2174 				g_ptr_array_add(tag_list, tag);
2175 		}
2176 		show_goto_popup(old_doc, tag_list, best_tag != NULL);
2177 
2178 		g_ptr_array_free(tag_list, TRUE);
2179 	}
2180 
2181 	found = tags->len > 0;
2182 	g_ptr_array_free(tags, TRUE);
2183 
2184 	return found;
2185 }
2186 
2187 
symbols_goto_tag(const gchar * name,gboolean definition)2188 gboolean symbols_goto_tag(const gchar *name, gboolean definition)
2189 {
2190 	if (goto_tag(name, definition))
2191 		return TRUE;
2192 
2193 	/* if we are here, there was no match and we are beeping ;-) */
2194 	utils_beep();
2195 
2196 	if (!definition)
2197 		ui_set_statusbar(FALSE, _("Forward declaration \"%s\" not found."), name);
2198 	else
2199 		ui_set_statusbar(FALSE, _("Definition of \"%s\" not found."), name);
2200 	return FALSE;
2201 }
2202 
2203 
2204 /* This could perhaps be improved to check for #if, class etc. */
get_function_fold_number(GeanyDocument * doc)2205 static gint get_function_fold_number(GeanyDocument *doc)
2206 {
2207 	/* for Java the functions are always one fold level above the class scope */
2208 	if (doc->file_type->id == GEANY_FILETYPES_JAVA)
2209 		return SC_FOLDLEVELBASE + 1;
2210 	else
2211 		return SC_FOLDLEVELBASE;
2212 }
2213 
2214 
2215 /* Should be used only with get_current_tag_cached.
2216  * tag_types caching might trigger recomputation too often but this isn't used differently often
2217  * enough to be an issue for now */
current_tag_changed(GeanyDocument * doc,gint cur_line,gint fold_level,guint tag_types)2218 static gboolean current_tag_changed(GeanyDocument *doc, gint cur_line, gint fold_level, guint tag_types)
2219 {
2220 	static gint old_line = -2;
2221 	static GeanyDocument *old_doc = NULL;
2222 	static gint old_fold_num = -1;
2223 	static guint old_tag_types = 0;
2224 	const gint fold_num = fold_level & SC_FOLDLEVELNUMBERMASK;
2225 	gboolean ret;
2226 
2227 	/* check if the cached line and file index have changed since last time: */
2228 	if (doc == NULL || doc != old_doc || old_tag_types != tag_types)
2229 		ret = TRUE;
2230 	else if (cur_line == old_line)
2231 		ret = FALSE;
2232 	else
2233 	{
2234 		/* if the line has only changed by 1 */
2235 		if (abs(cur_line - old_line) == 1)
2236 		{
2237 			/* It's the same function if the fold number hasn't changed */
2238 			ret = (fold_num != old_fold_num);
2239 		}
2240 		else ret = TRUE;
2241 	}
2242 
2243 	/* record current line and file index for next time */
2244 	old_line = cur_line;
2245 	old_doc = doc;
2246 	old_fold_num = fold_num;
2247 	old_tag_types = tag_types;
2248 	return ret;
2249 }
2250 
2251 
2252 /* Parse the function name up to 2 lines before tag_line.
2253  * C++ like syntax should be parsed by parse_cpp_function_at_line, otherwise the return
2254  * type or argument names can be confused with the function name. */
parse_function_at_line(ScintillaObject * sci,gint tag_line)2255 static gchar *parse_function_at_line(ScintillaObject *sci, gint tag_line)
2256 {
2257 	gint start, end, max_pos;
2258 	gint fn_style;
2259 
2260 	switch (sci_get_lexer(sci))
2261 	{
2262 		case SCLEX_RUBY:	fn_style = SCE_RB_DEFNAME; break;
2263 		case SCLEX_PYTHON:	fn_style = SCE_P_DEFNAME; break;
2264 		default: fn_style = SCE_C_IDENTIFIER;	/* several lexers use SCE_C_IDENTIFIER */
2265 	}
2266 	start = sci_get_position_from_line(sci, tag_line - 2);
2267 	max_pos = sci_get_position_from_line(sci, tag_line + 1);
2268 	while (start < max_pos && sci_get_style_at(sci, start) != fn_style)
2269 		start++;
2270 
2271 	end = start;
2272 	while (end < max_pos && sci_get_style_at(sci, end) == fn_style)
2273 		end++;
2274 
2275 	if (start == end)
2276 		return NULL;
2277 	return sci_get_contents_range(sci, start, end);
2278 }
2279 
2280 
2281 /* Parse the function name */
parse_cpp_function_at_line(ScintillaObject * sci,gint tag_line)2282 static gchar *parse_cpp_function_at_line(ScintillaObject *sci, gint tag_line)
2283 {
2284 	gint start, end, first_pos, max_pos;
2285 	gint tmp;
2286 	gchar c;
2287 
2288 	first_pos = end = sci_get_position_from_line(sci, tag_line);
2289 	max_pos = sci_get_position_from_line(sci, tag_line + 1);
2290 	tmp = 0;
2291 	/* goto the begin of function body */
2292 	while (end < max_pos &&
2293 		(tmp = sci_get_char_at(sci, end)) != '{' &&
2294 		tmp != 0) end++;
2295 	if (tmp == 0) end --;
2296 
2297 	/* go back to the end of function identifier */
2298 	while (end > 0 && end > first_pos - 500 &&
2299 		(tmp = sci_get_char_at(sci, end)) != '(' &&
2300 		tmp != 0) end--;
2301 	end--;
2302 	if (end < 0) end = 0;
2303 
2304 	/* skip whitespaces between identifier and ( */
2305 	while (end > 0 && isspace(sci_get_char_at(sci, end))) end--;
2306 
2307 	start = end;
2308 	/* Use tmp to find SCE_C_IDENTIFIER or SCE_C_GLOBALCLASS chars */
2309 	while (start >= 0 && ((tmp = sci_get_style_at(sci, start)) == SCE_C_IDENTIFIER
2310 		 ||  tmp == SCE_C_GLOBALCLASS
2311 		 || (c = sci_get_char_at(sci, start)) == '~'
2312 		 ||  c == ':'))
2313 		start--;
2314 	if (start != 0 && start < end) start++;	/* correct for last non-matching char */
2315 
2316 	if (start == end) return NULL;
2317 	return sci_get_contents_range(sci, start, end + 1);
2318 }
2319 
2320 
2321 /* gets the fold header after or on @line, but skipping folds created because of parentheses */
get_fold_header_after(ScintillaObject * sci,gint line)2322 static gint get_fold_header_after(ScintillaObject *sci, gint line)
2323 {
2324 	const gint line_count = sci_get_line_count(sci);
2325 
2326 	for (; line < line_count; line++)
2327 	{
2328 		if (sci_get_fold_level(sci, line) & SC_FOLDLEVELHEADERFLAG)
2329 		{
2330 			const gint last_child = SSM(sci, SCI_GETLASTCHILD, line, -1);
2331 			const gint line_end = sci_get_line_end_position(sci, line);
2332 			const gint lexer = sci_get_lexer(sci);
2333 			gint parenthesis_match_line = -1;
2334 
2335 			/* now find any unbalanced open parenthesis on the line and see where the matching
2336 			 * brace would be, mimicking what folding on () does */
2337 			for (gint pos = sci_get_position_from_line(sci, line); pos < line_end; pos++)
2338 			{
2339 				if (highlighting_is_code_style(lexer, sci_get_style_at(sci, pos)) &&
2340 				    sci_get_char_at(sci, pos) == '(')
2341 				{
2342 					const gint matching = sci_find_matching_brace(sci, pos);
2343 
2344 					if (matching >= 0)
2345 					{
2346 						parenthesis_match_line = sci_get_line_from_position(sci, matching);
2347 						if (parenthesis_match_line != line)
2348 							break;  /* match is on a different line, we found a possible fold */
2349 						else
2350 							pos = matching;  /* just skip the range and continue searching */
2351 					}
2352 				}
2353 			}
2354 
2355 			/* if the matching parenthesis matches the fold level, skip it and continue.
2356 			 * it matches if it either spans the same lines, or spans one more but the next one is
2357 			 * a fold header (in which case the last child of the fold is one less to let the
2358 			 * header be at the parent level) */
2359 			if ((parenthesis_match_line == last_child) ||
2360 			    (parenthesis_match_line == last_child + 1 &&
2361 			     sci_get_fold_level(sci, parenthesis_match_line) & SC_FOLDLEVELHEADERFLAG))
2362 				line = last_child;
2363 			else
2364 				return line;
2365 		}
2366 	}
2367 
2368 	return -1;
2369 }
2370 
2371 
get_current_tag_name(GeanyDocument * doc,gchar ** tagname,TMTagType tag_types)2372 static gint get_current_tag_name(GeanyDocument *doc, gchar **tagname, TMTagType tag_types)
2373 {
2374 	gint line;
2375 	gint parent;
2376 
2377 	line = sci_get_current_line(doc->editor->sci);
2378 	parent = sci_get_fold_parent(doc->editor->sci, line);
2379 	/* if we're inside a fold level and we have up-to-date tags, get the function from TM */
2380 	if (parent >= 0 && doc->tm_file != NULL && doc->tm_file->tags_array != NULL &&
2381 		(! doc->changed || editor_prefs.autocompletion_update_freq > 0))
2382 	{
2383 		const TMTag *tag = tm_get_current_tag(doc->tm_file->tags_array, parent + 1, tag_types);
2384 
2385 		if (tag)
2386 		{
2387 			gint tag_line = tag->line - 1;
2388 			gint last_child = line + 1;
2389 
2390 			/* if it may be a false positive because we're inside a fold level not inside anything
2391 			 * we match, e.g. a #if in C or C++, we check we're inside the fold level that start
2392 			 * right after the tag we got from TM.
2393 			 * Additionally, we perform parentheses matching on the initial line not to get confused
2394 			 * by folding on () in case the parameter list spans multiple lines */
2395 			if (abs(tag_line - parent) > 1)
2396 			{
2397 				const gint tag_fold = get_fold_header_after(doc->editor->sci, tag_line);
2398 				if (tag_fold >= 0)
2399 					last_child = SSM(doc->editor->sci, SCI_GETLASTCHILD, tag_fold, -1);
2400 			}
2401 
2402 			if (line <= last_child)
2403 			{
2404 				if (tag->scope)
2405 					*tagname = g_strconcat(tag->scope,
2406 							symbols_get_context_separator(doc->file_type->id), tag->name, NULL);
2407 				else
2408 					*tagname = g_strdup(tag->name);
2409 
2410 				return tag_line;
2411 			}
2412 		}
2413 	}
2414 	/* for the poor guy with a modified document and without real time tag parsing, we fallback
2415 	 * to dirty and inaccurate hand-parsing */
2416 	else if (parent >= 0 && doc->file_type != NULL && doc->file_type->id != GEANY_FILETYPES_NONE)
2417 	{
2418 		const gint fn_fold = get_function_fold_number(doc);
2419 		gint tag_line = parent;
2420 		gint fold_level = sci_get_fold_level(doc->editor->sci, tag_line);
2421 
2422 		/* find the top level fold point */
2423 		while (tag_line >= 0 && (fold_level & SC_FOLDLEVELNUMBERMASK) != fn_fold)
2424 		{
2425 			tag_line = sci_get_fold_parent(doc->editor->sci, tag_line);
2426 			fold_level = sci_get_fold_level(doc->editor->sci, tag_line);
2427 		}
2428 
2429 		if (tag_line >= 0)
2430 		{
2431 			gchar *cur_tag;
2432 
2433 			if (sci_get_lexer(doc->editor->sci) == SCLEX_CPP)
2434 				cur_tag = parse_cpp_function_at_line(doc->editor->sci, tag_line);
2435 			else
2436 				cur_tag = parse_function_at_line(doc->editor->sci, tag_line);
2437 
2438 			if (cur_tag != NULL)
2439 			{
2440 				*tagname = cur_tag;
2441 				return tag_line;
2442 			}
2443 		}
2444 	}
2445 
2446 	*tagname = g_strdup(_("unknown"));
2447 	return -1;
2448 }
2449 
2450 
get_current_tag_name_cached(GeanyDocument * doc,const gchar ** tagname,TMTagType tag_types)2451 static gint get_current_tag_name_cached(GeanyDocument *doc, const gchar **tagname, TMTagType tag_types)
2452 {
2453 	static gint tag_line = -1;
2454 	static gchar *cur_tag = NULL;
2455 
2456 	g_return_val_if_fail(doc == NULL || doc->is_valid, -1);
2457 
2458 	if (doc == NULL)	/* reset current function */
2459 	{
2460 		current_tag_changed(NULL, -1, -1, 0);
2461 		g_free(cur_tag);
2462 		cur_tag = g_strdup(_("unknown"));
2463 		if (tagname != NULL)
2464 			*tagname = cur_tag;
2465 		tag_line = -1;
2466 	}
2467 	else
2468 	{
2469 		gint line = sci_get_current_line(doc->editor->sci);
2470 		gint fold_level = sci_get_fold_level(doc->editor->sci, line);
2471 
2472 		if (current_tag_changed(doc, line, fold_level, tag_types))
2473 		{
2474 			g_free(cur_tag);
2475 			tag_line = get_current_tag_name(doc, &cur_tag, tag_types);
2476 		}
2477 		*tagname = cur_tag;
2478 	}
2479 
2480 	return tag_line;
2481 }
2482 
2483 
2484 /* Sets *tagname to point at the current function or tag name.
2485  * If doc is NULL, reset the cached current tag data to ensure it will be reparsed on the next
2486  * call to this function.
2487  * Returns: line number of the current tag, or -1 if unknown. */
symbols_get_current_function(GeanyDocument * doc,const gchar ** tagname)2488 gint symbols_get_current_function(GeanyDocument *doc, const gchar **tagname)
2489 {
2490 	return get_current_tag_name_cached(doc, tagname, tm_tag_function_t | tm_tag_method_t);
2491 }
2492 
2493 
2494 /* same as symbols_get_current_function() but finds class, namespaces and more */
symbols_get_current_scope(GeanyDocument * doc,const gchar ** tagname)2495 gint symbols_get_current_scope(GeanyDocument *doc, const gchar **tagname)
2496 {
2497 	TMTagType tag_types = (tm_tag_function_t | tm_tag_method_t | tm_tag_class_t |
2498 			tm_tag_struct_t | tm_tag_enum_t | tm_tag_union_t);
2499 
2500 	/* Python parser reports imports as namespaces which confuses the scope detection */
2501 	if (doc && doc->file_type->lang != filetypes[GEANY_FILETYPES_PYTHON]->lang)
2502 		tag_types |= tm_tag_namespace_t;
2503 
2504 	return get_current_tag_name_cached(doc, tagname, tag_types);
2505 }
2506 
2507 
on_symbol_tree_sort_clicked(GtkMenuItem * menuitem,gpointer user_data)2508 static void on_symbol_tree_sort_clicked(GtkMenuItem *menuitem, gpointer user_data)
2509 {
2510 	gint sort_mode = GPOINTER_TO_INT(user_data);
2511 	GeanyDocument *doc = document_get_current();
2512 
2513 	if (ignore_callback)
2514 		return;
2515 
2516 	if (doc != NULL)
2517 		doc->has_tags = symbols_recreate_tag_list(doc, sort_mode);
2518 }
2519 
2520 
on_symbol_tree_menu_show(GtkWidget * widget,gpointer user_data)2521 static void on_symbol_tree_menu_show(GtkWidget *widget,
2522 		gpointer user_data)
2523 {
2524 	GeanyDocument *doc = document_get_current();
2525 	gboolean enable;
2526 
2527 	enable = doc && doc->has_tags;
2528 	gtk_widget_set_sensitive(symbol_menu.sort_by_name, enable);
2529 	gtk_widget_set_sensitive(symbol_menu.sort_by_appearance, enable);
2530 	gtk_widget_set_sensitive(symbol_menu.expand_all, enable);
2531 	gtk_widget_set_sensitive(symbol_menu.collapse_all, enable);
2532 	gtk_widget_set_sensitive(symbol_menu.find_usage, enable);
2533 	gtk_widget_set_sensitive(symbol_menu.find_doc_usage, enable);
2534 
2535 	if (! doc)
2536 		return;
2537 
2538 	ignore_callback = TRUE;
2539 
2540 	if (doc->priv->symbol_list_sort_mode == SYMBOLS_SORT_BY_NAME)
2541 		gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(symbol_menu.sort_by_name), TRUE);
2542 	else
2543 		gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(symbol_menu.sort_by_appearance), TRUE);
2544 
2545 	ignore_callback = FALSE;
2546 }
2547 
2548 
on_expand_collapse(GtkWidget * widget,gpointer user_data)2549 static void on_expand_collapse(GtkWidget *widget, gpointer user_data)
2550 {
2551 	gboolean expand = GPOINTER_TO_INT(user_data);
2552 	GeanyDocument *doc = document_get_current();
2553 
2554 	if (! doc)
2555 		return;
2556 
2557 	g_return_if_fail(doc->priv->tag_tree);
2558 
2559 	if (expand)
2560 		gtk_tree_view_expand_all(GTK_TREE_VIEW(doc->priv->tag_tree));
2561 	else
2562 		gtk_tree_view_collapse_all(GTK_TREE_VIEW(doc->priv->tag_tree));
2563 }
2564 
2565 
on_find_usage(GtkWidget * widget,G_GNUC_UNUSED gpointer unused)2566 static void on_find_usage(GtkWidget *widget, G_GNUC_UNUSED gpointer unused)
2567 {
2568 	GtkTreeIter iter;
2569 	GtkTreeSelection *selection;
2570 	GtkTreeModel *model;
2571 	GeanyDocument *doc;
2572 	TMTag *tag = NULL;
2573 
2574 	doc = document_get_current();
2575 	if (!doc)
2576 		return;
2577 
2578 	selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(doc->priv->tag_tree));
2579 	if (gtk_tree_selection_get_selected(selection, &model, &iter))
2580 		gtk_tree_model_get(model, &iter, SYMBOLS_COLUMN_TAG, &tag, -1);
2581 	if (tag)
2582 	{
2583 		if (widget == symbol_menu.find_in_files)
2584 			search_show_find_in_files_dialog_full(tag->name, NULL);
2585 		else
2586 			search_find_usage(tag->name, tag->name, GEANY_FIND_WHOLEWORD | GEANY_FIND_MATCHCASE,
2587 				widget == symbol_menu.find_usage);
2588 
2589 		tm_tag_unref(tag);
2590 	}
2591 }
2592 
2593 
create_taglist_popup_menu(void)2594 static void create_taglist_popup_menu(void)
2595 {
2596 	GtkWidget *item, *menu;
2597 
2598 	tv.popup_taglist = menu = gtk_menu_new();
2599 
2600 	symbol_menu.expand_all = item = ui_image_menu_item_new(GTK_STOCK_ADD, _("_Expand All"));
2601 	gtk_widget_show(item);
2602 	gtk_container_add(GTK_CONTAINER(menu), item);
2603 	g_signal_connect(item, "activate", G_CALLBACK(on_expand_collapse), GINT_TO_POINTER(TRUE));
2604 
2605 	symbol_menu.collapse_all = item = ui_image_menu_item_new(GTK_STOCK_REMOVE, _("_Collapse All"));
2606 	gtk_widget_show(item);
2607 	gtk_container_add(GTK_CONTAINER(menu), item);
2608 	g_signal_connect(item, "activate", G_CALLBACK(on_expand_collapse), GINT_TO_POINTER(FALSE));
2609 
2610 	item = gtk_separator_menu_item_new();
2611 	gtk_widget_show(item);
2612 	gtk_container_add(GTK_CONTAINER(menu), item);
2613 
2614 	symbol_menu.sort_by_name = item = gtk_radio_menu_item_new_with_mnemonic(NULL,
2615 		_("Sort by _Name"));
2616 	gtk_widget_show(item);
2617 	gtk_container_add(GTK_CONTAINER(menu), item);
2618 	g_signal_connect(item, "activate", G_CALLBACK(on_symbol_tree_sort_clicked),
2619 			GINT_TO_POINTER(SYMBOLS_SORT_BY_NAME));
2620 
2621 	symbol_menu.sort_by_appearance = item = gtk_radio_menu_item_new_with_mnemonic_from_widget(
2622 		GTK_RADIO_MENU_ITEM(item), _("Sort by _Appearance"));
2623 	gtk_widget_show(item);
2624 	gtk_container_add(GTK_CONTAINER(menu), item);
2625 	g_signal_connect(item, "activate", G_CALLBACK(on_symbol_tree_sort_clicked),
2626 			GINT_TO_POINTER(SYMBOLS_SORT_BY_APPEARANCE));
2627 
2628 	item = gtk_separator_menu_item_new();
2629 	gtk_widget_show(item);
2630 	gtk_container_add(GTK_CONTAINER(menu), item);
2631 
2632 	symbol_menu.find_usage = item = ui_image_menu_item_new(GTK_STOCK_FIND, _("Find _Usage"));
2633 	gtk_widget_show(item);
2634 	gtk_container_add(GTK_CONTAINER(menu), item);
2635 	g_signal_connect(item, "activate", G_CALLBACK(on_find_usage), symbol_menu.find_usage);
2636 
2637 	symbol_menu.find_doc_usage = item = ui_image_menu_item_new(GTK_STOCK_FIND, _("Find _Document Usage"));
2638 	gtk_widget_show(item);
2639 	gtk_container_add(GTK_CONTAINER(menu), item);
2640 	g_signal_connect(item, "activate", G_CALLBACK(on_find_usage), symbol_menu.find_doc_usage);
2641 
2642 	symbol_menu.find_in_files = item = ui_image_menu_item_new(GTK_STOCK_FIND, _("Find in F_iles..."));
2643 	gtk_widget_show(item);
2644 	gtk_container_add(GTK_CONTAINER(menu), item);
2645 	g_signal_connect(item, "activate", G_CALLBACK(on_find_usage), NULL);
2646 
2647 	g_signal_connect(menu, "show", G_CALLBACK(on_symbol_tree_menu_show), NULL);
2648 
2649 	sidebar_add_common_menu_items(GTK_MENU(menu));
2650 }
2651 
2652 
on_document_save(G_GNUC_UNUSED GObject * object,GeanyDocument * doc)2653 static void on_document_save(G_GNUC_UNUSED GObject *object, GeanyDocument *doc)
2654 {
2655 	gchar *f;
2656 
2657 	g_return_if_fail(!EMPTY(doc->real_path));
2658 
2659 	f = g_build_filename(app->configdir, "ignore.tags", NULL);
2660 	if (utils_str_equal(doc->real_path, f))
2661 		load_c_ignore_tags();
2662 
2663 	g_free(f);
2664 }
2665 
2666 
symbols_init(void)2667 void symbols_init(void)
2668 {
2669 	gchar *f;
2670 	guint i;
2671 
2672 	create_taglist_popup_menu();
2673 
2674 	f = g_build_filename(app->configdir, "ignore.tags", NULL);
2675 	ui_add_config_file_menu_item(f, NULL, NULL);
2676 	g_free(f);
2677 
2678 	g_signal_connect(geany_object, "document-save", G_CALLBACK(on_document_save), NULL);
2679 
2680 	for (i = 0; i < G_N_ELEMENTS(symbols_icons); i++)
2681 		symbols_icons[i].pixbuf = get_tag_icon(symbols_icons[i].icon_name);
2682 }
2683 
2684 
symbols_finalize(void)2685 void symbols_finalize(void)
2686 {
2687 	guint i;
2688 
2689 	g_strfreev(c_tags_ignore);
2690 
2691 	for (i = 0; i < G_N_ELEMENTS(symbols_icons); i++)
2692 	{
2693 		if (symbols_icons[i].pixbuf)
2694 			g_object_unref(symbols_icons[i].pixbuf);
2695 	}
2696 }
2697