summaryrefslogtreecommitdiff
path: root/pluma/pluma-document.c
blob: 563e950085e87480070f592a7e6291852fb2cc9b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
/*
 * pluma-document.c
 * This file is part of pluma
 *
 * Copyright (C) 1998, 1999 Alex Roberts, Evan Lawrence
 * Copyright (C) 2000, 2001 Chema Celorio, Paolo Maggi 
 * Copyright (C) 2002-2005 Paolo Maggi 
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, 
 * Boston, MA 02110-1301, USA.
 */
 
/*
 * Modified by the pluma Team, 1998-2005. See the AUTHORS file for a 
 * list of people on the pluma Team.  
 * See the ChangeLog files for a list of changes. 
 *
 * $Id$
 */

#ifdef HAVE_CONFIG_H
#include <config.h>
#endif

#include <string.h>
#include <stdlib.h>

#include <glib/gi18n.h>
#include <gtk/gtk.h>
#if GTK_CHECK_VERSION (3, 0, 0)
#include <gtksourceview/gtksource.h>
#else
#include <gtksourceview/gtksourceiter.h>
#endif

#include "pluma-prefs-manager-app.h"
#include "pluma-document.h"
#include "pluma-debug.h"
#include "pluma-utils.h"
#include "pluma-language-manager.h"
#include "pluma-style-scheme-manager.h"
#include "pluma-document-loader.h"
#include "pluma-document-saver.h"
#include "pluma-marshal.h"
#include "pluma-enum-types.h"
#include "plumatextregion.h"

#ifndef ENABLE_GVFS_METADATA
#include "pluma-metadata-manager.h"
#else
#define METADATA_QUERY "metadata::*"
#endif

#undef ENABLE_PROFILE 

#ifdef ENABLE_PROFILE
#define PROFILE(x) x
#else
#define PROFILE(x)
#endif

PROFILE (static GTimer *timer = NULL)

#ifdef MAXPATHLEN
#define PLUMA_MAX_PATH_LEN  MAXPATHLEN
#elif defined (PATH_MAX)
#define PLUMA_MAX_PATH_LEN  PATH_MAX
#else
#define PLUMA_MAX_PATH_LEN  2048
#endif

#define PLUMA_DOCUMENT_GET_PRIVATE(object)(G_TYPE_INSTANCE_GET_PRIVATE ((object), PLUMA_TYPE_DOCUMENT, PlumaDocumentPrivate))

static void	pluma_document_load_real	(PlumaDocument          *doc,
						 const gchar            *uri,
						 const PlumaEncoding    *encoding,
						 gint                    line_pos,
						 gboolean                create);
static void	pluma_document_save_real	(PlumaDocument          *doc,
						 const gchar            *uri,
						 const PlumaEncoding    *encoding,
						 PlumaDocumentSaveFlags  flags);
static void	to_search_region_range 		(PlumaDocument *doc,
						 GtkTextIter   *start, 
						 GtkTextIter   *end);
static void 	insert_text_cb		 	(PlumaDocument *doc, 
						 GtkTextIter   *pos,
						 const gchar   *text, 
						 gint           length);
						 
static void	delete_range_cb 		(PlumaDocument *doc, 
						 GtkTextIter   *start,
						 GtkTextIter   *end);
			     
struct _PlumaDocumentPrivate
{
	gchar	    *uri;
	gint 	     untitled_number;
	gchar       *short_name;

	GFileInfo   *metadata_info;

	const PlumaEncoding *encoding;

	gchar	    *content_type;

	GTimeVal     mtime;
	GTimeVal     time_of_last_save_or_load;

	guint        search_flags;
	gchar       *search_text;
	gint	     num_of_lines_search_text;

	PlumaDocumentNewlineType newline_type;

	/* Temp data while loading */
	PlumaDocumentLoader *loader;
	gboolean             create; /* Create file if uri points 
	                              * to a non existing file */
	const PlumaEncoding *requested_encoding;
	gint                 requested_line_pos;

	/* Saving stuff */
	PlumaDocumentSaver *saver;

	/* Search highlighting support variables */
	PlumaTextRegion *to_search_region;
	GtkTextTag      *found_tag;

	/* Mount operation factory */
	PlumaMountOperationFactory  mount_operation_factory;
	gpointer		    mount_operation_userdata;

	gint readonly : 1;
	gint last_save_was_manually : 1; 
	gint language_set_by_user : 1;
	gint stop_cursor_moved_emission : 1;
	gint dispose_has_run : 1;
};

enum {
	PROP_0,

	PROP_URI,
	PROP_SHORTNAME,
	PROP_CONTENT_TYPE,
	PROP_MIME_TYPE,
	PROP_READ_ONLY,
	PROP_ENCODING,
	PROP_CAN_SEARCH_AGAIN,
	PROP_ENABLE_SEARCH_HIGHLIGHTING,
	PROP_NEWLINE_TYPE
};

enum {
	CURSOR_MOVED,
	LOAD,
	LOADING,
	LOADED,
	SAVE,
	SAVING,
	SAVED,
	SEARCH_HIGHLIGHT_UPDATED,
	LAST_SIGNAL
};

static guint document_signals[LAST_SIGNAL] = { 0 };

#if GTK_CHECK_VERSION (3, 0, 0)
G_DEFINE_TYPE(PlumaDocument, pluma_document, GTK_SOURCE_TYPE_BUFFER)
#else
G_DEFINE_TYPE(PlumaDocument, pluma_document, GTK_TYPE_SOURCE_BUFFER)
#endif

GQuark
pluma_document_error_quark (void)
{
	static GQuark quark = 0;

	if (G_UNLIKELY (quark == 0))
		quark = g_quark_from_static_string ("pluma_io_load_error");

	return quark;
}

static GHashTable *allocated_untitled_numbers = NULL;

static gint
get_untitled_number (void)
{
	gint i = 1;

	if (allocated_untitled_numbers == NULL)
		allocated_untitled_numbers = g_hash_table_new (NULL, NULL);

	g_return_val_if_fail (allocated_untitled_numbers != NULL, -1);

	while (TRUE)
	{
		if (g_hash_table_lookup (allocated_untitled_numbers, GINT_TO_POINTER (i)) == NULL)
		{
			g_hash_table_insert (allocated_untitled_numbers, 
					     GINT_TO_POINTER (i),
					     GINT_TO_POINTER (i));

			return i;
		}

		++i;
	}
}

static void
release_untitled_number (gint n)
{
	g_return_if_fail (allocated_untitled_numbers != NULL);

	g_hash_table_remove (allocated_untitled_numbers, GINT_TO_POINTER (n));
}

static void
pluma_document_dispose (GObject *object)
{
	PlumaDocument *doc = PLUMA_DOCUMENT (object); 

	pluma_debug (DEBUG_DOCUMENT);

	/* Metadata must be saved here and not in finalize
	 * because the language is gone by the time finalize runs.
	 * beside if some plugin prevents proper finalization by
	 * holding a ref to the doc, we still save the metadata */
	if ((!doc->priv->dispose_has_run) && (doc->priv->uri != NULL))
	{
		GtkTextIter iter;
		gchar *position;
		const gchar *language = NULL;

		if (doc->priv->language_set_by_user)
		{
			GtkSourceLanguage *lang;

			lang = pluma_document_get_language (doc);

			if (lang == NULL)
				language = "_NORMAL_";
			else
				language = gtk_source_language_get_id (lang);
		}

		gtk_text_buffer_get_iter_at_mark (
				GTK_TEXT_BUFFER (doc),
				&iter,
				gtk_text_buffer_get_insert (GTK_TEXT_BUFFER (doc)));

		position = g_strdup_printf ("%d", 
					    gtk_text_iter_get_offset (&iter));

		if (language == NULL)
			pluma_document_set_metadata (doc, PLUMA_METADATA_ATTRIBUTE_POSITION,
						     position, NULL);
		else
			pluma_document_set_metadata (doc, PLUMA_METADATA_ATTRIBUTE_POSITION,
						     position, PLUMA_METADATA_ATTRIBUTE_LANGUAGE,
						     language, NULL);
		g_free (position);
	}

	if (doc->priv->loader)
	{
		g_object_unref (doc->priv->loader);
		doc->priv->loader = NULL;
	}

	if (doc->priv->metadata_info != NULL)
	{
		g_object_unref (doc->priv->metadata_info);
		doc->priv->metadata_info = NULL;
	}

	doc->priv->dispose_has_run = TRUE;

	G_OBJECT_CLASS (pluma_document_parent_class)->dispose (object);
}

static void
pluma_document_finalize (GObject *object)
{
	PlumaDocument *doc = PLUMA_DOCUMENT (object); 

	pluma_debug (DEBUG_DOCUMENT);

	if (doc->priv->untitled_number > 0)
	{
		g_return_if_fail (doc->priv->uri == NULL);
		release_untitled_number (doc->priv->untitled_number);
	}

	g_free (doc->priv->uri);
	g_free (doc->priv->content_type);
	g_free (doc->priv->search_text);

	if (doc->priv->to_search_region != NULL)
	{
		/* we can't delete marks if we're finalizing the buffer */
		pluma_text_region_destroy (doc->priv->to_search_region, FALSE);
	}

	G_OBJECT_CLASS (pluma_document_parent_class)->finalize (object);
}

static void
pluma_document_get_property (GObject    *object,
			     guint       prop_id,
			     GValue     *value,
			     GParamSpec *pspec)
{
	PlumaDocument *doc = PLUMA_DOCUMENT (object);

	switch (prop_id)
	{
		case PROP_URI:
			g_value_set_string (value, doc->priv->uri);
			break;
		case PROP_SHORTNAME:
			g_value_take_string (value, pluma_document_get_short_name_for_display (doc));
			break;
		case PROP_CONTENT_TYPE:
			g_value_take_string (value, pluma_document_get_content_type (doc));
			break;
		case PROP_MIME_TYPE:
			g_value_take_string (value, pluma_document_get_mime_type (doc));
			break;
		case PROP_READ_ONLY:
			g_value_set_boolean (value, doc->priv->readonly);
			break;
		case PROP_ENCODING:
			g_value_set_boxed (value, doc->priv->encoding);
			break;
		case PROP_CAN_SEARCH_AGAIN:
			g_value_set_boolean (value, pluma_document_get_can_search_again (doc));
			break;
		case PROP_ENABLE_SEARCH_HIGHLIGHTING:
			g_value_set_boolean (value, pluma_document_get_enable_search_highlighting (doc));
			break;
		case PROP_NEWLINE_TYPE:
			g_value_set_enum (value, doc->priv->newline_type);
			break;
		default:
			G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
			break;
	}
}

