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