2 * templates.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005-2012 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2012 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 * Templates to insert into the current document, or file templates to create a new
31 #include "templates.h"
35 #include "encodings.h"
36 #include "filetypes.h"
38 #include "geanymenubuttonaction.h"
39 #include "geanyobject.h"
45 #include "gtkcompat.h"
51 GeanyTemplatePrefs template_prefs
;
53 static GtkWidget
*new_with_template_menu
= NULL
; /* submenu used for both file menu and toolbar */
55 /* TODO: implement custom insertion templates instead? */
56 static gchar
*templates
[GEANY_MAX_TEMPLATES
];
59 static void replace_static_values(GString
*text
);
60 static gchar
*get_template_fileheader(GeanyFiletype
*ft
);
62 /* called by templates_replace_common */
63 static void templates_replace_default_dates(GString
*text
);
64 static void templates_replace_command(GString
*text
, const gchar
*file_name
,
65 const gchar
*file_type
, const gchar
*func_name
);
68 static gchar
*read_file(const gchar
*locale_fname
)
74 if (! g_file_get_contents(locale_fname
, &contents
, &length
, NULL
))
77 if (! encodings_convert_to_utf8_auto(&contents
, &length
, NULL
, NULL
, NULL
, NULL
))
79 gchar
*utf8_fname
= utils_get_utf8_from_locale(locale_fname
);
81 ui_set_statusbar(TRUE
, _("Failed to convert template file \"%s\" to UTF-8"), utf8_fname
);
87 str
= g_string_new(contents
);
90 /* convert to LF endings for consistency in mixing templates */
91 utils_ensure_same_eol_characters(str
, SC_EOL_LF
);
92 return g_string_free(str
, FALSE
);
96 static void read_template(const gchar
*name
, gint id
)
98 gchar
*fname
= g_build_path(G_DIR_SEPARATOR_S
, app
->configdir
,
99 GEANY_TEMPLATES_SUBDIR
, name
, NULL
);
101 /* try system if user template doesn't exist */
102 if (!g_file_test(fname
, G_FILE_TEST_EXISTS
))
103 SETPTR(fname
, g_build_path(G_DIR_SEPARATOR_S
, app
->datadir
,
104 GEANY_TEMPLATES_SUBDIR
, name
, NULL
));
106 templates
[id
] = read_file(fname
);
111 /* called when inserting templates into an existing document */
112 static void convert_eol_characters(GString
*template, GeanyDocument
*doc
)
116 g_return_if_fail(doc
== NULL
|| doc
->is_valid
);
119 doc
= document_get_current();
121 g_return_if_fail(doc
!= NULL
);
123 doc_eol_mode
= editor_get_eol_char_mode(doc
->editor
);
124 utils_ensure_same_eol_characters(template, doc_eol_mode
);
128 static void init_general_templates(void)
130 /* read the contents */
131 read_template("fileheader", GEANY_TEMPLATE_FILEHEADER
);
132 read_template("gpl", GEANY_TEMPLATE_GPL
);
133 read_template("bsd", GEANY_TEMPLATE_BSD
);
134 read_template("function", GEANY_TEMPLATE_FUNCTION
);
135 read_template("changelog", GEANY_TEMPLATE_CHANGELOG
);
139 void templates_replace_common(GString
*tmpl
, const gchar
*fname
,
140 GeanyFiletype
*ft
, const gchar
*func_name
)
147 shortname
= g_strdup(GEANY_STRING_UNTITLED
);
149 shortname
= g_strconcat(GEANY_STRING_UNTITLED
, ".", ft
->extension
, NULL
);
152 shortname
= g_path_get_basename(fname
);
154 templates_replace_valist(tmpl
,
155 "{filename}", shortname
,
156 "{project}", app
->project
? app
->project
->name
: "",
157 "{description}", app
->project
? app
->project
->description
: "",
161 templates_replace_default_dates(tmpl
);
162 templates_replace_command(tmpl
, fname
, ft
->name
, func_name
);
163 /* Bug: command results could have {ob} {cb} strings in! */
164 /* replace braces last */
165 templates_replace_valist(tmpl
,
172 static gchar
*get_template_from_file(const gchar
*locale_fname
, const gchar
*doc_filename
,
176 GString
*template = NULL
;
178 content
= read_file(locale_fname
);
184 template = g_string_new(content
);
186 file_header
= get_template_fileheader(ft
);
187 templates_replace_valist(template,
188 "{fileheader}", file_header
,
190 templates_replace_common(template, doc_filename
, ft
, NULL
);
192 utils_free_pointers(2, file_header
, content
, NULL
);
193 return g_string_free(template, FALSE
);
200 on_new_with_file_template(GtkMenuItem
*menuitem
, G_GNUC_UNUSED gpointer user_data
)
202 gchar
*fname
= ui_menu_item_get_text(menuitem
);
205 const gchar
*extension
= strrchr(fname
, '.'); /* easy way to get the file extension */
206 gchar
*new_filename
= g_strconcat(GEANY_STRING_UNTITLED
, extension
, NULL
);
209 ft
= filetypes_detect_from_extension(fname
);
210 SETPTR(fname
, utils_get_locale_from_utf8(fname
));
212 /* fname is just the basename from the menu item, so prepend the custom files path */
213 path
= g_build_path(G_DIR_SEPARATOR_S
, app
->configdir
, GEANY_TEMPLATES_SUBDIR
,
214 "files", fname
, NULL
);
215 template = get_template_from_file(path
, new_filename
, ft
);
218 /* try the system path */
220 path
= g_build_path(G_DIR_SEPARATOR_S
, app
->datadir
, GEANY_TEMPLATES_SUBDIR
,
221 "files", fname
, NULL
);
222 template = get_template_from_file(path
, new_filename
, ft
);
226 /* line endings will be converted */
227 document_new_file(new_filename
, ft
, template);
231 SETPTR(fname
, utils_get_utf8_from_locale(fname
));
232 ui_set_statusbar(TRUE
, _("Could not find file '%s'."), fname
);
236 g_free(new_filename
);
241 static void add_file_item(const gchar
*fname
, GtkWidget
*menu
)
243 GtkWidget
*tmp_button
;
246 g_return_if_fail(fname
);
247 g_return_if_fail(menu
);
249 label
= utils_get_utf8_from_locale(fname
);
251 tmp_button
= gtk_menu_item_new_with_label(label
);
252 gtk_widget_show(tmp_button
);
253 gtk_container_add(GTK_CONTAINER(menu
), tmp_button
);
254 g_signal_connect(tmp_button
, "activate", G_CALLBACK(on_new_with_file_template
), NULL
);
260 static gboolean
add_custom_template_items(void)
262 GSList
*list
= utils_get_config_files(GEANY_TEMPLATES_SUBDIR G_DIR_SEPARATOR_S
"files");
265 foreach_slist(node
, list
)
267 gchar
*fname
= node
->data
;
269 add_file_item(fname
, new_with_template_menu
);
277 static void create_file_template_menu(void)
279 new_with_template_menu
= gtk_menu_new();
280 add_custom_template_items();
282 /* unless the file menu is showing, menu should be in the toolbar widget */
283 geany_menu_button_action_set_menu(GEANY_MENU_BUTTON_ACTION(
284 toolbar_get_action_by_name("New")), new_with_template_menu
);
288 static void on_file_menu_show(GtkWidget
*item
)
290 geany_menu_button_action_set_menu(
291 GEANY_MENU_BUTTON_ACTION(toolbar_get_action_by_name("New")), NULL
);
292 item
= ui_lookup_widget(main_widgets
.window
, "menu_new_with_template1");
293 gtk_menu_item_set_submenu(GTK_MENU_ITEM(item
), new_with_template_menu
);
297 static void on_file_menu_hide(GtkWidget
*item
)
299 item
= ui_lookup_widget(main_widgets
.window
, "menu_new_with_template1");
300 gtk_menu_item_set_submenu(GTK_MENU_ITEM(item
), NULL
);
301 geany_menu_button_action_set_menu(
302 GEANY_MENU_BUTTON_ACTION(toolbar_get_action_by_name("New")), new_with_template_menu
);
306 /* reload templates if any file in the templates path is saved */
307 static void on_document_save(G_GNUC_UNUSED GObject
*object
, GeanyDocument
*doc
)
311 g_return_if_fail(!EMPTY(doc
->real_path
));
313 path
= g_build_filename(app
->configdir
, GEANY_TEMPLATES_SUBDIR
, NULL
);
314 if (strncmp(doc
->real_path
, path
, strlen(path
)) == 0)
316 /* reload templates */
317 templates_free_templates();
324 /* warning: also called when reloading template settings */
325 void templates_init(void)
327 static gboolean init_done
= FALSE
;
329 init_general_templates();
331 create_file_template_menu();
332 /* we hold our own ref for the menu as it has no parent whilst being moved */
333 g_object_ref(new_with_template_menu
);
335 /* only connect signals to persistent objects once */
339 /* reparent the template menu as needed */
340 item
= ui_lookup_widget(main_widgets
.window
, "file1");
341 item
= gtk_menu_item_get_submenu(GTK_MENU_ITEM(item
));
342 g_signal_connect(item
, "show", G_CALLBACK(on_file_menu_show
), NULL
);
343 g_signal_connect(item
, "hide", G_CALLBACK(on_file_menu_hide
), NULL
);
345 g_signal_connect(geany_object
, "document-save", G_CALLBACK(on_document_save
), NULL
);
351 /* indent is used to make some whitespace between comment char and real start of the line
352 * e.g. indent = 8 prints " * here comes the text of the line"
353 * indent is meant to be the whole amount of characters before the real line content follows, i.e.
354 * 6 characters are filled with whitespace when the comment characters include " *" */
355 static void make_comment_block(GString
*comment_text
, gint filetype_idx
, guint indent
)
357 gchar
*frame_start
; /* to add before comment_text */
358 gchar
*frame_end
; /* to add after comment_text */
359 const gchar
*line_prefix
; /* to add before every line in comment_text */
364 gint template_eol_mode
;
365 const gchar
*template_eol_char
;
366 GeanyFiletype
*ft
= filetypes_index(filetype_idx
);
370 g_return_if_fail(comment_text
!= NULL
);
371 g_return_if_fail(ft
!= NULL
);
373 template_eol_mode
= utils_get_line_endings(comment_text
->str
, comment_text
->len
);
374 template_eol_char
= utils_get_eol_char(template_eol_mode
);
376 filetype_get_comment_open_close(ft
, FALSE
, &co
, &cc
);
381 frame_start
= g_strconcat(co
, template_eol_char
, NULL
);
382 frame_end
= g_strconcat(cc
, template_eol_char
, NULL
);
393 { /* use C-like multi-line comments as fallback */
394 frame_start
= g_strconcat("/*", template_eol_char
, NULL
);
395 frame_end
= g_strconcat("*/", template_eol_char
, NULL
);
399 /* do some magic to nicely format C-like multi-line comments */
400 if (!EMPTY(frame_start
) && frame_start
[1] == '*')
402 /* prefix the string with a space */
403 SETPTR(frame_end
, g_strconcat(" ", frame_end
, NULL
));
407 /* construct the real prefix with given amount of whitespace */
408 i
= (indent
> strlen(line_prefix
)) ? (indent
- strlen(line_prefix
)) : strlen(line_prefix
);
409 tmp
= g_strnfill(i
, ' ');
410 prefix
= g_strconcat(line_prefix
, tmp
, NULL
);
413 /* add line_prefix to every line of comment_text */
414 lines
= g_strsplit(comment_text
->str
, template_eol_char
, -1);
415 len
= g_strv_length(lines
);
416 if (len
> 0) /* prevent unsigned wraparound if comment_text is empty */
418 for (i
= 0; i
< len
- 1; i
++)
421 lines
[i
] = g_strconcat(prefix
, tmp
, NULL
);
425 tmp
= g_strjoinv(template_eol_char
, lines
);
427 /* clear old contents */
428 g_string_erase(comment_text
, 0, -1);
431 if (frame_start
!= NULL
)
432 g_string_append(comment_text
, frame_start
);
433 /* add the new main content */
434 g_string_append(comment_text
, tmp
);
435 /* add frame_start */
436 if (frame_end
!= NULL
)
437 g_string_append(comment_text
, frame_end
);
439 utils_free_pointers(4, prefix
, tmp
, frame_start
, frame_end
, NULL
);
444 gchar
*templates_get_template_licence(GeanyDocument
*doc
, gint licence_type
)
448 g_return_val_if_fail(DOC_VALID(doc
), NULL
);
449 g_return_val_if_fail(licence_type
== GEANY_TEMPLATE_GPL
|| licence_type
== GEANY_TEMPLATE_BSD
, NULL
);
451 template = g_string_new(templates
[licence_type
]);
452 replace_static_values(template);
453 templates_replace_default_dates(template);
454 templates_replace_command(template, DOC_FILENAME(doc
), doc
->file_type
->name
, NULL
);
456 make_comment_block(template, doc
->file_type
->id
, GEANY_TEMPLATES_INDENT
);
457 convert_eol_characters(template, doc
);
459 return g_string_free(template, FALSE
);
463 static gchar
*get_template_fileheader(GeanyFiletype
*ft
)
465 GString
*template = g_string_new(templates
[GEANY_TEMPLATE_FILEHEADER
]);
467 filetypes_load_config(ft
->id
, FALSE
); /* load any user extension setting */
469 templates_replace_valist(template,
470 "{gpl}", templates
[GEANY_TEMPLATE_GPL
],
471 "{bsd}", templates
[GEANY_TEMPLATE_BSD
],
474 /* we don't replace other wildcards here otherwise they would get done twice for files */
475 make_comment_block(template, ft
->id
, GEANY_TEMPLATES_INDENT
);
476 return g_string_free(template, FALSE
);
480 /* TODO change the signature to take a GeanyDocument? this would break plugin API/ABI */
481 gchar
*templates_get_template_fileheader(gint filetype_idx
, const gchar
*fname
)
483 GeanyFiletype
*ft
= filetypes
[filetype_idx
];
484 gchar
*str
= get_template_fileheader(ft
);
485 GString
*template = g_string_new(str
);
488 templates_replace_common(template, fname
, ft
, NULL
);
489 convert_eol_characters(template, NULL
);
490 return g_string_free(template, FALSE
);
494 gchar
*templates_get_template_function(GeanyDocument
*doc
, const gchar
*func_name
)
498 func_name
= (func_name
!= NULL
) ? func_name
: "";
499 text
= g_string_new(templates
[GEANY_TEMPLATE_FUNCTION
]);
501 templates_replace_valist(text
, "{functionname}", func_name
, NULL
);
502 templates_replace_default_dates(text
);
503 templates_replace_command(text
, DOC_FILENAME(doc
), doc
->file_type
->name
, func_name
);
505 make_comment_block(text
, doc
->file_type
->id
, GEANY_TEMPLATES_INDENT
);
506 convert_eol_characters(text
, doc
);
508 return g_string_free(text
, FALSE
);
512 gchar
*templates_get_template_changelog(GeanyDocument
*doc
)
515 const gchar
*file_type_name
;
517 g_return_val_if_fail(DOC_VALID(doc
), NULL
);
519 result
= g_string_new(templates
[GEANY_TEMPLATE_CHANGELOG
]);
520 file_type_name
= (doc
->file_type
!= NULL
) ? doc
->file_type
->name
: "";
521 replace_static_values(result
);
522 templates_replace_default_dates(result
);
523 templates_replace_command(result
, DOC_FILENAME(doc
), file_type_name
, NULL
);
524 convert_eol_characters(result
, doc
);
526 return g_string_free(result
, FALSE
);
530 void templates_free_templates(void)
533 GList
*children
, *item
;
535 /* disconnect the menu from the action widget, so destroying the items below doesn't
536 * trigger rebuilding of the menu on each item destroy */
537 geany_menu_button_action_set_menu(
538 GEANY_MENU_BUTTON_ACTION(toolbar_get_action_by_name("New")), NULL
);
540 for (i
= 0; i
< GEANY_MAX_TEMPLATES
; i
++)
542 g_free(templates
[i
]);
544 /* destroy "New with template" sub menu items (in case we want to reload the templates) */
545 children
= gtk_container_get_children(GTK_CONTAINER(new_with_template_menu
));
546 foreach_list(item
, children
)
548 gtk_widget_destroy(GTK_WIDGET(item
->data
));
550 g_list_free(children
);
552 g_object_unref(new_with_template_menu
);
553 new_with_template_menu
= NULL
;
557 static void replace_static_values(GString
*text
)
559 utils_string_replace_all(text
, "{version}", template_prefs
.version
);
560 utils_string_replace_all(text
, "{initial}", template_prefs
.initials
);
561 utils_string_replace_all(text
, "{developer}", template_prefs
.developer
);
562 utils_string_replace_all(text
, "{mail}", template_prefs
.mail
);
563 utils_string_replace_all(text
, "{company}", template_prefs
.company
);
564 utils_string_replace_all(text
, "{untitled}", GEANY_STRING_UNTITLED
);
565 utils_string_replace_all(text
, "{geanyversion}", "Geany " VERSION
);
569 /* Replaces all static template wildcards (version, mail, company, name, ...)
570 * plus those wildcard, value pairs which are passed, e.g.
572 * templates_replace_valist(text, "{some_wildcard}", "some value",
573 * "{another_wildcard}", "another value", NULL);
575 * The argument list must be terminated with NULL. */
576 void templates_replace_valist(GString
*text
, const gchar
*first_wildcard
, ...)
579 const gchar
*key
, *value
;
581 g_return_if_fail(text
!= NULL
);
583 va_start(args
, first_wildcard
);
585 key
= first_wildcard
;
586 value
= va_arg(args
, gchar
*);
590 utils_string_replace_all(text
, key
, value
);
592 key
= va_arg(args
, gchar
*);
593 if (key
== NULL
|| text
== NULL
)
595 value
= va_arg(args
, gchar
*);
599 replace_static_values(text
);
603 static void templates_replace_default_dates(GString
*text
)
605 gchar
*year
= utils_get_date_time(template_prefs
.year_format
, NULL
);
606 gchar
*date
= utils_get_date_time(template_prefs
.date_format
, NULL
);
607 gchar
*datetime
= utils_get_date_time(template_prefs
.datetime_format
, NULL
);
609 g_return_if_fail(text
!= NULL
);
611 templates_replace_valist(text
,
614 "{datetime}", datetime
,
617 utils_free_pointers(3, year
, date
, datetime
, NULL
);
621 static gchar
*run_command(const gchar
*command
, const gchar
*file_name
,
622 const gchar
*file_type
, const gchar
*func_name
)
624 gchar
*result
= NULL
;
627 if (g_shell_parse_argv(command
, NULL
, &argv
, NULL
))
629 GError
*error
= NULL
;
632 file_name
= (file_name
!= NULL
) ? file_name
: "";
633 file_type
= (file_type
!= NULL
) ? file_type
: "";
634 func_name
= (func_name
!= NULL
) ? func_name
: "";
636 env
= utils_copy_environment(NULL
,
637 "GEANY_FILENAME", file_name
,
638 "GEANY_FILETYPE", file_type
,
639 "GEANY_FUNCNAME", func_name
,
641 if (! utils_spawn_sync(NULL
, argv
, env
, G_SPAWN_SEARCH_PATH
,
642 NULL
, NULL
, &result
, NULL
, NULL
, &error
))
644 g_warning("templates_replace_command: %s", error
->message
);
655 static void templates_replace_command(GString
*text
, const gchar
*file_name
,
656 const gchar
*file_type
, const gchar
*func_name
)
659 gchar
*wildcard
= NULL
;
663 g_return_if_fail(text
!= NULL
);
665 while ((match
= strstr(text
->str
, "{command:")) != NULL
)
668 while (*match
!= '}' && *match
!= '\0')
671 wildcard
= g_strndup(cmd
, (gsize
) (match
- cmd
+ 1));
672 cmd
= g_strndup(wildcard
+ 9, strlen(wildcard
) - 10);
674 result
= run_command(cmd
, file_name
, file_type
, func_name
);
677 result
= g_strstrip(result
);
678 utils_string_replace_first(text
, wildcard
, result
);
682 utils_string_replace_first(text
, wildcard
, "");