static void
pluma_document_set_property (GObject      *object,
			     guint         prop_id,
			     const GValue *value,
			     GParamSpec   *pspec)
{
	PlumaDocument *doc = PLUMA_DOCUMENT (object);

	switch (prop_id)
	{
		case PROP_ENABLE_SEARCH_HIGHLIGHTING:
			pluma_document_set_enable_search_highlighting (doc,
								       g_value_get_boolean (value));
			break;
		case PROP_NEWLINE_TYPE:
			pluma_document_set_newline_type (doc,
							 g_value_get_enum (value));
			break;
		case PROP_SHORTNAME:
			pluma_document_set_short_name_for_display (doc,
			                                           g_value_get_string (value));
			break;
		case PROP_CONTENT_TYPE:
			pluma_document_set_content_type (doc,
			                                 g_value_get_string (value));
			break;
		default:
			G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
			break;
	}
}

static void
emit_cursor_moved (PlumaDocument *doc)
{
	if (!doc->priv->stop_cursor_moved_emission)
	{
		g_signal_emit (doc,
			       document_signals[CURSOR_MOVED],
			       0);
	}
}

static void
pluma_document_mark_set (GtkTextBuffer     *buffer,
                         const GtkTextIter *iter,
                         GtkTextMark       *mark)
{
	PlumaDocument *doc = PLUMA_DOCUMENT (buffer);

	if (GTK_TEXT_BUFFER_CLASS (pluma_document_parent_class)->mark_set)
		GTK_TEXT_BUFFER_CLASS (pluma_document_parent_class)->mark_set (buffer,
									       iter,
									       mark);

	if (mark == gtk_text_buffer_get_insert (buffer))
	{
		emit_cursor_moved (doc);
	}
}

static void
pluma_document_changed (GtkTextBuffer *buffer)
{
	emit_cursor_moved (PLUMA_DOCUMENT (buffer));

	GTK_TEXT_BUFFER_CLASS (pluma_document_parent_class)->changed (buffer);
}

static void 
pluma_document_class_init (PlumaDocumentClass *klass)
{
	GObjectClass *object_class = G_OBJECT_CLASS (klass);
	GtkTextBufferClass *buf_class = GTK_TEXT_BUFFER_CLASS (klass);

	object_class->dispose = pluma_document_dispose;
	object_class->finalize = pluma_document_finalize;
	object_class->get_property = pluma_document_get_property;
	object_class->set_property = pluma_document_set_property;

	buf_class->mark_set = pluma_document_mark_set;
	buf_class->changed = pluma_document_changed;

	klass->load = pluma_document_load_real;
	klass->save = pluma_document_save_real;

	g_object_class_install_property (object_class, PROP_URI,
					 g_param_spec_string ("uri",
							      "URI",
							      "The document's URI",
							      NULL,
							      G_PARAM_READABLE |
							      G_PARAM_STATIC_STRINGS));

	g_object_class_install_property (object_class, PROP_SHORTNAME,
					 g_param_spec_string ("shortname",
							      "Short Name",
							      "The document's short name",
							      NULL,
							      G_PARAM_READWRITE |
							      G_PARAM_STATIC_STRINGS));

	g_object_class_install_property (object_class, PROP_CONTENT_TYPE,
					 g_param_spec_string ("content-type",
							      "Content Type",
							      "The document's Content Type",
							      NULL,
							      G_PARAM_READWRITE |
							      G_PARAM_STATIC_STRINGS));

	g_object_class_install_property (object_class, PROP_MIME_TYPE,
					 g_param_spec_string ("mime-type",
							      "MIME Type",
							      "The document's MIME Type",
							      "text/plain",
							      G_PARAM_READABLE |
							      G_PARAM_STATIC_STRINGS));

	g_object_class_install_property (object_class, PROP_READ_ONLY,
					 g_param_spec_boolean ("read-only",
							       "Read Only",
							       "Whether the document is read only or not",
							       FALSE,
							       G_PARAM_READABLE |
							       G_PARAM_STATIC_STRINGS));

	g_object_class_install_property (object_class, PROP_ENCODING,
					 g_param_spec_boxed ("encoding",
							     "Encoding",
							     "The PlumaEncoding used for the document",
							     PLUMA_TYPE_ENCODING,
							     G_PARAM_READABLE |
							     G_PARAM_STATIC_STRINGS));

	g_object_class_install_property (object_class, PROP_CAN_SEARCH_AGAIN,
					 g_param_spec_boolean ("can-search-again",
							       "Can search again",
							       "Whether it's possible to search again in the document",
							       FALSE,
							       G_PARAM_READABLE |
							       G_PARAM_STATIC_STRINGS));

	g_object_class_install_property (object_class, PROP_ENABLE_SEARCH_HIGHLIGHTING,
					 g_param_spec_boolean ("enable-search-highlighting",
							       "Enable Search Highlighting",
							       "Whether all the occurences of the searched string must be highlighted",
							       FALSE,
							       G_PARAM_READWRITE |
							       G_PARAM_STATIC_STRINGS));

	/**
	 * PlumaDocument:newline-type:
	 *
	 * The :newline-type property determines what is considered
	 * as a line ending when saving the document
	 */
	g_object_class_install_property (object_class, PROP_NEWLINE_TYPE,
	                                 g_param_spec_enum ("newline-type",
	                                                    "Newline type",
	                                                    "The accepted types of line ending",
	                                                    PLUMA_TYPE_DOCUMENT_NEWLINE_TYPE,
	                                                    PLUMA_DOCUMENT_NEWLINE_TYPE_LF,
	                                                    G_PARAM_READWRITE |
	                                                    G_PARAM_STATIC_NAME |
	                                                    G_PARAM_STATIC_BLURB));

	/* This signal is used to update the cursor position is the statusbar,
	 * it's emitted either when the insert mark is moved explicitely or
	 * when the buffer changes (insert/delete).
	 * We prevent the emission of the signal during replace_all to 
	 * improve performance.
	 */
	document_signals[CURSOR_MOVED] =
   		g_signal_new ("cursor-moved",
			      G_OBJECT_CLASS_TYPE (object_class),
			      G_SIGNAL_RUN_LAST,
			      G_STRUCT_OFFSET (PlumaDocumentClass, cursor_moved),
			      NULL, NULL,
			      g_cclosure_marshal_VOID__VOID,
			      G_TYPE_NONE,
			      0);

	/**
	 * PlumaDocument::load:
	 * @document: the #PlumaDocument.
	 * @uri: the uri where to load the document from.
	 * @encoding: the #PlumaEncoding to encode the document.
	 * @line_pos: the line to show.
	 * @create: whether the document should be created if it doesn't exist.
	 *
	 * The "load" signal is emitted when a document is loaded.
	 *
	 * Since: 2.22
	 */
	document_signals[LOAD] =
		g_signal_new ("load",
			      G_OBJECT_CLASS_TYPE (object_class),
			      G_SIGNAL_RUN_LAST,
			      G_STRUCT_OFFSET (PlumaDocumentClass, load),
			      NULL, NULL,
			      pluma_marshal_VOID__STRING_BOXED_INT_BOOLEAN,
			      G_TYPE_NONE,
			      4,
			      G_TYPE_STRING,
			      /* we rely on the fact that the PlumaEncoding pointer stays
			       * the same forever */
			      PLUMA_TYPE_ENCODING | G_SIGNAL_TYPE_STATIC_SCOPE,
			      G_TYPE_INT,
			      G_TYPE_BOOLEAN);


	document_signals[LOADING] =
		g_signal_new ("loading",
			      G_OBJECT_CLASS_TYPE (object_class),
			      G_SIGNAL_RUN_LAST,
			      G_STRUCT_OFFSET (PlumaDocumentClass, loading),
			      NULL, NULL,
			      pluma_marshal_VOID__UINT64_UINT64,
			      G_TYPE_NONE,
			      2,
			      G_TYPE_UINT64,
			      G_TYPE_UINT64);

	document_signals[LOADED] =
   		g_signal_new ("loaded",
			      G_OBJECT_CLASS_TYPE (object_class),
			      G_SIGNAL_RUN_LAST,
			      G_STRUCT_OFFSET (PlumaDocumentClass, loaded),
			      NULL, NULL,
			      g_cclosure_marshal_VOID__POINTER,
			      G_TYPE_NONE,
			      1,
			      G_TYPE_POINTER);

	/**
	 * PlumaDocument::save:
	 * @document: the #PlumaDocument.
	 * @uri: the uri where the document is about to be saved.
	 * @encoding: the #PlumaEncoding used to save the document.
	 * @flags: the #PlumaDocumentSaveFlags for the save operation.
	 *
	 * The "save" signal is emitted when the document is saved.
	 *
	 * Since: 2.20
	 */
	document_signals[SAVE] =
		g_signal_new ("save",
			      G_OBJECT_CLASS_TYPE (object_class),
			      G_SIGNAL_RUN_LAST,
			      G_STRUCT_OFFSET (PlumaDocumentClass, save),
			      NULL, NULL,
			      pluma_marshal_VOID__STRING_BOXED_FLAGS,
			      G_TYPE_NONE,
			      3,
			      G_TYPE_STRING,
			      /* we rely on the fact that the PlumaEncoding pointer stays
			       * the same forever */
			      PLUMA_TYPE_ENCODING | G_SIGNAL_TYPE_STATIC_SCOPE,
			      PLUMA_TYPE_DOCUMENT_SAVE_FLAGS);

	document_signals[SAVING] =
   		g_signal_new ("saving",
			      G_OBJECT_CLASS_TYPE (object_class),
			      G_SIGNAL_RUN_LAST,
			      G_STRUCT_OFFSET (PlumaDocumentClass, saving),
			      NULL, NULL,
			      pluma_marshal_VOID__UINT64_UINT64,
			      G_TYPE_NONE,
			      2,
			      G_TYPE_UINT64,
			      G_TYPE_UINT64);

	document_signals[SAVED] =
   		g_signal_new ("saved",
			      G_OBJECT_CLASS_TYPE (object_class),
			      G_SIGNAL_RUN_LAST,
			      G_STRUCT_OFFSET (PlumaDocumentClass, saved),
			      NULL, NULL,
			      g_cclosure_marshal_VOID__POINTER,
			      G_TYPE_NONE,
			      1,
			      G_TYPE_POINTER);

	document_signals[SEARCH_HIGHLIGHT_UPDATED] =
	    	g_signal_new ("search_highlight_updated",
			      G_OBJECT_CLASS_TYPE (object_class),
			      G_SIGNAL_RUN_LAST,
			      G_STRUCT_OFFSET (PlumaDocumentClass, search_highlight_updated),
			      NULL, NULL,
			      pluma_marshal_VOID__BOXED_BOXED,
			      G_TYPE_NONE, 
			      2, 
			      GTK_TYPE_TEXT_ITER | G_SIGNAL_TYPE_STATIC_SCOPE,
			      GTK_TYPE_TEXT_ITER | G_SIGNAL_TYPE_STATIC_SCOPE);

	g_type_class_add_private (object_class, sizeof(PlumaDocumentPrivate));
}

