Add Clojure filetype
[geany-mirror.git] / src / templates.c
blobba74b5a8fe32e915c5add7d79436aa6368082617
1 /*
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
24 * document from.
27 #include <time.h>
28 #include <string.h>
30 #include "geany.h"
32 #include "templates.h"
33 #include "support.h"
34 #include "utils.h"
35 #include "document.h"
36 #include "encodings.h"
37 #include "editor.h"
38 #include "filetypes.h"
39 #include "ui_utils.h"
40 #include "toolbar.h"
41 #include "geanymenubuttonaction.h"
42 #include "project.h"
45 GeanyTemplatePrefs template_prefs;
47 static GtkWidget *new_with_template_menu = NULL; /* submenu used for both file menu and toolbar */
49 /* TODO: implement custom insertion templates instead? */
50 static gchar *templates[GEANY_MAX_TEMPLATES];
53 static void replace_static_values(GString *text);
54 static gchar *get_template_fileheader(GeanyFiletype *ft);
56 /* called by templates_replace_common */
57 static void templates_replace_default_dates(GString *text);
58 static void templates_replace_command(GString *text, const gchar *file_name,
59 const gchar *file_type, const gchar *func_name);
62 static gchar *read_file(const gchar *locale_fname)
64 gchar *contents;
65 gsize length;
66 GString *str;
68 if (! g_file_get_contents(locale_fname, &contents, &length, NULL))
69 return NULL;
71 if (! encodings_convert_to_utf8_auto(&contents, &length, NULL, NULL, NULL, NULL))
73 gchar *utf8_fname = utils_get_utf8_from_locale(locale_fname);
75 ui_set_statusbar(TRUE, _("Failed to convert template file \"%s\" to UTF-8"), utf8_fname);
76 g_free(utf8_fname);
77 g_free(contents);
78 return NULL;
81 str = g_string_new(contents);
82 g_free(contents);
84 /* convert to LF endings for consistency in mixing templates */
85 utils_ensure_same_eol_characters(str, SC_EOL_LF);
86 return g_string_free(str, FALSE);
90 static void read_template(const gchar *name, gint id)
92 gchar *fname = g_build_path(G_DIR_SEPARATOR_S, app->configdir,
93 GEANY_TEMPLATES_SUBDIR, name, NULL);
95 /* try system if user template doesn't exist */
96 if (!g_file_test(fname, G_FILE_TEST_EXISTS))
97 SETPTR(fname, g_build_path(G_DIR_SEPARATOR_S, app->datadir,
98 GEANY_TEMPLATES_SUBDIR, name, NULL));
100 templates[id] = read_file(fname);
101 g_free(fname);
105 /* called when inserting templates into an existing document */
106 static void convert_eol_characters(GString *template, GeanyDocument *doc)
108 gint doc_eol_mode;
110 if (doc == NULL)
111 doc = document_get_current();
113 g_return_if_fail(doc != NULL);
115 doc_eol_mode = editor_get_eol_char_mode(doc->editor);
116 utils_ensure_same_eol_characters(template, doc_eol_mode);
120 static void init_general_templates(void)
122 /* read the contents */
123 read_template("fileheader", GEANY_TEMPLATE_FILEHEADER);
124 read_template("gpl", GEANY_TEMPLATE_GPL);
125 read_template("bsd", GEANY_TEMPLATE_BSD);
126 read_template("function", GEANY_TEMPLATE_FUNCTION);
127 read_template("changelog", GEANY_TEMPLATE_CHANGELOG);
131 void templates_replace_common(GString *tmpl, const gchar *fname,
132 GeanyFiletype *ft, const gchar *func_name)
134 gchar *shortname;
136 if (fname == NULL)
138 if (!ft->extension)
139 shortname = g_strdup(GEANY_STRING_UNTITLED);
140 else
141 shortname = g_strconcat(GEANY_STRING_UNTITLED, ".", ft->extension, NULL);
143 else
144 shortname = g_path_get_basename(fname);
146 templates_replace_valist(tmpl,
147 "{filename}", shortname,
148 "{project}", app->project ? app->project->name : "",
149 "{description}", app->project ? app->project->description : "",
150 NULL);
151 g_free(shortname);
153 templates_replace_default_dates(tmpl);
154 templates_replace_command(tmpl, fname, ft->name, func_name);
155 /* Bug: command results could have {ob} {cb} strings in! */
156 /* replace braces last */
157 templates_replace_valist(tmpl,
158 "{ob}", "{",
159 "{cb}", "}",
160 NULL);
164 static gchar *get_template_from_file(const gchar *locale_fname, const gchar *doc_filename,
165 GeanyFiletype *ft)
167 gchar *content;
168 GString *template = NULL;
170 content = read_file(locale_fname);
172 if (content != NULL)
174 gchar *file_header;
176 template = g_string_new(content);
178 file_header = get_template_fileheader(ft);
179 templates_replace_valist(template,
180 "{fileheader}", file_header,
181 NULL);
182 templates_replace_common(template, doc_filename, ft, NULL);
184 utils_free_pointers(2, file_header, content, NULL);
185 return g_string_free(template, FALSE);
187 return NULL;
191 static void
192 on_new_with_file_template(GtkMenuItem *menuitem, G_GNUC_UNUSED gpointer user_data)
194 gchar *fname = ui_menu_item_get_text(menuitem);
195 GeanyFiletype *ft;
196 gchar *template;
197 const gchar *extension = strrchr(fname, '.'); /* easy way to get the file extension */
198 gchar *new_filename = g_strconcat(GEANY_STRING_UNTITLED, extension, NULL);
199 gchar *path;
201 ft = filetypes_detect_from_extension(fname);
202 SETPTR(fname, utils_get_locale_from_utf8(fname));
204 /* fname is just the basename from the menu item, so prepend the custom files path */
205 path = g_build_path(G_DIR_SEPARATOR_S, app->configdir, GEANY_TEMPLATES_SUBDIR,
206 "files", fname, NULL);
207 template = get_template_from_file(path, new_filename, ft);
208 if (!template)
210 /* try the system path */
211 g_free(path);
212 path = g_build_path(G_DIR_SEPARATOR_S, app->datadir, GEANY_TEMPLATES_SUBDIR,
213 "files", fname, NULL);
214 template = get_template_from_file(path, new_filename, ft);
216 if (template)
218 /* line endings will be converted */
219 document_new_file(new_filename, ft, template);
221 else
223 SETPTR(fname, utils_get_utf8_from_locale(fname));
224 ui_set_statusbar(TRUE, _("Could not find file '%s'."), fname);
226 g_free(template);
227 g_free(path);
228 g_free(new_filename);
229 g_free(fname);
233 static void add_file_item(const gchar *fname, GtkWidget *menu)
235 GtkWidget *tmp_button;
236 gchar *label;
238 g_return_if_fail(fname);
239 g_return_if_fail(menu);
241 label = utils_get_utf8_from_locale(fname);
243 tmp_button = gtk_menu_item_new_with_label(label);
244 gtk_widget_show(tmp_button);
245 gtk_container_add(GTK_CONTAINER(menu), tmp_button);
246 g_signal_connect(tmp_button, "activate", G_CALLBACK(on_new_with_file_template), NULL);
248 g_free(label);
252 static gboolean add_custom_template_items(void)
254 GSList *list = utils_get_config_files(GEANY_TEMPLATES_SUBDIR G_DIR_SEPARATOR_S "files");
255 GSList *node;
257 foreach_slist(node, list)
259 gchar *fname = node->data;
261 add_file_item(fname, new_with_template_menu);
262 g_free(fname);
264 g_slist_free(list);
265 return list != NULL;
269 static void create_file_template_menu(void)
271 new_with_template_menu = gtk_menu_new();
272 add_custom_template_items();
274 /* unless the file menu is showing, menu should be in the toolbar widget */
275 geany_menu_button_action_set_menu(GEANY_MENU_BUTTON_ACTION(
276 toolbar_get_action_by_name("New")), new_with_template_menu);
280 static void on_file_menu_show(GtkWidget *item)
282 geany_menu_button_action_set_menu(
283 GEANY_MENU_BUTTON_ACTION(toolbar_get_action_by_name("New")), NULL);
284 item = ui_lookup_widget(main_widgets.window, "menu_new_with_template1");
285 gtk_menu_item_set_submenu(GTK_MENU_ITEM(item), new_with_template_menu);
289 static void on_file_menu_hide(GtkWidget *item)
291 item = ui_lookup_widget(main_widgets.window, "menu_new_with_template1");
292 gtk_menu_item_set_submenu(GTK_MENU_ITEM(item), NULL);
293 geany_menu_button_action_set_menu(
294 GEANY_MENU_BUTTON_ACTION(toolbar_get_action_by_name("New")), new_with_template_menu);
298 /* reload templates if any file in the templates path is saved */
299 static void on_document_save(G_GNUC_UNUSED GObject *object, GeanyDocument *doc)
301 gchar *path = g_build_filename(app->configdir, GEANY_TEMPLATES_SUBDIR, NULL);
303 g_return_if_fail(!EMPTY(doc->real_path));
305 if (strncmp(doc->real_path, path, strlen(path)) == 0)
307 /* reload templates */
308 templates_free_templates();
309 templates_init();
311 g_free(path);
315 /* warning: also called when reloading template settings */
316 void templates_init(void)
318 static gboolean init_done = FALSE;
320 init_general_templates();
322 create_file_template_menu();
323 /* we hold our own ref for the menu as it has no parent whilst being moved */
324 g_object_ref(new_with_template_menu);
326 /* only connect signals to persistent objects once */
327 if (!init_done)
329 GtkWidget *item;
330 /* reparent the template menu as needed */
331 item = ui_lookup_widget(main_widgets.window, "file1");
332 item = gtk_menu_item_get_submenu(GTK_MENU_ITEM(item));
333 g_signal_connect(item, "show", G_CALLBACK(on_file_menu_show), NULL);
334 g_signal_connect(item, "hide", G_CALLBACK(on_file_menu_hide), NULL);
336 g_signal_connect(geany_object, "document-save", G_CALLBACK(on_document_save), NULL);
338 init_done = TRUE;
342 /* indent is used to make some whitespace between comment char and real start of the line
343 * e.g. indent = 8 prints " * here comes the text of the line"
344 * indent is meant to be the whole amount of characters before the real line content follows, i.e.
345 * 6 characters are filled with whitespace when the comment characters include " *" */
346 static void make_comment_block(GString *comment_text, gint filetype_idx, guint indent)
348 gchar *frame_start; /* to add before comment_text */
349 gchar *frame_end; /* to add after comment_text */
350 const gchar *line_prefix; /* to add before every line in comment_text */
351 gchar *tmp;
352 gchar *prefix;
353 gchar **lines;
354 gsize i, len;
355 gint template_eol_mode;
356 const gchar *template_eol_char;
357 GeanyFiletype *ft = filetypes_index(filetype_idx);
358 const gchar *co;
359 const gchar *cc;
361 g_return_if_fail(comment_text != NULL);
362 g_return_if_fail(ft != NULL);
364 template_eol_mode = utils_get_line_endings(comment_text->str, comment_text->len);
365 template_eol_char = utils_get_eol_char(template_eol_mode);
367 filetype_get_comment_open_close(ft, FALSE, &co, &cc);
368 if (!EMPTY(co))
370 if (!EMPTY(cc))
372 frame_start = g_strconcat(co, template_eol_char, NULL);
373 frame_end = g_strconcat(cc, template_eol_char, NULL);
374 line_prefix = "";
376 else
378 frame_start = NULL;
379 frame_end = NULL;
380 line_prefix = co;
383 else
384 { /* use C-like multi-line comments as fallback */
385 frame_start = g_strconcat("/*", template_eol_char, NULL);
386 frame_end = g_strconcat("*/", template_eol_char, NULL);
387 line_prefix = "";
390 /* do some magic to nicely format C-like multi-line comments */
391 if (!EMPTY(frame_start) && frame_start[1] == '*')
393 /* prefix the string with a space */
394 SETPTR(frame_end, g_strconcat(" ", frame_end, NULL));
395 line_prefix = " *";
398 /* construct the real prefix with given amount of whitespace */
399 i = (indent > strlen(line_prefix)) ? (indent - strlen(line_prefix)) : strlen(line_prefix);
400 tmp = g_strnfill(i, ' ');
401 prefix = g_strconcat(line_prefix, tmp, NULL);
402 g_free(tmp);
404 /* add line_prefix to every line of comment_text */
405 lines = g_strsplit(comment_text->str, template_eol_char, -1);
406 len = g_strv_length(lines);
407 if (len > 0) /* prevent unsigned wraparound if comment_text is empty */
409 for (i = 0; i < len - 1; i++)
411 tmp = lines[i];
412 lines[i] = g_strconcat(prefix, tmp, NULL);
413 g_free(tmp);
416 tmp = g_strjoinv(template_eol_char, lines);
418 /* clear old contents */
419 g_string_erase(comment_text, 0, -1);
421 /* add frame_end */
422 if (frame_start != NULL)
423 g_string_append(comment_text, frame_start);
424 /* add the new main content */
425 g_string_append(comment_text, tmp);
426 /* add frame_start */
427 if (frame_end != NULL)
428 g_string_append(comment_text, frame_end);
430 utils_free_pointers(4, prefix, tmp, frame_start, frame_end, NULL);
431 g_strfreev(lines);
435 gchar *templates_get_template_licence(GeanyDocument *doc, gint licence_type)
437 GString *template;
439 g_return_val_if_fail(doc != NULL, NULL);
440 g_return_val_if_fail(licence_type == GEANY_TEMPLATE_GPL || licence_type == GEANY_TEMPLATE_BSD, NULL);
442 template = g_string_new(templates[licence_type]);
443 replace_static_values(template);
444 templates_replace_default_dates(template);
445 templates_replace_command(template, DOC_FILENAME(doc), doc->file_type->name, NULL);
447 make_comment_block(template, doc->file_type->id, GEANY_TEMPLATES_INDENT);
448 convert_eol_characters(template, doc);
450 return g_string_free(template, FALSE);
454 static gchar *get_template_fileheader(GeanyFiletype *ft)
456 GString *template = g_string_new(templates[GEANY_TEMPLATE_FILEHEADER]);
458 filetypes_load_config(ft->id, FALSE); /* load any user extension setting */
460 templates_replace_valist(template,
461 "{gpl}", templates[GEANY_TEMPLATE_GPL],
462 "{bsd}", templates[GEANY_TEMPLATE_BSD],
463 NULL);
465 /* we don't replace other wildcards here otherwise they would get done twice for files */
466 make_comment_block(template, ft->id, GEANY_TEMPLATES_INDENT);
467 return g_string_free(template, FALSE);
471 /* TODO change the signature to take a GeanyDocument? this would break plugin API/ABI */
472 gchar *templates_get_template_fileheader(gint filetype_idx, const gchar *fname)
474 GeanyFiletype *ft = filetypes[filetype_idx];
475 gchar *str = get_template_fileheader(ft);
476 GString *template = g_string_new(str);
478 g_free(str);
479 templates_replace_common(template, fname, ft, NULL);
480 convert_eol_characters(template, NULL);
481 return g_string_free(template, FALSE);
485 gchar *templates_get_template_function(GeanyDocument *doc, const gchar *func_name)
487 GString *text;
489 func_name = (func_name != NULL) ? func_name : "";
490 text = g_string_new(templates[GEANY_TEMPLATE_FUNCTION]);
492 templates_replace_valist(text, "{functionname}", func_name, NULL);
493 templates_replace_default_dates(text);
494 templates_replace_command(text, DOC_FILENAME(doc), doc->file_type->name, func_name);
496 make_comment_block(text, doc->file_type->id, GEANY_TEMPLATES_INDENT);
497 convert_eol_characters(text, doc);
499 return g_string_free(text, FALSE);
503 gchar *templates_get_template_changelog(GeanyDocument *doc)
505 GString *result = g_string_new(templates[GEANY_TEMPLATE_CHANGELOG]);
506 const gchar *file_type_name = (doc != NULL) ? doc->file_type->name : "";
508 replace_static_values(result);
509 templates_replace_default_dates(result);
510 templates_replace_command(result, DOC_FILENAME(doc), file_type_name, NULL);
511 convert_eol_characters(result, doc);
513 return g_string_free(result, FALSE);
517 void templates_free_templates(void)
519 gint i;
520 GList *children, *item;
522 /* disconnect the menu from the action widget, so destroying the items below doesn't
523 * trigger rebuilding of the menu on each item destroy */
524 geany_menu_button_action_set_menu(
525 GEANY_MENU_BUTTON_ACTION(toolbar_get_action_by_name("New")), NULL);
527 for (i = 0; i < GEANY_MAX_TEMPLATES; i++)
529 g_free(templates[i]);
531 /* destroy "New with template" sub menu items (in case we want to reload the templates) */
532 children = gtk_container_get_children(GTK_CONTAINER(new_with_template_menu));
533 foreach_list(item, children)
535 gtk_widget_destroy(GTK_WIDGET(item->data));
537 g_list_free(children);
539 g_object_unref(new_with_template_menu);
540 new_with_template_menu = NULL;
544 static void replace_static_values(GString *text)
546 utils_string_replace_all(text, "{version}", template_prefs.version);
547 utils_string_replace_all(text, "{initial}", template_prefs.initials);
548 utils_string_replace_all(text, "{developer}", template_prefs.developer);
549 utils_string_replace_all(text, "{mail}", template_prefs.mail);
550 utils_string_replace_all(text, "{company}", template_prefs.company);
551 utils_string_replace_all(text, "{untitled}", GEANY_STRING_UNTITLED);
552 utils_string_replace_all(text, "{geanyversion}", "Geany " VERSION);
556 /* Replaces all static template wildcards (version, mail, company, name, ...)
557 * plus those wildcard, value pairs which are passed, e.g.
559 * templates_replace_valist(text, "{some_wildcard}", "some value",
560 * "{another_wildcard}", "another value", NULL);
562 * The argument list must be terminated with NULL. */
563 void templates_replace_valist(GString *text, const gchar *first_wildcard, ...)
565 va_list args;
566 const gchar *key, *value;
568 g_return_if_fail(text != NULL);
570 va_start(args, first_wildcard);
572 key = first_wildcard;
573 value = va_arg(args, gchar*);
575 while (key != NULL)
577 utils_string_replace_all(text, key, value);
579 key = va_arg(args, gchar*);
580 if (key == NULL || text == NULL)
581 break;
582 value = va_arg(args, gchar*);
584 va_end(args);
586 replace_static_values(text);
590 static void templates_replace_default_dates(GString *text)
592 gchar *year = utils_get_date_time(template_prefs.year_format, NULL);
593 gchar *date = utils_get_date_time(template_prefs.date_format, NULL);
594 gchar *datetime = utils_get_date_time(template_prefs.datetime_format, NULL);
596 g_return_if_fail(text != NULL);
598 templates_replace_valist(text,
599 "{year}", year,
600 "{date}", date,
601 "{datetime}", datetime,
602 NULL);
604 utils_free_pointers(3, year, date, datetime, NULL);
608 static gchar *run_command(const gchar *command, const gchar *file_name,
609 const gchar *file_type, const gchar *func_name)
611 gchar *result = NULL;
612 gchar **argv;
614 if (g_shell_parse_argv(command, NULL, &argv, NULL))
616 GError *error = NULL;
617 gchar **env;
619 file_name = (file_name != NULL) ? file_name : "";
620 file_type = (file_type != NULL) ? file_type : "";
621 func_name = (func_name != NULL) ? func_name : "";
623 env = utils_copy_environment(NULL,
624 "GEANY_FILENAME", file_name,
625 "GEANY_FILETYPE", file_type,
626 "GEANY_FUNCNAME", func_name,
627 NULL);
628 if (! utils_spawn_sync(NULL, argv, env, G_SPAWN_SEARCH_PATH,
629 NULL, NULL, &result, NULL, NULL, &error))
631 g_warning("templates_replace_command: %s", error->message);
632 g_error_free(error);
633 return NULL;
635 g_strfreev(argv);
636 g_strfreev(env);
638 return result;
642 static void templates_replace_command(GString *text, const gchar *file_name,
643 const gchar *file_type, const gchar *func_name)
645 gchar *match = NULL;
646 gchar *wildcard = NULL;
647 gchar *cmd;
648 gchar *result;
650 g_return_if_fail(text != NULL);
652 while ((match = strstr(text->str, "{command:")) != NULL)
654 cmd = match;
655 while (*match != '}' && *match != '\0')
656 match++;
658 wildcard = g_strndup(cmd, (gsize) (match - cmd + 1));
659 cmd = g_strndup(wildcard + 9, strlen(wildcard) - 10);
661 result = run_command(cmd, file_name, file_type, func_name);
662 if (result != NULL)
664 result = g_strstrip(result);
665 utils_string_replace_first(text, wildcard, result);
666 g_free(result);
668 else
669 utils_string_replace_first(text, wildcard, "");
671 g_free(wildcard);
672 g_free(cmd);