Docs: use quotes instead of firstterm
[platform/upstream/glib.git] / glib / gkeyfile.c
1 /* gkeyfile.c - key file parser
2  *
3  *  Copyright 2004  Red Hat, Inc.  
4  *  Copyright 2009-2010  Collabora Ltd.
5  *  Copyright 2009  Nokia Corporation
6  *
7  * Written by Ray Strode <rstrode@redhat.com>
8  *            Matthias Clasen <mclasen@redhat.com>
9  *
10  * GLib is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU Lesser General Public License as
12  * published by the Free Software Foundation; either version 2 of the
13  * License, or (at your option) any later version.
14  *
15  * GLib is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with GLib; see the file COPYING.LIB.  If not,
22  * see <http://www.gnu.org/licenses/>.
23  */
24
25 #include "config.h"
26
27 #include "gkeyfile.h"
28 #include "gutils.h"
29
30 #include <errno.h>
31 #include <fcntl.h>
32 #include <locale.h>
33 #include <string.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #ifdef G_OS_UNIX
39 #include <unistd.h>
40 #endif
41 #ifdef G_OS_WIN32
42 #include <io.h>
43
44 #undef fstat
45 #define fstat(a,b) _fstati64(a,b)
46 #undef stat
47 #define stat _stati64
48
49 #ifndef S_ISREG
50 #define S_ISREG(mode) ((mode)&_S_IFREG)
51 #endif
52
53 #endif  /* G_OS_WIN23 */
54
55 #include "gconvert.h"
56 #include "gdataset.h"
57 #include "gerror.h"
58 #include "gfileutils.h"
59 #include "ghash.h"
60 #include "glibintl.h"
61 #include "glist.h"
62 #include "gslist.h"
63 #include "gmem.h"
64 #include "gmessages.h"
65 #include "gstdio.h"
66 #include "gstring.h"
67 #include "gstrfuncs.h"
68 #include "gutils.h"
69
70
71 /**
72  * SECTION:keyfile
73  * @title: Key-value file parser
74  * @short_description: parses .ini-like config files
75  *
76  * #GKeyFile lets you parse, edit or create files containing groups of
77  * key-value pairs, which we call "key files" for lack of a better name.
78  * Several freedesktop.org specifications use key files now, e.g the
79  * [Desktop Entry Specification](http://freedesktop.org/Standards/desktop-entry-spec)
80  * and the
81  * [Icon Theme Specification](http://freedesktop.org/Standards/icon-theme-spec).
82  *
83  * The syntax of key files is described in detail in the
84  * [Desktop Entry Specification](http://freedesktop.org/Standards/desktop-entry-spec),
85  * here is a quick summary: Key files
86  * consists of groups of key-value pairs, interspersed with comments.
87  *
88  * |[
89  * # this is just an example
90  * # there can be comments before the first group
91  *
92  * [First Group]
93  *
94  * Name=Key File Example\tthis value shows\nescaping
95  *
96  * # localized strings are stored in multiple key-value pairs
97  * Welcome=Hello
98  * Welcome[de]=Hallo
99  * Welcome[fr_FR]=Bonjour
100  * Welcome[it]=Ciao
101  * Welcome[be@latin]=Hello
102  *
103  * [Another Group]
104  *
105  * Numbers=2;20;-200;0
106  *
107  * Booleans=true;false;true;true
108  * ]|
109  *
110  * Lines beginning with a '#' and blank lines are considered comments.
111  *
112  * Groups are started by a header line containing the group name enclosed
113  * in '[' and ']', and ended implicitly by the start of the next group or
114  * the end of the file. Each key-value pair must be contained in a group.
115  *
116  * Key-value pairs generally have the form <literal>key=value</literal>,
117  * with the exception of localized strings, which have the form
118  * <literal>key[locale]=value</literal>, with a locale identifier of the
119  * form <literal>lang_COUNTRY\@MODIFIER</literal>
120  * where <literal>COUNTRY</literal> and <literal>MODIFIER</literal>
121  * are optional.
122  * Space before and after the '=' character are ignored. Newline, tab,
123  * carriage return and backslash characters in value are escaped as \n,
124  * \t, \r, and \\, respectively. To preserve leading spaces in values,
125  * these can also be escaped as \s.
126  *
127  * Key files can store strings (possibly with localized variants), integers,
128  * booleans and lists of these. Lists are separated by a separator character,
129  * typically ';' or ','. To use the list separator character in a value in
130  * a list, it has to be escaped by prefixing it with a backslash.
131  *
132  * This syntax is obviously inspired by the .ini files commonly met
133  * on Windows, but there are some important differences:
134  *
135  * - .ini files use the ';' character to begin comments,
136  *   key files use the '#' character.
137  *
138  * - Key files do not allow for ungrouped keys meaning only
139  *   comments can precede the first group.
140  *
141  * - Key files are always encoded in UTF-8.
142  *
143  * - Key and Group names are case-sensitive. For example, a group called
144  *   [GROUP] is a different from [group].
145  *
146  * - .ini files don't have a strongly typed boolean entry type,
147  *    they only have GetProfileInt(). In key files, only
148  *    true and false (in lower case) are allowed.
149  *
150  * Note that in contrast to the
151  * [Desktop Entry Specification](http://freedesktop.org/Standards/desktop-entry-spec),
152  * groups in key files may contain the same
153  * key multiple times; the last entry wins. Key files may also contain
154  * multiple groups with the same name; they are merged together.
155  * Another difference is that keys and group names in key files are not
156  * restricted to ASCII characters.
157  */
158
159 /**
160  * G_KEY_FILE_ERROR:
161  *
162  * Error domain for key file parsing. Errors in this domain will
163  * be from the #GKeyFileError enumeration.
164  *
165  * See #GError for information on error domains.
166  */
167
168 /**
169  * GKeyFileError:
170  * @G_KEY_FILE_ERROR_UNKNOWN_ENCODING: the text being parsed was in
171  *     an unknown encoding
172  * @G_KEY_FILE_ERROR_PARSE: document was ill-formed
173  * @G_KEY_FILE_ERROR_NOT_FOUND: the file was not found
174  * @G_KEY_FILE_ERROR_KEY_NOT_FOUND: a requested key was not found
175  * @G_KEY_FILE_ERROR_GROUP_NOT_FOUND: a requested group was not found
176  * @G_KEY_FILE_ERROR_INVALID_VALUE: a value could not be parsed
177  *
178  * Error codes returned by key file parsing.
179  */
180
181 /**
182  * GKeyFileFlags:
183  * @G_KEY_FILE_NONE: No flags, default behaviour
184  * @G_KEY_FILE_KEEP_COMMENTS: Use this flag if you plan to write the
185  *     (possibly modified) contents of the key file back to a file;
186  *     otherwise all comments will be lost when the key file is
187  *     written back.
188  * @G_KEY_FILE_KEEP_TRANSLATIONS: Use this flag if you plan to write the
189  *     (possibly modified) contents of the key file back to a file;
190  *     otherwise only the translations for the current language will be
191  *     written back.
192  *
193  * Flags which influence the parsing.
194  */
195
196 /**
197  * G_KEY_FILE_DESKTOP_GROUP:
198  *
199  * The name of the main group of a desktop entry file, as defined in the
200  * [Desktop Entry Specification](http://freedesktop.org/Standards/desktop-entry-spec).
201  * Consult the specification for more
202  * details about the meanings of the keys below.
203  *
204  * Since: 2.14
205  */
206
207 /**
208  * G_KEY_FILE_DESKTOP_KEY_TYPE:
209  *
210  * A key under #G_KEY_FILE_DESKTOP_GROUP, whose value is a string
211  * giving the type of the desktop entry. Usually
212  * #G_KEY_FILE_DESKTOP_TYPE_APPLICATION,
213  * #G_KEY_FILE_DESKTOP_TYPE_LINK, or
214  * #G_KEY_FILE_DESKTOP_TYPE_DIRECTORY.
215  *
216  * Since: 2.14
217  */
218
219 /**
220  * G_KEY_FILE_DESKTOP_KEY_VERSION:
221  *
222  * A key under #G_KEY_FILE_DESKTOP_GROUP, whose value is a string
223  * giving the version of the Desktop Entry Specification used for
224  * the desktop entry file.
225  *
226  * Since: 2.14
227  */
228
229 /**
230  * G_KEY_FILE_DESKTOP_KEY_NAME:
231  *
232  * A key under #G_KEY_FILE_DESKTOP_GROUP, whose value is a localized
233  * string giving the specific name of the desktop entry.
234  *
235  * Since: 2.14
236  */
237
238 /**
239  * G_KEY_FILE_DESKTOP_KEY_GENERIC_NAME:
240  *
241  * A key under #G_KEY_FILE_DESKTOP_GROUP, whose value is a localized
242  * string giving the generic name of the desktop entry.
243  *
244  * Since: 2.14
245  */
246
247 /**
248  * G_KEY_FILE_DESKTOP_KEY_NO_DISPLAY:
249  *
250  * A key under #G_KEY_FILE_DESKTOP_GROUP, whose value is a boolean
251  * stating whether the desktop entry should be shown in menus.
252  *
253  * Since: 2.14
254  */
255
256 /**
257  * G_KEY_FILE_DESKTOP_KEY_COMMENT:
258  *
259  * A key under #G_KEY_FILE_DESKTOP_GROUP, whose value is a localized
260  * string giving the tooltip for the desktop entry.
261  *
262  * Since: 2.14
263  */
264
265 /**
266  * G_KEY_FILE_DESKTOP_KEY_ICON:
267  *
268  * A key under #G_KEY_FILE_DESKTOP_GROUP, whose value is a localized
269  * string giving the name of the icon to be displayed for the desktop
270  * entry.
271  *
272  * Since: 2.14
273  */
274
275 /**
276  * G_KEY_FILE_DESKTOP_KEY_HIDDEN:
277  *
278  * A key under #G_KEY_FILE_DESKTOP_GROUP, whose value is a boolean
279  * stating whether the desktop entry has been deleted by the user.
280  *
281  * Since: 2.14
282  */
283
284 /**
285  * G_KEY_FILE_DESKTOP_KEY_ONLY_SHOW_IN:
286  *
287  * A key under #G_KEY_FILE_DESKTOP_GROUP, whose value is a list of
288  * strings identifying the environments that should display the
289  * desktop entry.
290  *
291  * Since: 2.14
292  */
293
294 /**
295  * G_KEY_FILE_DESKTOP_KEY_NOT_SHOW_IN:
296  *
297  * A key under #G_KEY_FILE_DESKTOP_GROUP, whose value is a list of
298  * strings identifying the environments that should not display the
299  * desktop entry.
300  *
301  * Since: 2.14
302  */
303
304 /**
305  * G_KEY_FILE_DESKTOP_KEY_TRY_EXEC:
306  *
307  * A key under #G_KEY_FILE_DESKTOP_GROUP, whose value is a string
308  * giving the file name of a binary on disk used to determine if the
309  * program is actually installed. It is only valid for desktop entries
310  * with the <literal>Application</literal> type.
311  *
312  * Since: 2.14
313  */
314
315 /**
316  * G_KEY_FILE_DESKTOP_KEY_EXEC:
317  *
318  * A key under #G_KEY_FILE_DESKTOP_GROUP, whose value is a string
319  * giving the command line to execute. It is only valid for desktop
320  * entries with the <literal>Application</literal> type.
321  *
322  * Since: 2.14
323  */
324
325  /**
326   * G_KEY_FILE_DESKTOP_KEY_PATH:
327   *
328   * A key under #G_KEY_FILE_DESKTOP_GROUP, whose value is a string
329   * containing the working directory to run the program in. It is only
330   * valid for desktop entries with the <literal>Application</literal> type.
331   *
332   * Since: 2.14
333   */
334
335 /**
336  * G_KEY_FILE_DESKTOP_KEY_TERMINAL:
337  *
338  * A key under #G_KEY_FILE_DESKTOP_GROUP, whose value is a boolean
339  * stating whether the program should be run in a terminal window.
340  * It is only valid for desktop entries with the
341  * <literal>Application</literal> type.
342  *
343  * Since: 2.14
344  */
345
346 /**
347  * G_KEY_FILE_DESKTOP_KEY_MIME_TYPE:
348  *
349  * A key under #G_KEY_FILE_DESKTOP_GROUP, whose value is a list
350  * of strings giving the MIME types supported by this desktop entry.
351  *
352  * Since: 2.14
353  */
354
355 /**
356  * G_KEY_FILE_DESKTOP_KEY_CATEGORIES:
357  *
358  * A key under #G_KEY_FILE_DESKTOP_GROUP, whose value is a list
359  * of strings giving the categories in which the desktop entry
360  * should be shown in a menu.
361  *
362  * Since: 2.14
363  */
364
365 /**
366  * G_KEY_FILE_DESKTOP_KEY_STARTUP_NOTIFY:
367  *
368  * A key under #G_KEY_FILE_DESKTOP_GROUP, whose value is a boolean
369  * stating whether the application supports the
370  * [Startup Notification Protocol Specification](http://www.freedesktop.org/Standards/startup-notification-spec).
371  *
372  * Since: 2.14
373  */
374
375 /**
376  * G_KEY_FILE_DESKTOP_KEY_STARTUP_WM_CLASS:
377  *
378  * A key under #G_KEY_FILE_DESKTOP_GROUP, whose value is string
379  * identifying the WM class or name hint of a window that the application
380  * will create, which can be used to emulate Startup Notification with
381  * older applications.
382  *
383  * Since: 2.14
384  */
385
386 /**
387  * G_KEY_FILE_DESKTOP_KEY_URL :
388  *
389  * A key under #G_KEY_FILE_DESKTOP_GROUP, whose value is a string
390  * giving the URL to access. It is only valid for desktop entries
391  * with the <literal>Link</literal> type.
392  *
393  * Since: 2.14
394  */
395
396 /**
397  * G_KEY_FILE_DESKTOP_TYPE_APPLICATION:
398  *
399  * The value of the #G_KEY_FILE_DESKTOP_KEY_TYPE, key for desktop
400  * entries representing applications.
401  *
402  * Since: 2.14
403  */
404
405 /**
406  * G_KEY_FILE_DESKTOP_TYPE_LINK:
407  *
408  * The value of the #G_KEY_FILE_DESKTOP_KEY_TYPE, key for desktop
409  * entries representing links to documents.
410  *
411  * Since: 2.14
412  */
413
414 /**
415  * G_KEY_FILE_DESKTOP_TYPE_DIRECTORY:
416  *
417  * The value of the #G_KEY_FILE_DESKTOP_KEY_TYPE, key for desktop
418  * entries representing directories.
419  *
420  * Since: 2.14
421  */
422
423 typedef struct _GKeyFileGroup GKeyFileGroup;
424
425 /**
426  * GKeyFile:
427  *
428  * The GKeyFile struct contains only private data
429  * and should not be accessed directly.
430  */
431 struct _GKeyFile
432 {
433   GList *groups;
434   GHashTable *group_hash;
435
436   GKeyFileGroup *start_group;
437   GKeyFileGroup *current_group;
438
439   GString *parse_buffer; /* Holds up to one line of not-yet-parsed data */
440
441   gchar list_separator;
442
443   GKeyFileFlags flags;
444
445   gchar **locales;
446
447   volatile gint ref_count;
448 };
449
450 typedef struct _GKeyFileKeyValuePair GKeyFileKeyValuePair;
451
452 struct _GKeyFileGroup
453 {
454   const gchar *name;  /* NULL for above first group (which will be comments) */
455
456   GKeyFileKeyValuePair *comment; /* Special comment that is stuck to the top of a group */
457
458   GList *key_value_pairs;
459
460   /* Used in parallel with key_value_pairs for
461    * increased lookup performance
462    */
463   GHashTable *lookup_map;
464 };
465
466 struct _GKeyFileKeyValuePair
467 {
468   gchar *key;  /* NULL for comments */
469   gchar *value;
470 };
471
472 static gint                  find_file_in_data_dirs            (const gchar            *file,
473                                                                 const gchar           **data_dirs,
474                                                                 gchar                 **output_file,
475                                                                 GError                **error);
476 static gboolean              g_key_file_load_from_fd           (GKeyFile               *key_file,
477                                                                 gint                    fd,
478                                                                 GKeyFileFlags           flags,
479                                                                 GError                **error);
480 static GList                *g_key_file_lookup_group_node      (GKeyFile               *key_file,
481                                                                 const gchar            *group_name);
482 static GKeyFileGroup        *g_key_file_lookup_group           (GKeyFile               *key_file,
483                                                                 const gchar            *group_name);
484
485 static GList                *g_key_file_lookup_key_value_pair_node  (GKeyFile       *key_file,
486                                                                      GKeyFileGroup  *group,
487                                                                      const gchar    *key);
488 static GKeyFileKeyValuePair *g_key_file_lookup_key_value_pair       (GKeyFile       *key_file,
489                                                                      GKeyFileGroup  *group,
490                                                                      const gchar    *key);
491
492 static void                  g_key_file_remove_group_node          (GKeyFile      *key_file,
493                                                                     GList         *group_node);
494 static void                  g_key_file_remove_key_value_pair_node (GKeyFile      *key_file,
495                                                                     GKeyFileGroup *group,
496                                                                     GList         *pair_node);
497
498 static void                  g_key_file_add_key_value_pair     (GKeyFile               *key_file,
499                                                                 GKeyFileGroup          *group,
500                                                                 GKeyFileKeyValuePair   *pair);
501 static void                  g_key_file_add_key                (GKeyFile               *key_file,
502                                                                 GKeyFileGroup          *group,
503                                                                 const gchar            *key,
504                                                                 const gchar            *value);
505 static void                  g_key_file_add_group              (GKeyFile               *key_file,
506                                                                 const gchar            *group_name);
507 static gboolean              g_key_file_is_group_name          (const gchar *name);
508 static gboolean              g_key_file_is_key_name            (const gchar *name);
509 static void                  g_key_file_key_value_pair_free    (GKeyFileKeyValuePair   *pair);
510 static gboolean              g_key_file_line_is_comment        (const gchar            *line);
511 static gboolean              g_key_file_line_is_group          (const gchar            *line);
512 static gboolean              g_key_file_line_is_key_value_pair (const gchar            *line);
513 static gchar                *g_key_file_parse_value_as_string  (GKeyFile               *key_file,
514                                                                 const gchar            *value,
515                                                                 GSList                **separators,
516                                                                 GError                **error);
517 static gchar                *g_key_file_parse_string_as_value  (GKeyFile               *key_file,
518                                                                 const gchar            *string,
519                                                                 gboolean                escape_separator);
520 static gint                  g_key_file_parse_value_as_integer (GKeyFile               *key_file,
521                                                                 const gchar            *value,
522                                                                 GError                **error);
523 static gchar                *g_key_file_parse_integer_as_value (GKeyFile               *key_file,
524                                                                 gint                    value);
525 static gdouble               g_key_file_parse_value_as_double  (GKeyFile               *key_file,
526                                                                 const gchar            *value,
527                                                                 GError                **error);
528 static gboolean              g_key_file_parse_value_as_boolean (GKeyFile               *key_file,
529                                                                 const gchar            *value,
530                                                                 GError                **error);
531 static gchar                *g_key_file_parse_boolean_as_value (GKeyFile               *key_file,
532                                                                 gboolean                value);
533 static gchar                *g_key_file_parse_value_as_comment (GKeyFile               *key_file,
534                                                                 const gchar            *value);
535 static gchar                *g_key_file_parse_comment_as_value (GKeyFile               *key_file,
536                                                                 const gchar            *comment);
537 static void                  g_key_file_parse_key_value_pair   (GKeyFile               *key_file,
538                                                                 const gchar            *line,
539                                                                 gsize                   length,
540                                                                 GError                **error);
541 static void                  g_key_file_parse_comment          (GKeyFile               *key_file,
542                                                                 const gchar            *line,
543                                                                 gsize                   length,
544                                                                 GError                **error);
545 static void                  g_key_file_parse_group            (GKeyFile               *key_file,
546                                                                 const gchar            *line,
547                                                                 gsize                   length,
548                                                                 GError                **error);
549 static gchar                *key_get_locale                    (const gchar            *key);
550 static void                  g_key_file_parse_data             (GKeyFile               *key_file,
551                                                                 const gchar            *data,
552                                                                 gsize                   length,
553                                                                 GError                **error);
554 static void                  g_key_file_flush_parse_buffer     (GKeyFile               *key_file,
555                                                                 GError                **error);
556
557 G_DEFINE_QUARK (g-key-file-error-quark, g_key_file_error)
558
559 static void
560 g_key_file_init (GKeyFile *key_file)
561 {  
562   key_file->current_group = g_slice_new0 (GKeyFileGroup);
563   key_file->groups = g_list_prepend (NULL, key_file->current_group);
564   key_file->group_hash = g_hash_table_new (g_str_hash, g_str_equal);
565   key_file->start_group = NULL;
566   key_file->parse_buffer = g_string_sized_new (128);
567   key_file->list_separator = ';';
568   key_file->flags = 0;
569   key_file->locales = g_strdupv ((gchar **)g_get_language_names ());
570 }
571
572 static void
573 g_key_file_clear (GKeyFile *key_file)
574 {
575   GList *tmp, *group_node;
576
577   if (key_file->locales) 
578     {
579       g_strfreev (key_file->locales);
580       key_file->locales = NULL;
581     }
582
583   if (key_file->parse_buffer)
584     {
585       g_string_free (key_file->parse_buffer, TRUE);
586       key_file->parse_buffer = NULL;
587     }
588
589   tmp = key_file->groups;
590   while (tmp != NULL)
591     {
592       group_node = tmp;
593       tmp = tmp->next;
594       g_key_file_remove_group_node (key_file, group_node);
595     }
596
597   if (key_file->group_hash != NULL)
598     {
599       g_hash_table_destroy (key_file->group_hash);
600       key_file->group_hash = NULL;
601     }
602
603   g_warn_if_fail (key_file->groups == NULL);
604 }
605
606
607 /**
608  * g_key_file_new:
609  *
610  * Creates a new empty #GKeyFile object. Use
611  * g_key_file_load_from_file(), g_key_file_load_from_data(),
612  * g_key_file_load_from_dirs() or g_key_file_load_from_data_dirs() to
613  * read an existing key file.
614  *
615  * Return value: (transfer full): an empty #GKeyFile.
616  *
617  * Since: 2.6
618  **/
619 GKeyFile *
620 g_key_file_new (void)
621 {
622   GKeyFile *key_file;
623
624   key_file = g_slice_new0 (GKeyFile);
625   key_file->ref_count = 1;
626   g_key_file_init (key_file);
627
628   return key_file;
629 }
630
631 /**
632  * g_key_file_set_list_separator:
633  * @key_file: a #GKeyFile 
634  * @separator: the separator
635  *
636  * Sets the character which is used to separate
637  * values in lists. Typically ';' or ',' are used
638  * as separators. The default list separator is ';'.
639  *
640  * Since: 2.6
641  */
642 void
643 g_key_file_set_list_separator (GKeyFile *key_file,
644                                gchar     separator)
645 {
646   g_return_if_fail (key_file != NULL);
647
648   key_file->list_separator = separator;
649 }
650
651
652 /* Iterates through all the directories in *dirs trying to
653  * open file.  When it successfully locates and opens a file it
654  * returns the file descriptor to the open file.  It also
655  * outputs the absolute path of the file in output_file.
656  */
657 static gint
658 find_file_in_data_dirs (const gchar   *file,
659                         const gchar  **dirs,
660                         gchar        **output_file,
661                         GError       **error)
662 {
663   const gchar **data_dirs, *data_dir;
664   gchar *path;
665   gint fd;
666
667   path = NULL;
668   fd = -1;
669
670   if (dirs == NULL)
671     return fd;
672
673   data_dirs = dirs;
674
675   while (data_dirs && (data_dir = *data_dirs) && fd == -1)
676     {
677       gchar *candidate_file, *sub_dir;
678
679       candidate_file = (gchar *) file;
680       sub_dir = g_strdup ("");
681       while (candidate_file != NULL && fd == -1)
682         {
683           gchar *p;
684
685           path = g_build_filename (data_dir, sub_dir,
686                                    candidate_file, NULL);
687
688           fd = g_open (path, O_RDONLY, 0);
689
690           if (fd == -1)
691             {
692               g_free (path);
693               path = NULL;
694             }
695
696           candidate_file = strchr (candidate_file, '-');
697
698           if (candidate_file == NULL)
699             break;
700
701           candidate_file++;
702
703           g_free (sub_dir);
704           sub_dir = g_strndup (file, candidate_file - file - 1);
705
706           for (p = sub_dir; *p != '\0'; p++)
707             {
708               if (*p == '-')
709                 *p = G_DIR_SEPARATOR;
710             }
711         }
712       g_free (sub_dir);
713       data_dirs++;
714     }
715
716   if (fd == -1)
717     {
718       g_set_error_literal (error, G_KEY_FILE_ERROR,
719                            G_KEY_FILE_ERROR_NOT_FOUND,
720                            _("Valid key file could not be "
721                              "found in search dirs"));
722     }
723
724   if (output_file != NULL && fd > 0)
725     *output_file = g_strdup (path);
726
727   g_free (path);
728
729   return fd;
730 }
731
732 static gboolean
733 g_key_file_load_from_fd (GKeyFile       *key_file,
734                          gint            fd,
735                          GKeyFileFlags   flags,
736                          GError        **error)
737 {
738   GError *key_file_error = NULL;
739   gssize bytes_read;
740   struct stat stat_buf;
741   gchar read_buf[4096];
742   gchar list_separator;
743
744   if (fstat (fd, &stat_buf) < 0)
745     {
746       g_set_error_literal (error, G_FILE_ERROR,
747                            g_file_error_from_errno (errno),
748                            g_strerror (errno));
749       return FALSE;
750     }
751
752   if (!S_ISREG (stat_buf.st_mode))
753     {
754       g_set_error_literal (error, G_KEY_FILE_ERROR,
755                            G_KEY_FILE_ERROR_PARSE,
756                            _("Not a regular file"));
757       return FALSE;
758     }
759
760   list_separator = key_file->list_separator;
761   g_key_file_clear (key_file);
762   g_key_file_init (key_file);
763   key_file->list_separator = list_separator;
764   key_file->flags = flags;
765
766   do
767     {
768       bytes_read = read (fd, read_buf, 4096);
769
770       if (bytes_read == 0)  /* End of File */
771         break;
772
773       if (bytes_read < 0)
774         {
775           if (errno == EINTR || errno == EAGAIN)
776             continue;
777
778           g_set_error_literal (error, G_FILE_ERROR,
779                                g_file_error_from_errno (errno),
780                                g_strerror (errno));
781           return FALSE;
782         }
783
784       g_key_file_parse_data (key_file,
785                              read_buf, bytes_read,
786                              &key_file_error);
787     }
788   while (!key_file_error);
789
790   if (key_file_error)
791     {
792       g_propagate_error (error, key_file_error);
793       return FALSE;
794     }
795
796   g_key_file_flush_parse_buffer (key_file, &key_file_error);
797
798   if (key_file_error)
799     {
800       g_propagate_error (error, key_file_error);
801       return FALSE;
802     }
803
804   return TRUE;
805 }
806
807 /**
808  * g_key_file_load_from_file:
809  * @key_file: an empty #GKeyFile struct
810  * @file: (type filename): the path of a filename to load, in the GLib filename encoding
811  * @flags: flags from #GKeyFileFlags
812  * @error: return location for a #GError, or %NULL
813  *
814  * Loads a key file into an empty #GKeyFile structure.
815  * If the file could not be loaded then @error is set to
816  * either a #GFileError or #GKeyFileError.
817  *
818  * Return value: %TRUE if a key file could be loaded, %FALSE otherwise
819  *
820  * Since: 2.6
821  **/
822 gboolean
823 g_key_file_load_from_file (GKeyFile       *key_file,
824                            const gchar    *file,
825                            GKeyFileFlags   flags,
826                            GError        **error)
827 {
828   GError *key_file_error = NULL;
829   gint fd;
830
831   g_return_val_if_fail (key_file != NULL, FALSE);
832   g_return_val_if_fail (file != NULL, FALSE);
833
834   fd = g_open (file, O_RDONLY, 0);
835
836   if (fd == -1)
837     {
838       g_set_error_literal (error, G_FILE_ERROR,
839                            g_file_error_from_errno (errno),
840                            g_strerror (errno));
841       return FALSE;
842     }
843
844   g_key_file_load_from_fd (key_file, fd, flags, &key_file_error);
845   close (fd);
846
847   if (key_file_error)
848     {
849       g_propagate_error (error, key_file_error);
850       return FALSE;
851     }
852
853   return TRUE;
854 }
855
856 /**
857  * g_key_file_load_from_data:
858  * @key_file: an empty #GKeyFile struct
859  * @data: key file loaded in memory
860  * @length: the length of @data in bytes (or (gsize)-1 if data is nul-terminated)
861  * @flags: flags from #GKeyFileFlags
862  * @error: return location for a #GError, or %NULL
863  *
864  * Loads a key file from memory into an empty #GKeyFile structure.  
865  * If the object cannot be created then %error is set to a #GKeyFileError. 
866  *
867  * Return value: %TRUE if a key file could be loaded, %FALSE otherwise
868  *
869  * Since: 2.6
870  **/
871 gboolean
872 g_key_file_load_from_data (GKeyFile       *key_file,
873                            const gchar    *data,
874                            gsize           length,
875                            GKeyFileFlags   flags,
876                            GError        **error)
877 {
878   GError *key_file_error = NULL;
879   gchar list_separator;
880
881   g_return_val_if_fail (key_file != NULL, FALSE);
882   g_return_val_if_fail (data != NULL || length == 0, FALSE);
883
884   if (length == (gsize)-1)
885     length = strlen (data);
886
887   list_separator = key_file->list_separator;
888   g_key_file_clear (key_file);
889   g_key_file_init (key_file);
890   key_file->list_separator = list_separator;
891   key_file->flags = flags;
892
893   g_key_file_parse_data (key_file, data, length, &key_file_error);
894   
895   if (key_file_error)
896     {
897       g_propagate_error (error, key_file_error);
898       return FALSE;
899     }
900
901   g_key_file_flush_parse_buffer (key_file, &key_file_error);
902   
903   if (key_file_error)
904     {
905       g_propagate_error (error, key_file_error);
906       return FALSE;
907     }
908
909   return TRUE;
910 }
911
912 /**
913  * g_key_file_load_from_dirs:
914  * @key_file: an empty #GKeyFile struct
915  * @file: (type filename): a relative path to a filename to open and parse
916  * @search_dirs: (array zero-terminated=1) (element-type filename): %NULL-terminated array of directories to search
917  * @full_path: (out) (type filename) (allow-none): return location for a string containing the full path
918  *   of the file, or %NULL
919  * @flags: flags from #GKeyFileFlags
920  * @error: return location for a #GError, or %NULL
921  *
922  * This function looks for a key file named @file in the paths
923  * specified in @search_dirs, loads the file into @key_file and
924  * returns the file's full path in @full_path.  If the file could not
925  * be loaded then an %error is set to either a #GFileError or
926  * #GKeyFileError.
927  *
928  * Return value: %TRUE if a key file could be loaded, %FALSE otherwise
929  *
930  * Since: 2.14
931  **/
932 gboolean
933 g_key_file_load_from_dirs (GKeyFile       *key_file,
934                            const gchar    *file,
935                            const gchar   **search_dirs,
936                            gchar         **full_path,
937                            GKeyFileFlags   flags,
938                            GError        **error)
939 {
940   GError *key_file_error = NULL;
941   const gchar **data_dirs;
942   gchar *output_path;
943   gint fd;
944   gboolean found_file;
945
946   g_return_val_if_fail (key_file != NULL, FALSE);
947   g_return_val_if_fail (!g_path_is_absolute (file), FALSE);
948   g_return_val_if_fail (search_dirs != NULL, FALSE);
949
950   found_file = FALSE;
951   data_dirs = search_dirs;
952   output_path = NULL;
953   while (*data_dirs != NULL && !found_file)
954     {
955       g_free (output_path);
956
957       fd = find_file_in_data_dirs (file, data_dirs, &output_path,
958                                    &key_file_error);
959
960       if (fd == -1)
961         {
962           if (key_file_error)
963             g_propagate_error (error, key_file_error);
964           break;
965         }
966
967       found_file = g_key_file_load_from_fd (key_file, fd, flags,
968                                             &key_file_error);
969       close (fd);
970
971       if (key_file_error)
972         {
973           g_propagate_error (error, key_file_error);
974           break;
975         }
976     }
977
978   if (found_file && full_path)
979     *full_path = output_path;
980   else
981     g_free (output_path);
982
983   return found_file;
984 }
985
986 /**
987  * g_key_file_load_from_data_dirs:
988  * @key_file: an empty #GKeyFile struct
989  * @file: (type filename): a relative path to a filename to open and parse
990  * @full_path: (out) (type filename) (allow-none): return location for a string containing the full path
991  *   of the file, or %NULL
992  * @flags: flags from #GKeyFileFlags 
993  * @error: return location for a #GError, or %NULL
994  *
995  * This function looks for a key file named @file in the paths 
996  * returned from g_get_user_data_dir() and g_get_system_data_dirs(), 
997  * loads the file into @key_file and returns the file's full path in 
998  * @full_path.  If the file could not be loaded then an %error is
999  * set to either a #GFileError or #GKeyFileError.
1000  *
1001  * Return value: %TRUE if a key file could be loaded, %FALSE othewise
1002  * Since: 2.6
1003  **/
1004 gboolean
1005 g_key_file_load_from_data_dirs (GKeyFile       *key_file,
1006                                 const gchar    *file,
1007                                 gchar         **full_path,
1008                                 GKeyFileFlags   flags,
1009                                 GError        **error)
1010 {
1011   gchar **all_data_dirs;
1012   const gchar * user_data_dir;
1013   const gchar * const * system_data_dirs;
1014   gsize i, j;
1015   gboolean found_file;
1016
1017   g_return_val_if_fail (key_file != NULL, FALSE);
1018   g_return_val_if_fail (!g_path_is_absolute (file), FALSE);
1019
1020   user_data_dir = g_get_user_data_dir ();
1021   system_data_dirs = g_get_system_data_dirs ();
1022   all_data_dirs = g_new (gchar *, g_strv_length ((gchar **)system_data_dirs) + 2);
1023
1024   i = 0;
1025   all_data_dirs[i++] = g_strdup (user_data_dir);
1026
1027   j = 0;
1028   while (system_data_dirs[j] != NULL)
1029     all_data_dirs[i++] = g_strdup (system_data_dirs[j++]);
1030   all_data_dirs[i] = NULL;
1031
1032   found_file = g_key_file_load_from_dirs (key_file,
1033                                           file,
1034                                           (const gchar **)all_data_dirs,
1035                                           full_path,
1036                                           flags,
1037                                           error);
1038
1039   g_strfreev (all_data_dirs);
1040
1041   return found_file;
1042 }
1043
1044 /**
1045  * g_key_file_ref: (skip)
1046  * @key_file: a #GKeyFile
1047  *
1048  * Increases the reference count of @key_file.
1049  *
1050  * Returns: the same @key_file.
1051  *
1052  * Since: 2.32
1053  **/
1054 GKeyFile *
1055 g_key_file_ref (GKeyFile *key_file)
1056 {
1057   g_return_val_if_fail (key_file != NULL, NULL);
1058
1059   g_atomic_int_inc (&key_file->ref_count);
1060
1061   return key_file;
1062 }
1063
1064 /**
1065  * g_key_file_free: (skip)
1066  * @key_file: a #GKeyFile
1067  *
1068  * Clears all keys and groups from @key_file, and decreases the
1069  * reference count by 1. If the reference count reaches zero,
1070  * frees the key file and all its allocated memory.
1071  *
1072  * Since: 2.6
1073  **/
1074 void
1075 g_key_file_free (GKeyFile *key_file)
1076 {
1077   g_return_if_fail (key_file != NULL);
1078
1079   g_key_file_clear (key_file);
1080   g_key_file_unref (key_file);
1081 }
1082
1083 /**
1084  * g_key_file_unref:
1085  * @key_file: a #GKeyFile
1086  *
1087  * Decreases the reference count of @key_file by 1. If the reference count
1088  * reaches zero, frees the key file and all its allocated memory.
1089  *
1090  * Since: 2.32
1091  **/
1092 void
1093 g_key_file_unref (GKeyFile *key_file)
1094 {
1095   g_return_if_fail (key_file != NULL);
1096
1097   if (g_atomic_int_dec_and_test (&key_file->ref_count))
1098     {
1099       g_key_file_clear (key_file);
1100       g_slice_free (GKeyFile, key_file);
1101     }
1102 }
1103
1104 /* If G_KEY_FILE_KEEP_TRANSLATIONS is not set, only returns
1105  * true for locales that match those in g_get_language_names().
1106  */
1107 static gboolean
1108 g_key_file_locale_is_interesting (GKeyFile    *key_file,
1109                                   const gchar *locale)
1110 {
1111   gsize i;
1112
1113   if (key_file->flags & G_KEY_FILE_KEEP_TRANSLATIONS)
1114     return TRUE;
1115
1116   for (i = 0; key_file->locales[i] != NULL; i++)
1117     {
1118       if (g_ascii_strcasecmp (key_file->locales[i], locale) == 0)
1119         return TRUE;
1120     }
1121
1122   return FALSE;
1123 }
1124
1125 static void
1126 g_key_file_parse_line (GKeyFile     *key_file,
1127                        const gchar  *line,
1128                        gsize         length,
1129                        GError      **error)
1130 {
1131   GError *parse_error = NULL;
1132   gchar *line_start;
1133
1134   g_return_if_fail (key_file != NULL);
1135   g_return_if_fail (line != NULL);
1136
1137   line_start = (gchar *) line;
1138   while (g_ascii_isspace (*line_start))
1139     line_start++;
1140
1141   if (g_key_file_line_is_comment (line_start))
1142     g_key_file_parse_comment (key_file, line, length, &parse_error);
1143   else if (g_key_file_line_is_group (line_start))
1144     g_key_file_parse_group (key_file, line_start,
1145                             length - (line_start - line),
1146                             &parse_error);
1147   else if (g_key_file_line_is_key_value_pair (line_start))
1148     g_key_file_parse_key_value_pair (key_file, line_start,
1149                                      length - (line_start - line),
1150                                      &parse_error);
1151   else
1152     {
1153       gchar *line_utf8 = _g_utf8_make_valid (line);
1154       g_set_error (error, G_KEY_FILE_ERROR,
1155                    G_KEY_FILE_ERROR_PARSE,
1156                    _("Key file contains line '%s' which is not "
1157                      "a key-value pair, group, or comment"),
1158                    line_utf8);
1159       g_free (line_utf8);
1160
1161       return;
1162     }
1163
1164   if (parse_error)
1165     g_propagate_error (error, parse_error);
1166 }
1167
1168 static void
1169 g_key_file_parse_comment (GKeyFile     *key_file,
1170                           const gchar  *line,
1171                           gsize         length,
1172                           GError      **error)
1173 {
1174   GKeyFileKeyValuePair *pair;
1175   
1176   if (!(key_file->flags & G_KEY_FILE_KEEP_COMMENTS))
1177     return;
1178   
1179   g_warn_if_fail (key_file->current_group != NULL);
1180
1181   pair = g_slice_new (GKeyFileKeyValuePair);
1182   pair->key = NULL;
1183   pair->value = g_strndup (line, length);
1184   
1185   key_file->current_group->key_value_pairs =
1186     g_list_prepend (key_file->current_group->key_value_pairs, pair);
1187 }
1188
1189 static void
1190 g_key_file_parse_group (GKeyFile     *key_file,
1191                         const gchar  *line,
1192                         gsize         length,
1193                         GError      **error)
1194 {
1195   gchar *group_name;
1196   const gchar *group_name_start, *group_name_end;
1197   
1198   /* advance past opening '['
1199    */
1200   group_name_start = line + 1;
1201   group_name_end = line + length - 1;
1202   
1203   while (*group_name_end != ']')
1204     group_name_end--;
1205
1206   group_name = g_strndup (group_name_start, 
1207                           group_name_end - group_name_start);
1208   
1209   if (!g_key_file_is_group_name (group_name))
1210     {
1211       g_set_error (error, G_KEY_FILE_ERROR,
1212                    G_KEY_FILE_ERROR_PARSE,
1213                    _("Invalid group name: %s"), group_name);
1214       g_free (group_name);
1215       return;
1216     }
1217
1218   g_key_file_add_group (key_file, group_name);
1219   g_free (group_name);
1220 }
1221
1222 static void
1223 g_key_file_parse_key_value_pair (GKeyFile     *key_file,
1224                                  const gchar  *line,
1225                                  gsize         length,
1226                                  GError      **error)
1227 {
1228   gchar *key, *value, *key_end, *value_start, *locale;
1229   gsize key_len, value_len;
1230
1231   if (key_file->current_group == NULL || key_file->current_group->name == NULL)
1232     {
1233       g_set_error_literal (error, G_KEY_FILE_ERROR,
1234                            G_KEY_FILE_ERROR_GROUP_NOT_FOUND,
1235                            _("Key file does not start with a group"));
1236       return;
1237     }
1238
1239   key_end = value_start = strchr (line, '=');
1240
1241   g_warn_if_fail (key_end != NULL);
1242
1243   key_end--;
1244   value_start++;
1245
1246   /* Pull the key name from the line (chomping trailing whitespace)
1247    */
1248   while (g_ascii_isspace (*key_end))
1249     key_end--;
1250
1251   key_len = key_end - line + 2;
1252
1253   g_warn_if_fail (key_len <= length);
1254
1255   key = g_strndup (line, key_len - 1);
1256
1257   if (!g_key_file_is_key_name (key))
1258     {
1259       g_set_error (error, G_KEY_FILE_ERROR,
1260                    G_KEY_FILE_ERROR_PARSE,
1261                    _("Invalid key name: %s"), key);
1262       g_free (key);
1263       return; 
1264     }
1265
1266   /* Pull the value from the line (chugging leading whitespace)
1267    */
1268   while (g_ascii_isspace (*value_start))
1269     value_start++;
1270
1271   value_len = line + length - value_start + 1;
1272
1273   value = g_strndup (value_start, value_len);
1274
1275   g_warn_if_fail (key_file->start_group != NULL);
1276
1277   if (key_file->current_group
1278       && key_file->current_group->name
1279       && strcmp (key_file->start_group->name,
1280                  key_file->current_group->name) == 0
1281       && strcmp (key, "Encoding") == 0)
1282     {
1283       if (g_ascii_strcasecmp (value, "UTF-8") != 0)
1284         {
1285           gchar *value_utf8 = _g_utf8_make_valid (value);
1286           g_set_error (error, G_KEY_FILE_ERROR,
1287                        G_KEY_FILE_ERROR_UNKNOWN_ENCODING,
1288                        _("Key file contains unsupported "
1289                          "encoding '%s'"), value_utf8);
1290           g_free (value_utf8);
1291
1292           g_free (key);
1293           g_free (value);
1294           return;
1295         }
1296     }
1297
1298   /* Is this key a translation? If so, is it one that we care about?
1299    */
1300   locale = key_get_locale (key);
1301
1302   if (locale == NULL || g_key_file_locale_is_interesting (key_file, locale))
1303     {
1304       GKeyFileKeyValuePair *pair;
1305
1306       pair = g_slice_new (GKeyFileKeyValuePair);
1307       pair->key = key;
1308       pair->value = value;
1309
1310       g_key_file_add_key_value_pair (key_file, key_file->current_group, pair);
1311     }
1312   else
1313     {
1314       g_free (key);
1315       g_free (value);
1316     }
1317
1318   g_free (locale);
1319 }
1320
1321 static gchar *
1322 key_get_locale (const gchar *key)
1323 {
1324   gchar *locale;
1325
1326   locale = g_strrstr (key, "[");
1327
1328   if (locale && strlen (locale) <= 2)
1329     locale = NULL;
1330
1331   if (locale)
1332     locale = g_strndup (locale + 1, strlen (locale) - 2);
1333
1334   return locale;
1335 }
1336
1337 static void
1338 g_key_file_parse_data (GKeyFile     *key_file,
1339                        const gchar  *data,
1340                        gsize         length,
1341                        GError      **error)
1342 {
1343   GError *parse_error;
1344   gsize i;
1345
1346   g_return_if_fail (key_file != NULL);
1347   g_return_if_fail (data != NULL || length == 0);
1348
1349   parse_error = NULL;
1350
1351   i = 0;
1352   while (i < length)
1353     {
1354       if (data[i] == '\n')
1355         {
1356           if (key_file->parse_buffer->len > 0
1357               && (key_file->parse_buffer->str[key_file->parse_buffer->len - 1]
1358                   == '\r'))
1359             g_string_erase (key_file->parse_buffer,
1360                             key_file->parse_buffer->len - 1,
1361                             1);
1362             
1363           /* When a newline is encountered flush the parse buffer so that the
1364            * line can be parsed.  Note that completely blank lines won't show
1365            * up in the parse buffer, so they get parsed directly.
1366            */
1367           if (key_file->parse_buffer->len > 0)
1368             g_key_file_flush_parse_buffer (key_file, &parse_error);
1369           else
1370             g_key_file_parse_comment (key_file, "", 1, &parse_error);
1371
1372           if (parse_error)
1373             {
1374               g_propagate_error (error, parse_error);
1375               return;
1376             }
1377           i++;
1378         }
1379       else
1380         {
1381           const gchar *start_of_line;
1382           const gchar *end_of_line;
1383           gsize line_length;
1384
1385           start_of_line = data + i;
1386           end_of_line = memchr (start_of_line, '\n', length - i);
1387
1388           if (end_of_line == NULL)
1389             end_of_line = data + length;
1390
1391           line_length = end_of_line - start_of_line;
1392
1393           g_string_append_len (key_file->parse_buffer, start_of_line, line_length);
1394           i += line_length;
1395         }
1396     }
1397 }
1398
1399 static void
1400 g_key_file_flush_parse_buffer (GKeyFile  *key_file,
1401                                GError   **error)
1402 {
1403   GError *file_error = NULL;
1404
1405   g_return_if_fail (key_file != NULL);
1406
1407   file_error = NULL;
1408
1409   if (key_file->parse_buffer->len > 0)
1410     {
1411       g_key_file_parse_line (key_file, key_file->parse_buffer->str,
1412                              key_file->parse_buffer->len,
1413                              &file_error);
1414       g_string_erase (key_file->parse_buffer, 0, -1);
1415
1416       if (file_error)
1417         {
1418           g_propagate_error (error, file_error);
1419           return;
1420         }
1421     }
1422 }
1423
1424 /**
1425  * g_key_file_to_data:
1426  * @key_file: a #GKeyFile
1427  * @length: (out) (allow-none): return location for the length of the
1428  *   returned string, or %NULL
1429  * @error: return location for a #GError, or %NULL
1430  *
1431  * This function outputs @key_file as a string.  
1432  *
1433  * Note that this function never reports an error,
1434  * so it is safe to pass %NULL as @error.
1435  *
1436  * Return value: a newly allocated string holding
1437  *   the contents of the #GKeyFile 
1438  *
1439  * Since: 2.6
1440  **/
1441 gchar *
1442 g_key_file_to_data (GKeyFile  *key_file,
1443                     gsize     *length,
1444                     GError   **error)
1445 {
1446   GString *data_string;
1447   GList *group_node, *key_file_node;
1448
1449   g_return_val_if_fail (key_file != NULL, NULL);
1450
1451   data_string = g_string_new (NULL);
1452
1453   for (group_node = g_list_last (key_file->groups);
1454        group_node != NULL;
1455        group_node = group_node->prev)
1456     {
1457       GKeyFileGroup *group;
1458
1459       group = (GKeyFileGroup *) group_node->data;
1460
1461       /* separate groups by at least an empty line */
1462       if (data_string->len >= 2 &&
1463           data_string->str[data_string->len - 2] != '\n')
1464         g_string_append_c (data_string, '\n');
1465
1466       if (group->comment != NULL)
1467         g_string_append_printf (data_string, "%s\n", group->comment->value);
1468
1469       if (group->name != NULL)
1470         g_string_append_printf (data_string, "[%s]\n", group->name);
1471
1472       for (key_file_node = g_list_last (group->key_value_pairs);
1473            key_file_node != NULL;
1474            key_file_node = key_file_node->prev)
1475         {
1476           GKeyFileKeyValuePair *pair;
1477
1478           pair = (GKeyFileKeyValuePair *) key_file_node->data;
1479
1480           if (pair->key != NULL)
1481             g_string_append_printf (data_string, "%s=%s\n", pair->key, pair->value);
1482           else
1483             g_string_append_printf (data_string, "%s\n", pair->value);
1484         }
1485     }
1486
1487   if (length)
1488     *length = data_string->len;
1489
1490   return g_string_free (data_string, FALSE);
1491 }
1492
1493 /**
1494  * g_key_file_get_keys:
1495  * @key_file: a #GKeyFile
1496  * @group_name: a group name
1497  * @length: (out) (allow-none): return location for the number of keys returned, or %NULL
1498  * @error: return location for a #GError, or %NULL
1499  *
1500  * Returns all keys for the group name @group_name.  The array of
1501  * returned keys will be %NULL-terminated, so @length may
1502  * optionally be %NULL. In the event that the @group_name cannot
1503  * be found, %NULL is returned and @error is set to
1504  * #G_KEY_FILE_ERROR_GROUP_NOT_FOUND.
1505  *
1506  * Return value: (array zero-terminated=1) (transfer full): a newly-allocated %NULL-terminated array of strings.
1507  *     Use g_strfreev() to free it.
1508  *
1509  * Since: 2.6
1510  **/
1511 gchar **
1512 g_key_file_get_keys (GKeyFile     *key_file,
1513                      const gchar  *group_name,
1514                      gsize        *length,
1515                      GError      **error)
1516 {
1517   GKeyFileGroup *group;
1518   GList *tmp;
1519   gchar **keys;
1520   gsize i, num_keys;
1521   
1522   g_return_val_if_fail (key_file != NULL, NULL);
1523   g_return_val_if_fail (group_name != NULL, NULL);
1524   
1525   group = g_key_file_lookup_group (key_file, group_name);
1526   
1527   if (!group)
1528     {
1529       g_set_error (error, G_KEY_FILE_ERROR,
1530                    G_KEY_FILE_ERROR_GROUP_NOT_FOUND,
1531                    _("Key file does not have group '%s'"),
1532                    group_name ? group_name : "(null)");
1533       return NULL;
1534     }
1535
1536   num_keys = 0;
1537   for (tmp = group->key_value_pairs; tmp; tmp = tmp->next)
1538     {
1539       GKeyFileKeyValuePair *pair;
1540
1541       pair = (GKeyFileKeyValuePair *) tmp->data;
1542
1543       if (pair->key)
1544         num_keys++;
1545     }
1546   
1547   keys = g_new (gchar *, num_keys + 1);
1548
1549   i = num_keys - 1;
1550   for (tmp = group->key_value_pairs; tmp; tmp = tmp->next)
1551     {
1552       GKeyFileKeyValuePair *pair;
1553
1554       pair = (GKeyFileKeyValuePair *) tmp->data;
1555
1556       if (pair->key)
1557         {
1558           keys[i] = g_strdup (pair->key);
1559           i--;
1560         }
1561     }
1562
1563   keys[num_keys] = NULL;
1564
1565   if (length)
1566     *length = num_keys;
1567
1568   return keys;
1569 }
1570
1571 /**
1572  * g_key_file_get_start_group:
1573  * @key_file: a #GKeyFile
1574  *
1575  * Returns the name of the start group of the file. 
1576  *
1577  * Return value: The start group of the key file.
1578  *
1579  * Since: 2.6
1580  **/
1581 gchar *
1582 g_key_file_get_start_group (GKeyFile *key_file)
1583 {
1584   g_return_val_if_fail (key_file != NULL, NULL);
1585
1586   if (key_file->start_group)
1587     return g_strdup (key_file->start_group->name);
1588
1589   return NULL;
1590 }
1591
1592 /**
1593  * g_key_file_get_groups:
1594  * @key_file: a #GKeyFile
1595  * @length: (out) (allow-none): return location for the number of returned groups, or %NULL
1596  *
1597  * Returns all groups in the key file loaded with @key_file.  
1598  * The array of returned groups will be %NULL-terminated, so 
1599  * @length may optionally be %NULL.
1600  *
1601  * Return value: (array zero-terminated=1) (transfer full): a newly-allocated %NULL-terminated array of strings.
1602  *   Use g_strfreev() to free it.
1603  * Since: 2.6
1604  **/
1605 gchar **
1606 g_key_file_get_groups (GKeyFile *key_file,
1607                        gsize    *length)
1608 {
1609   GList *group_node;
1610   gchar **groups;
1611   gsize i, num_groups;
1612
1613   g_return_val_if_fail (key_file != NULL, NULL);
1614
1615   num_groups = g_list_length (key_file->groups);
1616
1617   g_return_val_if_fail (num_groups > 0, NULL);
1618
1619   group_node = g_list_last (key_file->groups);
1620   
1621   g_return_val_if_fail (((GKeyFileGroup *) group_node->data)->name == NULL, NULL);
1622
1623   /* Only need num_groups instead of num_groups + 1
1624    * because the first group of the file (last in the
1625    * list) is always the comment group at the top,
1626    * which we skip
1627    */
1628   groups = g_new (gchar *, num_groups);
1629
1630
1631   i = 0;
1632   for (group_node = group_node->prev;
1633        group_node != NULL;
1634        group_node = group_node->prev)
1635     {
1636       GKeyFileGroup *group;
1637
1638       group = (GKeyFileGroup *) group_node->data;
1639
1640       g_warn_if_fail (group->name != NULL);
1641
1642       groups[i++] = g_strdup (group->name);
1643     }
1644   groups[i] = NULL;
1645
1646   if (length)
1647     *length = i;
1648
1649   return groups;
1650 }
1651
1652 /**
1653  * g_key_file_get_value:
1654  * @key_file: a #GKeyFile
1655  * @group_name: a group name
1656  * @key: a key
1657  * @error: return location for a #GError, or %NULL
1658  *
1659  * Returns the raw value associated with @key under @group_name. 
1660  * Use g_key_file_get_string() to retrieve an unescaped UTF-8 string. 
1661  *
1662  * In the event the key cannot be found, %NULL is returned and 
1663  * @error is set to #G_KEY_FILE_ERROR_KEY_NOT_FOUND.  In the 
1664  * event that the @group_name cannot be found, %NULL is returned 
1665  * and @error is set to #G_KEY_FILE_ERROR_GROUP_NOT_FOUND.
1666  *
1667  *
1668  * Return value: a newly allocated string or %NULL if the specified 
1669  *  key cannot be found.
1670  *
1671  * Since: 2.6
1672  **/
1673 gchar *
1674 g_key_file_get_value (GKeyFile     *key_file,
1675                       const gchar  *group_name,
1676                       const gchar  *key,
1677                       GError      **error)
1678 {
1679   GKeyFileGroup *group;
1680   GKeyFileKeyValuePair *pair;
1681   gchar *value = NULL;
1682
1683   g_return_val_if_fail (key_file != NULL, NULL);
1684   g_return_val_if_fail (group_name != NULL, NULL);
1685   g_return_val_if_fail (key != NULL, NULL);
1686   
1687   group = g_key_file_lookup_group (key_file, group_name);
1688
1689   if (!group)
1690     {
1691       g_set_error (error, G_KEY_FILE_ERROR,
1692                    G_KEY_FILE_ERROR_GROUP_NOT_FOUND,
1693                    _("Key file does not have group '%s'"),
1694                    group_name ? group_name : "(null)");
1695       return NULL;
1696     }
1697
1698   pair = g_key_file_lookup_key_value_pair (key_file, group, key);
1699
1700   if (pair)
1701     value = g_strdup (pair->value);
1702   else
1703     g_set_error (error, G_KEY_FILE_ERROR,
1704                  G_KEY_FILE_ERROR_KEY_NOT_FOUND,
1705                  _("Key file does not have key '%s'"), key);
1706
1707   return value;
1708 }
1709
1710 /**
1711  * g_key_file_set_value:
1712  * @key_file: a #GKeyFile
1713  * @group_name: a group name
1714  * @key: a key
1715  * @value: a string
1716  *
1717  * Associates a new value with @key under @group_name.  
1718  *
1719  * If @key cannot be found then it is created. If @group_name cannot 
1720  * be found then it is created. To set an UTF-8 string which may contain 
1721  * characters that need escaping (such as newlines or spaces), use 
1722  * g_key_file_set_string().
1723  *
1724  * Since: 2.6
1725  **/
1726 void
1727 g_key_file_set_value (GKeyFile    *key_file,
1728                       const gchar *group_name,
1729                       const gchar *key,
1730                       const gchar *value)
1731 {
1732   GKeyFileGroup *group;
1733   GKeyFileKeyValuePair *pair;
1734
1735   g_return_if_fail (key_file != NULL);
1736   g_return_if_fail (g_key_file_is_group_name (group_name));
1737   g_return_if_fail (g_key_file_is_key_name (key));
1738   g_return_if_fail (value != NULL);
1739
1740   group = g_key_file_lookup_group (key_file, group_name);
1741
1742   if (!group)
1743     {
1744       g_key_file_add_group (key_file, group_name);
1745       group = (GKeyFileGroup *) key_file->groups->data;
1746
1747       g_key_file_add_key (key_file, group, key, value);
1748     }
1749   else
1750     {
1751       pair = g_key_file_lookup_key_value_pair (key_file, group, key);
1752
1753       if (!pair)
1754         g_key_file_add_key (key_file, group, key, value);
1755       else
1756         {
1757           g_free (pair->value);
1758           pair->value = g_strdup (value);
1759         }
1760     }
1761 }
1762
1763 /**
1764  * g_key_file_get_string:
1765  * @key_file: a #GKeyFile
1766  * @group_name: a group name
1767  * @key: a key
1768  * @error: return location for a #GError, or %NULL
1769  *
1770  * Returns the string value associated with @key under @group_name.
1771  * Unlike g_key_file_get_value(), this function handles escape sequences
1772  * like \s.
1773  *
1774  * In the event the key cannot be found, %NULL is returned and 
1775  * @error is set to #G_KEY_FILE_ERROR_KEY_NOT_FOUND.  In the 
1776  * event that the @group_name cannot be found, %NULL is returned 
1777  * and @error is set to #G_KEY_FILE_ERROR_GROUP_NOT_FOUND.
1778  *
1779  * Return value: a newly allocated string or %NULL if the specified 
1780  *   key cannot be found.
1781  *
1782  * Since: 2.6
1783  **/
1784 gchar *
1785 g_key_file_get_string (GKeyFile     *key_file,
1786                        const gchar  *group_name,
1787                        const gchar  *key,
1788                        GError      **error)
1789 {
1790   gchar *value, *string_value;
1791   GError *key_file_error;
1792
1793   g_return_val_if_fail (key_file != NULL, NULL);
1794   g_return_val_if_fail (group_name != NULL, NULL);
1795   g_return_val_if_fail (key != NULL, NULL);
1796
1797   key_file_error = NULL;
1798
1799   value = g_key_file_get_value (key_file, group_name, key, &key_file_error);
1800
1801   if (key_file_error)
1802     {
1803       g_propagate_error (error, key_file_error);
1804       return NULL;
1805     }
1806
1807   if (!g_utf8_validate (value, -1, NULL))
1808     {
1809       gchar *value_utf8 = _g_utf8_make_valid (value);
1810       g_set_error (error, G_KEY_FILE_ERROR,
1811                    G_KEY_FILE_ERROR_UNKNOWN_ENCODING,
1812                    _("Key file contains key '%s' with value '%s' "
1813                      "which is not UTF-8"), key, value_utf8);
1814       g_free (value_utf8);
1815       g_free (value);
1816
1817       return NULL;
1818     }
1819
1820   string_value = g_key_file_parse_value_as_string (key_file, value, NULL,
1821                                                    &key_file_error);
1822   g_free (value);
1823
1824   if (key_file_error)
1825     {
1826       if (g_error_matches (key_file_error,
1827                            G_KEY_FILE_ERROR,
1828                            G_KEY_FILE_ERROR_INVALID_VALUE))
1829         {
1830           g_set_error (error, G_KEY_FILE_ERROR,
1831                        G_KEY_FILE_ERROR_INVALID_VALUE,
1832                        _("Key file contains key '%s' "
1833                          "which has a value that cannot be interpreted."),
1834                        key);
1835           g_error_free (key_file_error);
1836         }
1837       else
1838         g_propagate_error (error, key_file_error);
1839     }
1840
1841   return string_value;
1842 }
1843
1844 /**
1845  * g_key_file_set_string:
1846  * @key_file: a #GKeyFile
1847  * @group_name: a group name
1848  * @key: a key
1849  * @string: a string
1850  *
1851  * Associates a new string value with @key under @group_name.  
1852  * If @key cannot be found then it is created.  
1853  * If @group_name cannot be found then it is created.
1854  * Unlike g_key_file_set_value(), this function handles characters
1855  * that need escaping, such as newlines.
1856  *
1857  * Since: 2.6
1858  **/
1859 void
1860 g_key_file_set_string (GKeyFile    *key_file,
1861                        const gchar *group_name,
1862                        const gchar *key,
1863                        const gchar *string)
1864 {
1865   gchar *value;
1866
1867   g_return_if_fail (key_file != NULL);
1868   g_return_if_fail (string != NULL);
1869
1870   value = g_key_file_parse_string_as_value (key_file, string, FALSE);
1871   g_key_file_set_value (key_file, group_name, key, value);
1872   g_free (value);
1873 }
1874
1875 /**
1876  * g_key_file_get_string_list:
1877  * @key_file: a #GKeyFile
1878  * @group_name: a group name
1879  * @key: a key
1880  * @length: (out) (allow-none): return location for the number of returned strings, or %NULL
1881  * @error: return location for a #GError, or %NULL
1882  *
1883  * Returns the values associated with @key under @group_name.
1884  *
1885  * In the event the key cannot be found, %NULL is returned and
1886  * @error is set to #G_KEY_FILE_ERROR_KEY_NOT_FOUND.  In the
1887  * event that the @group_name cannot be found, %NULL is returned
1888  * and @error is set to #G_KEY_FILE_ERROR_GROUP_NOT_FOUND.
1889  *
1890  * Return value: (array zero-terminated=1 length=length) (element-type utf8) (transfer full): 
1891  *  a %NULL-terminated string array or %NULL if the specified 
1892  *  key cannot be found. The array should be freed with g_strfreev().
1893  *
1894  * Since: 2.6
1895  **/
1896 gchar **
1897 g_key_file_get_string_list (GKeyFile     *key_file,
1898                             const gchar  *group_name,
1899                             const gchar  *key,
1900                             gsize        *length,
1901                             GError      **error)
1902 {
1903   GError *key_file_error = NULL;
1904   gchar *value, *string_value, **values;
1905   gint i, len;
1906   GSList *p, *pieces = NULL;
1907
1908   g_return_val_if_fail (key_file != NULL, NULL);
1909   g_return_val_if_fail (group_name != NULL, NULL);
1910   g_return_val_if_fail (key != NULL, NULL);
1911
1912   if (length)
1913     *length = 0;
1914
1915   value = g_key_file_get_value (key_file, group_name, key, &key_file_error);
1916
1917   if (key_file_error)
1918     {
1919       g_propagate_error (error, key_file_error);
1920       return NULL;
1921     }
1922
1923   if (!g_utf8_validate (value, -1, NULL))
1924     {
1925       gchar *value_utf8 = _g_utf8_make_valid (value);
1926       g_set_error (error, G_KEY_FILE_ERROR,
1927                    G_KEY_FILE_ERROR_UNKNOWN_ENCODING,
1928                    _("Key file contains key '%s' with value '%s' "
1929                      "which is not UTF-8"), key, value_utf8);
1930       g_free (value_utf8);
1931       g_free (value);
1932
1933       return NULL;
1934     }
1935
1936   string_value = g_key_file_parse_value_as_string (key_file, value, &pieces, &key_file_error);
1937   g_free (value);
1938   g_free (string_value);
1939
1940   if (key_file_error)
1941     {
1942       if (g_error_matches (key_file_error,
1943                            G_KEY_FILE_ERROR,
1944                            G_KEY_FILE_ERROR_INVALID_VALUE))
1945         {
1946           g_set_error (error, G_KEY_FILE_ERROR,
1947                        G_KEY_FILE_ERROR_INVALID_VALUE,
1948                        _("Key file contains key '%s' "
1949                          "which has a value that cannot be interpreted."),
1950                        key);
1951           g_error_free (key_file_error);
1952         }
1953       else
1954         g_propagate_error (error, key_file_error);
1955
1956       g_slist_free_full (pieces, g_free);
1957       return NULL;
1958     }
1959
1960   len = g_slist_length (pieces);
1961   values = g_new (gchar *, len + 1);
1962   for (p = pieces, i = 0; p; p = p->next)
1963     values[i++] = p->data;
1964   values[len] = NULL;
1965
1966   g_slist_free (pieces);
1967
1968   if (length)
1969     *length = len;
1970
1971   return values;
1972 }
1973
1974 /**
1975  * g_key_file_set_string_list:
1976  * @key_file: a #GKeyFile
1977  * @group_name: a group name
1978  * @key: a key
1979  * @list: (array zero-terminated=1 length=length) (element-type utf8): an array of string values
1980  * @length: number of string values in @list
1981  *
1982  * Associates a list of string values for @key under @group_name.
1983  * If @key cannot be found then it is created.
1984  * If @group_name cannot be found then it is created.
1985  *
1986  * Since: 2.6
1987  **/
1988 void
1989 g_key_file_set_string_list (GKeyFile            *key_file,
1990                             const gchar         *group_name,
1991                             const gchar         *key,
1992                             const gchar * const  list[],
1993                             gsize                length)
1994 {
1995   GString *value_list;
1996   gsize i;
1997
1998   g_return_if_fail (key_file != NULL);
1999   g_return_if_fail (list != NULL || length == 0);
2000
2001   value_list = g_string_sized_new (length * 128);
2002   for (i = 0; i < length && list[i] != NULL; i++)
2003     {
2004       gchar *value;
2005
2006       value = g_key_file_parse_string_as_value (key_file, list[i], TRUE);
2007       g_string_append (value_list, value);
2008       g_string_append_c (value_list, key_file->list_separator);
2009
2010       g_free (value);
2011     }
2012
2013   g_key_file_set_value (key_file, group_name, key, value_list->str);
2014   g_string_free (value_list, TRUE);
2015 }
2016
2017 /**
2018  * g_key_file_set_locale_string:
2019  * @key_file: a #GKeyFile
2020  * @group_name: a group name
2021  * @key: a key
2022  * @locale: a locale identifier
2023  * @string: a string
2024  *
2025  * Associates a string value for @key and @locale under @group_name.
2026  * If the translation for @key cannot be found then it is created.
2027  *
2028  * Since: 2.6
2029  **/
2030 void
2031 g_key_file_set_locale_string (GKeyFile     *key_file,
2032                               const gchar  *group_name,
2033                               const gchar  *key,
2034                               const gchar  *locale,
2035                               const gchar  *string)
2036 {
2037   gchar *full_key, *value;
2038
2039   g_return_if_fail (key_file != NULL);
2040   g_return_if_fail (key != NULL);
2041   g_return_if_fail (locale != NULL);
2042   g_return_if_fail (string != NULL);
2043
2044   value = g_key_file_parse_string_as_value (key_file, string, FALSE);
2045   full_key = g_strdup_printf ("%s[%s]", key, locale);
2046   g_key_file_set_value (key_file, group_name, full_key, value);
2047   g_free (full_key);
2048   g_free (value);
2049 }
2050
2051 /**
2052  * g_key_file_get_locale_string:
2053  * @key_file: a #GKeyFile
2054  * @group_name: a group name
2055  * @key: a key
2056  * @locale: (allow-none): a locale identifier or %NULL
2057  * @error: return location for a #GError, or %NULL
2058  *
2059  * Returns the value associated with @key under @group_name
2060  * translated in the given @locale if available.  If @locale is
2061  * %NULL then the current locale is assumed. 
2062  *
2063  * If @key cannot be found then %NULL is returned and @error is set 
2064  * to #G_KEY_FILE_ERROR_KEY_NOT_FOUND. If the value associated
2065  * with @key cannot be interpreted or no suitable translation can
2066  * be found then the untranslated value is returned.
2067  *
2068  * Return value: a newly allocated string or %NULL if the specified 
2069  *   key cannot be found.
2070  *
2071  * Since: 2.6
2072  **/
2073 gchar *
2074 g_key_file_get_locale_string (GKeyFile     *key_file,
2075                               const gchar  *group_name,
2076                               const gchar  *key,
2077                               const gchar  *locale,
2078                               GError      **error)
2079 {
2080   gchar *candidate_key, *translated_value;
2081   GError *key_file_error;
2082   gchar **languages;
2083   gboolean free_languages = FALSE;
2084   gint i;
2085
2086   g_return_val_if_fail (key_file != NULL, NULL);
2087   g_return_val_if_fail (group_name != NULL, NULL);
2088   g_return_val_if_fail (key != NULL, NULL);
2089
2090   candidate_key = NULL;
2091   translated_value = NULL;
2092   key_file_error = NULL;
2093
2094   if (locale)
2095     {
2096       languages = g_get_locale_variants (locale);
2097       free_languages = TRUE;
2098     }
2099   else
2100     {
2101       languages = (gchar **) g_get_language_names ();
2102       free_languages = FALSE;
2103     }
2104   
2105   for (i = 0; languages[i]; i++)
2106     {
2107       candidate_key = g_strdup_printf ("%s[%s]", key, languages[i]);
2108       
2109       translated_value = g_key_file_get_string (key_file,
2110                                                 group_name,
2111                                                 candidate_key, NULL);
2112       g_free (candidate_key);
2113
2114       if (translated_value)
2115         break;
2116
2117       g_free (translated_value);
2118       translated_value = NULL;
2119    }
2120
2121   /* Fallback to untranslated key
2122    */
2123   if (!translated_value)
2124     {
2125       translated_value = g_key_file_get_string (key_file, group_name, key,
2126                                                 &key_file_error);
2127       
2128       if (!translated_value)
2129         g_propagate_error (error, key_file_error);
2130     }
2131
2132   if (free_languages)
2133     g_strfreev (languages);
2134
2135   return translated_value;
2136 }
2137
2138 /**
2139  * g_key_file_get_locale_string_list:
2140  * @key_file: a #GKeyFile
2141  * @group_name: a group name
2142  * @key: a key
2143  * @locale: (allow-none): a locale identifier or %NULL
2144  * @length: (out) (allow-none): return location for the number of returned strings or %NULL
2145  * @error: return location for a #GError or %NULL
2146  *
2147  * Returns the values associated with @key under @group_name
2148  * translated in the given @locale if available.  If @locale is
2149  * %NULL then the current locale is assumed.
2150
2151  * If @key cannot be found then %NULL is returned and @error is set 
2152  * to #G_KEY_FILE_ERROR_KEY_NOT_FOUND. If the values associated
2153  * with @key cannot be interpreted or no suitable translations
2154  * can be found then the untranslated values are returned. The 
2155  * returned array is %NULL-terminated, so @length may optionally 
2156  * be %NULL.
2157  *
2158  * Return value: (array zero-terminated=1 length=length) (element-type utf8) (transfer full): a newly allocated %NULL-terminated string array
2159  *   or %NULL if the key isn't found. The string array should be freed
2160  *   with g_strfreev().
2161  *
2162  * Since: 2.6
2163  **/
2164 gchar **
2165 g_key_file_get_locale_string_list (GKeyFile     *key_file,
2166                                    const gchar  *group_name,
2167                                    const gchar  *key,
2168                                    const gchar  *locale,
2169                                    gsize        *length,
2170                                    GError      **error)
2171 {
2172   GError *key_file_error;
2173   gchar **values, *value;
2174   char list_separator[2];
2175   gsize len;
2176
2177   g_return_val_if_fail (key_file != NULL, NULL);
2178   g_return_val_if_fail (group_name != NULL, NULL);
2179   g_return_val_if_fail (key != NULL, NULL);
2180
2181   key_file_error = NULL;
2182
2183   value = g_key_file_get_locale_string (key_file, group_name, 
2184                                         key, locale,
2185                                         &key_file_error);
2186   
2187   if (key_file_error)
2188     g_propagate_error (error, key_file_error);
2189   
2190   if (!value)
2191     {
2192       if (length)
2193         *length = 0;
2194       return NULL;
2195     }
2196
2197   len = strlen (value);
2198   if (value[len - 1] == key_file->list_separator)
2199     value[len - 1] = '\0';
2200
2201   list_separator[0] = key_file->list_separator;
2202   list_separator[1] = '\0';
2203   values = g_strsplit (value, list_separator, 0);
2204
2205   g_free (value);
2206
2207   if (length)
2208     *length = g_strv_length (values);
2209
2210   return values;
2211 }
2212
2213 /**
2214  * g_key_file_set_locale_string_list:
2215  * @key_file: a #GKeyFile
2216  * @group_name: a group name
2217  * @key: a key
2218  * @locale: a locale identifier
2219  * @list: (array zero-terminated=1 length=length): a %NULL-terminated array of locale string values
2220  * @length: the length of @list
2221  *
2222  * Associates a list of string values for @key and @locale under
2223  * @group_name.  If the translation for @key cannot be found then
2224  * it is created. 
2225  *
2226  * Since: 2.6
2227  **/
2228 void
2229 g_key_file_set_locale_string_list (GKeyFile            *key_file,
2230                                    const gchar         *group_name,
2231                                    const gchar         *key,
2232                                    const gchar         *locale,
2233                                    const gchar * const  list[],
2234                                    gsize                length)
2235 {
2236   GString *value_list;
2237   gchar *full_key;
2238   gsize i;
2239
2240   g_return_if_fail (key_file != NULL);
2241   g_return_if_fail (key != NULL);
2242   g_return_if_fail (locale != NULL);
2243   g_return_if_fail (length != 0);
2244
2245   value_list = g_string_sized_new (length * 128);
2246   for (i = 0; i < length && list[i] != NULL; i++)
2247     {
2248       gchar *value;
2249       
2250       value = g_key_file_parse_string_as_value (key_file, list[i], TRUE);
2251       g_string_append (value_list, value);
2252       g_string_append_c (value_list, key_file->list_separator);
2253
2254       g_free (value);
2255     }
2256
2257   full_key = g_strdup_printf ("%s[%s]", key, locale);
2258   g_key_file_set_value (key_file, group_name, full_key, value_list->str);
2259   g_free (full_key);
2260   g_string_free (value_list, TRUE);
2261 }
2262
2263 /**
2264  * g_key_file_get_boolean:
2265  * @key_file: a #GKeyFile
2266  * @group_name: a group name
2267  * @key: a key
2268  * @error: return location for a #GError
2269  *
2270  * Returns the value associated with @key under @group_name as a
2271  * boolean. 
2272  *
2273  * If @key cannot be found then %FALSE is returned and @error is set
2274  * to #G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the value
2275  * associated with @key cannot be interpreted as a boolean then %FALSE
2276  * is returned and @error is set to #G_KEY_FILE_ERROR_INVALID_VALUE.
2277  *
2278  * Return value: the value associated with the key as a boolean, 
2279  *    or %FALSE if the key was not found or could not be parsed.
2280  *
2281  * Since: 2.6
2282  **/
2283 gboolean
2284 g_key_file_get_boolean (GKeyFile     *key_file,
2285                         const gchar  *group_name,
2286                         const gchar  *key,
2287                         GError      **error)
2288 {
2289   GError *key_file_error = NULL;
2290   gchar *value;
2291   gboolean bool_value;
2292
2293   g_return_val_if_fail (key_file != NULL, FALSE);
2294   g_return_val_if_fail (group_name != NULL, FALSE);
2295   g_return_val_if_fail (key != NULL, FALSE);
2296
2297   value = g_key_file_get_value (key_file, group_name, key, &key_file_error);
2298
2299   if (!value)
2300     {
2301       g_propagate_error (error, key_file_error);
2302       return FALSE;
2303     }
2304
2305   bool_value = g_key_file_parse_value_as_boolean (key_file, value,
2306                                                   &key_file_error);
2307   g_free (value);
2308
2309   if (key_file_error)
2310     {
2311       if (g_error_matches (key_file_error,
2312                            G_KEY_FILE_ERROR,
2313                            G_KEY_FILE_ERROR_INVALID_VALUE))
2314         {
2315           g_set_error (error, G_KEY_FILE_ERROR,
2316                        G_KEY_FILE_ERROR_INVALID_VALUE,
2317                        _("Key file contains key '%s' "
2318                          "which has a value that cannot be interpreted."),
2319                        key);
2320           g_error_free (key_file_error);
2321         }
2322       else
2323         g_propagate_error (error, key_file_error);
2324     }
2325
2326   return bool_value;
2327 }
2328
2329 /**
2330  * g_key_file_set_boolean:
2331  * @key_file: a #GKeyFile
2332  * @group_name: a group name
2333  * @key: a key
2334  * @value: %TRUE or %FALSE
2335  *
2336  * Associates a new boolean value with @key under @group_name.
2337  * If @key cannot be found then it is created. 
2338  *
2339  * Since: 2.6
2340  **/
2341 void
2342 g_key_file_set_boolean (GKeyFile    *key_file,
2343                         const gchar *group_name,
2344                         const gchar *key,
2345                         gboolean     value)
2346 {
2347   gchar *result;
2348
2349   g_return_if_fail (key_file != NULL);
2350
2351   result = g_key_file_parse_boolean_as_value (key_file, value);
2352   g_key_file_set_value (key_file, group_name, key, result);
2353   g_free (result);
2354 }
2355
2356 /**
2357  * g_key_file_get_boolean_list:
2358  * @key_file: a #GKeyFile
2359  * @group_name: a group name
2360  * @key: a key
2361  * @length: (out): the number of booleans returned
2362  * @error: return location for a #GError
2363  *
2364  * Returns the values associated with @key under @group_name as
2365  * booleans. 
2366  *
2367  * If @key cannot be found then %NULL is returned and @error is set to
2368  * #G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the values associated
2369  * with @key cannot be interpreted as booleans then %NULL is returned
2370  * and @error is set to #G_KEY_FILE_ERROR_INVALID_VALUE.
2371  *
2372  * Return value: (array length=length) (element-type gboolean) (transfer container):
2373  *    the values associated with the key as a list of booleans, or %NULL if the
2374  *    key was not found or could not be parsed. The returned list of booleans
2375  *    should be freed with g_free() when no longer needed.
2376  * 
2377  * Since: 2.6
2378  **/
2379 gboolean *
2380 g_key_file_get_boolean_list (GKeyFile     *key_file,
2381                              const gchar  *group_name,
2382                              const gchar  *key,
2383                              gsize        *length,
2384                              GError      **error)
2385 {
2386   GError *key_file_error;
2387   gchar **values;
2388   gboolean *bool_values;
2389   gsize i, num_bools;
2390
2391   g_return_val_if_fail (key_file != NULL, NULL);
2392   g_return_val_if_fail (group_name != NULL, NULL);
2393   g_return_val_if_fail (key != NULL, NULL);
2394
2395   if (length)
2396     *length = 0;
2397
2398   key_file_error = NULL;
2399
2400   values = g_key_file_get_string_list (key_file, group_name, key,
2401                                        &num_bools, &key_file_error);
2402
2403   if (key_file_error)
2404     g_propagate_error (error, key_file_error);
2405
2406   if (!values)
2407     return NULL;
2408
2409   bool_values = g_new (gboolean, num_bools);
2410
2411   for (i = 0; i < num_bools; i++)
2412     {
2413       bool_values[i] = g_key_file_parse_value_as_boolean (key_file,
2414                                                           values[i],
2415                                                           &key_file_error);
2416
2417       if (key_file_error)
2418         {
2419           g_propagate_error (error, key_file_error);
2420           g_strfreev (values);
2421           g_free (bool_values);
2422
2423           return NULL;
2424         }
2425     }
2426   g_strfreev (values);
2427
2428   if (length)
2429     *length = num_bools;
2430
2431   return bool_values;
2432 }
2433
2434 /**
2435  * g_key_file_set_boolean_list:
2436  * @key_file: a #GKeyFile
2437  * @group_name: a group name
2438  * @key: a key
2439  * @list: (array length=length): an array of boolean values
2440  * @length: length of @list
2441  *
2442  * Associates a list of boolean values with @key under @group_name.  
2443  * If @key cannot be found then it is created.
2444  * If @group_name is %NULL, the start_group is used.
2445  *
2446  * Since: 2.6
2447  **/
2448 void
2449 g_key_file_set_boolean_list (GKeyFile    *key_file,
2450                              const gchar *group_name,
2451                              const gchar *key,
2452                              gboolean     list[],
2453                              gsize        length)
2454 {
2455   GString *value_list;
2456   gsize i;
2457
2458   g_return_if_fail (key_file != NULL);
2459   g_return_if_fail (list != NULL);
2460
2461   value_list = g_string_sized_new (length * 8);
2462   for (i = 0; i < length; i++)
2463     {
2464       gchar *value;
2465
2466       value = g_key_file_parse_boolean_as_value (key_file, list[i]);
2467
2468       g_string_append (value_list, value);
2469       g_string_append_c (value_list, key_file->list_separator);
2470
2471       g_free (value);
2472     }
2473
2474   g_key_file_set_value (key_file, group_name, key, value_list->str);
2475   g_string_free (value_list, TRUE);
2476 }
2477
2478 /**
2479  * g_key_file_get_integer:
2480  * @key_file: a #GKeyFile
2481  * @group_name: a group name
2482  * @key: a key
2483  * @error: return location for a #GError
2484  *
2485  * Returns the value associated with @key under @group_name as an
2486  * integer. 
2487  *
2488  * If @key cannot be found then 0 is returned and @error is set to
2489  * #G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the value associated
2490  * with @key cannot be interpreted as an integer then 0 is returned
2491  * and @error is set to #G_KEY_FILE_ERROR_INVALID_VALUE.
2492  *
2493  * Return value: the value associated with the key as an integer, or
2494  *     0 if the key was not found or could not be parsed.
2495  *
2496  * Since: 2.6
2497  **/
2498 gint
2499 g_key_file_get_integer (GKeyFile     *key_file,
2500                         const gchar  *group_name,
2501                         const gchar  *key,
2502                         GError      **error)
2503 {
2504   GError *key_file_error;
2505   gchar *value;
2506   gint int_value;
2507
2508   g_return_val_if_fail (key_file != NULL, -1);
2509   g_return_val_if_fail (group_name != NULL, -1);
2510   g_return_val_if_fail (key != NULL, -1);
2511
2512   key_file_error = NULL;
2513
2514   value = g_key_file_get_value (key_file, group_name, key, &key_file_error);
2515
2516   if (key_file_error)
2517     {
2518       g_propagate_error (error, key_file_error);
2519       return 0;
2520     }
2521
2522   int_value = g_key_file_parse_value_as_integer (key_file, value,
2523                                                  &key_file_error);
2524   g_free (value);
2525
2526   if (key_file_error)
2527     {
2528       if (g_error_matches (key_file_error,
2529                            G_KEY_FILE_ERROR,
2530                            G_KEY_FILE_ERROR_INVALID_VALUE))
2531         {
2532           g_set_error (error, G_KEY_FILE_ERROR,
2533                        G_KEY_FILE_ERROR_INVALID_VALUE,
2534                        _("Key file contains key '%s' in group '%s' "
2535                          "which has a value that cannot be interpreted."),
2536                          key, group_name);
2537           g_error_free (key_file_error);
2538         }
2539       else
2540         g_propagate_error (error, key_file_error);
2541     }
2542
2543   return int_value;
2544 }
2545
2546 /**
2547  * g_key_file_set_integer:
2548  * @key_file: a #GKeyFile
2549  * @group_name: a group name
2550  * @key: a key
2551  * @value: an integer value
2552  *
2553  * Associates a new integer value with @key under @group_name.
2554  * If @key cannot be found then it is created.
2555  *
2556  * Since: 2.6
2557  **/
2558 void
2559 g_key_file_set_integer (GKeyFile    *key_file,
2560                         const gchar *group_name,
2561                         const gchar *key,
2562                         gint         value)
2563 {
2564   gchar *result;
2565
2566   g_return_if_fail (key_file != NULL);
2567
2568   result = g_key_file_parse_integer_as_value (key_file, value);
2569   g_key_file_set_value (key_file, group_name, key, result);
2570   g_free (result);
2571 }
2572
2573 /**
2574  * g_key_file_get_int64:
2575  * @key_file: a non-%NULL #GKeyFile
2576  * @group_name: a non-%NULL group name
2577  * @key: a non-%NULL key
2578  * @error: return location for a #GError
2579  *
2580  * Returns the value associated with @key under @group_name as a signed
2581  * 64-bit integer. This is similar to g_key_file_get_integer() but can return
2582  * 64-bit results without truncation.
2583  *
2584  * Returns: the value associated with the key as a signed 64-bit integer, or
2585  * 0 if the key was not found or could not be parsed.
2586  *
2587  * Since: 2.26
2588  */
2589 gint64
2590 g_key_file_get_int64 (GKeyFile     *key_file,
2591                       const gchar  *group_name,
2592                       const gchar  *key,
2593                       GError      **error)
2594 {
2595   gchar *s, *end;
2596   gint64 v;
2597
2598   g_return_val_if_fail (key_file != NULL, -1);
2599   g_return_val_if_fail (group_name != NULL, -1);
2600   g_return_val_if_fail (key != NULL, -1);
2601
2602   s = g_key_file_get_value (key_file, group_name, key, error);
2603
2604   if (s == NULL)
2605     return 0;
2606
2607   v = g_ascii_strtoll (s, &end, 10);
2608
2609   if (*s == '\0' || *end != '\0')
2610     {
2611       g_set_error (error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_INVALID_VALUE,
2612                    _("Key '%s' in group '%s' has value '%s' "
2613                      "where %s was expected"),
2614                    key, group_name, s, "int64");
2615       g_free (s);
2616       return 0;
2617     }
2618
2619   g_free (s);
2620   return v;
2621 }
2622
2623 /**
2624  * g_key_file_set_int64:
2625  * @key_file: a #GKeyFile
2626  * @group_name: a group name
2627  * @key: a key
2628  * @value: an integer value
2629  *
2630  * Associates a new integer value with @key under @group_name.
2631  * If @key cannot be found then it is created.
2632  *
2633  * Since: 2.26
2634  **/
2635 void
2636 g_key_file_set_int64 (GKeyFile    *key_file,
2637                       const gchar *group_name,
2638                       const gchar *key,
2639                       gint64       value)
2640 {
2641   gchar *result;
2642
2643   g_return_if_fail (key_file != NULL);
2644
2645   result = g_strdup_printf ("%" G_GINT64_FORMAT, value);
2646   g_key_file_set_value (key_file, group_name, key, result);
2647   g_free (result);
2648 }
2649
2650 /**
2651  * g_key_file_get_uint64:
2652  * @key_file: a non-%NULL #GKeyFile
2653  * @group_name: a non-%NULL group name
2654  * @key: a non-%NULL key
2655  * @error: return location for a #GError
2656  *
2657  * Returns the value associated with @key under @group_name as an unsigned
2658  * 64-bit integer. This is similar to g_key_file_get_integer() but can return
2659  * large positive results without truncation.
2660  *
2661  * Returns: the value associated with the key as an unsigned 64-bit integer,
2662  * or 0 if the key was not found or could not be parsed.
2663  *
2664  * Since: 2.26
2665  */
2666 guint64
2667 g_key_file_get_uint64 (GKeyFile     *key_file,
2668                        const gchar  *group_name,
2669                        const gchar  *key,
2670                        GError      **error)
2671 {
2672   gchar *s, *end;
2673   guint64 v;
2674
2675   g_return_val_if_fail (key_file != NULL, -1);
2676   g_return_val_if_fail (group_name != NULL, -1);
2677   g_return_val_if_fail (key != NULL, -1);
2678
2679   s = g_key_file_get_value (key_file, group_name, key, error);
2680
2681   if (s == NULL)
2682     return 0;
2683
2684   v = g_ascii_strtoull (s, &end, 10);
2685
2686   if (*s == '\0' || *end != '\0')
2687     {
2688       g_set_error (error, G_KEY_FILE_ERROR, G_KEY_FILE_ERROR_INVALID_VALUE,
2689                    _("Key '%s' in group '%s' has value '%s' "
2690                      "where %s was expected"),
2691                    key, group_name, s, "uint64");
2692       g_free (s);
2693       return 0;
2694     }
2695
2696   g_free (s);
2697   return v;
2698 }
2699
2700 /**
2701  * g_key_file_set_uint64:
2702  * @key_file: a #GKeyFile
2703  * @group_name: a group name
2704  * @key: a key
2705  * @value: an integer value
2706  *
2707  * Associates a new integer value with @key under @group_name.
2708  * If @key cannot be found then it is created.
2709  *
2710  * Since: 2.26
2711  **/
2712 void
2713 g_key_file_set_uint64 (GKeyFile    *key_file,
2714                        const gchar *group_name,
2715                        const gchar *key,
2716                        guint64      value)
2717 {
2718   gchar *result;
2719
2720   g_return_if_fail (key_file != NULL);
2721
2722   result = g_strdup_printf ("%" G_GUINT64_FORMAT, value);
2723   g_key_file_set_value (key_file, group_name, key, result);
2724   g_free (result);
2725 }
2726
2727 /**
2728  * g_key_file_get_integer_list:
2729  * @key_file: a #GKeyFile
2730  * @group_name: a group name
2731  * @key: a key
2732  * @length: (out): the number of integers returned
2733  * @error: return location for a #GError
2734  *
2735  * Returns the values associated with @key under @group_name as
2736  * integers. 
2737  *
2738  * If @key cannot be found then %NULL is returned and @error is set to
2739  * #G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the values associated
2740  * with @key cannot be interpreted as integers then %NULL is returned
2741  * and @error is set to #G_KEY_FILE_ERROR_INVALID_VALUE.
2742  *
2743  * Return value: (array length=length) (element-type gint) (transfer container):
2744  *     the values associated with the key as a list of integers, or %NULL if
2745  *     the key was not found or could not be parsed. The returned list of
2746  *     integers should be freed with g_free() when no longer needed.
2747  *
2748  * Since: 2.6
2749  **/
2750 gint *
2751 g_key_file_get_integer_list (GKeyFile     *key_file,
2752                              const gchar  *group_name,
2753                              const gchar  *key,
2754                              gsize        *length,
2755                              GError      **error)
2756 {
2757   GError *key_file_error = NULL;
2758   gchar **values;
2759   gint *int_values;
2760   gsize i, num_ints;
2761
2762   g_return_val_if_fail (key_file != NULL, NULL);
2763   g_return_val_if_fail (group_name != NULL, NULL);
2764   g_return_val_if_fail (key != NULL, NULL);
2765
2766   if (length)
2767     *length = 0;
2768
2769   values = g_key_file_get_string_list (key_file, group_name, key,
2770                                        &num_ints, &key_file_error);
2771
2772   if (key_file_error)
2773     g_propagate_error (error, key_file_error);
2774
2775   if (!values)
2776     return NULL;
2777
2778   int_values = g_new (gint, num_ints);
2779
2780   for (i = 0; i < num_ints; i++)
2781     {
2782       int_values[i] = g_key_file_parse_value_as_integer (key_file,
2783                                                          values[i],
2784                                                          &key_file_error);
2785
2786       if (key_file_error)
2787         {
2788           g_propagate_error (error, key_file_error);
2789           g_strfreev (values);
2790           g_free (int_values);
2791
2792           return NULL;
2793         }
2794     }
2795   g_strfreev (values);
2796
2797   if (length)
2798     *length = num_ints;
2799
2800   return int_values;
2801 }
2802
2803 /**
2804  * g_key_file_set_integer_list:
2805  * @key_file: a #GKeyFile
2806  * @group_name: a group name
2807  * @key: a key
2808  * @list: (array length=length): an array of integer values
2809  * @length: number of integer values in @list
2810  *
2811  * Associates a list of integer values with @key under @group_name.  
2812  * If @key cannot be found then it is created.
2813  *
2814  * Since: 2.6
2815  **/
2816 void
2817 g_key_file_set_integer_list (GKeyFile    *key_file,
2818                              const gchar *group_name,
2819                              const gchar *key,
2820                              gint         list[],
2821                              gsize        length)
2822 {
2823   GString *values;
2824   gsize i;
2825
2826   g_return_if_fail (key_file != NULL);
2827   g_return_if_fail (list != NULL);
2828
2829   values = g_string_sized_new (length * 16);
2830   for (i = 0; i < length; i++)
2831     {
2832       gchar *value;
2833
2834       value = g_key_file_parse_integer_as_value (key_file, list[i]);
2835
2836       g_string_append (values, value);
2837       g_string_append_c (values, key_file->list_separator);
2838
2839       g_free (value);
2840     }
2841
2842   g_key_file_set_value (key_file, group_name, key, values->str);
2843   g_string_free (values, TRUE);
2844 }
2845
2846 /**
2847  * g_key_file_get_double:
2848  * @key_file: a #GKeyFile
2849  * @group_name: a group name
2850  * @key: a key
2851  * @error: return location for a #GError
2852  *
2853  * Returns the value associated with @key under @group_name as a
2854  * double. If @group_name is %NULL, the start_group is used.
2855  *
2856  * If @key cannot be found then 0.0 is returned and @error is set to
2857  * #G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the value associated
2858  * with @key cannot be interpreted as a double then 0.0 is returned
2859  * and @error is set to #G_KEY_FILE_ERROR_INVALID_VALUE.
2860  *
2861  * Return value: the value associated with the key as a double, or
2862  *     0.0 if the key was not found or could not be parsed.
2863  *
2864  * Since: 2.12
2865  **/
2866 gdouble
2867 g_key_file_get_double  (GKeyFile     *key_file,
2868                         const gchar  *group_name,
2869                         const gchar  *key,
2870                         GError      **error)
2871 {
2872   GError *key_file_error;
2873   gchar *value;
2874   gdouble double_value;
2875
2876   g_return_val_if_fail (key_file != NULL, -1);
2877   g_return_val_if_fail (group_name != NULL, -1);
2878   g_return_val_if_fail (key != NULL, -1);
2879
2880   key_file_error = NULL;
2881
2882   value = g_key_file_get_value (key_file, group_name, key, &key_file_error);
2883
2884   if (key_file_error)
2885     {
2886       g_propagate_error (error, key_file_error);
2887       return 0;
2888     }
2889
2890   double_value = g_key_file_parse_value_as_double (key_file, value,
2891                                                   &key_file_error);
2892   g_free (value);
2893
2894   if (key_file_error)
2895     {
2896       if (g_error_matches (key_file_error,
2897                            G_KEY_FILE_ERROR,
2898                            G_KEY_FILE_ERROR_INVALID_VALUE))
2899         {
2900           g_set_error (error, G_KEY_FILE_ERROR,
2901                        G_KEY_FILE_ERROR_INVALID_VALUE,
2902                        _("Key file contains key '%s' in group '%s' "
2903                          "which has a value that cannot be interpreted."),
2904                        key, group_name);
2905           g_error_free (key_file_error);
2906         }
2907       else
2908         g_propagate_error (error, key_file_error);
2909     }
2910
2911   return double_value;
2912 }
2913
2914 /**
2915  * g_key_file_set_double:
2916  * @key_file: a #GKeyFile
2917  * @group_name: a group name
2918  * @key: a key
2919  * @value: an double value
2920  *
2921  * Associates a new double value with @key under @group_name.
2922  * If @key cannot be found then it is created. 
2923  *
2924  * Since: 2.12
2925  **/
2926 void
2927 g_key_file_set_double  (GKeyFile    *key_file,
2928                         const gchar *group_name,
2929                         const gchar *key,
2930                         gdouble      value)
2931 {
2932   gchar result[G_ASCII_DTOSTR_BUF_SIZE];
2933
2934   g_return_if_fail (key_file != NULL);
2935
2936   g_ascii_dtostr (result, sizeof (result), value);
2937   g_key_file_set_value (key_file, group_name, key, result);
2938 }
2939
2940 /**
2941  * g_key_file_get_double_list:
2942  * @key_file: a #GKeyFile
2943  * @group_name: a group name
2944  * @key: a key
2945  * @length: (out): the number of doubles returned
2946  * @error: return location for a #GError
2947  *
2948  * Returns the values associated with @key under @group_name as
2949  * doubles. 
2950  *
2951  * If @key cannot be found then %NULL is returned and @error is set to
2952  * #G_KEY_FILE_ERROR_KEY_NOT_FOUND. Likewise, if the values associated
2953  * with @key cannot be interpreted as doubles then %NULL is returned
2954  * and @error is set to #G_KEY_FILE_ERROR_INVALID_VALUE.
2955  *
2956  * Return value: (array length=length) (element-type gdouble) (transfer container):
2957  *     the values associated with the key as a list of doubles, or %NULL if the
2958  *     key was not found or could not be parsed. The returned list of doubles
2959  *     should be freed with g_free() when no longer needed.
2960  *
2961  * Since: 2.12
2962  **/
2963 gdouble *
2964 g_key_file_get_double_list  (GKeyFile     *key_file,
2965                              const gchar  *group_name,
2966                              const gchar  *key,
2967                              gsize        *length,
2968                              GError      **error)
2969 {
2970   GError *key_file_error = NULL;
2971   gchar **values;
2972   gdouble *double_values;
2973   gsize i, num_doubles;
2974
2975   g_return_val_if_fail (key_file != NULL, NULL);
2976   g_return_val_if_fail (group_name != NULL, NULL);
2977   g_return_val_if_fail (key != NULL, NULL);
2978
2979   if (length)
2980     *length = 0;
2981
2982   values = g_key_file_get_string_list (key_file, group_name, key,
2983                                        &num_doubles, &key_file_error);
2984
2985   if (key_file_error)
2986     g_propagate_error (error, key_file_error);
2987
2988   if (!values)
2989     return NULL;
2990
2991   double_values = g_new (gdouble, num_doubles);
2992
2993   for (i = 0; i < num_doubles; i++)
2994     {
2995       double_values[i] = g_key_file_parse_value_as_double (key_file,
2996                                                            values[i],
2997                                                            &key_file_error);
2998
2999       if (key_file_error)
3000         {
3001           g_propagate_error (error, key_file_error);
3002           g_strfreev (values);
3003           g_free (double_values);
3004
3005           return NULL;
3006         }
3007     }
3008   g_strfreev (values);
3009
3010   if (length)
3011     *length = num_doubles;
3012
3013   return double_values;
3014 }
3015
3016 /**
3017  * g_key_file_set_double_list:
3018  * @key_file: a #GKeyFile
3019  * @group_name: a group name
3020  * @key: a key
3021  * @list: (array length=length): an array of double values
3022  * @length: number of double values in @list
3023  *
3024  * Associates a list of double values with @key under
3025  * @group_name.  If @key cannot be found then it is created.
3026  *
3027  * Since: 2.12
3028  **/
3029 void
3030 g_key_file_set_double_list (GKeyFile    *key_file,
3031                             const gchar *group_name,
3032                             const gchar *key,
3033                             gdouble      list[],
3034                             gsize        length)
3035 {
3036   GString *values;
3037   gsize i;
3038
3039   g_return_if_fail (key_file != NULL);
3040   g_return_if_fail (list != NULL);
3041
3042   values = g_string_sized_new (length * 16);
3043   for (i = 0; i < length; i++)
3044     {
3045       gchar result[G_ASCII_DTOSTR_BUF_SIZE];
3046
3047       g_ascii_dtostr( result, sizeof (result), list[i] );
3048
3049       g_string_append (values, result);
3050       g_string_append_c (values, key_file->list_separator);
3051     }
3052
3053   g_key_file_set_value (key_file, group_name, key, values->str);
3054   g_string_free (values, TRUE);
3055 }
3056
3057 static gboolean
3058 g_key_file_set_key_comment (GKeyFile     *key_file,
3059                             const gchar  *group_name,
3060                             const gchar  *key,
3061                             const gchar  *comment,
3062                             GError      **error)
3063 {
3064   GKeyFileGroup *group;
3065   GKeyFileKeyValuePair *pair;
3066   GList *key_node, *comment_node, *tmp;
3067   
3068   group = g_key_file_lookup_group (key_file, group_name);
3069   if (!group)
3070     {
3071       g_set_error (error, G_KEY_FILE_ERROR,
3072                    G_KEY_FILE_ERROR_GROUP_NOT_FOUND,
3073                    _("Key file does not have group '%s'"),
3074                    group_name ? group_name : "(null)");
3075
3076       return FALSE;
3077     }
3078
3079   /* First find the key the comments are supposed to be
3080    * associated with
3081    */
3082   key_node = g_key_file_lookup_key_value_pair_node (key_file, group, key);
3083
3084   if (key_node == NULL)
3085     {
3086       g_set_error (error, G_KEY_FILE_ERROR,
3087                    G_KEY_FILE_ERROR_KEY_NOT_FOUND,
3088                    _("Key file does not have key '%s' in group '%s'"),
3089                    key, group->name);
3090       return FALSE;
3091     }
3092
3093   /* Then find all the comments already associated with the
3094    * key and free them
3095    */
3096   tmp = key_node->next;
3097   while (tmp != NULL)
3098     {
3099       pair = (GKeyFileKeyValuePair *) tmp->data;
3100
3101       if (pair->key != NULL)
3102         break;
3103
3104       comment_node = tmp;
3105       tmp = tmp->next;
3106       g_key_file_remove_key_value_pair_node (key_file, group,
3107                                              comment_node); 
3108     }
3109
3110   if (comment == NULL)
3111     return TRUE;
3112
3113   /* Now we can add our new comment
3114    */
3115   pair = g_slice_new (GKeyFileKeyValuePair);
3116   pair->key = NULL;
3117   pair->value = g_key_file_parse_comment_as_value (key_file, comment);
3118   
3119   key_node = g_list_insert (key_node, pair, 1);
3120
3121   return TRUE;
3122 }
3123
3124 static gboolean
3125 g_key_file_set_group_comment (GKeyFile     *key_file,
3126                               const gchar  *group_name,
3127                               const gchar  *comment,
3128                               GError      **error)
3129 {
3130   GKeyFileGroup *group;
3131   
3132   g_return_val_if_fail (g_key_file_is_group_name (group_name), FALSE);
3133
3134   group = g_key_file_lookup_group (key_file, group_name);
3135   if (!group)
3136     {
3137       g_set_error (error, G_KEY_FILE_ERROR,
3138                    G_KEY_FILE_ERROR_GROUP_NOT_FOUND,
3139                    _("Key file does not have group '%s'"),
3140                    group_name ? group_name : "(null)");
3141
3142       return FALSE;
3143     }
3144
3145   /* First remove any existing comment
3146    */
3147   if (group->comment)
3148     {
3149       g_key_file_key_value_pair_free (group->comment);
3150       group->comment = NULL;
3151     }
3152
3153   if (comment == NULL)
3154     return TRUE;
3155
3156   /* Now we can add our new comment
3157    */
3158   group->comment = g_slice_new (GKeyFileKeyValuePair);
3159   group->comment->key = NULL;
3160   group->comment->value = g_key_file_parse_comment_as_value (key_file, comment);
3161
3162   return TRUE;
3163 }
3164
3165 static gboolean
3166 g_key_file_set_top_comment (GKeyFile     *key_file,
3167                             const gchar  *comment,
3168                             GError      **error)
3169 {
3170   GList *group_node;
3171   GKeyFileGroup *group;
3172   GKeyFileKeyValuePair *pair;
3173
3174   /* The last group in the list should be the top (comments only)
3175    * group in the file
3176    */
3177   g_warn_if_fail (key_file->groups != NULL);
3178   group_node = g_list_last (key_file->groups);
3179   group = (GKeyFileGroup *) group_node->data;
3180   g_warn_if_fail (group->name == NULL);
3181
3182   /* Note all keys must be comments at the top of
3183    * the file, so we can just free it all.
3184    */
3185   g_list_free_full (group->key_value_pairs, (GDestroyNotify) g_key_file_key_value_pair_free);
3186   group->key_value_pairs = NULL;
3187
3188   if (comment == NULL)
3189      return TRUE;
3190
3191   pair = g_slice_new (GKeyFileKeyValuePair);
3192   pair->key = NULL;
3193   pair->value = g_key_file_parse_comment_as_value (key_file, comment);
3194   
3195   group->key_value_pairs =
3196     g_list_prepend (group->key_value_pairs, pair);
3197
3198   return TRUE;
3199 }
3200
3201 /**
3202  * g_key_file_set_comment:
3203  * @key_file: a #GKeyFile
3204  * @group_name: (allow-none): a group name, or %NULL
3205  * @key: (allow-none): a key
3206  * @comment: a comment
3207  * @error: return location for a #GError
3208  *
3209  * Places a comment above @key from @group_name.
3210  * If @key is %NULL then @comment will be written above @group_name.  
3211  * If both @key and @group_name  are %NULL, then @comment will be 
3212  * written above the first group in the file.
3213  *
3214  * Returns: %TRUE if the comment was written, %FALSE otherwise
3215  *
3216  * Since: 2.6
3217  **/
3218 gboolean
3219 g_key_file_set_comment (GKeyFile     *key_file,
3220                         const gchar  *group_name,
3221                         const gchar  *key,
3222                         const gchar  *comment,
3223                         GError      **error)
3224 {
3225   g_return_val_if_fail (key_file != NULL, FALSE);
3226
3227   if (group_name != NULL && key != NULL) 
3228     {
3229       if (!g_key_file_set_key_comment (key_file, group_name, key, comment, error))
3230         return FALSE;
3231     } 
3232   else if (group_name != NULL) 
3233     {
3234       if (!g_key_file_set_group_comment (key_file, group_name, comment, error))
3235         return FALSE;
3236     } 
3237   else 
3238     {
3239       if (!g_key_file_set_top_comment (key_file, comment, error))
3240         return FALSE;
3241     }
3242
3243   return TRUE;
3244 }
3245
3246 static gchar *
3247 g_key_file_get_key_comment (GKeyFile     *key_file,
3248                             const gchar  *group_name,
3249                             const gchar  *key,
3250                             GError      **error)
3251 {
3252   GKeyFileGroup *group;
3253   GKeyFileKeyValuePair *pair;
3254   GList *key_node, *tmp;
3255   GString *string;
3256   gchar *comment;
3257
3258   g_return_val_if_fail (g_key_file_is_group_name (group_name), NULL);
3259
3260   group = g_key_file_lookup_group (key_file, group_name);
3261   if (!group)
3262     {
3263       g_set_error (error, G_KEY_FILE_ERROR,
3264                    G_KEY_FILE_ERROR_GROUP_NOT_FOUND,
3265                    _("Key file does not have group '%s'"),
3266                    group_name ? group_name : "(null)");
3267
3268       return NULL;
3269     }
3270
3271   /* First find the key the comments are supposed to be
3272    * associated with
3273    */
3274   key_node = g_key_file_lookup_key_value_pair_node (key_file, group, key);
3275
3276   if (key_node == NULL)
3277     {
3278       g_set_error (error, G_KEY_FILE_ERROR,
3279                    G_KEY_FILE_ERROR_KEY_NOT_FOUND,
3280                    _("Key file does not have key '%s' in group '%s'"),
3281                    key, group->name);
3282       return NULL;
3283     }
3284
3285   string = NULL;
3286
3287   /* Then find all the comments already associated with the
3288    * key and concatentate them.
3289    */
3290   tmp = key_node->next;
3291   if (!key_node->next)
3292     return NULL;
3293
3294   pair = (GKeyFileKeyValuePair *) tmp->data;
3295   if (pair->key != NULL)
3296     return NULL;
3297
3298   while (tmp->next)
3299     {
3300       pair = (GKeyFileKeyValuePair *) tmp->next->data;
3301       
3302       if (pair->key != NULL)
3303         break;
3304
3305       tmp = tmp->next;
3306     }
3307
3308   while (tmp != key_node)
3309     {
3310       pair = (GKeyFileKeyValuePair *) tmp->data;
3311       
3312       if (string == NULL)
3313         string = g_string_sized_new (512);
3314       
3315       comment = g_key_file_parse_value_as_comment (key_file, pair->value);
3316       g_string_append (string, comment);
3317       g_free (comment);
3318       
3319       tmp = tmp->prev;
3320     }
3321
3322   if (string != NULL)
3323     {
3324       comment = string->str;
3325       g_string_free (string, FALSE);
3326     }
3327   else
3328     comment = NULL;
3329
3330   return comment;
3331 }
3332
3333 static gchar *
3334 get_group_comment (GKeyFile       *key_file,
3335                    GKeyFileGroup  *group,
3336                    GError        **error)
3337 {
3338   GString *string;
3339   GList *tmp;
3340   gchar *comment;
3341
3342   string = NULL;
3343
3344   tmp = group->key_value_pairs;
3345   while (tmp)
3346     {
3347       GKeyFileKeyValuePair *pair;
3348
3349       pair = (GKeyFileKeyValuePair *) tmp->data;
3350
3351       if (pair->key != NULL)
3352         {
3353           tmp = tmp->prev;
3354           break;
3355         }
3356
3357       if (tmp->next == NULL)
3358         break;
3359
3360       tmp = tmp->next;
3361     }
3362   
3363   while (tmp != NULL)
3364     {
3365       GKeyFileKeyValuePair *pair;
3366
3367       pair = (GKeyFileKeyValuePair *) tmp->data;
3368
3369       if (string == NULL)
3370         string = g_string_sized_new (512);
3371
3372       comment = g_key_file_parse_value_as_comment (key_file, pair->value);
3373       g_string_append (string, comment);
3374       g_free (comment);
3375
3376       tmp = tmp->prev;
3377     }
3378
3379   if (string != NULL)
3380     return g_string_free (string, FALSE);
3381
3382   return NULL;
3383 }
3384
3385 static gchar *
3386 g_key_file_get_group_comment (GKeyFile     *key_file,
3387                               const gchar  *group_name,
3388                               GError      **error)
3389 {
3390   GList *group_node;
3391   GKeyFileGroup *group;
3392   
3393   group = g_key_file_lookup_group (key_file, group_name);
3394   if (!group)
3395     {
3396       g_set_error (error, G_KEY_FILE_ERROR,
3397                    G_KEY_FILE_ERROR_GROUP_NOT_FOUND,
3398                    _("Key file does not have group '%s'"),
3399                    group_name ? group_name : "(null)");
3400
3401       return NULL;
3402     }
3403
3404   if (group->comment)
3405     return g_strdup (group->comment->value);
3406   
3407   group_node = g_key_file_lookup_group_node (key_file, group_name);
3408   group_node = group_node->next;
3409   group = (GKeyFileGroup *)group_node->data;  
3410   return get_group_comment (key_file, group, error);
3411 }
3412
3413 static gchar *
3414 g_key_file_get_top_comment (GKeyFile  *key_file,
3415                             GError   **error)
3416 {
3417   GList *group_node;
3418   GKeyFileGroup *group;
3419
3420   /* The last group in the list should be the top (comments only)
3421    * group in the file
3422    */
3423   g_warn_if_fail (key_file->groups != NULL);
3424   group_node = g_list_last (key_file->groups);
3425   group = (GKeyFileGroup *) group_node->data;
3426   g_warn_if_fail (group->name == NULL);
3427
3428   return get_group_comment (key_file, group, error);
3429 }
3430
3431 /**
3432  * g_key_file_get_comment:
3433  * @key_file: a #GKeyFile
3434  * @group_name: (allow-none): a group name, or %NULL
3435  * @key: a key
3436  * @error: return location for a #GError
3437  *
3438  * Retrieves a comment above @key from @group_name.
3439  * If @key is %NULL then @comment will be read from above 
3440  * @group_name. If both @key and @group_name are %NULL, then 
3441  * @comment will be read from above the first group in the file.
3442  *
3443  * Returns: a comment that should be freed with g_free()
3444  *
3445  * Since: 2.6
3446  **/
3447 gchar * 
3448 g_key_file_get_comment (GKeyFile     *key_file,
3449                         const gchar  *group_name,
3450                         const gchar  *key,
3451                         GError      **error)
3452 {
3453   g_return_val_if_fail (key_file != NULL, NULL);
3454
3455   if (group_name != NULL && key != NULL)
3456     return g_key_file_get_key_comment (key_file, group_name, key, error);
3457   else if (group_name != NULL)
3458     return g_key_file_get_group_comment (key_file, group_name, error);
3459   else
3460     return g_key_file_get_top_comment (key_file, error);
3461 }
3462
3463 /**
3464  * g_key_file_remove_comment:
3465  * @key_file: a #GKeyFile
3466  * @group_name: (allow-none): a group name, or %NULL
3467  * @key: (allow-none): a key
3468  * @error: return location for a #GError
3469  *
3470  * Removes a comment above @key from @group_name.
3471  * If @key is %NULL then @comment will be removed above @group_name. 
3472  * If both @key and @group_name are %NULL, then @comment will
3473  * be removed above the first group in the file.
3474  *
3475  * Returns: %TRUE if the comment was removed, %FALSE otherwise
3476  *
3477  * Since: 2.6
3478  **/
3479
3480 gboolean
3481 g_key_file_remove_comment (GKeyFile     *key_file,
3482                            const gchar  *group_name,
3483                            const gchar  *key,
3484                            GError      **error)
3485 {
3486   g_return_val_if_fail (key_file != NULL, FALSE);
3487
3488   if (group_name != NULL && key != NULL)
3489     return g_key_file_set_key_comment (key_file, group_name, key, NULL, error);
3490   else if (group_name != NULL)
3491     return g_key_file_set_group_comment (key_file, group_name, NULL, error);
3492   else
3493     return g_key_file_set_top_comment (key_file, NULL, error);
3494 }
3495
3496 /**
3497  * g_key_file_has_group:
3498  * @key_file: a #GKeyFile
3499  * @group_name: a group name
3500  *
3501  * Looks whether the key file has the group @group_name.
3502  *
3503  * Return value: %TRUE if @group_name is a part of @key_file, %FALSE
3504  * otherwise.
3505  * Since: 2.6
3506  **/
3507 gboolean
3508 g_key_file_has_group (GKeyFile    *key_file,
3509                       const gchar *group_name)
3510 {
3511   g_return_val_if_fail (key_file != NULL, FALSE);
3512   g_return_val_if_fail (group_name != NULL, FALSE);
3513
3514   return g_key_file_lookup_group (key_file, group_name) != NULL;
3515 }
3516
3517 /* This code remains from a historical attempt to add a new public API
3518  * which respects the GError rules.
3519  */
3520 static gboolean
3521 g_key_file_has_key_full (GKeyFile     *key_file,
3522                          const gchar  *group_name,
3523                          const gchar  *key,
3524                          gboolean     *has_key,
3525                          GError      **error)
3526 {
3527   GKeyFileKeyValuePair *pair;
3528   GKeyFileGroup *group;
3529
3530   g_return_val_if_fail (key_file != NULL, FALSE);
3531   g_return_val_if_fail (group_name != NULL, FALSE);
3532   g_return_val_if_fail (key != NULL, FALSE);
3533
3534   group = g_key_file_lookup_group (key_file, group_name);
3535
3536   if (!group)
3537     {
3538       g_set_error (error, G_KEY_FILE_ERROR,
3539                    G_KEY_FILE_ERROR_GROUP_NOT_FOUND,
3540                    _("Key file does not have group '%s'"),
3541                    group_name ? group_name : "(null)");
3542
3543       return FALSE;
3544     }
3545
3546   pair = g_key_file_lookup_key_value_pair (key_file, group, key);
3547
3548   if (has_key)
3549     *has_key = pair != NULL;
3550   return TRUE;
3551 }
3552
3553 /**
3554  * g_key_file_has_key: (skip)
3555  * @key_file: a #GKeyFile
3556  * @group_name: a group name
3557  * @key: a key name
3558  * @error: return location for a #GError
3559  *
3560  * Looks whether the key file has the key @key in the group
3561  * @group_name.
3562  *
3563  * Note that this function does not follow the rules for #GError strictly;
3564  * the return value both carries meaning and signals an error.  To use
3565  * this function, you must pass a #GError pointer in @error, and check
3566  * whether it is not %NULL to see if an error occurred.
3567  *
3568  * Language bindings should use g_key_file_get_value() to test whether
3569  * or not a key exists.
3570  *
3571  * Return value: %TRUE if @key is a part of @group_name, %FALSE otherwise
3572  *
3573  * Since: 2.6
3574  **/
3575 gboolean
3576 g_key_file_has_key (GKeyFile     *key_file,
3577                     const gchar  *group_name,
3578                     const gchar  *key,
3579                     GError      **error)
3580 {
3581   GError *temp_error = NULL;
3582   gboolean has_key;
3583
3584   if (g_key_file_has_key_full (key_file, group_name, key, &has_key, &temp_error))
3585     {
3586       return has_key;
3587     }
3588   else
3589     {
3590       g_propagate_error (error, temp_error);
3591       return FALSE;
3592     }
3593 }
3594
3595 static void
3596 g_key_file_add_group (GKeyFile    *key_file,
3597                       const gchar *group_name)
3598 {
3599   GKeyFileGroup *group;
3600
3601   g_return_if_fail (key_file != NULL);
3602   g_return_if_fail (g_key_file_is_group_name (group_name));
3603
3604   group = g_key_file_lookup_group (key_file, group_name);
3605   if (group != NULL)
3606     {
3607       key_file->current_group = group;
3608       return;
3609     }
3610
3611   group = g_slice_new0 (GKeyFileGroup);
3612   group->name = g_strdup (group_name);
3613   group->lookup_map = g_hash_table_new (g_str_hash, g_str_equal);
3614   key_file->groups = g_list_prepend (key_file->groups, group);
3615   key_file->current_group = group;
3616
3617   if (key_file->start_group == NULL)
3618     key_file->start_group = group;
3619
3620   g_hash_table_insert (key_file->group_hash, (gpointer)group->name, group);
3621 }
3622
3623 static void
3624 g_key_file_key_value_pair_free (GKeyFileKeyValuePair *pair)
3625 {
3626   if (pair != NULL)
3627     {
3628       g_free (pair->key);
3629       g_free (pair->value);
3630       g_slice_free (GKeyFileKeyValuePair, pair);
3631     }
3632 }
3633
3634 /* Be careful not to call this function on a node with data in the
3635  * lookup map without removing it from the lookup map, first.
3636  *
3637  * Some current cases where this warning is not a concern are
3638  * when:
3639  *   - the node being removed is a comment node
3640  *   - the entire lookup map is getting destroyed soon after
3641  *     anyway.
3642  */ 
3643 static void
3644 g_key_file_remove_key_value_pair_node (GKeyFile      *key_file,
3645                                        GKeyFileGroup *group,
3646                                        GList         *pair_node)
3647 {
3648
3649   GKeyFileKeyValuePair *pair;
3650
3651   pair = (GKeyFileKeyValuePair *) pair_node->data;
3652
3653   group->key_value_pairs = g_list_remove_link (group->key_value_pairs, pair_node);
3654
3655   g_warn_if_fail (pair->value != NULL);
3656
3657   g_key_file_key_value_pair_free (pair);
3658
3659   g_list_free_1 (pair_node);
3660 }
3661
3662 static void
3663 g_key_file_remove_group_node (GKeyFile *key_file,
3664                               GList    *group_node)
3665 {
3666   GKeyFileGroup *group;
3667   GList *tmp;
3668
3669   group = (GKeyFileGroup *) group_node->data;
3670
3671   if (group->name)
3672     g_hash_table_remove (key_file->group_hash, group->name);
3673
3674   /* If the current group gets deleted make the current group the last
3675    * added group.
3676    */
3677   if (key_file->current_group == group)
3678     {
3679       /* groups should always contain at least the top comment group,
3680        * unless g_key_file_clear has been called
3681        */
3682       if (key_file->groups)
3683         key_file->current_group = (GKeyFileGroup *) key_file->groups->data;
3684       else
3685         key_file->current_group = NULL;
3686     }
3687
3688   /* If the start group gets deleted make the start group the first
3689    * added group.
3690    */
3691   if (key_file->start_group == group)
3692     {
3693       tmp = g_list_last (key_file->groups);
3694       while (tmp != NULL)
3695         {
3696           if (tmp != group_node &&
3697               ((GKeyFileGroup *) tmp->data)->name != NULL)
3698             break;
3699
3700           tmp = tmp->prev;
3701         }
3702
3703       if (tmp)
3704         key_file->start_group = (GKeyFileGroup *) tmp->data;
3705       else
3706         key_file->start_group = NULL;
3707     }
3708
3709   key_file->groups = g_list_remove_link (key_file->groups, group_node);
3710
3711   tmp = group->key_value_pairs;
3712   while (tmp != NULL)
3713     {
3714       GList *pair_node;
3715
3716       pair_node = tmp;
3717       tmp = tmp->next;
3718       g_key_file_remove_key_value_pair_node (key_file, group, pair_node);
3719     }
3720
3721   g_warn_if_fail (group->key_value_pairs == NULL);
3722
3723   if (group->comment)
3724     {
3725       g_key_file_key_value_pair_free (group->comment);
3726       group->comment = NULL;
3727     }
3728
3729   if (group->lookup_map)
3730     {
3731       g_hash_table_destroy (group->lookup_map);
3732       group->lookup_map = NULL;
3733     }
3734
3735   g_free ((gchar *) group->name);
3736   g_slice_free (GKeyFileGroup, group);
3737   g_list_free_1 (group_node);
3738 }
3739
3740 /**
3741  * g_key_file_remove_group:
3742  * @key_file: a #GKeyFile
3743  * @group_name: a group name
3744  * @error: return location for a #GError or %NULL
3745  *
3746  * Removes the specified group, @group_name, 
3747  * from the key file. 
3748  *
3749  * Returns: %TRUE if the group was removed, %FALSE otherwise
3750  *
3751  * Since: 2.6
3752  **/
3753 gboolean
3754 g_key_file_remove_group (GKeyFile     *key_file,
3755                          const gchar  *group_name,
3756                          GError      **error)
3757 {
3758   GList *group_node;
3759
3760   g_return_val_if_fail (key_file != NULL, FALSE);
3761   g_return_val_if_fail (group_name != NULL, FALSE);
3762
3763   group_node = g_key_file_lookup_group_node (key_file, group_name);
3764
3765   if (!group_node)
3766     {
3767       g_set_error (error, G_KEY_FILE_ERROR,
3768                    G_KEY_FILE_ERROR_GROUP_NOT_FOUND,
3769                    _("Key file does not have group '%s'"),
3770                    group_name);
3771       return FALSE;
3772     }
3773
3774   g_key_file_remove_group_node (key_file, group_node);
3775
3776   return TRUE;  
3777 }
3778
3779 static void
3780 g_key_file_add_key_value_pair (GKeyFile             *key_file,
3781                                GKeyFileGroup        *group,
3782                                GKeyFileKeyValuePair *pair)
3783 {
3784   g_hash_table_replace (group->lookup_map, pair->key, pair);
3785   group->key_value_pairs = g_list_prepend (group->key_value_pairs, pair);
3786 }
3787
3788 static void
3789 g_key_file_add_key (GKeyFile      *key_file,
3790                     GKeyFileGroup *group,
3791                     const gchar   *key,
3792                     const gchar   *value)
3793 {
3794   GKeyFileKeyValuePair *pair;
3795
3796   pair = g_slice_new (GKeyFileKeyValuePair);
3797   pair->key = g_strdup (key);
3798   pair->value = g_strdup (value);
3799
3800   g_key_file_add_key_value_pair (key_file, group, pair);
3801 }
3802
3803 /**
3804  * g_key_file_remove_key:
3805  * @key_file: a #GKeyFile
3806  * @group_name: a group name
3807  * @key: a key name to remove
3808  * @error: return location for a #GError or %NULL
3809  *
3810  * Removes @key in @group_name from the key file. 
3811  *
3812  * Returns: %TRUE if the key was removed, %FALSE otherwise
3813  *
3814  * Since: 2.6
3815  **/
3816 gboolean
3817 g_key_file_remove_key (GKeyFile     *key_file,
3818                        const gchar  *group_name,
3819                        const gchar  *key,
3820                        GError      **error)
3821 {
3822   GKeyFileGroup *group;
3823   GKeyFileKeyValuePair *pair;
3824
3825   g_return_val_if_fail (key_file != NULL, FALSE);
3826   g_return_val_if_fail (group_name != NULL, FALSE);
3827   g_return_val_if_fail (key != NULL, FALSE);
3828
3829   pair = NULL;
3830
3831   group = g_key_file_lookup_group (key_file, group_name);
3832   if (!group)
3833     {
3834       g_set_error (error, G_KEY_FILE_ERROR,
3835                    G_KEY_FILE_ERROR_GROUP_NOT_FOUND,
3836                    _("Key file does not have group '%s'"),
3837                    group_name ? group_name : "(null)");
3838       return FALSE;
3839     }
3840
3841   pair = g_key_file_lookup_key_value_pair (key_file, group, key);
3842
3843   if (!pair)
3844     {
3845       g_set_error (error, G_KEY_FILE_ERROR,
3846                    G_KEY_FILE_ERROR_KEY_NOT_FOUND,
3847                    _("Key file does not have key '%s' in group '%s'"),
3848                    key, group->name);
3849       return FALSE;
3850     }
3851
3852   group->key_value_pairs = g_list_remove (group->key_value_pairs, pair);
3853   g_hash_table_remove (group->lookup_map, pair->key);
3854   g_key_file_key_value_pair_free (pair);
3855
3856   return TRUE;
3857 }
3858
3859 static GList *
3860 g_key_file_lookup_group_node (GKeyFile    *key_file,
3861                               const gchar *group_name)
3862 {
3863   GKeyFileGroup *group;
3864   GList *tmp;
3865
3866   for (tmp = key_file->groups; tmp != NULL; tmp = tmp->next)
3867     {
3868       group = (GKeyFileGroup *) tmp->data;
3869
3870       if (group && group->name && strcmp (group->name, group_name) == 0)
3871         break;
3872     }
3873
3874   return tmp;
3875 }
3876
3877 static GKeyFileGroup *
3878 g_key_file_lookup_group (GKeyFile    *key_file,
3879                          const gchar *group_name)
3880 {
3881   return (GKeyFileGroup *)g_hash_table_lookup (key_file->group_hash, group_name);
3882 }
3883
3884 static GList *
3885 g_key_file_lookup_key_value_pair_node (GKeyFile       *key_file,
3886                                        GKeyFileGroup  *group,
3887                                        const gchar    *key)
3888 {
3889   GList *key_node;
3890
3891   for (key_node = group->key_value_pairs;
3892        key_node != NULL;
3893        key_node = key_node->next)
3894     {
3895       GKeyFileKeyValuePair *pair;
3896
3897       pair = (GKeyFileKeyValuePair *) key_node->data; 
3898
3899       if (pair->key && strcmp (pair->key, key) == 0)
3900         break;
3901     }
3902
3903   return key_node;
3904 }
3905
3906 static GKeyFileKeyValuePair *
3907 g_key_file_lookup_key_value_pair (GKeyFile      *key_file,
3908                                   GKeyFileGroup *group,
3909                                   const gchar   *key)
3910 {
3911   return (GKeyFileKeyValuePair *) g_hash_table_lookup (group->lookup_map, key);
3912 }
3913
3914 /* Lines starting with # or consisting entirely of whitespace are merely
3915  * recorded, not parsed. This function assumes all leading whitespace
3916  * has been stripped.
3917  */
3918 static gboolean
3919 g_key_file_line_is_comment (const gchar *line)
3920 {
3921   return (*line == '#' || *line == '\0' || *line == '\n');
3922 }
3923
3924 static gboolean 
3925 g_key_file_is_group_name (const gchar *name)
3926 {
3927   gchar *p, *q;
3928
3929   if (name == NULL)
3930     return FALSE;
3931
3932   p = q = (gchar *) name;
3933   while (*q && *q != ']' && *q != '[' && !g_ascii_iscntrl (*q))
3934     q = g_utf8_find_next_char (q, NULL);
3935   
3936   if (*q != '\0' || q == p)
3937     return FALSE;
3938
3939   return TRUE;
3940 }
3941
3942 static gboolean
3943 g_key_file_is_key_name (const gchar *name)
3944 {
3945   gchar *p, *q;
3946
3947   if (name == NULL)
3948     return FALSE;
3949
3950   p = q = (gchar *) name;
3951   /* We accept a little more than the desktop entry spec says,
3952    * since gnome-vfs uses mime-types as keys in its cache.
3953    */
3954   while (*q && *q != '=' && *q != '[' && *q != ']')
3955     q = g_utf8_find_next_char (q, NULL);
3956   
3957   /* No empty keys, please */
3958   if (q == p)
3959     return FALSE;
3960
3961   /* We accept spaces in the middle of keys to not break
3962    * existing apps, but we don't tolerate initial or final
3963    * spaces, which would lead to silent corruption when
3964    * rereading the file.
3965    */
3966   if (*p == ' ' || q[-1] == ' ')
3967     return FALSE;
3968
3969   if (*q == '[')
3970     {
3971       q++;
3972       while (*q && (g_unichar_isalnum (g_utf8_get_char_validated (q, -1)) || *q == '-' || *q == '_' || *q == '.' || *q == '@'))
3973         q = g_utf8_find_next_char (q, NULL);
3974
3975       if (*q != ']')
3976         return FALSE;     
3977
3978       q++;
3979     }
3980
3981   if (*q != '\0')
3982     return FALSE;
3983
3984   return TRUE;
3985 }
3986
3987 /* A group in a key file is made up of a starting '[' followed by one
3988  * or more letters making up the group name followed by ']'.
3989  */
3990 static gboolean
3991 g_key_file_line_is_group (const gchar *line)
3992 {
3993   gchar *p;
3994
3995   p = (gchar *) line;
3996   if (*p != '[')
3997     return FALSE;
3998
3999   p++;
4000
4001   while (*p && *p != ']')
4002     p = g_utf8_find_next_char (p, NULL);
4003
4004   if (*p != ']')
4005     return FALSE;
4006  
4007   /* silently accept whitespace after the ] */
4008   p = g_utf8_find_next_char (p, NULL);
4009   while (*p == ' ' || *p == '\t')
4010     p = g_utf8_find_next_char (p, NULL);
4011      
4012   if (*p)
4013     return FALSE;
4014
4015   return TRUE;
4016 }
4017
4018 static gboolean
4019 g_key_file_line_is_key_value_pair (const gchar *line)
4020 {
4021   gchar *p;
4022
4023   p = (gchar *) g_utf8_strchr (line, -1, '=');
4024
4025   if (!p)
4026     return FALSE;
4027
4028   /* Key must be non-empty
4029    */
4030   if (*p == line[0])
4031     return FALSE;
4032
4033   return TRUE;
4034 }
4035
4036 static gchar *
4037 g_key_file_parse_value_as_string (GKeyFile     *key_file,
4038                                   const gchar  *value,
4039                                   GSList      **pieces,
4040                                   GError      **error)
4041 {
4042   gchar *string_value, *p, *q0, *q;
4043
4044   string_value = g_new (gchar, strlen (value) + 1);
4045
4046   p = (gchar *) value;
4047   q0 = q = string_value;
4048   while (*p)
4049     {
4050       if (*p == '\\')
4051         {
4052           p++;
4053
4054           switch (*p)
4055             {
4056             case 's':
4057               *q = ' ';
4058               break;
4059
4060             case 'n':
4061               *q = '\n';
4062               break;
4063
4064             case 't':
4065               *q = '\t';
4066               break;
4067
4068             case 'r':
4069               *q = '\r';
4070               break;
4071
4072             case '\\':
4073               *q = '\\';
4074               break;
4075
4076             case '\0':
4077               g_set_error_literal (error, G_KEY_FILE_ERROR,
4078                                    G_KEY_FILE_ERROR_INVALID_VALUE,
4079                                    _("Key file contains escape character "
4080                                      "at end of line"));
4081               break;
4082
4083             default:
4084               if (pieces && *p == key_file->list_separator)
4085                 *q = key_file->list_separator;
4086               else
4087                 {
4088                   *q++ = '\\';
4089                   *q = *p;
4090                   
4091                   if (*error == NULL)
4092                     {
4093                       gchar sequence[3];
4094                       
4095                       sequence[0] = '\\';
4096                       sequence[1] = *p;
4097                       sequence[2] = '\0';
4098                       
4099                       g_set_error (error, G_KEY_FILE_ERROR,
4100                                    G_KEY_FILE_ERROR_INVALID_VALUE,
4101                                    _("Key file contains invalid escape "
4102                                      "sequence '%s'"), sequence);
4103                     }
4104                 }
4105               break;
4106             }
4107         }
4108       else
4109         {
4110           *q = *p;
4111           if (pieces && (*p == key_file->list_separator))
4112             {
4113               *pieces = g_slist_prepend (*pieces, g_strndup (q0, q - q0));
4114               q0 = q + 1; 
4115             }
4116         }
4117
4118       if (*p == '\0')
4119         break;
4120
4121       q++;
4122       p++;
4123     }
4124
4125   *q = '\0';
4126   if (pieces)
4127   {
4128     if (q0 < q)
4129       *pieces = g_slist_prepend (*pieces, g_strndup (q0, q - q0));
4130     *pieces = g_slist_reverse (*pieces);
4131   }
4132
4133   return string_value;
4134 }
4135
4136 static gchar *
4137 g_key_file_parse_string_as_value (GKeyFile    *key_file,
4138                                   const gchar *string,
4139                                   gboolean     escape_separator)
4140 {
4141   gchar *value, *p, *q;
4142   gsize length;
4143   gboolean parsing_leading_space;
4144
4145   length = strlen (string) + 1;
4146
4147   /* Worst case would be that every character needs to be escaped.
4148    * In other words every character turns to two characters
4149    */
4150   value = g_new (gchar, 2 * length);
4151
4152   p = (gchar *) string;
4153   q = value;
4154   parsing_leading_space = TRUE;
4155   while (p < (string + length - 1))
4156     {
4157       gchar escaped_character[3] = { '\\', 0, 0 };
4158
4159       switch (*p)
4160         {
4161         case ' ':
4162           if (parsing_leading_space)
4163             {
4164               escaped_character[1] = 's';
4165               strcpy (q, escaped_character);
4166               q += 2;
4167             }
4168           else
4169             {
4170               *q = *p;
4171               q++;
4172             }
4173           break;
4174         case '\t':
4175           if (parsing_leading_space)
4176             {
4177               escaped_character[1] = 't';
4178               strcpy (q, escaped_character);
4179               q += 2;
4180             }
4181           else
4182             {
4183               *q = *p;
4184               q++;
4185             }
4186           break;
4187         case '\n':
4188           escaped_character[1] = 'n';
4189           strcpy (q, escaped_character);
4190           q += 2;
4191           break;
4192         case '\r':
4193           escaped_character[1] = 'r';
4194           strcpy (q, escaped_character);
4195           q += 2;
4196           break;
4197         case '\\':
4198           escaped_character[1] = '\\';
4199           strcpy (q, escaped_character);
4200           q += 2;
4201           parsing_leading_space = FALSE;
4202           break;
4203         default:
4204           if (escape_separator && *p == key_file->list_separator)
4205             {
4206               escaped_character[1] = key_file->list_separator;
4207               strcpy (q, escaped_character);
4208               q += 2;
4209               parsing_leading_space = TRUE;
4210             }
4211           else 
4212             {
4213               *q = *p;
4214               q++;
4215               parsing_leading_space = FALSE;
4216             }
4217           break;
4218         }
4219       p++;
4220     }
4221   *q = '\0';
4222
4223   return value;
4224 }
4225
4226 static gint
4227 g_key_file_parse_value_as_integer (GKeyFile     *key_file,
4228                                    const gchar  *value,
4229                                    GError      **error)
4230 {
4231   gchar *eof_int;
4232   glong long_value;
4233   gint int_value;
4234
4235   errno = 0;
4236   long_value = strtol (value, &eof_int, 10);
4237
4238   if (*value == '\0' || (*eof_int != '\0' && !g_ascii_isspace(*eof_int)))
4239     {
4240       gchar *value_utf8 = _g_utf8_make_valid (value);
4241       g_set_error (error, G_KEY_FILE_ERROR,
4242                    G_KEY_FILE_ERROR_INVALID_VALUE,
4243                    _("Value '%s' cannot be interpreted "
4244                      "as a number."), value_utf8);
4245       g_free (value_utf8);
4246
4247       return 0;
4248     }
4249
4250   int_value = long_value;
4251   if (int_value != long_value || errno == ERANGE)
4252     {
4253       gchar *value_utf8 = _g_utf8_make_valid (value);
4254       g_set_error (error,
4255                    G_KEY_FILE_ERROR, 
4256                    G_KEY_FILE_ERROR_INVALID_VALUE,
4257                    _("Integer value '%s' out of range"), 
4258                    value_utf8);
4259       g_free (value_utf8);
4260
4261       return 0;
4262     }
4263   
4264   return int_value;
4265 }
4266
4267 static gchar *
4268 g_key_file_parse_integer_as_value (GKeyFile *key_file,
4269                                    gint      value)
4270
4271 {
4272   return g_strdup_printf ("%d", value);
4273 }
4274
4275 static gdouble
4276 g_key_file_parse_value_as_double  (GKeyFile     *key_file,
4277                                    const gchar  *value,
4278                                    GError      **error)
4279 {
4280   gchar *end_of_valid_d;
4281   gdouble double_value = 0;
4282
4283   double_value = g_ascii_strtod (value, &end_of_valid_d);
4284
4285   if (*end_of_valid_d != '\0' || end_of_valid_d == value)
4286     {
4287       gchar *value_utf8 = _g_utf8_make_valid (value);
4288       g_set_error (error, G_KEY_FILE_ERROR,
4289                    G_KEY_FILE_ERROR_INVALID_VALUE,
4290                    _("Value '%s' cannot be interpreted "
4291                      "as a float number."), 
4292                    value_utf8);
4293       g_free (value_utf8);
4294     }
4295
4296   return double_value;
4297 }
4298
4299 static gboolean
4300 g_key_file_parse_value_as_boolean (GKeyFile     *key_file,
4301                                    const gchar  *value,
4302                                    GError      **error)
4303 {
4304   gchar *value_utf8;
4305
4306   if (strcmp (value, "true") == 0 || strcmp (value, "1") == 0)
4307     return TRUE;
4308   else if (strcmp (value, "false") == 0 || strcmp (value, "0") == 0)
4309     return FALSE;
4310
4311   value_utf8 = _g_utf8_make_valid (value);
4312   g_set_error (error, G_KEY_FILE_ERROR,
4313                G_KEY_FILE_ERROR_INVALID_VALUE,
4314                _("Value '%s' cannot be interpreted "
4315                  "as a boolean."), value_utf8);
4316   g_free (value_utf8);
4317
4318   return FALSE;
4319 }
4320
4321 static gchar *
4322 g_key_file_parse_boolean_as_value (GKeyFile *key_file,
4323                                    gboolean  value)
4324 {
4325   if (value)
4326     return g_strdup ("true");
4327   else
4328     return g_strdup ("false");
4329 }
4330
4331 static gchar *
4332 g_key_file_parse_value_as_comment (GKeyFile    *key_file,
4333                                    const gchar *value)
4334 {
4335   GString *string;
4336   gchar **lines;
4337   gsize i;
4338
4339   string = g_string_sized_new (512);
4340
4341   lines = g_strsplit (value, "\n", 0);
4342
4343   for (i = 0; lines[i] != NULL; i++)
4344     {
4345         if (lines[i][0] != '#')
4346            g_string_append_printf (string, "%s\n", lines[i]);
4347         else 
4348            g_string_append_printf (string, "%s\n", lines[i] + 1);
4349     }
4350   g_strfreev (lines);
4351
4352   return g_string_free (string, FALSE);
4353 }
4354
4355 static gchar *
4356 g_key_file_parse_comment_as_value (GKeyFile      *key_file,
4357                                    const gchar   *comment)
4358 {
4359   GString *string;
4360   gchar **lines;
4361   gsize i;
4362
4363   string = g_string_sized_new (512);
4364
4365   lines = g_strsplit (comment, "\n", 0);
4366
4367   for (i = 0; lines[i] != NULL; i++)
4368     g_string_append_printf (string, "#%s%s", lines[i], 
4369                             lines[i + 1] == NULL? "" : "\n");
4370   g_strfreev (lines);
4371
4372   return g_string_free (string, FALSE);
4373 }
4374
4375 /**
4376  * g_key_file_save_to_file:
4377  * @key_file: a #GKeyFile
4378  * @filename: the name of the file to write to
4379  * @error: a pointer to a %NULL #GError, or %NULL
4380  *
4381  * Writes the contents of @key_file to @filename using
4382  * g_file_set_contents().
4383  *
4384  * This function can fail for any of the reasons that
4385  * g_file_set_contents() may fail.
4386  *
4387  * Returns: %TRUE if successful, else %FALSE with @error set
4388  *
4389  * Since: 2.40
4390  */
4391 gboolean
4392 g_key_file_save_to_file (GKeyFile     *key_file,
4393                          const gchar  *filename,
4394                          GError      **error)
4395 {
4396   gchar *contents;
4397   gboolean success;
4398   gsize length;
4399
4400   g_return_val_if_fail (key_file != NULL, FALSE);
4401   g_return_val_if_fail (filename != NULL, FALSE);
4402   g_return_val_if_fail (error == NULL || *error == NULL, FALSE);
4403
4404   contents = g_key_file_to_data (key_file, &length, NULL);
4405   g_assert (contents != NULL);
4406
4407   success = g_file_set_contents (filename, contents, length, error);
4408   g_free (contents);
4409
4410   return success;
4411 }