static void
set_language (PlumaDocument     *doc, 
              GtkSourceLanguage *lang,
              gboolean           set_by_user)
{
	GtkSourceLanguage *old_lang;

	pluma_debug (DEBUG_DOCUMENT);
	
	old_lang = gtk_source_buffer_get_language (GTK_SOURCE_BUFFER (doc));
	
	if (old_lang == lang)
		return;

	gtk_source_buffer_set_language (GTK_SOURCE_BUFFER (doc), lang);

	if (lang != NULL)
		gtk_source_buffer_set_highlight_syntax (GTK_SOURCE_BUFFER (doc),
				 pluma_prefs_manager_get_enable_syntax_highlighting ());
	else
		gtk_source_buffer_set_highlight_syntax (GTK_SOURCE_BUFFER (doc), 
				 FALSE);

	if (set_by_user && (doc->priv->uri != NULL))
	{
		pluma_document_set_metadata (doc, PLUMA_METADATA_ATTRIBUTE_LANGUAGE,
			(lang == NULL) ? "_NORMAL_" : gtk_source_language_get_id (lang),
			NULL);
	}

	doc->priv->language_set_by_user = set_by_user;
}

static void
set_encoding (PlumaDocument       *doc, 
	      const PlumaEncoding *encoding,
	      gboolean             set_by_user)
{
	g_return_if_fail (encoding != NULL);

	pluma_debug (DEBUG_DOCUMENT);

	if (doc->priv->encoding == encoding)
		return;

	doc->priv->encoding = encoding;

	if (set_by_user)
	{
		const gchar *charset;

		charset = pluma_encoding_get_charset (encoding);

		pluma_document_set_metadata (doc, PLUMA_METADATA_ATTRIBUTE_ENCODING,
					     charset, NULL);
	}

	g_object_notify (G_OBJECT (doc), "encoding");
}

static GtkSourceStyleScheme *
get_default_style_scheme (void)
{
	gchar *scheme_id;
	GtkSourceStyleScheme *def_style;
	GtkSourceStyleSchemeManager *manager;

	manager = pluma_get_style_scheme_manager ();
	scheme_id = pluma_prefs_manager_get_source_style_scheme ();
	def_style = gtk_source_style_scheme_manager_get_scheme (manager,
								scheme_id);

	if (def_style == NULL)
	{
		g_warning ("Default style scheme '%s' cannot be found, falling back to 'classic' style scheme ", scheme_id);

		def_style = gtk_source_style_scheme_manager_get_scheme (manager, "classic");
		if (def_style == NULL) 
		{
			g_warning ("Style scheme 'classic' cannot be found, check your GtkSourceView installation.");			
		}
	}

	g_free (scheme_id);

	return def_style;
}

static void
on_uri_changed (PlumaDocument *doc,
		GParamSpec    *pspec,
		gpointer       useless)
{
#ifdef ENABLE_GVFS_METADATA
	GFile *location;

	location = pluma_document_get_location (doc);

	/* load metadata for this uri: we load sync since metadata is
	 * always local so it should be fast and we need the information
	 * right after the uri was set.
	 */
	if (location != NULL)
	{
		GError *error = NULL;

		if (doc->priv->metadata_info != NULL)
			g_object_unref (doc->priv->metadata_info);

		doc->priv->metadata_info = g_file_query_info (location,
							      METADATA_QUERY,
							      G_FILE_QUERY_INFO_NONE,
							      NULL,
							      &error);

		if (error != NULL)
		{
			if (error->code != G_FILE_ERROR_ISDIR &&
			    error->code != G_FILE_ERROR_NOTDIR &&
			    error->code != G_FILE_ERROR_NOENT)
			{
				g_warning ("%s", error->message);
			}

			g_error_free (error);
		}

		g_object_unref (location);
	}
#endif
}

static GtkSourceLanguage *
guess_language (PlumaDocument *doc,
		const gchar   *content_type)
{
	gchar *data;
	GtkSourceLanguage *language = NULL;

	data = pluma_document_get_metadata (doc, PLUMA_METADATA_ATTRIBUTE_LANGUAGE);

	if (data != NULL)
	{
		pluma_debug_message (DEBUG_DOCUMENT, "Language from metadata: %s", data);

		if (strcmp (data, "_NORMAL_") != 0)
		{
			language = gtk_source_language_manager_get_language (
						pluma_get_language_manager (),
						data);
		}

		g_free (data);
	}
	else
	{
		GFile *file;
		gchar *basename = NULL;

		file = pluma_document_get_location (doc);
		pluma_debug_message (DEBUG_DOCUMENT, "Sniffing Language");

		if (file)
		{
			basename = g_file_get_basename (file);
		}
		else if (doc->priv->short_name != NULL)
		{
			basename = g_strdup (doc->priv->short_name);
		}

		language = gtk_source_language_manager_guess_language (
					pluma_get_language_manager (),
					basename,
					content_type);

		g_free (basename);

		if (file != NULL)
		{
			g_object_unref (file);
		}
	}

	return language;
}

static void
on_content_type_changed (PlumaDocument *doc,
			 GParamSpec    *pspec,
			 gpointer       useless)
{
	if (!doc->priv->language_set_by_user)
	{
		GtkSourceLanguage *language;

		language = guess_language (doc, doc->priv->content_type);

		pluma_debug_message (DEBUG_DOCUMENT, "Language: %s",
				     language != NULL ? gtk_source_language_get_name (language) : "None");

		set_language (doc, language, FALSE);
	}
}

static gchar *
get_default_content_type (void)
{
	return g_content_type_from_mime_type ("text/plain");
}

static void
pluma_document_init (PlumaDocument *doc)
{
	GtkSourceStyleScheme *style_scheme;

	pluma_debug (DEBUG_DOCUMENT);

	doc->priv = PLUMA_DOCUMENT_GET_PRIVATE (doc);

	doc->priv->uri = NULL;
	doc->priv->untitled_number = get_untitled_number ();

	doc->priv->metadata_info = NULL;

	doc->priv->content_type = get_default_content_type ();

	doc->priv->readonly = FALSE;

	doc->priv->stop_cursor_moved_emission = FALSE;

	doc->priv->last_save_was_manually = TRUE;
	doc->priv->language_set_by_user = FALSE;

	doc->priv->dispose_has_run = FALSE;

	doc->priv->mtime.tv_sec = 0;
	doc->priv->mtime.tv_usec = 0;

	g_get_current_time (&doc->priv->time_of_last_save_or_load);

	doc->priv->encoding = pluma_encoding_get_utf8 ();

	doc->priv->newline_type = PLUMA_DOCUMENT_NEWLINE_TYPE_DEFAULT;

	gtk_source_buffer_set_max_undo_levels (GTK_SOURCE_BUFFER (doc), 
					       pluma_prefs_manager_get_undo_actions_limit ());

	gtk_source_buffer_set_highlight_matching_brackets (GTK_SOURCE_BUFFER (doc), 
							   pluma_prefs_manager_get_bracket_matching ());

	pluma_document_set_enable_search_highlighting (doc,
						       pluma_prefs_manager_get_enable_search_highlighting ());

	style_scheme = get_default_style_scheme ();
	if (style_scheme != NULL)
		gtk_source_buffer_set_style_scheme (GTK_SOURCE_BUFFER (doc),
						    style_scheme);

	g_signal_connect_after (doc, 
			  	"insert-text",
			  	G_CALLBACK (insert_text_cb),
			  	NULL);

	g_signal_connect_after (doc, 
			  	"delete-range",
			  	G_CALLBACK (delete_range_cb),
			  	NULL);

	g_signal_connect (doc,
			  "notify::content-type",
			  G_CALLBACK (on_content_type_changed),
			  NULL);

	g_signal_connect (doc,
			  "notify::uri",
			  G_CALLBACK (on_uri_changed),
			  NULL);
}

PlumaDocument *
pluma_document_new (void)
{
	pluma_debug (DEBUG_DOCUMENT);

	return PLUMA_DOCUMENT (g_object_new (PLUMA_TYPE_DOCUMENT, NULL));
}

static void
set_content_type_no_guess (PlumaDocument *doc,
			   const gchar   *content_type)
{
	pluma_debug (DEBUG_DOCUMENT);

	if (doc->priv->content_type != NULL && content_type != NULL &&
	    (0 == strcmp (doc->priv->content_type, content_type)))
		return;

	g_free (doc->priv->content_type);

	if (content_type == NULL || g_content_type_is_unknown (content_type))
		doc->priv->content_type = get_default_content_type ();
	else
		doc->priv->content_type = g_strdup (content_type);

	g_object_notify (G_OBJECT (doc), "content-type");
}

