Windows installer: copyright and NSIS version update
[geany-mirror.git] / src / templates.c
blobca942af3783469fc14abebc8dd8df69f0d682996
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 #ifdef HAVE_CONFIG_H
28 # include "config.h"
29 #endif
31 #include "templates.h"
33 #include "app.h"
34 #include "document.h"
35 #include "encodingsprivate.h"
36 #include "filetypes.h"
37 #include "geany.h"
38 #include "geanymenubuttonaction.h"
39 #include "geanyobject.h"
40 #include "spawn.h"
41 #include "support.h"
42 #include "toolbar.h"
43 #include "ui_utils.h"
44 #include "utils.h"
46 #include "gtkcompat.h"
48 #include <time.h>
49 #include <string.h>
52 GeanyTemplatePrefs template_prefs;
54 static GtkWidget *new_with_template_menu = NULL;
55 static GtkWidget *new_with_template_toolbar_menu = NULL;
57 /* TODO: implement custom insertion templates instead? */
58 static gchar *templates[GEANY_MAX_TEMPLATES];
61 static void replace_static_values(GString *text);
62 static gchar *get_template_fileheader(GeanyFiletype *ft);
64 /* called by templates_replace_common */
65 static void templates_replace_default_dates(GString *text);
66 static void templates_replace_command(GString *text, const gchar *file_name,
67 const gchar *file_type, const gchar *func_name);
70 static gchar *read_file(const gchar *locale_fname)
72 gchar *contents;
73 gsize length;
74 GString *str;
76 if (! g_file_get_contents(locale_fname, &contents, &length, NULL))
77 return NULL;
79 if (! encodings_convert_to_utf8_auto(&contents, &length, NULL, NULL, NULL, NULL))
81 gchar *utf8_fname = utils_get_utf8_from_locale(locale_fname);
83 ui_set_statusbar(TRUE, _("Failed to convert template file \"%s\" to UTF-8"), utf8_fname);
84 g_free(utf8_fname);
85 g_free(contents);
86 return NULL;
89 str = g_string_new(contents);
90 g_free(contents);
92 /* convert to LF endings for consistency in mixing templates */
93 utils_ensure_same_eol_characters(str, SC_EOL_LF);
94 return g_string_free(str, FALSE);
98 static void read_template(const gchar *name, gint id)
100 gchar *fname = g_build_path(G_DIR_SEPARATOR_S, app->configdir,
101 GEANY_TEMPLATES_SUBDIR, name, NULL);
103 /* try system if user template doesn't exist */
104 if (!g_file_test(fname, G_FILE_TEST_EXISTS))
105 SETPTR(fname, g_build_path(G_DIR_SEPARATOR_S, app->datadir,
106 GEANY_TEMPLATES_SUBDIR, name, NULL));
108 templates[id] = read_file(fname);
109 g_free(fname);
113 /* called when inserting templates into an existing document */
114 static void convert_eol_characters(GString *template, GeanyDocument *doc)
116 gint doc_eol_mode;
118 g_return_if_fail(doc == NULL || doc->is_valid);
120 if (doc == NULL)
121 doc = document_get_current();
123 g_return_if_fail(doc != NULL);
125 doc_eol_mode = editor_get_eol_char_mode(doc->editor);
126 utils_ensure_same_eol_characters(template, doc_eol_mode);
130 static void init_general_templates(void)
132 /* read the contents */
133 read_template("fileheader", GEANY_TEMPLATE_FILEHEADER);
134 read_template("gpl", GEANY_TEMPLATE_GPL);
135 read_template("bsd", GEANY_TEMPLATE_BSD);
136 read_template("function", GEANY_TEMPLATE_FUNCTION);
137 read_template("changelog", GEANY_TEMPLATE_CHANGELOG);
141 void templates_replace_common(GString *tmpl, const gchar *fname,
142 GeanyFiletype *ft, const gchar *func_name)
144 gchar *shortname;
146 if (fname == NULL)
148 if (!ft->extension)
149 shortname = g_strdup(GEANY_STRING_UNTITLED);
150 else
151 shortname = g_strconcat(GEANY_STRING_UNTITLED, ".", ft->extension, NULL);
153 else
154 shortname = g_path_get_basename(fname);
156 templates_replace_valist(tmpl,
157 "{filename}", shortname,
158 "{project}", app->project ? app->project->name : "",
159 "{description}", app->project ? app->project->description : "",
160 NULL);
161 g_free(shortname);
163 templates_replace_default_dates(tmpl);
164 templates_replace_command(tmpl, fname, ft->name, func_name);
165 /* Bug: command results could have {ob} {cb} strings in! */
166 /* replace braces last */
167 templates_replace_valist(tmpl,
168 "{ob}", "{",
169 "{cb}", "}",
170 NULL);
174 static gchar *get_template_from_file(const gchar *locale_fname, const gchar *doc_filename,
175 GeanyFiletype *ft)
177 gchar *content;
179 content = read_file(locale_fname);
181 if (content != NULL)
183 gchar *file_header;
184 GString *template = g_string_new(content);
186 file_header = get_template_fileheader(ft);
187 templates_replace_valist(template,
188 "{fileheader}", file_header,
189 NULL);
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);
195 return NULL;
199 static void
200 on_new_with_file_template(GtkMenuItem *menuitem, G_GNUC_UNUSED gpointer user_data)
202 gchar *fname = ui_menu_item_get_text(menuitem);
203 GeanyFiletype *ft;
204 gchar *template;
205 const gchar *extension = strrchr(fname, '.'); /* easy way to get the file extension */
206 gchar *new_filename = g_strconcat(GEANY_STRING_UNTITLED, extension, NULL);
207 gchar *path;
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);
216 if (!template)
218 /* try the system path */
219 g_free(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);
224 if (template)
226 /* line endings will be converted */
227 document_new_file(new_filename, ft, template);
229 else
231 SETPTR(fname, utils_get_utf8_from_locale(fname));
232 ui_set_statusbar(TRUE, _("Could not find file '%s'."), fname);
234 g_free(template);
235 g_free(path);
236 g_free(new_filename);
237 g_free(fname);
241 static void add_file_item(const gchar *fname, GtkWidget *menu)
243 GtkWidget *tmp_button;
244 gchar *label;
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);
256 g_free(label);
260 static void populate_file_template_menu(GtkWidget *menu)
262 GSList *list = utils_get_config_files(GEANY_TEMPLATES_SUBDIR G_DIR_SEPARATOR_S "files");
263 GSList *node;
265 foreach_slist(node, list)
267 gchar *fname = node->data;
269 add_file_item(fname, menu);
270 g_free(fname);
272 g_slist_free(list);
276 static void create_file_template_menu(void)
278 GtkWidget *item;
280 new_with_template_menu = gtk_menu_new();
281 item = ui_lookup_widget(main_widgets.window, "menu_new_with_template1");
282 gtk_menu_item_set_submenu(GTK_MENU_ITEM(item), new_with_template_menu);
284 new_with_template_toolbar_menu = gtk_menu_new();
285 g_object_ref(new_with_template_toolbar_menu);
286 geany_menu_button_action_set_menu(GEANY_MENU_BUTTON_ACTION(toolbar_get_action_by_name("New")),
287 new_with_template_toolbar_menu);
291 /* reload templates if any file in the templates path is saved */
292 static void on_document_save(G_GNUC_UNUSED GObject *object, GeanyDocument *doc)
294 gchar *path;
296 g_return_if_fail(!EMPTY(doc->real_path));
298 path = g_build_filename(app->configdir, GEANY_TEMPLATES_SUBDIR, NULL);
299 if (strncmp(doc->real_path, path, strlen(path)) == 0)
301 /* reload templates */
302 templates_free_templates();
303 templates_init();
305 g_free(path);
309 /* warning: also called when reloading template settings */
310 void templates_init(void)
312 static gboolean init_done = FALSE;
314 init_general_templates();
316 if (!init_done)
318 create_file_template_menu();
319 g_signal_connect(geany_object, "document-save", G_CALLBACK(on_document_save), NULL);
320 init_done = TRUE;
323 populate_file_template_menu(new_with_template_menu);
324 populate_file_template_menu(new_with_template_toolbar_menu);
328 /* indent is used to make some whitespace between comment char and real start of the line
329 * e.g. indent = 8 prints " * here comes the text of the line"
330 * indent is meant to be the whole amount of characters before the real line content follows, i.e.
331 * 6 characters are filled with whitespace when the comment characters include " *" */
332 static void make_comment_block(GString *comment_text, gint filetype_idx, guint indent)
334 gchar *frame_start; /* to add before comment_text */
335 gchar *frame_end; /* to add after comment_text */
336 const gchar *line_prefix; /* to add before every line in comment_text */
337 gchar *tmp;
338 gchar *prefix;
339 gchar **lines;
340 gsize i, len;
341 gint template_eol_mode;
342 const gchar *template_eol_char;
343 GeanyFiletype *ft = filetypes_index(filetype_idx);
344 const gchar *co;
345 const gchar *cc;
347 g_return_if_fail(comment_text != NULL);
348 g_return_if_fail(ft != NULL);
350 template_eol_mode = utils_get_line_endings(comment_text->str, comment_text->len);
351 template_eol_char = utils_get_eol_char(template_eol_mode);
353 filetype_get_comment_open_close(ft, FALSE, &co, &cc);
354 if (!EMPTY(co))
356 if (!EMPTY(cc))
358 frame_start = g_strconcat(co, template_eol_char, NULL);
359 frame_end = g_strconcat(cc, template_eol_char, NULL);
360 line_prefix = "";
362 else
364 frame_start = NULL;
365 frame_end = NULL;
366 line_prefix = co;
369 else
370 { /* use C-like multi-line comments as fallback */
371 frame_start = g_strconcat("/*", template_eol_char, NULL);
372 frame_end = g_strconcat("*/", template_eol_char, NULL);
373 line_prefix = "";
376 /* do some magic to nicely format C-like multi-line comments */
377 if (!EMPTY(frame_start) && frame_start[1] == '*')
379 /* prefix the string with a space */
380 SETPTR(frame_end, g_strconcat(" ", frame_end, NULL));
381 line_prefix = " *";
384 /* construct the real prefix with given amount of whitespace */
385 i = (indent > strlen(line_prefix)) ? (indent - strlen(line_prefix)) : strlen(line_prefix);
386 tmp = g_strnfill(i, ' ');
387 prefix = g_strconcat(line_prefix, tmp, NULL);
388 g_free(tmp);
390 /* add line_prefix to every line of comment_text */
391 lines = g_strsplit(comment_text->str, template_eol_char, -1);
392 len = g_strv_length(lines);
393 if (len > 0) /* prevent unsigned wraparound if comment_text is empty */
395 for (i = 0; i < len - 1; i++)
397 tmp = lines[i];
398 lines[i] = g_strconcat(prefix, tmp, NULL);
399 g_free(tmp);
402 tmp = g_strjoinv(template_eol_char, lines);
404 /* clear old contents */
405 g_string_erase(comment_text, 0, -1);
407 /* add frame_end */
408 if (frame_start != NULL)
409 g_string_append(comment_text, frame_start);
410 /* add the new main content */
411 g_string_append(comment_text, tmp);
412 /* add frame_start */
413 if (frame_end != NULL)
414 g_string_append(comment_text, frame_end);
416 utils_free_pointers(4, prefix, tmp, frame_start, frame_end, NULL);
417 g_strfreev(lines);
421 gchar *templates_get_template_licence(GeanyDocument *doc, gint licence_type)
423 GString *template;
425 g_return_val_if_fail(DOC_VALID(doc), NULL);
426 g_return_val_if_fail(licence_type == GEANY_TEMPLATE_GPL || licence_type == GEANY_TEMPLATE_BSD, NULL);
428 template = g_string_new(templates[licence_type]);
429 replace_static_values(template);
430 templates_replace_default_dates(template);
431 templates_replace_command(template, DOC_FILENAME(doc), doc->file_type->name, NULL);
433 make_comment_block(template, doc->file_type->id, GEANY_TEMPLATES_INDENT);
434 convert_eol_characters(template, doc);
436 return g_string_free(template, FALSE);
440 static gchar *get_template_fileheader(GeanyFiletype *ft)
442 GString *template = g_string_new(templates[GEANY_TEMPLATE_FILEHEADER]);
444 filetypes_load_config(ft->id, FALSE); /* load any user extension setting */
446 templates_replace_valist(template,
447 "{gpl}", templates[GEANY_TEMPLATE_GPL],
448 "{bsd}", templates[GEANY_TEMPLATE_BSD],
449 NULL);
451 /* we don't replace other wildcards here otherwise they would get done twice for files */
452 make_comment_block(template, ft->id, GEANY_TEMPLATES_INDENT);
453 return g_string_free(template, FALSE);
457 /* TODO change the signature to take a GeanyDocument? this would break plugin API/ABI */
458 GEANY_API_SYMBOL
459 gchar *templates_get_template_fileheader(gint filetype_idx, const gchar *fname)
461 GeanyFiletype *ft = filetypes[filetype_idx];
462 gchar *str = get_template_fileheader(ft);
463 GString *template = g_string_new(str);
465 g_free(str);
466 templates_replace_common(template, fname, ft, NULL);
467 convert_eol_characters(template, NULL);
468 return g_string_free(template, FALSE);
472 gchar *templates_get_template_function(GeanyDocument *doc, const gchar *func_name)
474 GString *text;
476 func_name = (func_name != NULL) ? func_name : "";
477 text = g_string_new(templates[GEANY_TEMPLATE_FUNCTION]);
479 templates_replace_valist(text, "{functionname}", func_name, NULL);
480 templates_replace_default_dates(text);
481 templates_replace_command(text, DOC_FILENAME(doc), doc->file_type->name, func_name);
483 make_comment_block(text, doc->file_type->id, GEANY_TEMPLATES_INDENT);
484 convert_eol_characters(text, doc);
486 return g_string_free(text, FALSE);
490 gchar *templates_get_template_changelog(GeanyDocument *doc)
492 GString *result;
493 const gchar *file_type_name;
495 g_return_val_if_fail(DOC_VALID(doc), NULL);
497 result = g_string_new(templates[GEANY_TEMPLATE_CHANGELOG]);
498 file_type_name = (doc->file_type != NULL) ? doc->file_type->name : "";
499 replace_static_values(result);
500 templates_replace_default_dates(result);
501 templates_replace_command(result, DOC_FILENAME(doc), file_type_name, NULL);
502 convert_eol_characters(result, doc);
504 return g_string_free(result, FALSE);
508 static void free_template_menu_items(GtkWidget *menu)
510 GList *children, *item;
512 children = gtk_container_get_children(GTK_CONTAINER(menu));
513 foreach_list(item, children)
514 gtk_widget_destroy(GTK_WIDGET(item->data));
515 g_list_free(children);
519 void templates_free_templates(void)
521 gint i;
523 for (i = 0; i < GEANY_MAX_TEMPLATES; i++)
524 g_free(templates[i]);
525 free_template_menu_items(new_with_template_menu);
526 free_template_menu_items(new_with_template_toolbar_menu);
530 static void replace_static_values(GString *text)
532 utils_string_replace_all(text, "{version}", template_prefs.version);
533 utils_string_replace_all(text, "{initial}", template_prefs.initials);
534 utils_string_replace_all(text, "{developer}", template_prefs.developer);
535 utils_string_replace_all(text, "{mail}", template_prefs.mail);
536 utils_string_replace_all(text, "{company}", template_prefs.company);
537 utils_string_replace_all(text, "{untitled}", GEANY_STRING_UNTITLED);
538 utils_string_replace_all(text, "{geanyversion}", "Geany " VERSION);
542 /* Replaces all static template wildcards (version, mail, company, name, ...)
543 * plus those wildcard, value pairs which are passed, e.g.
545 * templates_replace_valist(text, "{some_wildcard}", "some value",
546 * "{another_wildcard}", "another value", NULL);
548 * The argument list must be terminated with NULL. */
549 void templates_replace_valist(GString *text, const gchar *first_wildcard, ...)
551 va_list args;
552 const gchar *key, *value;
554 g_return_if_fail(text != NULL);
556 va_start(args, first_wildcard);
558 key = first_wildcard;
559 value = va_arg(args, gchar*);
561 while (key != NULL)
563 utils_string_replace_all(text, key, value);
565 key = va_arg(args, gchar*);
566 if (key == NULL || text == NULL)
567 break;
568 value = va_arg(args, gchar*);
570 va_end(args);
572 replace_static_values(text);
576 static void templates_replace_default_dates(GString *text)
578 gchar *year = utils_get_date_time(template_prefs.year_format, NULL);
579 gchar *date = utils_get_date_time(template_prefs.date_format, NULL);
580 gchar *datetime = utils_get_date_time(template_prefs.datetime_format, NULL);
582 g_return_if_fail(text != NULL);
584 templates_replace_valist(text,
585 "{year}", year,
586 "{date}", date,
587 "{datetime}", datetime,
588 NULL);
590 utils_free_pointers(3, year, date, datetime, NULL);
594 static gchar *run_command(const gchar *command, const gchar *file_name,
595 const gchar *file_type, const gchar *func_name)
597 GString *output = g_string_new(NULL);
598 gchar *result = NULL;
599 GError *error = NULL;
600 gchar **env;
602 file_name = (file_name != NULL) ? file_name : "";
603 file_type = (file_type != NULL) ? file_type : "";
604 func_name = (func_name != NULL) ? func_name : "";
606 env = utils_copy_environment(NULL,
607 "GEANY_FILENAME", file_name,
608 "GEANY_FILETYPE", file_type,
609 "GEANY_FUNCNAME", func_name,
610 NULL);
612 if (spawn_sync(NULL, command, NULL, env, NULL, output, NULL, NULL, &error))
614 result = g_string_free(output, FALSE);
616 else
618 g_warning(_("Cannot execute command \"%s\" from the template: %s. "
619 "Check the path in the template."), command, error->message);
620 g_error_free(error);
623 g_strfreev(env);
624 return result;
628 static void templates_replace_command(GString *text, const gchar *file_name,
629 const gchar *file_type, const gchar *func_name)
631 gchar *match;
633 g_return_if_fail(text != NULL);
635 while ((match = strstr(text->str, "{command:")) != NULL)
637 gchar *wildcard;
638 gchar *cmd = match;
639 gchar *result;
641 while (*match != '}' && *match != '\0')
642 match++;
644 wildcard = g_strndup(cmd, (gsize) (match - cmd + 1));
645 cmd = g_strndup(wildcard + 9, strlen(wildcard) - 10);
647 result = run_command(cmd, file_name, file_type, func_name);
648 if (result != NULL)
650 result = g_strstrip(result);
651 utils_string_replace_first(text, wildcard, result);
652 g_free(result);
654 else
655 utils_string_replace_first(text, wildcard, "");
657 g_free(wildcard);
658 g_free(cmd);