static void
set_content_type (PlumaDocument *doc,
		  const gchar   *content_type)
{
	pluma_debug (DEBUG_DOCUMENT);

	if (content_type == NULL)
	{
		GFile *file;
		gchar *guessed_type = NULL;

		/* If content type is null, we guess from the filename */
		file = pluma_document_get_location (doc);
		if (file != NULL)
		{
			gchar *basename;

			basename = g_file_get_basename (file);
			guessed_type = g_content_type_guess (basename, NULL, 0, NULL);

			g_free (basename);
			g_object_unref (file);
		}

		set_content_type_no_guess (doc, guessed_type);

		g_free (guessed_type);
	}
	else
	{
		set_content_type_no_guess (doc, content_type);
	}
}

void
pluma_document_set_content_type (PlumaDocument *doc,
                                 const gchar   *content_type)
{
	g_return_if_fail (PLUMA_IS_DOCUMENT (doc));

	set_content_type (doc, content_type);
}

static void
set_uri (PlumaDocument *doc,
	 const gchar   *uri)
{
	pluma_debug (DEBUG_DOCUMENT);

	g_return_if_fail ((uri == NULL) || pluma_utils_is_valid_uri (uri));

	if (uri != NULL)
	{
		if (doc->priv->uri == uri)
			return;

		g_free (doc->priv->uri);
		doc->priv->uri = g_strdup (uri);

		if (doc->priv->untitled_number > 0)
		{
			release_untitled_number (doc->priv->untitled_number);
			doc->priv->untitled_number = 0;
		}
	}

	g_object_notify (G_OBJECT (doc), "uri");

	if (doc->priv->short_name == NULL)
	{
		g_object_notify (G_OBJECT (doc), "shortname");
	}
}

GFile *
pluma_document_get_location (PlumaDocument *doc)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), NULL);

	return doc->priv->uri == NULL ? NULL : g_file_new_for_uri (doc->priv->uri);
}

gchar *
pluma_document_get_uri (PlumaDocument *doc)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), NULL);

	return g_strdup (doc->priv->uri);
}

void
pluma_document_set_uri (PlumaDocument *doc,
			const gchar   *uri)
{
	g_return_if_fail (PLUMA_IS_DOCUMENT (doc));
	g_return_if_fail (uri != NULL);

	set_uri (doc, uri);
	set_content_type (doc, NULL);
}

/* Never returns NULL */
gchar *
pluma_document_get_uri_for_display (PlumaDocument *doc)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), g_strdup (""));

	if (doc->priv->uri == NULL)
		return g_strdup_printf (_("Unsaved Document %d"),
					doc->priv->untitled_number);
	else
		return pluma_utils_uri_for_display (doc->priv->uri);
}

/* Never returns NULL */
gchar *
pluma_document_get_short_name_for_display (PlumaDocument *doc)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), g_strdup (""));

	if (doc->priv->short_name != NULL)
		return g_strdup (doc->priv->short_name);
	else if (doc->priv->uri == NULL)
		return g_strdup_printf (_("Unsaved Document %d"),
					doc->priv->untitled_number);
	else
		return pluma_utils_basename_for_display (doc->priv->uri);
}

void
pluma_document_set_short_name_for_display (PlumaDocument *doc,
                                           const gchar   *short_name)
{
	g_return_if_fail (PLUMA_IS_DOCUMENT (doc));

	g_free (doc->priv->short_name);
	doc->priv->short_name = g_strdup (short_name);

	g_object_notify (G_OBJECT (doc), "shortname");
}

gchar *
pluma_document_get_content_type (PlumaDocument *doc)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), NULL);

 	return g_strdup (doc->priv->content_type);
}

/* Never returns NULL */
gchar *
pluma_document_get_mime_type (PlumaDocument *doc)
{
	gchar *mime_type = NULL;

	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), g_strdup ("text/plain"));

	if ((doc->priv->content_type != NULL) &&
	    (!g_content_type_is_unknown (doc->priv->content_type)))
	{
		mime_type = g_content_type_get_mime_type (doc->priv->content_type);
	}

 	return mime_type != NULL ? mime_type : g_strdup ("text/plain");
}

/* Note: do not emit the notify::read-only signal */
static gboolean
set_readonly (PlumaDocument *doc,
	      gboolean       readonly)
{
	pluma_debug (DEBUG_DOCUMENT);

	readonly = (readonly != FALSE);

	if (doc->priv->readonly == readonly) 
		return FALSE;

	doc->priv->readonly = readonly;

	return TRUE;
}

/**
 * pluma_document_set_readonly:
 * @doc: a #PlumaDocument
 * @readonly: %TRUE to se the document as read-only
 *
 * If @readonly is %TRUE sets @doc as read-only.
 */
void
_pluma_document_set_readonly (PlumaDocument *doc,
			      gboolean       readonly)
{
	pluma_debug (DEBUG_DOCUMENT);

	g_return_if_fail (PLUMA_IS_DOCUMENT (doc));

	if (set_readonly (doc, readonly))
	{
		g_object_notify (G_OBJECT (doc), "read-only");
	}
}

gboolean
pluma_document_get_readonly (PlumaDocument *doc)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), TRUE);

	return doc->priv->readonly;
}

gboolean
_pluma_document_check_externally_modified (PlumaDocument *doc)
{
	GFile *gfile;
	GFileInfo *info;

	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), FALSE);

	if (doc->priv->uri == NULL)
	{
		return FALSE;
	}

	gfile = g_file_new_for_uri (doc->priv->uri);
	info = g_file_query_info (gfile,
				  G_FILE_ATTRIBUTE_TIME_MODIFIED "," \
				  G_FILE_ATTRIBUTE_ACCESS_CAN_WRITE,
				  G_FILE_QUERY_INFO_NONE,
				  NULL, NULL);
	g_object_unref (gfile);

	if (info != NULL)
	{
		/* While at it also check if permissions changed */
		if (g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_ACCESS_CAN_WRITE))
		{
			gboolean read_only;

			read_only = !g_file_info_get_attribute_boolean (info,
									G_FILE_ATTRIBUTE_ACCESS_CAN_WRITE);

			_pluma_document_set_readonly (doc, read_only);
		}

		if (g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_TIME_MODIFIED))
		{
			GTimeVal timeval;

			g_file_info_get_modification_time (info, &timeval);
			g_object_unref (info);
	
			return (timeval.tv_sec > doc->priv->mtime.tv_sec) ||
			       (timeval.tv_sec == doc->priv->mtime.tv_sec && 
			       timeval.tv_usec > doc->priv->mtime.tv_usec);
		}
	}

	return FALSE;
}

static void
reset_temp_loading_data (PlumaDocument       *doc)
{
	/* the loader has been used, throw it away */
	g_object_unref (doc->priv->loader);
	doc->priv->loader = NULL;

	doc->priv->requested_encoding = NULL;
	doc->priv->requested_line_pos = 0;
}

static void
document_loader_loaded (PlumaDocumentLoader *loader,
			const GError        *error,
			PlumaDocument       *doc)
{
	/* load was successful */
	if (error == NULL ||
	    (error->domain == PLUMA_DOCUMENT_ERROR &&
	     error->code == PLUMA_DOCUMENT_ERROR_CONVERSION_FALLBACK))
	{
		GtkTextIter iter;
		GFileInfo *info;
		const gchar *content_type = NULL;
		gboolean read_only = FALSE;
		GTimeVal mtime = {0, 0};

		info = pluma_document_loader_get_info (loader);

		if (info)
		{
			if (g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE))
				content_type = g_file_info_get_attribute_string (info,
										 G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE);

			if (g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_TIME_MODIFIED))
				g_file_info_get_modification_time (info, &mtime);

			if (g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_ACCESS_CAN_WRITE))
				read_only = !g_file_info_get_attribute_boolean (info,
										G_FILE_ATTRIBUTE_ACCESS_CAN_WRITE);
		}

		doc->priv->mtime = mtime;

		set_readonly (doc, read_only);

		g_get_current_time (&doc->priv->time_of_last_save_or_load);

		set_encoding (doc, 
			      pluma_document_loader_get_encoding (loader),
			      (doc->priv->requested_encoding != NULL));

		set_content_type (doc, content_type);

		pluma_document_set_newline_type (doc,
		                                 pluma_document_loader_get_newline_type (loader));

		/* move the cursor at the requested line if any */
		if (doc->priv->requested_line_pos > 0)
		{
			/* line_pos - 1 because get_iter_at_line counts from 0 */
			gtk_text_buffer_get_iter_at_line (GTK_TEXT_BUFFER (doc),
							  &iter,
							  doc->priv->requested_line_pos - 1);
		}
		/* else, if enabled, to the position stored in the metadata */
		else if (pluma_prefs_manager_get_restore_cursor_position ())
		{
			gchar *pos;
			gint offset;

			pos = pluma_document_get_metadata (doc, PLUMA_METADATA_ATTRIBUTE_POSITION);

			offset = pos ? atoi (pos) : 0;
			g_free (pos);

			gtk_text_buffer_get_iter_at_offset (GTK_TEXT_BUFFER (doc),
							    &iter,
							    MAX (offset, 0));

			/* make sure it's a valid position, if the file
			 * changed we may have ended up in the middle of
			 * a utf8 character cluster */
			if (!gtk_text_iter_is_cursor_position (&iter))
			{
				gtk_text_buffer_get_start_iter (GTK_TEXT_BUFFER (doc),
								&iter);
			}
		}
		/* otherwise to the top */
		else
		{
			gtk_text_buffer_get_start_iter (GTK_TEXT_BUFFER (doc),
							&iter);
		}

		gtk_text_buffer_place_cursor (GTK_TEXT_BUFFER (doc), &iter);
	}

	/* special case creating a named new doc */
	else if (doc->priv->create &&
	         (error->domain == G_IO_ERROR && error->code == G_IO_ERROR_NOT_FOUND) &&
	         (pluma_utils_uri_has_file_scheme (doc->priv->uri)))
	{
		reset_temp_loading_data (doc);

		g_signal_emit (doc,
			       document_signals[LOADED],
			       0,
			       NULL);

		return;
	}
	
	g_signal_emit (doc,
		       document_signals[LOADED],
		       0,
		       error);

	reset_temp_loading_data (doc);
}

static void
document_loader_loading (PlumaDocumentLoader *loader,
			 gboolean             completed,
			 const GError        *error,
			 PlumaDocument       *doc)
{
	if (completed)
	{
		document_loader_loaded (loader, error, doc);
	}
	else
	{
		goffset size = 0;
		goffset read;
		GFileInfo *info;

		info = pluma_document_loader_get_info (loader);

		if (info && g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_STANDARD_SIZE))
			size = g_file_info_get_attribute_uint64 (info,
								 G_FILE_ATTRIBUTE_STANDARD_SIZE);

		read = pluma_document_loader_get_bytes_read (loader);

		g_signal_emit (doc, 
			       document_signals[LOADING],
			       0,
			       read,
			       size);
	}
}

static void
pluma_document_load_real (PlumaDocument       *doc,
			  const gchar         *uri,
			  const PlumaEncoding *encoding,
			  gint                 line_pos,
			  gboolean             create)
{
	g_return_if_fail (doc->priv->loader == NULL);

	pluma_debug_message (DEBUG_DOCUMENT, "load_real: uri = %s", uri);

	/* create a loader. It will be destroyed when loading is completed */
	doc->priv->loader = pluma_document_loader_new (doc, uri, encoding);

	g_signal_connect (doc->priv->loader,
			  "loading",
			  G_CALLBACK (document_loader_loading),
			  doc);

	doc->priv->create = create;
	doc->priv->requested_encoding = encoding;
	doc->priv->requested_line_pos = line_pos;

	set_uri (doc, uri);
	set_content_type (doc, NULL);

	pluma_document_loader_load (doc->priv->loader);
}

/**
 * pluma_document_load:
 * @doc: the #PlumaDocument.
 * @uri: the uri where to load the document from.
 * @encoding: the #PlumaEncoding to encode the document.
 * @line_pos: the line to show.
 * @create: whether the document should be created if it doesn't exist.
 *
 * Load a document. This results in the "load" signal to be emitted.
 */
void
pluma_document_load (PlumaDocument       *doc,
		     const gchar         *uri,
		     const PlumaEncoding *encoding,
		     gint                 line_pos,
		     gboolean             create)
{
	g_return_if_fail (PLUMA_IS_DOCUMENT (doc));
	g_return_if_fail (uri != NULL);
	g_return_if_fail (pluma_utils_is_valid_uri (uri));

	g_signal_emit (doc, document_signals[LOAD], 0, uri, encoding, line_pos, create);
}

/**
 * pluma_document_load_cancel:
 * @doc: the #PlumaDocument.
 *
 * Cancel load of a document.
 */
gboolean
pluma_document_load_cancel (PlumaDocument *doc)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), FALSE);

	if (doc->priv->loader == NULL)
		return FALSE;

	return pluma_document_loader_cancel (doc->priv->loader);
}

static void
document_saver_saving (PlumaDocumentSaver *saver,
		       gboolean            completed,
		       const GError       *error,
		       PlumaDocument      *doc)
{
	pluma_debug (DEBUG_DOCUMENT);

	if (completed)
	{
		/* save was successful */
		if (error == NULL)
		{
			const gchar *uri;
			const gchar *content_type = NULL;
			GTimeVal mtime = {0, 0};
			GFileInfo *info;

			uri = pluma_document_saver_get_uri (saver);
			set_uri (doc, uri);

			info = pluma_document_saver_get_info (saver);

			if (info != NULL)
			{
				if (g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE))
					content_type = g_file_info_get_attribute_string (info,
											 G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE);

				if (g_file_info_has_attribute (info, G_FILE_ATTRIBUTE_TIME_MODIFIED))
					g_file_info_get_modification_time (info, &mtime);
			}

			set_content_type (doc, content_type);
			doc->priv->mtime = mtime;

			g_get_current_time (&doc->priv->time_of_last_save_or_load);

			_pluma_document_set_readonly (doc, FALSE);

			gtk_text_buffer_set_modified (GTK_TEXT_BUFFER (doc),
						      FALSE);

			set_encoding (doc, 
				      doc->priv->requested_encoding, 
				      TRUE);
		}

		g_signal_emit (doc,
			       document_signals[SAVED],
			       0,
			       error);

		/* the saver has been used, throw it away */
		g_object_unref (doc->priv->saver);
		doc->priv->saver = NULL;
	}
	else
	{
		goffset size = 0;
		goffset written = 0;

		size = pluma_document_saver_get_file_size (saver);
		written = pluma_document_saver_get_bytes_written (saver);

		pluma_debug_message (DEBUG_DOCUMENT, "save progress: %" G_GINT64_FORMAT " of %" G_GINT64_FORMAT, written, size);

		g_signal_emit (doc,
			       document_signals[SAVING],
			       0,
			       written,
			       size);
	}
}

static void
pluma_document_save_real (PlumaDocument          *doc,
			  const gchar            *uri,
			  const PlumaEncoding    *encoding,
			  PlumaDocumentSaveFlags  flags)
{
	g_return_if_fail (doc->priv->saver == NULL);

	/* create a saver, it will be destroyed once saving is complete */
	doc->priv->saver = pluma_document_saver_new (doc, uri, encoding,
						     doc->priv->newline_type,
						     flags);

	g_signal_connect (doc->priv->saver,
			  "saving",
			  G_CALLBACK (document_saver_saving),
			  doc);

	doc->priv->requested_encoding = encoding;

	pluma_document_saver_save (doc->priv->saver,
				   &doc->priv->mtime);
}

/**
 * pluma_document_save:
 * @doc: the #PlumaDocument.
 * @flags: optionnal #PlumaDocumentSaveFlags.
 *
 * Save the document to its previous location. This results in the "save"
 * signal to be emitted.
 */
void
pluma_document_save (PlumaDocument          *doc,
		     PlumaDocumentSaveFlags  flags)
{
	g_return_if_fail (PLUMA_IS_DOCUMENT (doc));
	g_return_if_fail (doc->priv->uri != NULL);

	g_signal_emit (doc,
		       document_signals[SAVE],
		       0,
		       doc->priv->uri,
		       doc->priv->encoding,
		       flags);
}

/**
 * pluma_document_save_as:
 * @doc: the #PlumaDocument.
 * @uri: the uri where to save the document.
 * @encoding: the #PlumaEncoding to encode the document.
 * @flags: optionnal #PlumaDocumentSaveFlags.
 *
 * Save the document to a new location. This results in the "save" signal
 * to be emitted.
 */
void
pluma_document_save_as (PlumaDocument          *doc,
			const gchar            *uri,
			const PlumaEncoding    *encoding,
			PlumaDocumentSaveFlags  flags)
{
	g_return_if_fail (PLUMA_IS_DOCUMENT (doc));
	g_return_if_fail (uri != NULL);
	g_return_if_fail (encoding != NULL);

	/* priv->mtime refers to the the old uri (if any). Thus, it should be
	 * ignored when saving as. */
	g_signal_emit (doc,
		       document_signals[SAVE],
		       0,
		       uri,
		       encoding,
		       flags | PLUMA_DOCUMENT_SAVE_IGNORE_MTIME);
}

gboolean
pluma_document_insert_file (PlumaDocument       *doc,
			    GtkTextIter         *iter,
			    const gchar         *uri,
			    const PlumaEncoding *encoding)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), FALSE);
	g_return_val_if_fail (iter != NULL, FALSE);
	g_return_val_if_fail (gtk_text_iter_get_buffer (iter) == 
				GTK_TEXT_BUFFER (doc), FALSE);

	/* TODO */

	return FALSE;
}

gboolean	 
pluma_document_is_untouched (PlumaDocument *doc)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), TRUE);

	return (doc->priv->uri == NULL) && 
		(!gtk_text_buffer_get_modified (GTK_TEXT_BUFFER (doc)));
}

gboolean 
pluma_document_is_untitled (PlumaDocument *doc)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), TRUE);

	return (doc->priv->uri == NULL);
}

gboolean
pluma_document_is_local (PlumaDocument *doc)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), FALSE);

	if (doc->priv->uri == NULL)
	{
		return FALSE;
	}

	return pluma_utils_uri_has_file_scheme (doc->priv->uri);
}

gboolean
pluma_document_get_deleted (PlumaDocument *doc)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), FALSE);

	return doc->priv->uri && !pluma_utils_uri_exists (doc->priv->uri);
}

/*
 * If @line is bigger than the lines of the document, the cursor is moved
 * to the last line and FALSE is returned.
 */
gboolean
pluma_document_goto_line (PlumaDocument *doc, 
			  gint           line)
{
	gboolean ret = TRUE;
	guint line_count;
	GtkTextIter iter;

	pluma_debug (DEBUG_DOCUMENT);

	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), FALSE);
	g_return_val_if_fail (line >= -1, FALSE);

	line_count = gtk_text_buffer_get_line_count (GTK_TEXT_BUFFER (doc));

	if (line >= line_count)
	{
		ret = FALSE;
		gtk_text_buffer_get_end_iter (GTK_TEXT_BUFFER (doc),
					      &iter);
	}
	else
	{
		gtk_text_buffer_get_iter_at_line (GTK_TEXT_BUFFER (doc),
						  &iter,
						  line);
	}

	gtk_text_buffer_place_cursor (GTK_TEXT_BUFFER (doc), &iter);

	return ret;
}

gboolean
pluma_document_goto_line_offset (PlumaDocument *doc,
				 gint           line,
				 gint           line_offset)
{
	gboolean ret = TRUE;
	guint offset_count;
	GtkTextIter iter;
	
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), FALSE);
	g_return_val_if_fail (line >= -1, FALSE);
	g_return_val_if_fail (line_offset >= -1, FALSE);
	
	gtk_text_buffer_get_iter_at_line (GTK_TEXT_BUFFER (doc),
					  &iter,
					  line);

	offset_count = gtk_text_iter_get_chars_in_line (&iter);
	if (line_offset > offset_count)
	{
		ret = FALSE;
	}
	else
	{
		gtk_text_iter_set_line_offset (&iter, line_offset);
	}
	
	gtk_text_buffer_place_cursor (GTK_TEXT_BUFFER (doc), &iter);

	return ret;
}

static gint
compute_num_of_lines (const gchar *text)
{
	const gchar *p;
	gint len;
	gint n = 1;

	g_return_val_if_fail (text != NULL, 0);

	len = strlen (text);
	p = text;

	while (len > 0)
	{
		gint del, par;

		pango_find_paragraph_boundary (p, len, &del, &par);

		if (del == par) /* not found */
			break;

		p += par;
		len -= par;
		++n;
	}

	return n;
}

void
pluma_document_set_search_text (PlumaDocument *doc,
				const gchar   *text,
				guint          flags)
{
	gchar *converted_text;
	gboolean notify = FALSE;
	gboolean update_to_search_region = FALSE;
	
	g_return_if_fail (PLUMA_IS_DOCUMENT (doc));
	g_return_if_fail ((text == NULL) || (doc->priv->search_text != text));
	g_return_if_fail ((text == NULL) || g_utf8_validate (text, -1, NULL));

	pluma_debug_message (DEBUG_DOCUMENT, "text = %s", text);

	if (text != NULL)
	{
		if (*text != '\0')
		{
			converted_text = pluma_utils_unescape_search_text (text);
			notify = !pluma_document_get_can_search_again (doc);
		}
		else
		{
			converted_text = g_strdup("");
			notify = pluma_document_get_can_search_again (doc);
		}
		
		g_free (doc->priv->search_text);
	
		doc->priv->search_text = converted_text;
		doc->priv->num_of_lines_search_text = compute_num_of_lines (doc->priv->search_text);
		update_to_search_region = TRUE;
	}
	
	if (!PLUMA_SEARCH_IS_DONT_SET_FLAGS (flags))
	{
		if (doc->priv->search_flags != flags)
			update_to_search_region = TRUE;
			
		doc->priv->search_flags = flags;

	}

	if (update_to_search_region)
	{
		GtkTextIter begin;
		GtkTextIter end;
		
		gtk_text_buffer_get_bounds (GTK_TEXT_BUFFER (doc),
					    &begin,
					    &end);
					    
		to_search_region_range (doc,
					&begin,
					&end);
	}
	
	if (notify)
		g_object_notify (G_OBJECT (doc), "can-search-again");
}

gchar *
pluma_document_get_search_text (PlumaDocument *doc,
				guint         *flags)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), NULL);

	if (flags != NULL)
		*flags = doc->priv->search_flags;

	return pluma_utils_escape_search_text (doc->priv->search_text);
}

gboolean
pluma_document_get_can_search_again (PlumaDocument *doc)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), FALSE);

	return ((doc->priv->search_text != NULL) && 
	        (*doc->priv->search_text != '\0'));
}

gboolean
pluma_document_search_forward (PlumaDocument     *doc,
			       const GtkTextIter *start,
			       const GtkTextIter *end,
			       GtkTextIter       *match_start,
			       GtkTextIter       *match_end)
{
	GtkTextIter iter;
#if GTK_CHECK_VERSION (3, 0, 0)
	GtkTextSearchFlags search_flags;
#else
	GtkSourceSearchFlags search_flags;
#endif
	gboolean found = FALSE;
	GtkTextIter m_start;
	GtkTextIter m_end;
	
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), FALSE);
	g_return_val_if_fail ((start == NULL) || 
			      (gtk_text_iter_get_buffer (start) ==  GTK_TEXT_BUFFER (doc)), FALSE);
	g_return_val_if_fail ((end == NULL) || 
			      (gtk_text_iter_get_buffer (end) ==  GTK_TEXT_BUFFER (doc)), FALSE);
	
	if (doc->priv->search_text == NULL)
	{
		pluma_debug_message (DEBUG_DOCUMENT, "doc->priv->search_text == NULL\n");
		return FALSE;
	}
	else
		pluma_debug_message (DEBUG_DOCUMENT, "doc->priv->search_text == \"%s\"\n", doc->priv->search_text);
				      
	if (start == NULL)
		gtk_text_buffer_get_start_iter (GTK_TEXT_BUFFER (doc), &iter);
	else
		iter = *start;

#if GTK_CHECK_VERSION (3, 0, 0)
	search_flags = GTK_TEXT_SEARCH_VISIBLE_ONLY | GTK_TEXT_SEARCH_TEXT_ONLY;
#else
	search_flags = GTK_SOURCE_SEARCH_VISIBLE_ONLY | GTK_SOURCE_SEARCH_TEXT_ONLY;
#endif

	if (!PLUMA_SEARCH_IS_CASE_SENSITIVE (doc->priv->search_flags))
	{
#if GTK_CHECK_VERSION (3, 0, 0)
		search_flags = search_flags | GTK_TEXT_SEARCH_CASE_INSENSITIVE;
#else
		search_flags = search_flags | GTK_SOURCE_SEARCH_CASE_INSENSITIVE;
#endif
	}
		
	while (!found)
	{
#if GTK_CHECK_VERSION (3, 0, 0)
		found = gtk_text_iter_forward_search (&iter,
#else
		found = gtk_source_iter_forward_search (&iter,
#endif
							doc->priv->search_text, 
							search_flags,
                        	                	&m_start, 
                        	                	&m_end,
                                	               	end);
      	               	
		if (found && PLUMA_SEARCH_IS_ENTIRE_WORD (doc->priv->search_flags))
		{
			found = gtk_text_iter_starts_word (&m_start) && 
					gtk_text_iter_ends_word (&m_end);

			if (!found) 
				iter = m_end;
		}
		else
			break;
	}
	
	if (found && (match_start != NULL))
		*match_start = m_start;
	
	if (found && (match_end != NULL))
		*match_end = m_end;
	
	return found;			    
}
						 
gboolean
pluma_document_search_backward (PlumaDocument     *doc,
				const GtkTextIter *start,
				const GtkTextIter *end,
				GtkTextIter       *match_start,
				GtkTextIter       *match_end)
{
	GtkTextIter iter;
#if GTK_CHECK_VERSION (3, 0, 0)
	GtkTextSearchFlags search_flags;
#else
	GtkSourceSearchFlags search_flags;
#endif
	gboolean found = FALSE;
	GtkTextIter m_start;
	GtkTextIter m_end;
	
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), FALSE);
	g_return_val_if_fail ((start == NULL) || 
			      (gtk_text_iter_get_buffer (start) ==  GTK_TEXT_BUFFER (doc)), FALSE);
	g_return_val_if_fail ((end == NULL) || 
			      (gtk_text_iter_get_buffer (end) ==  GTK_TEXT_BUFFER (doc)), FALSE);
	
	if (doc->priv->search_text == NULL)
	{
		pluma_debug_message (DEBUG_DOCUMENT, "doc->priv->search_text == NULL\n");
		return FALSE;
	}
	else
		pluma_debug_message (DEBUG_DOCUMENT, "doc->priv->search_text == \"%s\"\n", doc->priv->search_text);
				      
	if (end == NULL)
		gtk_text_buffer_get_end_iter (GTK_TEXT_BUFFER (doc), &iter);
	else
		iter = *end;

#if GTK_CHECK_VERSION (3, 0, 0)
	search_flags = GTK_TEXT_SEARCH_VISIBLE_ONLY | GTK_TEXT_SEARCH_TEXT_ONLY;
#else
	search_flags = GTK_SOURCE_SEARCH_VISIBLE_ONLY | GTK_SOURCE_SEARCH_TEXT_ONLY;
#endif

	if (!PLUMA_SEARCH_IS_CASE_SENSITIVE (doc->priv->search_flags))
	{
#if GTK_CHECK_VERSION (3, 0, 0)
		search_flags = search_flags | GTK_TEXT_SEARCH_CASE_INSENSITIVE;
#else
		search_flags = search_flags | GTK_SOURCE_SEARCH_CASE_INSENSITIVE;
#endif
	}

	while (!found)
	{
#if GTK_CHECK_VERSION (3, 0, 0)
		found = gtk_text_iter_backward_search (&iter,
#else
		found = gtk_source_iter_backward_search (&iter,
#endif
							 doc->priv->search_text, 
							 search_flags,
                        	                	 &m_start, 
                        	                	 &m_end,
                                	               	 start);
      	               	
		if (found && PLUMA_SEARCH_IS_ENTIRE_WORD (doc->priv->search_flags))
		{
			found = gtk_text_iter_starts_word (&m_start) && 
					gtk_text_iter_ends_word (&m_end);

			if (!found) 
				iter = m_start;
		}
		else
			break;
	}
	
	if (found && (match_start != NULL))
		*match_start = m_start;
	
	if (found && (match_end != NULL))
		*match_end = m_end;
	
	return found;		      
}

gint 
pluma_document_replace_all (PlumaDocument       *doc,
			    const gchar         *find, 
			    const gchar         *replace, 
			    guint                flags)
{
	GtkTextIter iter;
	GtkTextIter m_start;
	GtkTextIter m_end;
#if GTK_CHECK_VERSION (3, 0, 0)
	GtkTextSearchFlags search_flags = 0;
#else
	GtkSourceSearchFlags search_flags = 0;
#endif
	gboolean found = TRUE;
	gint cont = 0;
	gchar *search_text;
	gchar *replace_text;
	gint replace_text_len;
	GtkTextBuffer *buffer;
	gboolean brackets_highlighting;
	gboolean search_highliting;

	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), 0);
	g_return_val_if_fail (replace != NULL, 0);
	g_return_val_if_fail ((find != NULL) || (doc->priv->search_text != NULL), 0);

	buffer = GTK_TEXT_BUFFER (doc);

	if (find == NULL)
		search_text = g_strdup (doc->priv->search_text);
	else
		search_text = pluma_utils_unescape_search_text (find);

	replace_text = pluma_utils_unescape_search_text (replace);

	gtk_text_buffer_get_start_iter (buffer, &iter);

#if GTK_CHECK_VERSION (3, 0, 0)
	search_flags = GTK_TEXT_SEARCH_VISIBLE_ONLY | GTK_TEXT_SEARCH_TEXT_ONLY;
#else
	search_flags = GTK_SOURCE_SEARCH_VISIBLE_ONLY | GTK_SOURCE_SEARCH_TEXT_ONLY;
#endif

	if (!PLUMA_SEARCH_IS_CASE_SENSITIVE (flags))
	{
#if GTK_CHECK_VERSION (3, 0, 0)
		search_flags = search_flags | GTK_TEXT_SEARCH_CASE_INSENSITIVE;
#else
		search_flags = search_flags | GTK_SOURCE_SEARCH_CASE_INSENSITIVE;
#endif
	}

	replace_text_len = strlen (replace_text);

	/* disable cursor_moved emission until the end of the
	 * replace_all so that we don't spend all the time
	 * updating the position in the statusbar
	 */
	doc->priv->stop_cursor_moved_emission = TRUE;

	/* also avoid spending time matching brackets */
	brackets_highlighting = gtk_source_buffer_get_highlight_matching_brackets (GTK_SOURCE_BUFFER (buffer));
	gtk_source_buffer_set_highlight_matching_brackets (GTK_SOURCE_BUFFER (buffer), FALSE);

	/* and do search highliting later */
	search_highliting = pluma_document_get_enable_search_highlighting (doc);
	pluma_document_set_enable_search_highlighting (doc, FALSE);

	gtk_text_buffer_begin_user_action (buffer);

	do
	{
#if GTK_CHECK_VERSION (3, 0, 0)
		found = gtk_text_iter_forward_search (&iter,
#else
		found = gtk_source_iter_forward_search (&iter,
#endif
							search_text, 
							search_flags,
                        	                	&m_start, 
                        	                	&m_end,
                                	               	NULL);

		if (found && PLUMA_SEARCH_IS_ENTIRE_WORD (flags))
		{
			gboolean word;

			word = gtk_text_iter_starts_word (&m_start) && 
			       gtk_text_iter_ends_word (&m_end);

			if (!word)
			{
				iter = m_end;
				continue;
			}
		}

		if (found)
		{
			++cont;

			gtk_text_buffer_delete (buffer, 
						&m_start,
						&m_end);
			gtk_text_buffer_insert (buffer,
						&m_start,
						replace_text,
						replace_text_len);

			iter = m_start;
		}		

	} while (found);

	gtk_text_buffer_end_user_action (buffer);

	/* re-enable cursor_moved emission and notify
	 * the current position 
	 */
	doc->priv->stop_cursor_moved_emission = FALSE;
	emit_cursor_moved (doc);

	gtk_source_buffer_set_highlight_matching_brackets (GTK_SOURCE_BUFFER (buffer),
							   brackets_highlighting);
	pluma_document_set_enable_search_highlighting (doc, search_highliting);

	g_free (search_text);
	g_free (replace_text);

	return cont;
}

void
pluma_document_set_language (PlumaDocument     *doc, 
			     GtkSourceLanguage *lang)
{
	g_return_if_fail (PLUMA_IS_DOCUMENT (doc));

	set_language (doc, lang, TRUE);
}

GtkSourceLanguage *
pluma_document_get_language (PlumaDocument *doc)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), NULL);

	return gtk_source_buffer_get_language (GTK_SOURCE_BUFFER (doc));
}

const PlumaEncoding *
pluma_document_get_encoding (PlumaDocument *doc)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), NULL);

	return doc->priv->encoding;
}

glong
_pluma_document_get_seconds_since_last_save_or_load (PlumaDocument *doc)
{
	GTimeVal current_time;

	pluma_debug (DEBUG_DOCUMENT);
	
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), -1);

	g_get_current_time (&current_time);

	return (current_time.tv_sec - doc->priv->time_of_last_save_or_load.tv_sec);
}

static void
get_search_match_colors (PlumaDocument *doc,
			 gboolean      *foreground_set,
			 GdkColor      *foreground,
			 gboolean      *background_set,
			 GdkColor      *background)
{
	GtkSourceStyleScheme *style_scheme;
	GtkSourceStyle *style;
	gchar *bg;
	gchar *fg;

	style_scheme = gtk_source_buffer_get_style_scheme (GTK_SOURCE_BUFFER (doc));
	if (style_scheme == NULL)
		goto fallback;

	style = gtk_source_style_scheme_get_style (style_scheme,
						   "search-match");
	if (style == NULL)
		goto fallback;

	g_object_get (style, 
		      "foreground-set", foreground_set, 
		      "foreground", &fg,
		      "background-set", background_set, 
		      "background", &bg,
		      NULL);

	if (*foreground_set)
	{
		if (fg == NULL ||
		    !gdk_color_parse (fg, foreground))
		{
			*foreground_set = FALSE;
		}
	}

	if (*background_set)
	{
		if (bg == NULL ||
		    !gdk_color_parse (bg, background))
		{
			*background_set = FALSE;
		}
	}	

	g_free (fg);
	g_free (bg);

	return;

 fallback:
	pluma_debug_message (DEBUG_DOCUMENT, 
			     "Falling back to hard-coded colors "
			     "for the \"found\" text tag.");

	gdk_color_parse ("#FFFF78", background);
	*background_set = TRUE;
	*foreground_set = FALSE;

	return;
}

static void
sync_found_tag (PlumaDocument *doc,
		GParamSpec    *pspec,
		gpointer       data)
{
	GdkColor fg;
	GdkColor bg;
	gboolean fg_set;
	gboolean bg_set;

	pluma_debug (DEBUG_DOCUMENT);

	g_return_if_fail (GTK_TEXT_TAG (doc->priv->found_tag));

	get_search_match_colors (doc,
				 &fg_set, &fg,
				 &bg_set, &bg);

	g_object_set (doc->priv->found_tag,
		      "foreground-gdk", fg_set ? &fg : NULL,
		      NULL);
	g_object_set (doc->priv->found_tag,
		      "background-gdk", bg_set ? &bg : NULL,
		      NULL);
}

static void
text_tag_set_highest_priority (GtkTextTag    *tag,
			       GtkTextBuffer *buffer)
{
	GtkTextTagTable *table;
	gint n;

	table = gtk_text_buffer_get_tag_table (buffer);
	n = gtk_text_tag_table_get_size (table);
	gtk_text_tag_set_priority (tag, n - 1);
}

static void
search_region (PlumaDocument *doc,
	       GtkTextIter   *start,
	       GtkTextIter   *end)
{
	GtkTextIter iter;
	GtkTextIter m_start;
	GtkTextIter m_end;
#if GTK_CHECK_VERSION (3, 0, 0)
	GtkTextSearchFlags search_flags = 0;
#else
	GtkSourceSearchFlags search_flags = 0;
#endif
	gboolean found = TRUE;

	GtkTextBuffer *buffer;	

	pluma_debug (DEBUG_DOCUMENT);
	
	buffer = GTK_TEXT_BUFFER (doc);
	
	if (doc->priv->found_tag == NULL)
	{
		doc->priv->found_tag = gtk_text_buffer_create_tag (GTK_TEXT_BUFFER (doc), 
								   "found",
								   NULL);

		sync_found_tag (doc, NULL, NULL);

		g_signal_connect (doc, 
				  "notify::style-scheme",
				  G_CALLBACK (sync_found_tag),
				  NULL);
	}

	/* make sure the 'found' tag has the priority over
	 * syntax highlighting tags */
	text_tag_set_highest_priority (doc->priv->found_tag,
				       GTK_TEXT_BUFFER (doc));
				   

	if (doc->priv->search_text == NULL)
		return;

	g_return_if_fail (doc->priv->num_of_lines_search_text > 0);

	gtk_text_iter_backward_lines (start, doc->priv->num_of_lines_search_text);
	gtk_text_iter_forward_lines (end, doc->priv->num_of_lines_search_text);

	if (gtk_text_iter_has_tag (start, doc->priv->found_tag) &&
	    !gtk_text_iter_begins_tag (start, doc->priv->found_tag))
		gtk_text_iter_backward_to_tag_toggle (start, doc->priv->found_tag);

	if (gtk_text_iter_has_tag (end, doc->priv->found_tag) &&
	    !gtk_text_iter_ends_tag (end, doc->priv->found_tag))
		gtk_text_iter_forward_to_tag_toggle (end, doc->priv->found_tag);

	/*
	g_print ("[%u (%u), %u (%u)]\n", gtk_text_iter_get_line (start), gtk_text_iter_get_offset (start),
					   gtk_text_iter_get_line (end), gtk_text_iter_get_offset (end));
	*/

	gtk_text_buffer_remove_tag (buffer,
				    doc->priv->found_tag,
				    start,
				    end);

	if (*doc->priv->search_text == '\0')
		return;

	iter = *start;

#if GTK_CHECK_VERSION (3, 0, 0)
	search_flags = GTK_TEXT_SEARCH_VISIBLE_ONLY | GTK_TEXT_SEARCH_TEXT_ONLY;
#else
	search_flags = GTK_SOURCE_SEARCH_VISIBLE_ONLY | GTK_SOURCE_SEARCH_TEXT_ONLY;
#endif

	if (!PLUMA_SEARCH_IS_CASE_SENSITIVE (doc->priv->search_flags))
	{
#if GTK_CHECK_VERSION (3, 0, 0)
		search_flags = search_flags | GTK_TEXT_SEARCH_CASE_INSENSITIVE;
#else
		search_flags = search_flags | GTK_SOURCE_SEARCH_CASE_INSENSITIVE;
#endif
	}
	
	do
	{
		if ((end != NULL) && gtk_text_iter_is_end (end))
			end = NULL;
			
#if GTK_CHECK_VERSION (3, 0, 0)
		found = gtk_text_iter_forward_search (&iter,
#else
		found = gtk_source_iter_forward_search (&iter,
#endif
							doc->priv->search_text, 
							search_flags,
                        	                	&m_start, 
                        	                	&m_end,
                                	               	end);
				
		iter = m_end;
						      	               	
		if (found && PLUMA_SEARCH_IS_ENTIRE_WORD (doc->priv->search_flags))
		{
			gboolean word;
						
			word = gtk_text_iter_starts_word (&m_start) && 
			       gtk_text_iter_ends_word (&m_end);
				
			if (!word)
				continue;
		}

		if (found)
		{
			gtk_text_buffer_apply_tag (buffer,
						   doc->priv->found_tag,
						   &m_start,
						   &m_end);
		}		

	} while (found);
}

static void
to_search_region_range (PlumaDocument *doc,
			GtkTextIter   *start, 
			GtkTextIter   *end)
{
	pluma_debug (DEBUG_DOCUMENT);
	
	if (doc->priv->to_search_region == NULL)
		return;
		
	gtk_text_iter_set_line_offset (start, 0);
	gtk_text_iter_forward_to_line_end (end);
	
	/*
	g_print ("+ [%u (%u), %u (%u)]\n", gtk_text_iter_get_line (start), gtk_text_iter_get_offset (start),
					   gtk_text_iter_get_line (end), gtk_text_iter_get_offset (end));
	*/

	/* Add the region to the refresh region */
	pluma_text_region_add (doc->priv->to_search_region, start, end);

	/* Notify views of the updated highlight region */
	gtk_text_iter_backward_lines (start, doc->priv->num_of_lines_search_text);
	gtk_text_iter_forward_lines (end, doc->priv->num_of_lines_search_text);
	
	g_signal_emit (doc, document_signals [SEARCH_HIGHLIGHT_UPDATED], 0, start, end);
}

void
_pluma_document_search_region (PlumaDocument     *doc,
			       const GtkTextIter *start,
			       const GtkTextIter *end)
{
	PlumaTextRegion *region;

	pluma_debug (DEBUG_DOCUMENT);
		
	g_return_if_fail (PLUMA_IS_DOCUMENT (doc));
	g_return_if_fail (start != NULL);
	g_return_if_fail (end != NULL);
	
	if (doc->priv->to_search_region == NULL)
		return;

	/*
	g_print ("U [%u (%u), %u (%u)]\n", gtk_text_iter_get_line (start), gtk_text_iter_get_offset (start),
					   gtk_text_iter_get_line (end), gtk_text_iter_get_offset (end));
	*/
		
	/* get the subregions not yet highlighted */
	region = pluma_text_region_intersect (doc->priv->to_search_region, 
					      start,
					      end);
	if (region) 
	{
		gint i;
		GtkTextIter start_search;
		GtkTextIter end_search;

		i = pluma_text_region_subregions (region);
		pluma_text_region_nth_subregion (region, 
						 0,
						 &start_search,
						 NULL);

		pluma_text_region_nth_subregion (region, 
						 i - 1,
						 NULL,
						 &end_search);

		pluma_text_region_destroy (region, TRUE);

		gtk_text_iter_order (&start_search, &end_search);

		search_region (doc, &start_search, &end_search);

		/* remove the just highlighted region */
		pluma_text_region_subtract (doc->priv->to_search_region,
					    start, 
					    end);
	}
}

static void
insert_text_cb (PlumaDocument *doc, 
		GtkTextIter   *pos,
		const gchar   *text, 
		gint           length)
{
	GtkTextIter start;
	GtkTextIter end;

	pluma_debug (DEBUG_DOCUMENT);
		
	start = end = *pos;

	/*
	 * pos is invalidated when
	 * insertion occurs (because the buffer contents change), but the
	 * default signal handler revalidates it to point to the end of the
	 * inserted text 
	 */
	gtk_text_iter_backward_chars (&start,
				      g_utf8_strlen (text, length));
				     
	to_search_region_range (doc, &start, &end);
}
						 
static void	
delete_range_cb (PlumaDocument *doc, 
		 GtkTextIter   *start,
		 GtkTextIter   *end)
{
	GtkTextIter d_start;
	GtkTextIter d_end;

	pluma_debug (DEBUG_DOCUMENT);
		
	d_start = *start;
	d_end = *end;
	
	to_search_region_range (doc, &d_start, &d_end);
}

void
pluma_document_set_enable_search_highlighting (PlumaDocument *doc,
					       gboolean       enable)
{
	g_return_if_fail (PLUMA_IS_DOCUMENT (doc));
	
	enable = enable != FALSE;
	
	if ((doc->priv->to_search_region != NULL) == enable)
		return;
	
	if (doc->priv->to_search_region != NULL)
	{
		/* Disable search highlighting */
		if (doc->priv->found_tag != NULL)
		{
			/* If needed remove the found_tag */
			GtkTextIter begin;
			GtkTextIter end;
		
			gtk_text_buffer_get_bounds (GTK_TEXT_BUFFER (doc),
						    &begin,
						    &end);

			gtk_text_buffer_remove_tag (GTK_TEXT_BUFFER (doc),
				    		    doc->priv->found_tag,
				    		    &begin,
				    		    &end);
		}
		
		pluma_text_region_destroy (doc->priv->to_search_region,
					   TRUE);
		doc->priv->to_search_region = NULL;
	}
	else
	{
		doc->priv->to_search_region = pluma_text_region_new (GTK_TEXT_BUFFER (doc));
		if (pluma_document_get_can_search_again (doc))
		{
			/* If search_text is not empty, highligth all its occurrences */
			GtkTextIter begin;
			GtkTextIter end;
		
			gtk_text_buffer_get_bounds (GTK_TEXT_BUFFER (doc),
						    &begin,
						    &end);
					    
			to_search_region_range (doc,
						&begin,
						&end);
		}
	}
}

gboolean
pluma_document_get_enable_search_highlighting (PlumaDocument *doc)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), FALSE);
	
	return (doc->priv->to_search_region != NULL);
}

void
pluma_document_set_newline_type (PlumaDocument           *doc,
				 PlumaDocumentNewlineType newline_type)
{
	g_return_if_fail (PLUMA_IS_DOCUMENT (doc));

	if (doc->priv->newline_type != newline_type)
	{
		doc->priv->newline_type = newline_type;

		g_object_notify (G_OBJECT (doc), "newline-type");
	}
}

PlumaDocumentNewlineType
pluma_document_get_newline_type (PlumaDocument *doc)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), 0);

	return doc->priv->newline_type;
}

void
_pluma_document_set_mount_operation_factory (PlumaDocument 	       *doc,
					    PlumaMountOperationFactory	callback,
					    gpointer	                userdata)
{
	g_return_if_fail (PLUMA_IS_DOCUMENT (doc));
	
	doc->priv->mount_operation_factory = callback;
	doc->priv->mount_operation_userdata = userdata;
}

GMountOperation *
_pluma_document_create_mount_operation (PlumaDocument *doc)
{
	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), NULL);
	
	if (doc->priv->mount_operation_factory == NULL)
		return g_mount_operation_new ();
	else
		return doc->priv->mount_operation_factory (doc, 
						           doc->priv->mount_operation_userdata);
}

#ifndef ENABLE_GVFS_METADATA
gchar *
pluma_document_get_metadata (PlumaDocument *doc,
			     const gchar   *key)
{
	gchar *value = NULL;

	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), NULL);
	g_return_val_if_fail (key != NULL, NULL);

	if (!pluma_document_is_untitled (doc))
	{
		value = pluma_metadata_manager_get (doc->priv->uri, key);
	}

	return value;
}

void
pluma_document_set_metadata (PlumaDocument *doc,
			     const gchar   *first_key,
			     ...)
{
	const gchar *key;
	const gchar *value;
	va_list var_args;

	g_return_if_fail (PLUMA_IS_DOCUMENT (doc));
	g_return_if_fail (first_key != NULL);

	if (pluma_document_is_untitled (doc))
	{
		/* Can't set metadata for untitled documents */
		return;
	}

	va_start (var_args, first_key);

	for (key = first_key; key; key = va_arg (var_args, const gchar *))
	{
		value = va_arg (var_args, const gchar *);
		
		pluma_metadata_manager_set (doc->priv->uri,
					    key,
					    value);
	}

	va_end (var_args);
}

#else

/**
 * pluma_document_get_metadata:
 * @doc: a #PlumaDocument
 * @key: name of the key
 *
 * Gets the metadata assigned to @key.
 *
 * Returns: the value assigned to @key.
 */
gchar *
pluma_document_get_metadata (PlumaDocument *doc,
			     const gchar   *key)
{
	gchar *value = NULL;

	g_return_val_if_fail (PLUMA_IS_DOCUMENT (doc), NULL);
	g_return_val_if_fail (key != NULL, NULL);

	if (doc->priv->metadata_info && g_file_info_has_attribute (doc->priv->metadata_info,
								   key))
	{
		value = g_strdup (g_file_info_get_attribute_string (doc->priv->metadata_info,
								    key));
	}

	return value;
}

static void
set_attributes_cb (GObject      *source,
		   GAsyncResult *res,
		   gpointer      useless)
{
	g_file_set_attributes_finish (G_FILE (source),
				      res,
				      NULL,
				      NULL);
}

/**
 * pluma_document_set_metadata:
 * @doc: a #PlumaDocument
 * @first_key: name of the first key to set
 * @...: value for the first key, followed optionally by more key/value pairs,
 * followed by %NULL.
 *
 * Sets metadata on a document.
 */
void
pluma_document_set_metadata (PlumaDocument *doc,
			     const gchar   *first_key,
			     ...)
{
	const gchar *key;
	const gchar *value;
	va_list var_args;
	GFileInfo *info;
	GFile *location;

	g_return_if_fail (PLUMA_IS_DOCUMENT (doc));
	g_return_if_fail (first_key != NULL);

	info = g_file_info_new ();

	va_start (var_args, first_key);

	for (key = first_key; key; key = va_arg (var_args, const gchar *))
	{
		value = va_arg (var_args, const gchar *);
		
		if (value != NULL)
		{
			g_file_info_set_attribute_string (info,
							  key, value);
		}
		else
		{
			/* Unset the key */
			g_file_info_set_attribute (info, key,
						   G_FILE_ATTRIBUTE_TYPE_INVALID,
						   NULL);
		}
	}

	va_end (var_args);

	if (doc->priv->metadata_info != NULL)
		g_file_info_copy_into (info, doc->priv->metadata_info);

	location = pluma_document_get_location (doc);

	if (location != NULL)
	{
		g_file_set_attributes_async (location,
					     info,
					     G_FILE_QUERY_INFO_NONE,
					     G_PRIORITY_DEFAULT,
					     NULL,
					     set_attributes_cb,
					     NULL);

		g_object_unref (location);
	}
	
	g_object_unref (info);
}
#endif