summaryrefslogtreecommitdiff
path: root/gtk/gtktextiter.c
blob: aa5fbc442dfe238a16295afa2abe8e1fa8f0d221 (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
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
/* GTK - The GIMP Toolkit
 * gtktextiter.c Copyright (C) 2000 Red Hat, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */

/*
 * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
 * file for a list of people on the GTK+ Team.  See the ChangeLog
 * files for a list of changes.  These files are distributed with
 * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
 */

#define GTK_TEXT_USE_INTERNAL_UNSUPPORTED_API
#include "config.h"
#include "gtktextiter.h"
#include "gtktextbtree.h"
#include "gtktextiterprivate.h"
#include "gtkintl.h"
#include "gtkdebug.h"
#include "gtkalias.h"
#include <string.h>

#define FIX_OVERFLOWS(varname) if ((varname) == G_MININT) (varname) = G_MININT + 1

typedef struct _GtkTextRealIter GtkTextRealIter;

struct G_GNUC_MAY_ALIAS _GtkTextRealIter
{
  /* Always-valid information */
  GtkTextBTree *tree;
  GtkTextLine *line;
  /* At least one of these is always valid;
     if invalid, they are -1.

     If the line byte offset is valid, so is the segment byte offset;
     and ditto for char offsets. */
  gint line_byte_offset;
  gint line_char_offset;
  /* These two are valid if >= 0 */
  gint cached_char_index;
  gint cached_line_number;
  /* Stamps to detect the buffer changing under us */
  gint chars_changed_stamp;
  gint segments_changed_stamp;
  /* Valid if the segments_changed_stamp is up-to-date */
  GtkTextLineSegment *segment;     /* indexable segment we index */
  GtkTextLineSegment *any_segment; /* first segment in our location,
                                      maybe same as "segment" */
  /* One of these will always be valid if segments_changed_stamp is
     up-to-date. If invalid, they are -1.

     If the line byte offset is valid, so is the segment byte offset;
     and ditto for char offsets. */
  gint segment_byte_offset;
  gint segment_char_offset;

  /* padding */
  gint pad1;
  gpointer pad2;
};

/* These "set" functions should not assume any fields
   other than the char stamp and the tree are valid.
*/
static void
iter_set_common (GtkTextRealIter *iter,
                 GtkTextLine *line)
{
  /* Update segments stamp */
  iter->segments_changed_stamp =
    _gtk_text_btree_get_segments_changed_stamp (iter->tree);

  iter->line = line;

  iter->line_byte_offset = -1;
  iter->line_char_offset = -1;
  iter->segment_byte_offset = -1;
  iter->segment_char_offset = -1;
  iter->cached_char_index = -1;
  iter->cached_line_number = -1;
}

static void
iter_set_from_byte_offset (GtkTextRealIter *iter,
                           GtkTextLine *line,
                           gint byte_offset)
{
  iter_set_common (iter, line);

  if (!_gtk_text_line_byte_locate (iter->line,
                                   byte_offset,
                                   &iter->segment,
                                   &iter->any_segment,
                                   &iter->segment_byte_offset,
                                   &iter->line_byte_offset))
    g_error ("Byte index %d is off the end of the line",
             byte_offset);
}

static void
iter_set_from_char_offset (GtkTextRealIter *iter,
                           GtkTextLine *line,
                           gint char_offset)
{
  iter_set_common (iter, line);

  if (!_gtk_text_line_char_locate (iter->line,
                                   char_offset,
                                   &iter->segment,
                                   &iter->any_segment,
                                   &iter->segment_char_offset,
                                   &iter->line_char_offset))
    g_error ("Char offset %d is off the end of the line",
             char_offset);
}

static void
iter_set_from_segment (GtkTextRealIter *iter,
                       GtkTextLine *line,
                       GtkTextLineSegment *segment)
{
  GtkTextLineSegment *seg;
  gint byte_offset;

  /* This could theoretically be optimized by computing all the iter
     fields in this same loop, but I'm skipping it for now. */
  byte_offset = 0;
  seg = line->segments;
  while (seg != segment)
    {
      byte_offset += seg->byte_count;
      seg = seg->next;
    }

  iter_set_from_byte_offset (iter, line, byte_offset);
}

/* This function ensures that the segment-dependent information is
   truly computed lazily; often we don't need to do the full make_real
   work. This ensures the btree and line are valid, but doesn't
   update the segments. */
static GtkTextRealIter*
gtk_text_iter_make_surreal (const GtkTextIter *_iter)
{
  GtkTextRealIter *iter = (GtkTextRealIter*)_iter;

  if (iter->chars_changed_stamp !=
      _gtk_text_btree_get_chars_changed_stamp (iter->tree))
    {
      g_warning ("Invalid text buffer iterator: either the iterator "
                 "is uninitialized, or the characters/pixbufs/widgets "
                 "in the buffer have been modified since the iterator "
                 "was created.\nYou must use marks, character numbers, "
                 "or line numbers to preserve a position across buffer "
                 "modifications.\nYou can apply tags and insert marks "
                 "without invalidating your iterators,\n"
                 "but any mutation that affects 'indexable' buffer contents "
                 "(contents that can be referred to by character offset)\n"
                 "will invalidate all outstanding iterators");
      return NULL;
    }

  /* We don't update the segments information since we are becoming
     only surreal. However we do invalidate the segments information
     if appropriate, to be sure we segfault if we try to use it and we
     should have used make_real. */

  if (iter->segments_changed_stamp !=
      _gtk_text_btree_get_segments_changed_stamp (iter->tree))
    {
      iter->segment = NULL;
      iter->any_segment = NULL;
      /* set to segfault-causing values. */
      iter->segment_byte_offset = -10000;
      iter->segment_char_offset = -10000;
    }

  return iter;
}

static GtkTextRealIter*
gtk_text_iter_make_real (const GtkTextIter *_iter)
{
  GtkTextRealIter *iter;

  iter = gtk_text_iter_make_surreal (_iter);

  if (iter->segments_changed_stamp !=
      _gtk_text_btree_get_segments_changed_stamp (iter->tree))
    {
      if (iter->line_byte_offset >= 0)
        {
          iter_set_from_byte_offset (iter,
                                     iter->line,
                                     iter->line_byte_offset);
        }
      else
        {
          g_assert (iter->line_char_offset >= 0);

          iter_set_from_char_offset (iter,
                                     iter->line,
                                     iter->line_char_offset);
        }
    }

  g_assert (iter->segment != NULL);
  g_assert (iter->any_segment != NULL);
  g_assert (iter->segment->char_count > 0);

  return iter;
}

static GtkTextRealIter*
iter_init_common (GtkTextIter *_iter,
                  GtkTextBTree *tree)
{
  GtkTextRealIter *iter = (GtkTextRealIter*)_iter;

  g_return_val_if_fail (iter != NULL, NULL);
  g_return_val_if_fail (tree != NULL, NULL);

  iter->tree = tree;

  iter->chars_changed_stamp =
    _gtk_text_btree_get_chars_changed_stamp (iter->tree);

  return iter;
}

static GtkTextRealIter*
iter_init_from_segment (GtkTextIter *iter,
                        GtkTextBTree *tree,
                        GtkTextLine *line,
                        GtkTextLineSegment *segment)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (line != NULL, NULL);

  real = iter_init_common (iter, tree);

  iter_set_from_segment (real, line, segment);

  return real;
}

static GtkTextRealIter*
iter_init_from_byte_offset (GtkTextIter *iter,
                            GtkTextBTree *tree,
                            GtkTextLine *line,
                            gint line_byte_offset)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (line != NULL, NULL);

  real = iter_init_common (iter, tree);

  iter_set_from_byte_offset (real, line, line_byte_offset);

  if (real->segment->type == &gtk_text_char_type &&
      (real->segment->body.chars[real->segment_byte_offset] & 0xc0) == 0x80)
    g_warning ("Incorrect line byte index %d falls in the middle of a UTF-8 "
               "character; this will crash the text buffer. "
               "Byte indexes must refer to the start of a character.",
               line_byte_offset);
  
  return real;
}

static GtkTextRealIter*
iter_init_from_char_offset (GtkTextIter *iter,
                            GtkTextBTree *tree,
                            GtkTextLine *line,
                            gint line_char_offset)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (line != NULL, NULL);

  real = iter_init_common (iter, tree);

  iter_set_from_char_offset (real, line, line_char_offset);

  return real;
}

static inline void
invalidate_char_index (GtkTextRealIter *iter)
{
  iter->cached_char_index = -1;
}

static inline void
adjust_char_index (GtkTextRealIter *iter, gint count)
{
  if (iter->cached_char_index >= 0)
    iter->cached_char_index += count;
}

static inline void
adjust_line_number (GtkTextRealIter *iter, gint count)
{
  if (iter->cached_line_number >= 0)
    iter->cached_line_number += count;
}

static inline void
ensure_char_offsets (GtkTextRealIter *iter)
{
  if (iter->line_char_offset < 0)
    {
      g_assert (iter->line_byte_offset >= 0);

      _gtk_text_line_byte_to_char_offsets (iter->line,
                                          iter->line_byte_offset,
                                          &iter->line_char_offset,
                                          &iter->segment_char_offset);
    }
}

static inline void
ensure_byte_offsets (GtkTextRealIter *iter)
{
  if (iter->line_byte_offset < 0)
    {
      g_assert (iter->line_char_offset >= 0);

      _gtk_text_line_char_to_byte_offsets (iter->line,
                                          iter->line_char_offset,
                                          &iter->line_byte_offset,
                                          &iter->segment_byte_offset);
    }
}

static inline gboolean
is_segment_start (GtkTextRealIter *real)
{
  return real->segment_byte_offset == 0 || real->segment_char_offset == 0;
}

#ifdef G_ENABLE_DEBUG
static void
check_invariants (const GtkTextIter *iter)
{
  if (gtk_debug_flags & GTK_DEBUG_TEXT)
    _gtk_text_iter_check (iter);
}
#else
#define check_invariants(x)
#endif

/**
 * gtk_text_iter_get_buffer:
 * @iter: an iterator
 *
 * Returns the #GtkTextBuffer this iterator is associated with.
 *
 * Return value: (transfer none): the buffer
 **/
GtkTextBuffer*
gtk_text_iter_get_buffer (const GtkTextIter *iter)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, NULL);

  real = gtk_text_iter_make_surreal (iter);

  if (real == NULL)
    return NULL;

  check_invariants (iter);

  return _gtk_text_btree_get_buffer (real->tree);
}

/**
 * gtk_text_iter_copy:
 * @iter: an iterator
 *
 * Creates a dynamically-allocated copy of an iterator. This function
 * is not useful in applications, because iterators can be copied with a
 * simple assignment (<literal>GtkTextIter i = j;</literal>). The
 * function is used by language bindings.
 *
 * Return value: a copy of the @iter, free with gtk_text_iter_free ()
 **/
GtkTextIter*
gtk_text_iter_copy (const GtkTextIter *iter)
{
  GtkTextIter *new_iter;

  g_return_val_if_fail (iter != NULL, NULL);

  new_iter = g_slice_new (GtkTextIter);

  *new_iter = *iter;

  return new_iter;
}

/**
 * gtk_text_iter_free:
 * @iter: a dynamically-allocated iterator
 *
 * Free an iterator allocated on the heap. This function
 * is intended for use in language bindings, and is not
 * especially useful for applications, because iterators can
 * simply be allocated on the stack.
 **/
void
gtk_text_iter_free (GtkTextIter *iter)
{
  g_return_if_fail (iter != NULL);

  g_slice_free (GtkTextIter, iter);
}

GType
gtk_text_iter_get_type (void)
{
  static GType our_type = 0;
  
  if (our_type == 0)
    our_type = g_boxed_type_register_static (I_("GtkTextIter"),
					     (GBoxedCopyFunc) gtk_text_iter_copy,
					     (GBoxedFreeFunc) gtk_text_iter_free);

  return our_type;
}

GtkTextLineSegment*
_gtk_text_iter_get_indexable_segment (const GtkTextIter *iter)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, NULL);

  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return NULL;

  check_invariants (iter);

  g_assert (real->segment != NULL);

  return real->segment;
}

GtkTextLineSegment*
_gtk_text_iter_get_any_segment (const GtkTextIter *iter)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, NULL);

  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return NULL;

  check_invariants (iter);

  g_assert (real->any_segment != NULL);

  return real->any_segment;
}

gint
_gtk_text_iter_get_segment_byte (const GtkTextIter *iter)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, 0);

  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return 0;

  ensure_byte_offsets (real);

  check_invariants (iter);

  return real->segment_byte_offset;
}

gint
_gtk_text_iter_get_segment_char (const GtkTextIter *iter)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, 0);

  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return 0;

  ensure_char_offsets (real);

  check_invariants (iter);

  return real->segment_char_offset;
}

/* This function does not require a still-valid
   iterator */
GtkTextLine*
_gtk_text_iter_get_text_line (const GtkTextIter *iter)
{
  const GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, NULL);

  real = (const GtkTextRealIter*)iter;

  return real->line;
}

/* This function does not require a still-valid
   iterator */
GtkTextBTree*
_gtk_text_iter_get_btree (const GtkTextIter *iter)
{
  const GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, NULL);

  real = (const GtkTextRealIter*)iter;

  return real->tree;
}

/*
 * Conversions
 */

/**
 * gtk_text_iter_get_offset:
 * @iter: an iterator
 *
 * Returns the character offset of an iterator.
 * Each character in a #GtkTextBuffer has an offset,
 * starting with 0 for the first character in the buffer.
 * Use gtk_text_buffer_get_iter_at_offset () to convert an
 * offset back into an iterator.
 *
 * Return value: a character offset
 **/
gint
gtk_text_iter_get_offset (const GtkTextIter *iter)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, 0);

  real = gtk_text_iter_make_surreal (iter);

  if (real == NULL)
    return 0;

  check_invariants (iter);
  
  if (real->cached_char_index < 0)
    {
      ensure_char_offsets (real);
      
      real->cached_char_index =
        _gtk_text_line_char_index (real->line);
      real->cached_char_index += real->line_char_offset;
    }

  check_invariants (iter);

  return real->cached_char_index;
}

/**
 * gtk_text_iter_get_line:
 * @iter: an iterator
 *
 * Returns the line number containing the iterator. Lines in
 * a #GtkTextBuffer are numbered beginning with 0 for the first
 * line in the buffer.
 *
 * Return value: a line number
 **/
gint
gtk_text_iter_get_line (const GtkTextIter *iter)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, 0);

  real = gtk_text_iter_make_surreal (iter);

  if (real == NULL)
    return 0;

  if (real->cached_line_number < 0)
    real->cached_line_number =
      _gtk_text_line_get_number (real->line);

  check_invariants (iter);

  return real->cached_line_number;
}

/**
 * gtk_text_iter_get_line_offset:
 * @iter: an iterator
 *
 * Returns the character offset of the iterator,
 * counting from the start of a newline-terminated line.
 * The first character on the line has offset 0.
 *
 * Return value: offset from start of line
 **/
gint
gtk_text_iter_get_line_offset (const GtkTextIter *iter)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, 0);

  real = gtk_text_iter_make_surreal (iter);

  if (real == NULL)
    return 0;

  ensure_char_offsets (real);

  check_invariants (iter);

  return real->line_char_offset;
}

/**
 * gtk_text_iter_get_line_index:
 * @iter: an iterator
 *
 * Returns the byte index of the iterator, counting
 * from the start of a newline-terminated line.
 * Remember that #GtkTextBuffer encodes text in
 * UTF-8, and that characters can require a variable
 * number of bytes to represent.
 *
 * Return value: distance from start of line, in bytes
 **/
gint
gtk_text_iter_get_line_index (const GtkTextIter *iter)
{
  GtkTextRealIter *real;
  
  g_return_val_if_fail (iter != NULL, 0);

  real = gtk_text_iter_make_surreal (iter);

  if (real == NULL)
    return 0;

  ensure_byte_offsets (real);

  check_invariants (iter);

  return real->line_byte_offset;
}

/**
 * gtk_text_iter_get_visible_line_offset:
 * @iter: a #GtkTextIter
 * 
 * Returns the offset in characters from the start of the
 * line to the given @iter, not counting characters that
 * are invisible due to tags with the "invisible" flag
 * toggled on.
 * 
 * Return value: offset in visible characters from the start of the line 
 **/
gint
gtk_text_iter_get_visible_line_offset (const GtkTextIter *iter)
{
  GtkTextRealIter *real;
  gint vis_offset;
  GtkTextLineSegment *seg;
  GtkTextIter pos;
  
  g_return_val_if_fail (iter != NULL, 0);

  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return 0;

  ensure_char_offsets (real);

  check_invariants (iter);
  
  vis_offset = real->line_char_offset;

  g_assert (vis_offset >= 0);
  
  _gtk_text_btree_get_iter_at_line (real->tree,
                                    &pos,
                                    real->line,
                                    0);

  seg = _gtk_text_iter_get_indexable_segment (&pos);

  while (seg != real->segment)
    {
      /* This is a pretty expensive call, making the
       * whole function pretty lame; we could keep track
       * of current invisibility state by looking at toggle
       * segments as we loop, and then call this function
       * only once per line, in order to speed up the loop
       * quite a lot.
       */
      if (_gtk_text_btree_char_is_invisible (&pos))
        vis_offset -= seg->char_count;

      _gtk_text_iter_forward_indexable_segment (&pos);

      seg = _gtk_text_iter_get_indexable_segment (&pos);
    }

  if (_gtk_text_btree_char_is_invisible (&pos))
    vis_offset -= real->segment_char_offset;
  
  return vis_offset;
}


/**
 * gtk_text_iter_get_visible_line_index:
 * @iter: a #GtkTextIter
 * 
 * Returns the number of bytes from the start of the
 * line to the given @iter, not counting bytes that
 * are invisible due to tags with the "invisible" flag
 * toggled on.
 * 
 * Return value: byte index of @iter with respect to the start of the line
 **/
gint
gtk_text_iter_get_visible_line_index (const GtkTextIter *iter)
{
  GtkTextRealIter *real;
  gint vis_offset;
  GtkTextLineSegment *seg;
  GtkTextIter pos;
  
  g_return_val_if_fail (iter != NULL, 0);

  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return 0;

  ensure_byte_offsets (real);

  check_invariants (iter);

  vis_offset = real->line_byte_offset;

  g_assert (vis_offset >= 0);
  
  _gtk_text_btree_get_iter_at_line (real->tree,
                                    &pos,
                                    real->line,
                                    0);

  seg = _gtk_text_iter_get_indexable_segment (&pos);

  while (seg != real->segment)
    {
      /* This is a pretty expensive call, making the
       * whole function pretty lame; we could keep track
       * of current invisibility state by looking at toggle
       * segments as we loop, and then call this function
       * only once per line, in order to speed up the loop
       * quite a lot.
       */
      if (_gtk_text_btree_char_is_invisible (&pos))
        vis_offset -= seg->byte_count;

      _gtk_text_iter_forward_indexable_segment (&pos);

      seg = _gtk_text_iter_get_indexable_segment (&pos);
    }

  if (_gtk_text_btree_char_is_invisible (&pos))
    vis_offset -= real->segment_byte_offset;
  
  return vis_offset;
}

/*
 * Dereferencing
 */

/**
 * gtk_text_iter_get_char:
 * @iter: an iterator
 *
 * Returns the Unicode character at this iterator.  (Equivalent to
 * operator* on a C++ iterator.)  If the element at this iterator is a
 * non-character element, such as an image embedded in the buffer, the
 * Unicode "unknown" character 0xFFFC is returned. If invoked on
 * the end iterator, zero is returned; zero is not a valid Unicode character.
 * So you can write a loop which ends when gtk_text_iter_get_char ()
 * returns 0.
 *
 * Return value: a Unicode character, or 0 if @iter is not dereferenceable
 **/
gunichar
gtk_text_iter_get_char (const GtkTextIter *iter)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, 0);

  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return 0;

  check_invariants (iter);

  if (gtk_text_iter_is_end (iter))
    return 0;
  else if (real->segment->type == &gtk_text_char_type)
    {
      ensure_byte_offsets (real);
      
      return g_utf8_get_char (real->segment->body.chars +
                              real->segment_byte_offset);
    }
  else
    {
      /* Unicode "unknown character" 0xFFFC */
      return GTK_TEXT_UNKNOWN_CHAR;
    }
}

/**
 * gtk_text_iter_get_slice:
 * @start: iterator at start of a range
 * @end: iterator at end of a range
 *
 * Returns the text in the given range. A "slice" is an array of
 * characters encoded in UTF-8 format, including the Unicode "unknown"
 * character 0xFFFC for iterable non-character elements in the buffer,
 * such as images.  Because images are encoded in the slice, byte and
 * character offsets in the returned array will correspond to byte
 * offsets in the text buffer. Note that 0xFFFC can occur in normal
 * text as well, so it is not a reliable indicator that a pixbuf or
 * widget is in the buffer.
 *
 * Return value: slice of text from the buffer
 **/
gchar*
gtk_text_iter_get_slice       (const GtkTextIter *start,
                               const GtkTextIter *end)
{
  g_return_val_if_fail (start != NULL, NULL);
  g_return_val_if_fail (end != NULL, NULL);

  check_invariants (start);
  check_invariants (end);

  return _gtk_text_btree_get_text (start, end, TRUE, TRUE);
}

/**
 * gtk_text_iter_get_text:
 * @start: iterator at start of a range
 * @end: iterator at end of a range
 *
 * Returns <emphasis>text</emphasis> in the given range.  If the range
 * contains non-text elements such as images, the character and byte
 * offsets in the returned string will not correspond to character and
 * byte offsets in the buffer. If you want offsets to correspond, see
 * gtk_text_iter_get_slice ().
 *
 * Return value: array of characters from the buffer
 **/
gchar*
gtk_text_iter_get_text       (const GtkTextIter *start,
                              const GtkTextIter *end)
{
  g_return_val_if_fail (start != NULL, NULL);
  g_return_val_if_fail (end != NULL, NULL);

  check_invariants (start);
  check_invariants (end);

  return _gtk_text_btree_get_text (start, end, TRUE, FALSE);
}

/**
 * gtk_text_iter_get_visible_slice:
 * @start: iterator at start of range
 * @end: iterator at end of range
 *
 * Like gtk_text_iter_get_slice (), but invisible text is not included.
 * Invisible text is usually invisible because a #GtkTextTag with the
 * "invisible" attribute turned on has been applied to it.
 *
 * Return value: slice of text from the buffer
 **/
gchar*
gtk_text_iter_get_visible_slice (const GtkTextIter  *start,
                                 const GtkTextIter  *end)
{
  g_return_val_if_fail (start != NULL, NULL);
  g_return_val_if_fail (end != NULL, NULL);

  check_invariants (start);
  check_invariants (end);

  return _gtk_text_btree_get_text (start, end, FALSE, TRUE);
}

/**
 * gtk_text_iter_get_visible_text:
 * @start: iterator at start of range
 * @end: iterator at end of range
 *
 * Like gtk_text_iter_get_text (), but invisible text is not included.
 * Invisible text is usually invisible because a #GtkTextTag with the
 * "invisible" attribute turned on has been applied to it.
 *
 * Return value: string containing visible text in the range
 **/
gchar*
gtk_text_iter_get_visible_text (const GtkTextIter  *start,
                                const GtkTextIter  *end)
{
  g_return_val_if_fail (start != NULL, NULL);
  g_return_val_if_fail (end != NULL, NULL);

  check_invariants (start);
  check_invariants (end);

  return _gtk_text_btree_get_text (start, end, FALSE, FALSE);
}

/**
 * gtk_text_iter_get_pixbuf:
 * @iter: an iterator
 *
 * If the element at @iter is a pixbuf, the pixbuf is returned
 * (with no new reference count added). Otherwise,
 * %NULL is returned.
 *
 * Return value: (transfer none): the pixbuf at @iter
 **/
GdkPixbuf*
gtk_text_iter_get_pixbuf (const GtkTextIter *iter)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, NULL);

  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return NULL;

  check_invariants (iter);

  if (real->segment->type != &gtk_text_pixbuf_type)
    return NULL;
  else
    return real->segment->body.pixbuf.pixbuf;
}

/**
 * gtk_text_iter_get_child_anchor:
 * @iter: an iterator
 *
 * If the location at @iter contains a child anchor, the
 * anchor is returned (with no new reference count added). Otherwise,
 * %NULL is returned.
 *
 * Return value: the anchor at @iter
 **/
GtkTextChildAnchor*
gtk_text_iter_get_child_anchor (const GtkTextIter *iter)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, NULL);

  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return NULL;

  check_invariants (iter);

  if (real->segment->type != &gtk_text_child_type)
    return NULL;
  else
    return real->segment->body.child.obj;
}

/**
 * gtk_text_iter_get_marks:
 * @iter: an iterator
 *
 * Returns a list of all #GtkTextMark at this location. Because marks
 * are not iterable (they don't take up any "space" in the buffer,
 * they are just marks in between iterable locations), multiple marks
 * can exist in the same place. The returned list is not in any
 * meaningful order.
 *
 * Return value: (element-type GtkTextMark) (transfer container): list of #GtkTextMark
 **/
GSList*
gtk_text_iter_get_marks (const GtkTextIter *iter)
{
  GtkTextRealIter *real;
  GtkTextLineSegment *seg;
  GSList *retval;

  g_return_val_if_fail (iter != NULL, NULL);

  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return NULL;

  check_invariants (iter);

  retval = NULL;
  seg = real->any_segment;
  while (seg != real->segment)
    {
      if (seg->type == &gtk_text_left_mark_type ||
          seg->type == &gtk_text_right_mark_type)
        retval = g_slist_prepend (retval, seg->body.mark.obj);

      seg = seg->next;
    }

  /* The returned list isn't guaranteed to be in any special order,
     and it isn't. */
  return retval;
}

/**
 * gtk_text_iter_get_toggled_tags:
 * @iter: an iterator
 * @toggled_on: %TRUE to get toggled-on tags
 *
 * Returns a list of #GtkTextTag that are toggled on or off at this
 * point.  (If @toggled_on is %TRUE, the list contains tags that are
 * toggled on.) If a tag is toggled on at @iter, then some non-empty
 * range of characters following @iter has that tag applied to it.  If
 * a tag is toggled off, then some non-empty range following @iter
 * does <emphasis>not</emphasis> have the tag applied to it.
 *
 * Return value: (element-type GtkTextTag) (transfer container): tags toggled at this point
 **/
GSList*
gtk_text_iter_get_toggled_tags  (const GtkTextIter  *iter,
                                 gboolean            toggled_on)
{
  GtkTextRealIter *real;
  GtkTextLineSegment *seg;
  GSList *retval;

  g_return_val_if_fail (iter != NULL, NULL);

  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return NULL;

  check_invariants (iter);

  retval = NULL;
  seg = real->any_segment;
  while (seg != real->segment)
    {
      if (toggled_on)
        {
          if (seg->type == &gtk_text_toggle_on_type)
            {
              retval = g_slist_prepend (retval, seg->body.toggle.info->tag);
            }
        }
      else
        {
          if (seg->type == &gtk_text_toggle_off_type)
            {
              retval = g_slist_prepend (retval, seg->body.toggle.info->tag);
            }
        }

      seg = seg->next;
    }

  /* The returned list isn't guaranteed to be in any special order,
     and it isn't. */
  return retval;
}

/**
 * gtk_text_iter_begins_tag:
 * @iter: an iterator
 * @tag: (allow-none): a #GtkTextTag, or %NULL
 *
 * Returns %TRUE if @tag is toggled on at exactly this point. If @tag
 * is %NULL, returns %TRUE if any tag is toggled on at this point. Note
 * that the gtk_text_iter_begins_tag () returns %TRUE if @iter is the
 * <emphasis>start</emphasis> of the tagged range;
 * gtk_text_iter_has_tag () tells you whether an iterator is
 * <emphasis>within</emphasis> a tagged range.
 *
 * Return value: whether @iter is the start of a range tagged with @tag
 **/
gboolean
gtk_text_iter_begins_tag    (const GtkTextIter  *iter,
                             GtkTextTag         *tag)
{
  GtkTextRealIter *real;
  GtkTextLineSegment *seg;

  g_return_val_if_fail (iter != NULL, FALSE);

  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return FALSE;

  check_invariants (iter);

  seg = real->any_segment;
  while (seg != real->segment)
    {
      if (seg->type == &gtk_text_toggle_on_type)
        {
          if (tag == NULL ||
              seg->body.toggle.info->tag == tag)
            return TRUE;
        }

      seg = seg->next;
    }

  return FALSE;
}

/**
 * gtk_text_iter_ends_tag:
 * @iter: an iterator
 * @tag: (allow-none): a #GtkTextTag, or %NULL
 *
 * Returns %TRUE if @tag is toggled off at exactly this point. If @tag
 * is %NULL, returns %TRUE if any tag is toggled off at this point. Note
 * that the gtk_text_iter_ends_tag () returns %TRUE if @iter is the
 * <emphasis>end</emphasis> of the tagged range;
 * gtk_text_iter_has_tag () tells you whether an iterator is
 * <emphasis>within</emphasis> a tagged range.
 *
 * Return value: whether @iter is the end of a range tagged with @tag
 *
 **/
gboolean
gtk_text_iter_ends_tag   (const GtkTextIter  *iter,
                          GtkTextTag         *tag)
{
  GtkTextRealIter *real;
  GtkTextLineSegment *seg;

  g_return_val_if_fail (iter != NULL, FALSE);

  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return FALSE;

  check_invariants (iter);

  seg = real->any_segment;
  while (seg != real->segment)
    {
      if (seg->type == &gtk_text_toggle_off_type)
        {
          if (tag == NULL ||
              seg->body.toggle.info->tag == tag)
            return TRUE;
        }

      seg = seg->next;
    }

  return FALSE;
}

/**
 * gtk_text_iter_toggles_tag:
 * @iter: an iterator
 * @tag: (allow-none): a #GtkTextTag, or %NULL
 *
 * This is equivalent to (gtk_text_iter_begins_tag () ||
 * gtk_text_iter_ends_tag ()), i.e. it tells you whether a range with
 * @tag applied to it begins <emphasis>or</emphasis> ends at @iter.
 *
 * Return value: whether @tag is toggled on or off at @iter
 **/
gboolean
gtk_text_iter_toggles_tag (const GtkTextIter  *iter,
                           GtkTextTag         *tag)
{
  GtkTextRealIter *real;
  GtkTextLineSegment *seg;

  g_return_val_if_fail (iter != NULL, FALSE);

  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return FALSE;

  check_invariants (iter);

  seg = real->any_segment;
  while (seg != real->segment)
    {
      if ( (seg->type == &gtk_text_toggle_off_type ||
            seg->type == &gtk_text_toggle_on_type) &&
           (tag == NULL ||
            seg->body.toggle.info->tag == tag) )
        return TRUE;

      seg = seg->next;
    }

  return FALSE;
}

/**
 * gtk_text_iter_has_tag:
 * @iter: an iterator
 * @tag: a #GtkTextTag
 *
 * Returns %TRUE if @iter is within a range tagged with @tag.
 *
 * Return value: whether @iter is tagged with @tag
 **/
gboolean
gtk_text_iter_has_tag (const GtkTextIter   *iter,
                       GtkTextTag          *tag)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, FALSE);
  g_return_val_if_fail (GTK_IS_TEXT_TAG (tag), FALSE);

  real = gtk_text_iter_make_surreal (iter);

  if (real == NULL)
    return FALSE;

  check_invariants (iter);

  if (real->line_byte_offset >= 0)
    {
      return _gtk_text_line_byte_has_tag (real->line, real->tree,
                                          real->line_byte_offset, tag);
    }
  else
    {
      g_assert (real->line_char_offset >= 0);
      return _gtk_text_line_char_has_tag (real->line, real->tree,
                                          real->line_char_offset, tag);
    }
}

/**
 * gtk_text_iter_get_tags:
 * @iter: a #GtkTextIter
 * 
 * Returns a list of tags that apply to @iter, in ascending order of
 * priority (highest-priority tags are last). The #GtkTextTag in the
 * list don't have a reference added, but you have to free the list
 * itself.
 *
 * Return value: (element-type GtkTextTag) (transfer container): list of #GtkTextTag
 **/
GSList*
gtk_text_iter_get_tags (const GtkTextIter *iter)
{
  GtkTextTag** tags;
  gint tag_count = 0;
  gint i;
  GSList *retval;
  
  g_return_val_if_fail (iter != NULL, NULL);
  
  /* Get the tags at this spot */
  tags = _gtk_text_btree_get_tags (iter, &tag_count);

  /* No tags, use default style */
  if (tags == NULL || tag_count == 0)
    {
      g_free (tags);

      return NULL;
    }

  retval = NULL;
  i = 0;
  while (i < tag_count)
    {
      retval = g_slist_prepend (retval, tags[i]);
      ++i;
    }
  
  g_free (tags);

  /* Return tags in ascending order of priority */
  return g_slist_reverse (retval);
}

/**
 * gtk_text_iter_editable:
 * @iter: an iterator
 * @default_setting: %TRUE if text is editable by default
 *
 * Returns whether the character at @iter is within an editable region
 * of text.  Non-editable text is "locked" and can't be changed by the
 * user via #GtkTextView. This function is simply a convenience
 * wrapper around gtk_text_iter_get_attributes (). If no tags applied
 * to this text affect editability, @default_setting will be returned.
 *
 * You don't want to use this function to decide whether text can be
 * inserted at @iter, because for insertion you don't want to know
 * whether the char at @iter is inside an editable range, you want to
 * know whether a new character inserted at @iter would be inside an
 * editable range. Use gtk_text_iter_can_insert() to handle this
 * case.
 * 
 * Return value: whether @iter is inside an editable range
 **/
gboolean
gtk_text_iter_editable (const GtkTextIter *iter,
                        gboolean           default_setting)
{
  GtkTextAttributes *values;
  gboolean retval;

  g_return_val_if_fail (iter != NULL, FALSE);
  
  values = gtk_text_attributes_new ();

  values->editable = default_setting;

  gtk_text_iter_get_attributes (iter, values);

  retval = values->editable;

  gtk_text_attributes_unref (values);

  return retval;
}

/**
 * gtk_text_iter_can_insert:
 * @iter: an iterator
 * @default_editability: %TRUE if text is editable by default
 * 
 * Considering the default editability of the buffer, and tags that
 * affect editability, determines whether text inserted at @iter would
 * be editable. If text inserted at @iter would be editable then the
 * user should be allowed to insert text at @iter.
 * gtk_text_buffer_insert_interactive() uses this function to decide
 * whether insertions are allowed at a given position.
 * 
 * Return value: whether text inserted at @iter would be editable
 **/
gboolean
gtk_text_iter_can_insert (const GtkTextIter *iter,
                          gboolean           default_editability)
{
  g_return_val_if_fail (iter != NULL, FALSE);
  
  if (gtk_text_iter_editable (iter, default_editability))
    return TRUE;
  /* If at start/end of buffer, default editability is used */
  else if ((gtk_text_iter_is_start (iter) ||
            gtk_text_iter_is_end (iter)) &&
           default_editability)
    return TRUE;
  else
    {
      /* if iter isn't editable, and the char before iter is,
       * then iter is the first char in an editable region
       * and thus insertion at iter results in editable text.
       */
      GtkTextIter prev = *iter;
      gtk_text_iter_backward_char (&prev);
      return gtk_text_iter_editable (&prev, default_editability);
    }
}


/**
 * gtk_text_iter_get_language:
 * @iter: an iterator
 *
 * A convenience wrapper around gtk_text_iter_get_attributes (),
 * which returns the language in effect at @iter. If no tags affecting
 * language apply to @iter, the return value is identical to that of
 * gtk_get_default_language ().
 *
 * Return value: language in effect at @iter
 **/
PangoLanguage *
gtk_text_iter_get_language (const GtkTextIter *iter)
{
  GtkTextAttributes *values;
  PangoLanguage *retval;
  
  values = gtk_text_attributes_new ();

  gtk_text_iter_get_attributes (iter, values);

  retval = values->language;

  gtk_text_attributes_unref (values);

  return retval;
}

/**
 * gtk_text_iter_starts_line:
 * @iter: an iterator
 *
 * Returns %TRUE if @iter begins a paragraph,
 * i.e. if gtk_text_iter_get_line_offset () would return 0.
 * However this function is potentially more efficient than
 * gtk_text_iter_get_line_offset () because it doesn't have to compute
 * the offset, it just has to see whether it's 0.
 *
 * Return value: whether @iter begins a line
 **/
gboolean
gtk_text_iter_starts_line (const GtkTextIter   *iter)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, FALSE);

  real = gtk_text_iter_make_surreal (iter);

  if (real == NULL)
    return FALSE;

  check_invariants (iter);

  if (real->line_byte_offset >= 0)
    {
      return (real->line_byte_offset == 0);
    }
  else
    {
      g_assert (real->line_char_offset >= 0);
      return (real->line_char_offset == 0);
    }
}

/**
 * gtk_text_iter_ends_line:
 * @iter: an iterator
 *
 * Returns %TRUE if @iter points to the start of the paragraph
 * delimiter characters for a line (delimiters will be either a
 * newline, a carriage return, a carriage return followed by a
 * newline, or a Unicode paragraph separator character). Note that an
 * iterator pointing to the \n of a \r\n pair will not be counted as
 * the end of a line, the line ends before the \r. The end iterator is
 * considered to be at the end of a line, even though there are no
 * paragraph delimiter chars there.
 *
 * Return value: whether @iter is at the end of a line
 **/
gboolean
gtk_text_iter_ends_line (const GtkTextIter   *iter)
{
  gunichar wc;
  
  g_return_val_if_fail (iter != NULL, FALSE);

  check_invariants (iter);

  /* Only one character has type G_UNICODE_PARAGRAPH_SEPARATOR in
   * Unicode 3.0; update this if that changes.
   */
#define PARAGRAPH_SEPARATOR 0x2029

  wc = gtk_text_iter_get_char (iter);
  
  if (wc == '\r' || wc == PARAGRAPH_SEPARATOR || wc == 0) /* wc == 0 is end iterator */
    return TRUE;
  else if (wc == '\n')
    {
      GtkTextIter tmp = *iter;

      /* need to determine if a \r precedes the \n, in which case
       * we aren't the end of the line.
       * Note however that if \r and \n are on different lines, they
       * both are terminators. This for instance may happen after
       * deleting some text:

          1 some text\r    delete 'a'    1 some text\r
          2 a\n            --------->    2 \n
          3 ...                          3 ...

       */

      if (gtk_text_iter_get_line_offset (&tmp) == 0)
        return TRUE;

      if (!gtk_text_iter_backward_char (&tmp))
        return TRUE;

      return gtk_text_iter_get_char (&tmp) != '\r';
    }
  else
    return FALSE;
}

/**
 * gtk_text_iter_is_end:
 * @iter: an iterator
 *
 * Returns %TRUE if @iter is the end iterator, i.e. one past the last
 * dereferenceable iterator in the buffer. gtk_text_iter_is_end () is
 * the most efficient way to check whether an iterator is the end
 * iterator.
 *
 * Return value: whether @iter is the end iterator
 **/
gboolean
gtk_text_iter_is_end (const GtkTextIter *iter)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, FALSE);

  real = gtk_text_iter_make_surreal (iter);

  if (real == NULL)
    return FALSE;

  check_invariants (iter);

  if (!_gtk_text_line_contains_end_iter (real->line, real->tree))
    return FALSE;

  /* Now we need the segments validated */
  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return FALSE;
  
  return _gtk_text_btree_is_end (real->tree, real->line,
                                 real->segment,
                                 real->segment_byte_offset,
                                 real->segment_char_offset);
}

/**
 * gtk_text_iter_is_start:
 * @iter: an iterator
 *
 * Returns %TRUE if @iter is the first iterator in the buffer, that is
 * if @iter has a character offset of 0.
 *
 * Return value: whether @iter is the first in the buffer
 **/
gboolean
gtk_text_iter_is_start (const GtkTextIter *iter)
{
  return gtk_text_iter_get_offset (iter) == 0;
}

/**
 * gtk_text_iter_get_chars_in_line:
 * @iter: an iterator
 *
 * Returns the number of characters in the line containing @iter,
 * including the paragraph delimiters.
 *
 * Return value: number of characters in the line
 **/
gint
gtk_text_iter_get_chars_in_line (const GtkTextIter   *iter)
{
  GtkTextRealIter *real;
  gint count;
  GtkTextLineSegment *seg;

  g_return_val_if_fail (iter != NULL, 0);

  real = gtk_text_iter_make_surreal (iter);

  if (real == NULL)
    return 0;

  check_invariants (iter);

  if (real->line_char_offset >= 0)
    {
      /* We can start at the segments we've already found. */
      count = real->line_char_offset - real->segment_char_offset;
      seg = _gtk_text_iter_get_indexable_segment (iter);
    }
  else
    {
      /* count whole line. */
      seg = real->line->segments;
      count = 0;
    }


  while (seg != NULL)
    {
      count += seg->char_count;

      seg = seg->next;
    }

  if (_gtk_text_line_contains_end_iter (real->line, real->tree))
    count -= 1; /* Dump the newline that was in the last segment of the end iter line */
  
  return count;
}

/**
 * gtk_text_iter_get_bytes_in_line:
 * @iter: an iterator
 *
 * Returns the number of bytes in the line containing @iter,
 * including the paragraph delimiters.
 *
 * Return value: number of bytes in the line
 **/
gint
gtk_text_iter_get_bytes_in_line (const GtkTextIter   *iter)
{
  GtkTextRealIter *real;
  gint count;
  GtkTextLineSegment *seg;

  g_return_val_if_fail (iter != NULL, 0);

  real = gtk_text_iter_make_surreal (iter);

  if (real == NULL)
    return 0;

  check_invariants (iter);

  if (real->line_byte_offset >= 0)
    {
      /* We can start at the segments we've already found. */
      count = real->line_byte_offset - real->segment_byte_offset;
      seg = _gtk_text_iter_get_indexable_segment (iter);
    }
  else
    {
      /* count whole line. */
      seg = real->line->segments;
      count = 0;
    }

  while (seg != NULL)
    {
      count += seg->byte_count;

      seg = seg->next;
    }

  if (_gtk_text_line_contains_end_iter (real->line, real->tree))
    count -= 1; /* Dump the newline that was in the last segment of the end iter line */
  
  return count;
}

/**
 * gtk_text_iter_get_attributes:
 * @iter: an iterator
 * @values: a #GtkTextAttributes to be filled in
 *
 * Computes the effect of any tags applied to this spot in the
 * text. The @values parameter should be initialized to the default
 * settings you wish to use if no tags are in effect. You'd typically
 * obtain the defaults from gtk_text_view_get_default_attributes().
 *
 * gtk_text_iter_get_attributes () will modify @values, applying the
 * effects of any tags present at @iter. If any tags affected @values,
 * the function returns %TRUE.
 *
 * Return value: %TRUE if @values was modified
 **/
gboolean
gtk_text_iter_get_attributes (const GtkTextIter  *iter,
                              GtkTextAttributes  *values)
{
  GtkTextTag** tags;
  gint tag_count = 0;

  /* Get the tags at this spot */
  tags = _gtk_text_btree_get_tags (iter, &tag_count);

  /* No tags, use default style */
  if (tags == NULL || tag_count == 0)
    {
      g_free (tags);

      return FALSE;
    }

  _gtk_text_attributes_fill_from_tags (values,
                                       tags,
                                       tag_count);

  g_free (tags);

  return TRUE;
}

/*
 * Increments/decrements
 */

/* The return value of this indicates WHETHER WE MOVED.
 * The return value of public functions indicates
 * (MOVEMENT OCCURRED && NEW ITER IS DEREFERENCEABLE)
 *
 * This function will not change the iterator if
 * it's already on the last (end iter) line, i.e. it
 * won't move to the end of the last line.
 */
static gboolean
forward_line_leaving_caches_unmodified (GtkTextRealIter *real)
{
  if (!_gtk_text_line_contains_end_iter (real->line, real->tree))
    {
      GtkTextLine *new_line;
      
      new_line = _gtk_text_line_next (real->line);
      g_assert (new_line);
      g_assert (new_line != real->line);
      g_assert (!_gtk_text_line_is_last (new_line, real->tree));
      
      real->line = new_line;

      real->line_byte_offset = 0;
      real->line_char_offset = 0;

      real->segment_byte_offset = 0;
      real->segment_char_offset = 0;

      /* Find first segments in new line */
      real->any_segment = real->line->segments;
      real->segment = real->any_segment;
      while (real->segment->char_count == 0)
        real->segment = real->segment->next;

      return TRUE;
    }
  else
    {
      /* There is no way to move forward a line; we were already at
       * the line containing the end iterator.
       * However we may not be at the end iterator itself.
       */
      
      return FALSE;
    }
}

#if 0
/* The return value of this indicates WHETHER WE MOVED.
 * The return value of public functions indicates
 * (MOVEMENT OCCURRED && NEW ITER IS DEREFERENCEABLE)
 *
 * This function is currently unused, thus it is #if-0-ed. It is
 * left here, since it's non-trivial code that might be useful in
 * the future.
 */
static gboolean
backward_line_leaving_caches_unmodified (GtkTextRealIter *real)
{
  GtkTextLine *new_line;

  new_line = _gtk_text_line_previous (real->line);

  g_assert (new_line != real->line);

  if (new_line != NULL)
    {
      real->line = new_line;

      real->line_byte_offset = 0;
      real->line_char_offset = 0;

      real->segment_byte_offset = 0;
      real->segment_char_offset = 0;

      /* Find first segments in new line */
      real->any_segment = real->line->segments;
      real->segment = real->any_segment;
      while (real->segment->char_count == 0)
        real->segment = real->segment->next;

      return TRUE;
    }
  else
    {
      /* There is no way to move backward; we were already
         at the first line. */

      /* We leave real->line as-is */

      /* Note that we didn't clamp to the start of the first line. */

      return FALSE;
    }
}
#endif 

/* The return value indicates (MOVEMENT OCCURRED && NEW ITER IS
 * DEREFERENCEABLE)
 */
static gboolean
forward_char (GtkTextRealIter *real)
{
  GtkTextIter *iter = (GtkTextIter*)real;

  check_invariants ((GtkTextIter*)real);

  ensure_char_offsets (real);

  if ( (real->segment_char_offset + 1) == real->segment->char_count)
    {
      /* Need to move to the next segment; if no next segment,
         need to move to next line. */
      return _gtk_text_iter_forward_indexable_segment (iter);
    }
  else
    {
      /* Just moving within a segment. Keep byte count
         up-to-date, if it was already up-to-date. */

      g_assert (real->segment->type == &gtk_text_char_type);

      if (real->line_byte_offset >= 0)
        {
          gint bytes;
          const char * start =
            real->segment->body.chars + real->segment_byte_offset;

          bytes = g_utf8_next_char (start) - start;

          real->line_byte_offset += bytes;
          real->segment_byte_offset += bytes;

          g_assert (real->segment_byte_offset < real->segment->byte_count);
        }

      real->line_char_offset += 1;
      real->segment_char_offset += 1;

      adjust_char_index (real, 1);

      g_assert (real->segment_char_offset < real->segment->char_count);

      /* We moved into the middle of a segment, so the any_segment
         must now be the segment we're in the middle of. */
      real->any_segment = real->segment;

      check_invariants ((GtkTextIter*)real);

      if (gtk_text_iter_is_end ((GtkTextIter*)real))
        return FALSE;
      else
        return TRUE;
    }
}

gboolean
_gtk_text_iter_forward_indexable_segment (GtkTextIter *iter)
{
  /* Need to move to the next segment; if no next segment,
     need to move to next line. */
  GtkTextLineSegment *seg;
  GtkTextLineSegment *any_seg;
  GtkTextRealIter *real;
  gint chars_skipped;
  gint bytes_skipped;

  g_return_val_if_fail (iter != NULL, FALSE);

  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return FALSE;

  check_invariants (iter);

  if (real->line_char_offset >= 0)
    {
      chars_skipped = real->segment->char_count - real->segment_char_offset;
      g_assert (chars_skipped > 0);
    }
  else
    chars_skipped = 0;

  if (real->line_byte_offset >= 0)
    {
      bytes_skipped = real->segment->byte_count - real->segment_byte_offset;
      g_assert (bytes_skipped > 0);
    }
  else
    bytes_skipped = 0;

  /* Get first segment of any kind */
  any_seg = real->segment->next;
  /* skip non-indexable segments, if any */
  seg = any_seg;
  while (seg != NULL && seg->char_count == 0)
    seg = seg->next;

  if (seg != NULL)
    {
      real->any_segment = any_seg;
      real->segment = seg;

      if (real->line_byte_offset >= 0)
        {
          g_assert (bytes_skipped > 0);
          real->segment_byte_offset = 0;
          real->line_byte_offset += bytes_skipped;
        }

      if (real->line_char_offset >= 0)
        {
          g_assert (chars_skipped > 0);
          real->segment_char_offset = 0;
          real->line_char_offset += chars_skipped;
          adjust_char_index (real, chars_skipped);
        }

      check_invariants (iter);

      return !gtk_text_iter_is_end (iter);
    }
  else
    {
      /* End of the line */
      if (forward_line_leaving_caches_unmodified (real))
        {
          adjust_line_number (real, 1);
          if (real->line_char_offset >= 0)
            adjust_char_index (real, chars_skipped);

          g_assert (real->line_byte_offset == 0);
          g_assert (real->line_char_offset == 0);
          g_assert (real->segment_byte_offset == 0);
          g_assert (real->segment_char_offset == 0);
          g_assert (gtk_text_iter_starts_line (iter));

          check_invariants (iter);

          return !gtk_text_iter_is_end (iter);
        }
      else
        {
          /* End of buffer, but iter is still at start of last segment,
           * not at the end iterator. We put it on the end iterator.
           */
          
          check_invariants (iter);

          g_assert (!_gtk_text_line_is_last (real->line, real->tree));
          g_assert (_gtk_text_line_contains_end_iter (real->line, real->tree));

          gtk_text_iter_forward_to_line_end (iter);

          g_assert (gtk_text_iter_is_end (iter));
          
          return FALSE;
        }
    }
}

static gboolean
at_last_indexable_segment (GtkTextRealIter *real)
{
  GtkTextLineSegment *seg;

  /* Return TRUE if there are no indexable segments after
   * this iterator.
   */

  seg = real->segment->next;
  while (seg)
    {
      if (seg->char_count > 0)
        return FALSE;
      seg = seg->next;
    }
  return TRUE;
}

/* Goes back to the start of the next segment, even if
 * we're not at the start of the current segment (always
 * ends up on a different segment if it returns TRUE)
 */
gboolean
_gtk_text_iter_backward_indexable_segment (GtkTextIter *iter)
{
  /* Move to the start of the previous segment; if no previous
   * segment, to the last segment in the previous line. This is
   * inherently a bit inefficient due to the singly-linked list and
   * tree nodes, but we can't afford the RAM for doubly-linked.
   */
  GtkTextRealIter *real;
  GtkTextLineSegment *seg;
  GtkTextLineSegment *any_seg;
  GtkTextLineSegment *prev_seg;
  GtkTextLineSegment *prev_any_seg;
  gint bytes_skipped;
  gint chars_skipped;

  g_return_val_if_fail (iter != NULL, FALSE);

  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return FALSE;

  check_invariants (iter);

  /* Find first segments in line */
  any_seg = real->line->segments;
  seg = any_seg;
  while (seg->char_count == 0)
    seg = seg->next;

  if (seg == real->segment)
    {
      /* Could probably do this case faster by hand-coding the
       * iteration.
       */

      /* We were already at the start of a line;
       * go back to the previous line.
       */
      if (gtk_text_iter_backward_line (iter))
        {
          /* Go forward to last indexable segment in line. */
          while (!at_last_indexable_segment (real))
            _gtk_text_iter_forward_indexable_segment (iter);

          check_invariants (iter);

          return TRUE;
        }
      else
        return FALSE; /* We were at the start of the first line. */
    }

  /* We must be in the middle of a line; so find the indexable
   * segment just before our current segment.
   */
  g_assert (seg != real->segment);
  do
    {
      prev_seg = seg;
      prev_any_seg = any_seg;

      any_seg = seg->next;
      seg = any_seg;
      while (seg->char_count == 0)
        seg = seg->next;
    }
  while (seg != real->segment);

  g_assert (prev_seg != NULL);
  g_assert (prev_any_seg != NULL);
  g_assert (prev_seg->char_count > 0);

  /* We skipped the entire previous segment, plus any
   * chars we were into the current segment.
   */
  if (real->segment_byte_offset >= 0)
    bytes_skipped = prev_seg->byte_count + real->segment_byte_offset;
  else
    bytes_skipped = -1;

  if (real->segment_char_offset >= 0)
    chars_skipped = prev_seg->char_count + real->segment_char_offset;
  else
    chars_skipped = -1;

  real->segment = prev_seg;
  real->any_segment = prev_any_seg;
  real->segment_byte_offset = 0;
  real->segment_char_offset = 0;

  if (bytes_skipped >= 0)
    {
      if (real->line_byte_offset >= 0)
        {
          real->line_byte_offset -= bytes_skipped;
          g_assert (real->line_byte_offset >= 0);
        }
    }
  else
    real->line_byte_offset = -1;

  if (chars_skipped >= 0)
    {
      if (real->line_char_offset >= 0)
        {
          real->line_char_offset -= chars_skipped;
          g_assert (real->line_char_offset >= 0);
        }

      if (real->cached_char_index >= 0)
        {
          real->cached_char_index -= chars_skipped;
          g_assert (real->cached_char_index >= 0);
        }
    }
  else
    {
      real->line_char_offset = -1;
      real->cached_char_index = -1;
    }

  /* line number is unchanged. */

  check_invariants (iter);

  return TRUE;
}

/**
 * gtk_text_iter_forward_char:
 * @iter: an iterator
 *
 * Moves @iter forward by one character offset. Note that images
 * embedded in the buffer occupy 1 character slot, so
 * gtk_text_iter_forward_char () may actually move onto an image instead
 * of a character, if you have images in your buffer.  If @iter is the
 * end iterator or one character before it, @iter will now point at
 * the end iterator, and gtk_text_iter_forward_char () returns %FALSE for
 * convenience when writing loops.
 *
 * Return value: whether @iter moved and is dereferenceable
 **/
gboolean
gtk_text_iter_forward_char (GtkTextIter *iter)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, FALSE);

  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return FALSE;
  else
    {
      check_invariants (iter);
      return forward_char (real);
    }
}

/**
 * gtk_text_iter_backward_char:
 * @iter: an iterator
 *
 * Moves backward by one character offset. Returns %TRUE if movement
 * was possible; if @iter was the first in the buffer (character
 * offset 0), gtk_text_iter_backward_char () returns %FALSE for convenience when
 * writing loops.
 *
 * Return value: whether movement was possible
 **/
gboolean
gtk_text_iter_backward_char (GtkTextIter *iter)
{
  g_return_val_if_fail (iter != NULL, FALSE);

  check_invariants (iter);

  return gtk_text_iter_backward_chars (iter, 1);
}

/*
  Definitely we should try to linear scan as often as possible for
  movement within a single line, because we can't use the BTree to
  speed within-line searches up; for movement between lines, we would
  like to avoid the linear scan probably.

  Instead of using this constant, it might be nice to cache the line
  length in the iterator and linear scan if motion is within a single
  line.

  I guess you'd have to profile the various approaches.
*/
#define MAX_LINEAR_SCAN 150


/**
 * gtk_text_iter_forward_chars:
 * @iter: an iterator
 * @count: number of characters to move, may be negative
 *
 * Moves @count characters if possible (if @count would move past the
 * start or end of the buffer, moves to the start or end of the
 * buffer). The return value indicates whether the new position of
 * @iter is different from its original position, and dereferenceable
 * (the last iterator in the buffer is not dereferenceable). If @count
 * is 0, the function does nothing and returns %FALSE.
 *
 * Return value: whether @iter moved and is dereferenceable
 **/
gboolean
gtk_text_iter_forward_chars (GtkTextIter *iter, gint count)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, FALSE);

  FIX_OVERFLOWS (count);
  
  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return FALSE;
  else if (count == 0)
    return FALSE;
  else if (count < 0)
    return gtk_text_iter_backward_chars (iter, 0 - count);
  else if (count < MAX_LINEAR_SCAN)
    {
      check_invariants (iter);

      while (count > 1)
        {
          if (!forward_char (real))
            return FALSE;
          --count;
        }

      return forward_char (real);
    }
  else
    {
      gint current_char_index;
      gint new_char_index;

      check_invariants (iter);

      current_char_index = gtk_text_iter_get_offset (iter);

      if (current_char_index == _gtk_text_btree_char_count (real->tree))
        return FALSE; /* can't move forward */

      new_char_index = current_char_index + count;
      gtk_text_iter_set_offset (iter, new_char_index);

      check_invariants (iter);

      /* Return FALSE if we're on the non-dereferenceable end
       * iterator.
       */
      if (gtk_text_iter_is_end (iter))
        return FALSE;
      else
        return TRUE;
    }
}

/**
 * gtk_text_iter_backward_chars:
 * @iter: an iterator
 * @count: number of characters to move
 *
 * Moves @count characters backward, if possible (if @count would move
 * past the start or end of the buffer, moves to the start or end of
 * the buffer).  The return value indicates whether the iterator moved
 * onto a dereferenceable position; if the iterator didn't move, or
 * moved onto the end iterator, then %FALSE is returned. If @count is 0,
 * the function does nothing and returns %FALSE.
 *
 * Return value: whether @iter moved and is dereferenceable
 *
 **/
gboolean
gtk_text_iter_backward_chars (GtkTextIter *iter, gint count)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, FALSE);

  FIX_OVERFLOWS (count);
  
  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return FALSE;
  else if (count == 0)
    return FALSE;
  else if (count < 0)
    return gtk_text_iter_forward_chars (iter, 0 - count);

  ensure_char_offsets (real);
  check_invariants (iter);

  /* <, not <=, because if count == segment_char_offset
   * we're going to the front of the segment and the any_segment
   * might change
   */
  if (count < real->segment_char_offset)
    {
      /* Optimize the within-segment case */
      g_assert (real->segment->char_count > 0);
      g_assert (real->segment->type == &gtk_text_char_type);

      if (real->line_byte_offset >= 0)
        {
          const char *p;
          gint new_byte_offset;

          /* if in the last fourth of the segment walk backwards */
          if (count < real->segment_char_offset / 4)
            p = g_utf8_offset_to_pointer (real->segment->body.chars + real->segment_byte_offset, 
                                          -count);
          else
            p = g_utf8_offset_to_pointer (real->segment->body.chars,
                                          real->segment_char_offset - count);

          new_byte_offset = p - real->segment->body.chars;
          real->line_byte_offset -= (real->segment_byte_offset - new_byte_offset);
          real->segment_byte_offset = new_byte_offset;
        }

      real->segment_char_offset -= count;
      real->line_char_offset -= count;

      adjust_char_index (real, 0 - count);

      check_invariants (iter);

      return TRUE;
    }
  else
    {
      /* We need to go back into previous segments. For now,
       * just keep this really simple. FIXME
       * use backward_indexable_segment.
       */
      if (TRUE || count > MAX_LINEAR_SCAN)
        {
          gint current_char_index;
          gint new_char_index;

          current_char_index = gtk_text_iter_get_offset (iter);

          if (current_char_index == 0)
            return FALSE; /* can't move backward */

          new_char_index = current_char_index - count;
          if (new_char_index < 0)
            new_char_index = 0;

          gtk_text_iter_set_offset (iter, new_char_index);

          check_invariants (iter);

          return TRUE;
        }
      else
        {
          /* FIXME backward_indexable_segment here */

          return FALSE;
        }
    }
}

#if 0

/* These two can't be implemented efficiently (always have to use
 * a linear scan, since that's the only way to find all the non-text
 * segments)
 */

/**
 * gtk_text_iter_forward_text_chars:
 * @iter: a #GtkTextIter
 * @count: number of chars to move
 *
 * Moves forward by @count text characters (pixbufs, widgets,
 * etc. do not count as characters for this). Equivalent to moving
 * through the results of gtk_text_iter_get_text (), rather than
 * gtk_text_iter_get_slice ().
 *
 * Return value: whether @iter moved and is dereferenceable
 **/
gboolean
gtk_text_iter_forward_text_chars  (GtkTextIter *iter,
                                   gint         count)
{



}

/**
 * gtk_text_iter_forward_text_chars:
 * @iter: a #GtkTextIter
 * @count: number of chars to move
 *
 * Moves backward by @count text characters (pixbufs, widgets,
 * etc. do not count as characters for this). Equivalent to moving
 * through the results of gtk_text_iter_get_text (), rather than
 * gtk_text_iter_get_slice ().
 *
 * Return value: whether @iter moved and is dereferenceable
 **/
gboolean
gtk_text_iter_backward_text_chars (GtkTextIter *iter,
                                   gint         count)
{


}
#endif

/**
 * gtk_text_iter_forward_line:
 * @iter: an iterator
 *
 * Moves @iter to the start of the next line. If the iter is already on the
 * last line of the buffer, moves the iter to the end of the current line.
 * If after the operation, the iter is at the end of the buffer and not
 * dereferencable, returns %FALSE. Otherwise, returns %TRUE.
 *
 * Return value: whether @iter can be dereferenced
 **/
gboolean
gtk_text_iter_forward_line (GtkTextIter *iter)
{
  GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, FALSE);
  
  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return FALSE;

  check_invariants (iter);

  if (forward_line_leaving_caches_unmodified (real))
    {
      invalidate_char_index (real);
      adjust_line_number (real, 1);

      check_invariants (iter);

      if (gtk_text_iter_is_end (iter))
        return FALSE;
      else
        return TRUE;
    }
  else
    {
      /* On the last line, move to end of it */
      
      if (!gtk_text_iter_is_end (iter))
        gtk_text_iter_forward_to_end (iter);
      
      check_invariants (iter);
      return FALSE;
    }
}

/**
 * gtk_text_iter_backward_line:
 * @iter: an iterator
 *
 * Moves @iter to the start of the previous line. Returns %TRUE if
 * @iter could be moved; i.e. if @iter was at character offset 0, this
 * function returns %FALSE. Therefore if @iter was already on line 0,
 * but not at the start of the line, @iter is snapped to the start of
 * the line and the function returns %TRUE. (Note that this implies that
 * in a loop calling this function, the line number may not change on
 * every iteration, if your first iteration is on line 0.)
 *
 * Return value: whether @iter moved
 **/
gboolean
gtk_text_iter_backward_line (GtkTextIter *iter)
{
  GtkTextLine *new_line;
  GtkTextRealIter *real;
  gboolean offset_will_change;
  gint offset;

  g_return_val_if_fail (iter != NULL, FALSE);

  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return FALSE;

  check_invariants (iter);

  new_line = _gtk_text_line_previous (real->line);

  offset_will_change = FALSE;
  if (real->line_char_offset > 0)
    offset_will_change = TRUE;

  if (new_line != NULL)
    {
      real->line = new_line;

      adjust_line_number (real, -1);
    }
  else
    {
      if (!offset_will_change)
        return FALSE;
    }

  invalidate_char_index (real);

  real->line_byte_offset = 0;
  real->line_char_offset = 0;

  real->segment_byte_offset = 0;
  real->segment_char_offset = 0;

  /* Find first segment in line */
  real->any_segment = real->line->segments;
  real->segment = _gtk_text_line_byte_to_segment (real->line,
                                                  0, &offset);

  g_assert (offset == 0);

  /* Note that if we are on the first line, we snap to the start of
   * the first line and return TRUE, so TRUE means the iterator
   * changed, not that the line changed; this is maybe a bit
   * weird. I'm not sure there's an obvious right thing to do though.
   */

  check_invariants (iter);

  return TRUE;
}


/**
 * gtk_text_iter_forward_lines:
 * @iter: a #GtkTextIter
 * @count: number of lines to move forward
 *
 * Moves @count lines forward, if possible (if @count would move
 * past the start or end of the buffer, moves to the start or end of
 * the buffer).  The return value indicates whether the iterator moved
 * onto a dereferenceable position; if the iterator didn't move, or
 * moved onto the end iterator, then %FALSE is returned. If @count is 0,
 * the function does nothing and returns %FALSE. If @count is negative,
 * moves backward by 0 - @count lines.
 *
 * Return value: whether @iter moved and is dereferenceable
 **/
gboolean
gtk_text_iter_forward_lines (GtkTextIter *iter, gint count)
{
  FIX_OVERFLOWS (count);
  
  if (count < 0)
    return gtk_text_iter_backward_lines (iter, 0 - count);
  else if (count == 0)
    return FALSE;
  else if (count == 1)
    {
      check_invariants (iter);
      return gtk_text_iter_forward_line (iter);
    }
  else
    {
      gint old_line;

      if (gtk_text_iter_is_end (iter))
        return FALSE;
      
      old_line = gtk_text_iter_get_line (iter);

      gtk_text_iter_set_line (iter, old_line + count);

      if ((gtk_text_iter_get_line (iter) - old_line) < count)
        {
          /* count went past the last line, so move to end of last line */
          if (!gtk_text_iter_is_end (iter))
            gtk_text_iter_forward_to_end (iter);
        }
      
      return !gtk_text_iter_is_end (iter);
    }
}

/**
 * gtk_text_iter_backward_lines:
 * @iter: a #GtkTextIter
 * @count: number of lines to move backward
 *
 * Moves @count lines backward, if possible (if @count would move
 * past the start or end of the buffer, moves to the start or end of
 * the buffer).  The return value indicates whether the iterator moved
 * onto a dereferenceable position; if the iterator didn't move, or
 * moved onto the end iterator, then %FALSE is returned. If @count is 0,
 * the function does nothing and returns %FALSE. If @count is negative,
 * moves forward by 0 - @count lines.
 *
 * Return value: whether @iter moved and is dereferenceable
 **/
gboolean
gtk_text_iter_backward_lines (GtkTextIter *iter, gint count)
{
  FIX_OVERFLOWS (count);
  
  if (count < 0)
    return gtk_text_iter_forward_lines (iter, 0 - count);
  else if (count == 0)
    return FALSE;
  else if (count == 1)
    {
      return gtk_text_iter_backward_line (iter);
    }
  else
    {
      gint old_line;

      old_line = gtk_text_iter_get_line (iter);

      gtk_text_iter_set_line (iter, MAX (old_line - count, 0));

      return (gtk_text_iter_get_line (iter) != old_line);
    }
}

/**
 * gtk_text_iter_forward_visible_line:
 * @iter: an iterator
 *
 * Moves @iter to the start of the next visible line. Returns %TRUE if there
 * was a next line to move to, and %FALSE if @iter was simply moved to
 * the end of the buffer and is now not dereferenceable, or if @iter was
 * already at the end of the buffer.
 *
 * Return value: whether @iter can be dereferenced
 * 
 * Since: 2.8
 **/
gboolean
gtk_text_iter_forward_visible_line (GtkTextIter *iter)
{
  while (gtk_text_iter_forward_line (iter))
    {
      if (!_gtk_text_btree_char_is_invisible (iter))
        return TRUE;
      else
        {
          do
            {
              if (!gtk_text_iter_forward_char (iter))
                return FALSE;
          
              if (!_gtk_text_btree_char_is_invisible (iter))
                return TRUE;
            }
          while (!gtk_text_iter_ends_line (iter));
        }
    }
    
  return FALSE;
}

/**
 * gtk_text_iter_backward_visible_line:
 * @iter: an iterator
 *
 * Moves @iter to the start of the previous visible line. Returns %TRUE if
 * @iter could be moved; i.e. if @iter was at character offset 0, this
 * function returns %FALSE. Therefore if @iter was already on line 0,
 * but not at the start of the line, @iter is snapped to the start of
 * the line and the function returns %TRUE. (Note that this implies that
 * in a loop calling this function, the line number may not change on
 * every iteration, if your first iteration is on line 0.)
 *
 * Return value: whether @iter moved
 *
 * Since: 2.8
 **/
gboolean
gtk_text_iter_backward_visible_line (GtkTextIter *iter)
{
  while (gtk_text_iter_backward_line (iter))
    {
      if (!_gtk_text_btree_char_is_invisible (iter))
        return TRUE;
      else
        {
          do
            {
              if (!gtk_text_iter_backward_char (iter))
                return FALSE;
          
              if (!_gtk_text_btree_char_is_invisible (iter))
                return TRUE;
            }
          while (!gtk_text_iter_starts_line (iter));
        }
    }
    
  return FALSE;
}

/**
 * gtk_text_iter_forward_visible_lines:
 * @iter: a #GtkTextIter
 * @count: number of lines to move forward
 *
 * Moves @count visible lines forward, if possible (if @count would move
 * past the start or end of the buffer, moves to the start or end of
 * the buffer).  The return value indicates whether the iterator moved
 * onto a dereferenceable position; if the iterator didn't move, or
 * moved onto the end iterator, then %FALSE is returned. If @count is 0,
 * the function does nothing and returns %FALSE. If @count is negative,
 * moves backward by 0 - @count lines.
 *
 * Return value: whether @iter moved and is dereferenceable
 * 
 * Since: 2.8
 **/
gboolean
gtk_text_iter_forward_visible_lines (GtkTextIter *iter,
                                     gint         count)
{
  FIX_OVERFLOWS (count);
  
  if (count < 0)
    return gtk_text_iter_backward_visible_lines (iter, 0 - count);
  else if (count == 0)
    return FALSE;
  else if (count == 1)
    {
      check_invariants (iter);
      return gtk_text_iter_forward_visible_line (iter);
    }
  else
    {
      while (gtk_text_iter_forward_visible_line (iter) && count > 0)
        count--;
      return count == 0;
    }    
}

/**
 * gtk_text_iter_backward_visible_lines:
 * @iter: a #GtkTextIter
 * @count: number of lines to move backward
 *
 * Moves @count visible lines backward, if possible (if @count would move
 * past the start or end of the buffer, moves to the start or end of
 * the buffer).  The return value indicates whether the iterator moved
 * onto a dereferenceable position; if the iterator didn't move, or
 * moved onto the end iterator, then %FALSE is returned. If @count is 0,
 * the function does nothing and returns %FALSE. If @count is negative,
 * moves forward by 0 - @count lines.
 *
 * Return value: whether @iter moved and is dereferenceable
 *
 * Since: 2.8
 **/
gboolean
gtk_text_iter_backward_visible_lines (GtkTextIter *iter,
                                      gint         count)
{
  FIX_OVERFLOWS (count);
  
  if (count < 0)
    return gtk_text_iter_forward_visible_lines (iter, 0 - count);
  else if (count == 0)
    return FALSE;
  else if (count == 1)
    {
      return gtk_text_iter_backward_visible_line (iter);
    }
  else
    {
      while (gtk_text_iter_backward_visible_line (iter) && count > 0)
        count--;
      return count == 0;
    }
}

typedef gboolean (* FindLogAttrFunc) (const PangoLogAttr *attrs,
                                      gint                offset,
                                      gint                min_offset,
                                      gint                len,
                                      gint               *found_offset,
                                      gboolean            already_moved_initially);

typedef gboolean (* TestLogAttrFunc) (const PangoLogAttr *attrs,
                                      gint                offset,
                                      gint                min_offset,
                                      gint                len);

/* Word funcs */

static gboolean
find_word_end_func (const PangoLogAttr *attrs,
                    gint          offset,
                    gint          min_offset,
                    gint          len,
                    gint         *found_offset,
                    gboolean      already_moved_initially)
{
  if (!already_moved_initially)
    ++offset;

  /* Find end of next word */
  while (offset < min_offset + len &&
         !attrs[offset].is_word_end)
    ++offset;

  *found_offset = offset;

  return offset < min_offset + len;
}

static gboolean
is_word_end_func (const PangoLogAttr *attrs,
                  gint          offset,
                  gint          min_offset,
                  gint          len)
{
  return attrs[offset].is_word_end;
}

static gboolean
find_word_start_func (const PangoLogAttr *attrs,
                      gint          offset,
                      gint          min_offset,
                      gint          len,
                      gint         *found_offset,
                      gboolean      already_moved_initially)
{
  if (!already_moved_initially)
    --offset;

  /* Find start of prev word */
  while (offset >= min_offset &&
         !attrs[offset].is_word_start)
    --offset;

  *found_offset = offset;

  return offset >= min_offset;
}

static gboolean
is_word_start_func (const PangoLogAttr *attrs,
                    gint          offset,
                    gint          min_offset,
                    gint          len)
{
  return attrs[offset].is_word_start;
}

static gboolean
inside_word_func (const PangoLogAttr *attrs,
                  gint          offset,
                  gint          min_offset,
                  gint          len)
{
  /* Find next word start or end */
  while (offset >= min_offset &&
         !(attrs[offset].is_word_start || attrs[offset].is_word_end))
    --offset;

  if (offset >= 0)
    return attrs[offset].is_word_start;
  else
    return FALSE;
}

/* Sentence funcs */

static gboolean
find_sentence_end_func (const PangoLogAttr *attrs,
                        gint          offset,
                        gint          min_offset,
                        gint          len,
                        gint         *found_offset,
                        gboolean      already_moved_initially)
{
  if (!already_moved_initially)
    ++offset;

  /* Find end of next sentence */
  while (offset < min_offset + len &&
         !attrs[offset].is_sentence_end)
    ++offset;

  *found_offset = offset;

  return offset < min_offset + len;
}

static gboolean
is_sentence_end_func (const PangoLogAttr *attrs,
                      gint          offset,
                      gint          min_offset,
                      gint          len)
{
  return attrs[offset].is_sentence_end;
}

static gboolean
find_sentence_start_func (const PangoLogAttr *attrs,
                          gint          offset,
                          gint          min_offset,
                          gint          len,
                          gint         *found_offset,
                          gboolean      already_moved_initially)
{
  if (!already_moved_initially)
    --offset;

  /* Find start of prev sentence */
  while (offset >= min_offset &&
         !attrs[offset].is_sentence_start)
    --offset;

  *found_offset = offset;

  return offset >= min_offset;
}

static gboolean
is_sentence_start_func (const PangoLogAttr *attrs,
                        gint          offset,
                        gint          min_offset,
                        gint          len)
{
  return attrs[offset].is_sentence_start;
}

static gboolean
inside_sentence_func (const PangoLogAttr *attrs,
                      gint          offset,
                      gint          min_offset,
                      gint          len)
{
  /* Find next sentence start or end */
  while (offset >= min_offset &&
         !(attrs[offset].is_sentence_start || attrs[offset].is_sentence_end))
    --offset;

  return attrs[offset].is_sentence_start;
}

static gboolean
test_log_attrs (const GtkTextIter *iter,
                TestLogAttrFunc    func)
{
  gint char_len;
  const PangoLogAttr *attrs;
  int offset;
  gboolean result = FALSE;

  g_return_val_if_fail (iter != NULL, FALSE);

  attrs = _gtk_text_buffer_get_line_log_attrs (gtk_text_iter_get_buffer (iter),
                                               iter, &char_len);

  offset = gtk_text_iter_get_line_offset (iter);

  /* char_len may be 0 and attrs will be NULL if so, if
   * iter is the end iter and the last line is empty.
   * 
   * offset may be equal to char_len, since attrs contains an entry
   * for one past the end
   */
  
  if (attrs && offset <= char_len)
    result = (* func) (attrs, offset, 0, char_len);

  return result;
}

static gboolean
find_line_log_attrs (const GtkTextIter *iter,
                     FindLogAttrFunc    func,
                     gint              *found_offset,
                     gboolean           already_moved_initially)
{
  gint char_len;
  const PangoLogAttr *attrs;
  int offset;
  gboolean result = FALSE;

  g_return_val_if_fail (iter != NULL, FALSE);
  
  attrs = _gtk_text_buffer_get_line_log_attrs (gtk_text_iter_get_buffer (iter),
                                               iter, &char_len);      

  offset = gtk_text_iter_get_line_offset (iter);
  
  /* char_len may be 0 and attrs will be NULL if so, if
   * iter is the end iter and the last line is empty
   */
  
  if (attrs)
    result = (* func) (attrs, offset, 0, char_len, found_offset,
                       already_moved_initially);

  return result;
}

/* FIXME this function is very, very gratuitously slow */
static gboolean
find_by_log_attrs (GtkTextIter    *iter,
                   FindLogAttrFunc func,
                   gboolean        forward,
                   gboolean        already_moved_initially)
{
  GtkTextIter orig;
  gint offset = 0;
  gboolean found = FALSE;

  g_return_val_if_fail (iter != NULL, FALSE);

  orig = *iter;
  
  found = find_line_log_attrs (iter, func, &offset, already_moved_initially);
  
  if (!found)
    {
      if (forward)
        {
          if (gtk_text_iter_forward_line (iter))
            return find_by_log_attrs (iter, func, forward,
                                      TRUE);
          else
            return FALSE;
        }
      else
        {                    
          /* go to end of previous line. need to check that
           * line is > 0 because backward_line snaps to start of
           * line 0 if it's on line 0
           */
          if (gtk_text_iter_get_line (iter) > 0 && 
              gtk_text_iter_backward_line (iter))
            {
              if (!gtk_text_iter_ends_line (iter))
                gtk_text_iter_forward_to_line_end (iter);
              
              return find_by_log_attrs (iter, func, forward,
                                        TRUE);
            }
          else
            return FALSE;
        }
    }
  else
    {      
      gtk_text_iter_set_line_offset (iter, offset);

      return
        (already_moved_initially || !gtk_text_iter_equal (iter, &orig)) &&
        !gtk_text_iter_is_end (iter);
    }
}

static gboolean 
find_visible_by_log_attrs (GtkTextIter    *iter,
			   FindLogAttrFunc func,
			   gboolean        forward,
			   gboolean        already_moved_initially)
{
  GtkTextIter pos;

  g_return_val_if_fail (iter != NULL, FALSE);
  
  pos = *iter;
  
  while (find_by_log_attrs (&pos, func, forward, already_moved_initially)) 
    {
      if (!_gtk_text_btree_char_is_invisible (&pos)) 
	{
	  *iter = pos;
	  return TRUE;
	}
  }

  return FALSE;
}

typedef gboolean (* OneStepFunc) (GtkTextIter *iter);
typedef gboolean (* MultipleStepFunc) (GtkTextIter *iter, gint count);
				  
static gboolean 
move_multiple_steps (GtkTextIter *iter, 
		     gint count,
		     OneStepFunc step_forward,
		     MultipleStepFunc n_steps_backward)
{
  g_return_val_if_fail (iter != NULL, FALSE);

  FIX_OVERFLOWS (count);
  
  if (count == 0)
    return FALSE;
  
  if (count < 0)
    return n_steps_backward (iter, -count);
  
  if (!step_forward (iter))
    return FALSE;
  --count;

  while (count > 0)
    {
      if (!step_forward (iter))
        break;
      --count;
    }
  
  return !gtk_text_iter_is_end (iter);  
}
	       

/**
 * gtk_text_iter_forward_word_end:
 * @iter: a #GtkTextIter
 * 
 * Moves forward to the next word end. (If @iter is currently on a
 * word end, moves forward to the next one after that.) Word breaks
 * are determined by Pango and should be correct for nearly any
 * language (if not, the correct fix would be to the Pango word break
 * algorithms).
 * 
 * Return value: %TRUE if @iter moved and is not the end iterator 
 **/
gboolean
gtk_text_iter_forward_word_end (GtkTextIter *iter)
{
  return find_by_log_attrs (iter, find_word_end_func, TRUE, FALSE);
}

/**
 * gtk_text_iter_backward_word_start:
 * @iter: a #GtkTextIter
 * 
 * Moves backward to the previous word start. (If @iter is currently on a
 * word start, moves backward to the next one after that.) Word breaks
 * are determined by Pango and should be correct for nearly any
 * language (if not, the correct fix would be to the Pango word break
 * algorithms).
 * 
 * Return value: %TRUE if @iter moved and is not the end iterator 
 **/
gboolean
gtk_text_iter_backward_word_start (GtkTextIter      *iter)
{
  return find_by_log_attrs (iter, find_word_start_func, FALSE, FALSE);
}

/* FIXME a loop around a truly slow function means
 * a truly spectacularly slow function.
 */

/**
 * gtk_text_iter_forward_word_ends:
 * @iter: a #GtkTextIter
 * @count: number of times to move
 * 
 * Calls gtk_text_iter_forward_word_end() up to @count times.
 *
 * Return value: %TRUE if @iter moved and is not the end iterator 
 **/
gboolean
gtk_text_iter_forward_word_ends (GtkTextIter      *iter,
                                 gint              count)
{
  return move_multiple_steps (iter, count, 
			      gtk_text_iter_forward_word_end,
			      gtk_text_iter_backward_word_starts);
}

/**
 * gtk_text_iter_backward_word_starts
 * @iter: a #GtkTextIter
 * @count: number of times to move
 * 
 * Calls gtk_text_iter_backward_word_start() up to @count times.
 *
 * Return value: %TRUE if @iter moved and is not the end iterator 
 **/
gboolean
gtk_text_iter_backward_word_starts (GtkTextIter      *iter,
                                    gint               count)
{
  return move_multiple_steps (iter, count, 
			      gtk_text_iter_backward_word_start,
			      gtk_text_iter_forward_word_ends);
}

/**
 * gtk_text_iter_forward_visible_word_end:
 * @iter: a #GtkTextIter
 * 
 * Moves forward to the next visible word end. (If @iter is currently on a
 * word end, moves forward to the next one after that.) Word breaks
 * are determined by Pango and should be correct for nearly any
 * language (if not, the correct fix would be to the Pango word break
 * algorithms).
 * 
 * Return value: %TRUE if @iter moved and is not the end iterator 
 *
 * Since: 2.4
 **/
gboolean
gtk_text_iter_forward_visible_word_end (GtkTextIter *iter)
{
  return find_visible_by_log_attrs (iter, find_word_end_func, TRUE, FALSE);
}

/**
 * gtk_text_iter_backward_visible_word_start:
 * @iter: a #GtkTextIter
 * 
 * Moves backward to the previous visible word start. (If @iter is currently 
 * on a word start, moves backward to the next one after that.) Word breaks
 * are determined by Pango and should be correct for nearly any
 * language (if not, the correct fix would be to the Pango word break
 * algorithms).
 * 
 * Return value: %TRUE if @iter moved and is not the end iterator 
 * 
 * Since: 2.4
 **/
gboolean
gtk_text_iter_backward_visible_word_start (GtkTextIter      *iter)
{
  return find_visible_by_log_attrs (iter, find_word_start_func, FALSE, FALSE);
}

/**
 * gtk_text_iter_forward_visible_word_ends:
 * @iter: a #GtkTextIter
 * @count: number of times to move
 * 
 * Calls gtk_text_iter_forward_visible_word_end() up to @count times.
 *
 * Return value: %TRUE if @iter moved and is not the end iterator 
 *
 * Since: 2.4
 **/
gboolean
gtk_text_iter_forward_visible_word_ends (GtkTextIter *iter,
					 gint         count)
{
  return move_multiple_steps (iter, count, 
			      gtk_text_iter_forward_visible_word_end,
			      gtk_text_iter_backward_visible_word_starts);
}

/**
 * gtk_text_iter_backward_visible_word_starts
 * @iter: a #GtkTextIter
 * @count: number of times to move
 * 
 * Calls gtk_text_iter_backward_visible_word_start() up to @count times.
 *
 * Return value: %TRUE if @iter moved and is not the end iterator 
 * 
 * Since: 2.4
 **/
gboolean
gtk_text_iter_backward_visible_word_starts (GtkTextIter *iter,
					    gint         count)
{
  return move_multiple_steps (iter, count, 
			      gtk_text_iter_backward_visible_word_start,
			      gtk_text_iter_forward_visible_word_ends);
}

/**
 * gtk_text_iter_starts_word:
 * @iter: a #GtkTextIter
 * 
 * Determines whether @iter begins a natural-language word.  Word
 * breaks are determined by Pango and should be correct for nearly any
 * language (if not, the correct fix would be to the Pango word break
 * algorithms).
 *
 * Return value: %TRUE if @iter is at the start of a word
 **/
gboolean
gtk_text_iter_starts_word (const GtkTextIter *iter)
{
  return test_log_attrs (iter, is_word_start_func);
}

/**
 * gtk_text_iter_ends_word:
 * @iter: a #GtkTextIter
 * 
 * Determines whether @iter ends a natural-language word.  Word breaks
 * are determined by Pango and should be correct for nearly any
 * language (if not, the correct fix would be to the Pango word break
 * algorithms).
 *
 * Return value: %TRUE if @iter is at the end of a word
 **/
gboolean
gtk_text_iter_ends_word (const GtkTextIter *iter)
{
  return test_log_attrs (iter, is_word_end_func);
}

/**
 * gtk_text_iter_inside_word:
 * @iter: a #GtkTextIter
 * 
 * Determines whether @iter is inside a natural-language word (as
 * opposed to say inside some whitespace).  Word breaks are determined
 * by Pango and should be correct for nearly any language (if not, the
 * correct fix would be to the Pango word break algorithms).
 * 
 * Return value: %TRUE if @iter is inside a word
 **/
gboolean
gtk_text_iter_inside_word (const GtkTextIter *iter)
{
  return test_log_attrs (iter, inside_word_func);
}

/**
 * gtk_text_iter_starts_sentence:
 * @iter: a #GtkTextIter
 * 
 * Determines whether @iter begins a sentence.  Sentence boundaries are
 * determined by Pango and should be correct for nearly any language
 * (if not, the correct fix would be to the Pango text boundary
 * algorithms).
 * 
 * Return value: %TRUE if @iter is at the start of a sentence.
 **/
gboolean
gtk_text_iter_starts_sentence (const GtkTextIter *iter)
{
  return test_log_attrs (iter, is_sentence_start_func);
}

/**
 * gtk_text_iter_ends_sentence:
 * @iter: a #GtkTextIter
 * 
 * Determines whether @iter ends a sentence.  Sentence boundaries are
 * determined by Pango and should be correct for nearly any language
 * (if not, the correct fix would be to the Pango text boundary
 * algorithms).
 * 
 * Return value: %TRUE if @iter is at the end of a sentence.
 **/
gboolean
gtk_text_iter_ends_sentence (const GtkTextIter *iter)
{
  return test_log_attrs (iter, is_sentence_end_func);
}

/**
 * gtk_text_iter_inside_sentence:
 * @iter: a #GtkTextIter
 * 
 * Determines whether @iter is inside a sentence (as opposed to in
 * between two sentences, e.g. after a period and before the first
 * letter of the next sentence).  Sentence boundaries are determined
 * by Pango and should be correct for nearly any language (if not, the
 * correct fix would be to the Pango text boundary algorithms).
 * 
 * Return value: %TRUE if @iter is inside a sentence.
 **/
gboolean
gtk_text_iter_inside_sentence (const GtkTextIter *iter)
{
  return test_log_attrs (iter, inside_sentence_func);
}

/**
 * gtk_text_iter_forward_sentence_end:
 * @iter: a #GtkTextIter
 * 
 * Moves forward to the next sentence end. (If @iter is at the end of
 * a sentence, moves to the next end of sentence.)  Sentence
 * boundaries are determined by Pango and should be correct for nearly
 * any language (if not, the correct fix would be to the Pango text
 * boundary algorithms).
 * 
 * Return value: %TRUE if @iter moved and is not the end iterator
 **/
gboolean
gtk_text_iter_forward_sentence_end (GtkTextIter *iter)
{
  return find_by_log_attrs (iter, find_sentence_end_func, TRUE, FALSE);
}

/**
 * gtk_text_iter_backward_sentence_start:
 * @iter: a #GtkTextIter
 * 
 * Moves backward to the previous sentence start; if @iter is already at
 * the start of a sentence, moves backward to the next one.  Sentence
 * boundaries are determined by Pango and should be correct for nearly
 * any language (if not, the correct fix would be to the Pango text
 * boundary algorithms).
 * 
 * Return value: %TRUE if @iter moved and is not the end iterator
 **/
gboolean
gtk_text_iter_backward_sentence_start (GtkTextIter      *iter)
{
  return find_by_log_attrs (iter, find_sentence_start_func, FALSE, FALSE);
}

/* FIXME a loop around a truly slow function means
 * a truly spectacularly slow function.
 */
/**
 * gtk_text_iter_forward_sentence_ends:
 * @iter: a #GtkTextIter
 * @count: number of sentences to move
 * 
 * Calls gtk_text_iter_forward_sentence_end() @count times (or until
 * gtk_text_iter_forward_sentence_end() returns %FALSE). If @count is
 * negative, moves backward instead of forward.
 * 
 * Return value: %TRUE if @iter moved and is not the end iterator
 **/
gboolean
gtk_text_iter_forward_sentence_ends (GtkTextIter      *iter,
                                     gint              count)
{
  return move_multiple_steps (iter, count, 
			      gtk_text_iter_forward_sentence_end,
			      gtk_text_iter_backward_sentence_starts);
}

/**
 * gtk_text_iter_backward_sentence_starts:
 * @iter: a #GtkTextIter
 * @count: number of sentences to move
 * 
 * Calls gtk_text_iter_backward_sentence_start() up to @count times,
 * or until it returns %FALSE. If @count is negative, moves forward
 * instead of backward.
 * 
 * Return value: %TRUE if @iter moved and is not the end iterator
 **/
gboolean
gtk_text_iter_backward_sentence_starts (GtkTextIter      *iter,
                                        gint               count)
{
  return move_multiple_steps (iter, count, 
			      gtk_text_iter_backward_sentence_start,
			      gtk_text_iter_forward_sentence_ends);
}

static gboolean
find_forward_cursor_pos_func (const PangoLogAttr *attrs,
                              gint          offset,
                              gint          min_offset,
                              gint          len,
                              gint         *found_offset,
                              gboolean      already_moved_initially)
{
  if (!already_moved_initially)
    ++offset;

  while (offset < (min_offset + len) &&
         !attrs[offset].is_cursor_position)
    ++offset;

  *found_offset = offset;

  return offset < (min_offset + len);
}

static gboolean
find_backward_cursor_pos_func (const PangoLogAttr *attrs,
                               gint          offset,
                               gint          min_offset,
                               gint          len,
                               gint         *found_offset,
                               gboolean      already_moved_initially)
{  
  if (!already_moved_initially)
    --offset;

  while (offset > min_offset &&
         !attrs[offset].is_cursor_position)
    --offset;

  *found_offset = offset;
  
  return offset >= min_offset;
}

static gboolean
is_cursor_pos_func (const PangoLogAttr *attrs,
                    gint          offset,
                    gint          min_offset,
                    gint          len)
{
  return attrs[offset].is_cursor_position;
}

/**
 * gtk_text_iter_forward_cursor_position:
 * @iter: a #GtkTextIter
 * 
 * Moves @iter forward by a single cursor position. Cursor positions
 * are (unsurprisingly) positions where the cursor can appear. Perhaps
 * surprisingly, there may not be a cursor position between all
 * characters. The most common example for European languages would be
 * a carriage return/newline sequence. For some Unicode characters,
 * the equivalent of say the letter "a" with an accent mark will be
 * represented as two characters, first the letter then a "combining
 * mark" that causes the accent to be rendered; so the cursor can't go
 * between those two characters. See also the #PangoLogAttr structure and
 * pango_break() function.
 * 
 * Return value: %TRUE if we moved and the new position is dereferenceable
 **/
gboolean
gtk_text_iter_forward_cursor_position (GtkTextIter *iter)
{
  return find_by_log_attrs (iter, find_forward_cursor_pos_func, TRUE, FALSE);
}

/**
 * gtk_text_iter_backward_cursor_position:
 * @iter: a #GtkTextIter
 * 
 * Like gtk_text_iter_forward_cursor_position(), but moves backward.
 * 
 * Return value: %TRUE if we moved
 **/
gboolean
gtk_text_iter_backward_cursor_position (GtkTextIter *iter)
{
  return find_by_log_attrs (iter, find_backward_cursor_pos_func, FALSE, FALSE);
}

/**
 * gtk_text_iter_forward_cursor_positions:
 * @iter: a #GtkTextIter
 * @count: number of positions to move
 * 
 * Moves up to @count cursor positions. See
 * gtk_text_iter_forward_cursor_position() for details.
 * 
 * Return value: %TRUE if we moved and the new position is dereferenceable
 **/
gboolean
gtk_text_iter_forward_cursor_positions (GtkTextIter *iter,
                                        gint         count)
{
  return move_multiple_steps (iter, count, 
			      gtk_text_iter_forward_cursor_position,
			      gtk_text_iter_backward_cursor_positions);
}

/**
 * gtk_text_iter_backward_cursor_positions:
 * @iter: a #GtkTextIter
 * @count: number of positions to move
 *
 * Moves up to @count cursor positions. See
 * gtk_text_iter_forward_cursor_position() for details.
 * 
 * Return value: %TRUE if we moved and the new position is dereferenceable
 **/
gboolean
gtk_text_iter_backward_cursor_positions (GtkTextIter *iter,
                                         gint         count)
{
  return move_multiple_steps (iter, count, 
			      gtk_text_iter_backward_cursor_position,
			      gtk_text_iter_forward_cursor_positions);
}

/**
 * gtk_text_iter_forward_visible_cursor_position:
 * @iter: a #GtkTextIter
 * 
 * Moves @iter forward to the next visible cursor position. See 
 * gtk_text_iter_forward_cursor_position() for details.
 * 
 * Return value: %TRUE if we moved and the new position is dereferenceable
 * 
 * Since: 2.4
 **/
gboolean
gtk_text_iter_forward_visible_cursor_position (GtkTextIter *iter)
{
  return find_visible_by_log_attrs (iter, find_forward_cursor_pos_func, TRUE, FALSE);
}

/**
 * gtk_text_iter_backward_visible_cursor_position:
 * @iter: a #GtkTextIter
 * 
 * Moves @iter forward to the previous visible cursor position. See 
 * gtk_text_iter_backward_cursor_position() for details.
 * 
 * Return value: %TRUE if we moved and the new position is dereferenceable
 * 
 * Since: 2.4
 **/
gboolean
gtk_text_iter_backward_visible_cursor_position (GtkTextIter *iter)
{
  return find_visible_by_log_attrs (iter, find_backward_cursor_pos_func, FALSE, FALSE);
}

/**
 * gtk_text_iter_forward_visible_cursor_positions:
 * @iter: a #GtkTextIter
 * @count: number of positions to move
 * 
 * Moves up to @count visible cursor positions. See
 * gtk_text_iter_forward_cursor_position() for details.
 * 
 * Return value: %TRUE if we moved and the new position is dereferenceable
 * 
 * Since: 2.4
 **/
gboolean
gtk_text_iter_forward_visible_cursor_positions (GtkTextIter *iter,
						gint         count)
{
  return move_multiple_steps (iter, count, 
			      gtk_text_iter_forward_visible_cursor_position,
			      gtk_text_iter_backward_visible_cursor_positions);
}

/**
 * gtk_text_iter_backward_visible_cursor_positions:
 * @iter: a #GtkTextIter
 * @count: number of positions to move
 *
 * Moves up to @count visible cursor positions. See
 * gtk_text_iter_backward_cursor_position() for details.
 * 
 * Return value: %TRUE if we moved and the new position is dereferenceable
 * 
 * Since: 2.4
 **/
gboolean
gtk_text_iter_backward_visible_cursor_positions (GtkTextIter *iter,
						 gint         count)
{
  return move_multiple_steps (iter, count, 
			      gtk_text_iter_backward_visible_cursor_position,
			      gtk_text_iter_forward_visible_cursor_positions);
}

/**
 * gtk_text_iter_is_cursor_position:
 * @iter: a #GtkTextIter
 * 
 * See gtk_text_iter_forward_cursor_position() or #PangoLogAttr or
 * pango_break() for details on what a cursor position is.
 * 
 * Return value: %TRUE if the cursor can be placed at @iter
 **/
gboolean
gtk_text_iter_is_cursor_position (const GtkTextIter *iter)
{
  return test_log_attrs (iter, is_cursor_pos_func);
}

/**
 * gtk_text_iter_set_line_offset:
 * @iter: a #GtkTextIter 
 * @char_on_line: a character offset relative to the start of @iter's current line
 * 
 * Moves @iter within a line, to a new <emphasis>character</emphasis>
 * (not byte) offset. The given character offset must be less than or
 * equal to the number of characters in the line; if equal, @iter
 * moves to the start of the next line. See
 * gtk_text_iter_set_line_index() if you have a byte index rather than
 * a character offset.
 *
 **/
void
gtk_text_iter_set_line_offset (GtkTextIter *iter,
                               gint         char_on_line)
{
  GtkTextRealIter *real;
  gint chars_in_line;
  
  g_return_if_fail (iter != NULL);

  real = gtk_text_iter_make_surreal (iter);

  if (real == NULL)
    return;
  
  check_invariants (iter);

  chars_in_line = gtk_text_iter_get_chars_in_line (iter);

  g_return_if_fail (char_on_line <= chars_in_line);

  if (char_on_line < chars_in_line)
    iter_set_from_char_offset (real, real->line, char_on_line);
  else
    gtk_text_iter_forward_line (iter); /* set to start of next line */
  
  check_invariants (iter);
}

/**
 * gtk_text_iter_set_line_index:
 * @iter: a #GtkTextIter
 * @byte_on_line: a byte index relative to the start of @iter's current line
 *
 * Same as gtk_text_iter_set_line_offset(), but works with a
 * <emphasis>byte</emphasis> index. The given byte index must be at
 * the start of a character, it can't be in the middle of a UTF-8
 * encoded character.
 * 
 **/
void
gtk_text_iter_set_line_index (GtkTextIter *iter,
                              gint         byte_on_line)
{
  GtkTextRealIter *real;
  gint bytes_in_line;
  
  g_return_if_fail (iter != NULL);

  real = gtk_text_iter_make_surreal (iter);

  if (real == NULL)
    return;

  check_invariants (iter);

  bytes_in_line = gtk_text_iter_get_bytes_in_line (iter);

  g_return_if_fail (byte_on_line <= bytes_in_line);
  
  if (byte_on_line < bytes_in_line)
    iter_set_from_byte_offset (real, real->line, byte_on_line);
  else
    gtk_text_iter_forward_line (iter);

  if (real->segment->type == &gtk_text_char_type &&
      (real->segment->body.chars[real->segment_byte_offset] & 0xc0) == 0x80)
    g_warning ("%s: Incorrect byte offset %d falls in the middle of a UTF-8 "
               "character; this will crash the text buffer. "
               "Byte indexes must refer to the start of a character.",
               G_STRLOC, byte_on_line);

  check_invariants (iter);
}


/**
 * gtk_text_iter_set_visible_line_offset:
 * @iter: a #GtkTextIter
 * @char_on_line: a character offset
 * 
 * Like gtk_text_iter_set_line_offset(), but the offset is in visible
 * characters, i.e. text with a tag making it invisible is not
 * counted in the offset.
 **/
void
gtk_text_iter_set_visible_line_offset (GtkTextIter *iter,
                                       gint         char_on_line)
{
  gint chars_seen = 0;
  GtkTextIter pos;

  g_return_if_fail (iter != NULL);
  
  gtk_text_iter_set_line_offset (iter, 0);

  pos = *iter;

  /* For now we use a ludicrously slow implementation */
  while (chars_seen < char_on_line)
    {
      if (!_gtk_text_btree_char_is_invisible (&pos))
        ++chars_seen;

      if (!gtk_text_iter_forward_char (&pos))
        break;

      if (chars_seen == char_on_line)
        break;
    }
  
  if (_gtk_text_iter_get_text_line (&pos) == _gtk_text_iter_get_text_line (iter))
    *iter = pos;
  else
    gtk_text_iter_forward_line (iter);
}

/**
 * gtk_text_iter_set_visible_line_index:
 * @iter: a #GtkTextIter
 * @byte_on_line: a byte index
 * 
 * Like gtk_text_iter_set_line_index(), but the index is in visible
 * bytes, i.e. text with a tag making it invisible is not counted
 * in the index.
 **/
void
gtk_text_iter_set_visible_line_index (GtkTextIter *iter,
                                      gint         byte_on_line)
{
  GtkTextRealIter *real;
  gint offset = 0;
  GtkTextIter pos;
  GtkTextLineSegment *seg;
  
  g_return_if_fail (iter != NULL);

  gtk_text_iter_set_line_offset (iter, 0);

  pos = *iter;

  real = gtk_text_iter_make_real (&pos);

  if (real == NULL)
    return;

  ensure_byte_offsets (real);

  check_invariants (&pos);

  seg = _gtk_text_iter_get_indexable_segment (&pos);

  while (seg != NULL && byte_on_line > 0)
    {
      if (!_gtk_text_btree_char_is_invisible (&pos))
        {
          if (byte_on_line < seg->byte_count)
            {
              iter_set_from_byte_offset (real, real->line, offset + byte_on_line);
              byte_on_line = 0;
              break;
            }
          else
            byte_on_line -= seg->byte_count;
        }

      offset += seg->byte_count;
      _gtk_text_iter_forward_indexable_segment (&pos);
      seg = _gtk_text_iter_get_indexable_segment (&pos);
    }

  if (byte_on_line == 0)
    *iter = pos;
  else
    gtk_text_iter_forward_line (iter);
}

/**
 * gtk_text_iter_set_line:
 * @iter: a #GtkTextIter
 * @line_number: line number (counted from 0)
 *
 * Moves iterator @iter to the start of the line @line_number.  If
 * @line_number is negative or larger than the number of lines in the
 * buffer, moves @iter to the start of the last line in the buffer.
 * 
 **/
void
gtk_text_iter_set_line (GtkTextIter *iter,
                        gint         line_number)
{
  GtkTextLine *line;
  gint real_line;
  GtkTextRealIter *real;

  g_return_if_fail (iter != NULL);

  real = gtk_text_iter_make_surreal (iter);

  if (real == NULL)
    return;

  check_invariants (iter);

  line = _gtk_text_btree_get_line_no_last (real->tree, line_number, &real_line);

  iter_set_from_char_offset (real, line, 0);

  /* We might as well cache this, since we know it. */
  real->cached_line_number = real_line;

  check_invariants (iter);
}

/**
 * gtk_text_iter_set_offset:
 * @iter: a #GtkTextIter
 * @char_offset: a character number
 *
 * Sets @iter to point to @char_offset. @char_offset counts from the start
 * of the entire text buffer, starting with 0.
 **/
void
gtk_text_iter_set_offset (GtkTextIter *iter,
                          gint         char_offset)
{
  GtkTextLine *line;
  GtkTextRealIter *real;
  gint line_start;
  gint real_char_index;

  g_return_if_fail (iter != NULL);

  real = gtk_text_iter_make_surreal (iter);

  if (real == NULL)
    return;

  check_invariants (iter);

  if (real->cached_char_index >= 0 &&
      real->cached_char_index == char_offset)
    return;

  line = _gtk_text_btree_get_line_at_char (real->tree,
                                           char_offset,
                                           &line_start,
                                           &real_char_index);

  iter_set_from_char_offset (real, line, real_char_index - line_start);

  /* Go ahead and cache this since we have it. */
  real->cached_char_index = real_char_index;

  check_invariants (iter);
}

/**
 * gtk_text_iter_forward_to_end:
 * @iter: a #GtkTextIter
 *
 * Moves @iter forward to the "end iterator," which points one past the last
 * valid character in the buffer. gtk_text_iter_get_char() called on the
 * end iterator returns 0, which is convenient for writing loops.
 **/
void
gtk_text_iter_forward_to_end  (GtkTextIter *iter)
{
  GtkTextBuffer *buffer;
  GtkTextRealIter *real;

  g_return_if_fail (iter != NULL);

  real = gtk_text_iter_make_surreal (iter);

  if (real == NULL)
    return;

  buffer = _gtk_text_btree_get_buffer (real->tree);

  gtk_text_buffer_get_end_iter (buffer, iter);
}

/* FIXME this and gtk_text_iter_forward_to_line_end() could be cleaned up
 * and made faster. Look at iter_ends_line() for inspiration, perhaps.
 * If all else fails we could cache the para delimiter pos in the iter.
 * I think forward_to_line_end() actually gets called fairly often.
 */
static int
find_paragraph_delimiter_for_line (GtkTextIter *iter)
{
  GtkTextIter end;
  end = *iter;

  if (_gtk_text_line_contains_end_iter (_gtk_text_iter_get_text_line (&end),
                                        _gtk_text_iter_get_btree (&end)))
    {
      gtk_text_iter_forward_to_end (&end);
    }
  else
    {
      /* if we aren't on the last line, go forward to start of next line, then scan
       * back for the delimiters on the previous line
       */
      gtk_text_iter_forward_line (&end);
      gtk_text_iter_backward_char (&end);
      while (!gtk_text_iter_ends_line (&end))
        gtk_text_iter_backward_char (&end);
    }

  return gtk_text_iter_get_line_offset (&end);
}

/**
 * gtk_text_iter_forward_to_line_end:
 * @iter: a #GtkTextIter
 * 
 * Moves the iterator to point to the paragraph delimiter characters,
 * which will be either a newline, a carriage return, a carriage
 * return/newline in sequence, or the Unicode paragraph separator
 * character. If the iterator is already at the paragraph delimiter
 * characters, moves to the paragraph delimiter characters for the
 * next line. If @iter is on the last line in the buffer, which does
 * not end in paragraph delimiters, moves to the end iterator (end of
 * the last line), and returns %FALSE.
 * 
 * Return value: %TRUE if we moved and the new location is not the end iterator
 **/
gboolean
gtk_text_iter_forward_to_line_end (GtkTextIter *iter)
{
  gint current_offset;
  gint new_offset;

  
  g_return_val_if_fail (iter != NULL, FALSE);

  current_offset = gtk_text_iter_get_line_offset (iter);
  new_offset = find_paragraph_delimiter_for_line (iter);
  
  if (current_offset < new_offset)
    {
      /* Move to end of this line. */
      gtk_text_iter_set_line_offset (iter, new_offset);
      return !gtk_text_iter_is_end (iter);
    }
  else
    {
      /* Move to end of next line. */
      if (gtk_text_iter_forward_line (iter))
        {
          /* We don't want to move past all
           * empty lines.
           */
          if (!gtk_text_iter_ends_line (iter))
            gtk_text_iter_forward_to_line_end (iter);
          return !gtk_text_iter_is_end (iter);
        }
      else
        return FALSE;
    }
}

/**
 * gtk_text_iter_forward_to_tag_toggle:
 * @iter: a #GtkTextIter
 * @tag: (allow-none): a #GtkTextTag, or %NULL
 *
 * Moves forward to the next toggle (on or off) of the
 * #GtkTextTag @tag, or to the next toggle of any tag if
 * @tag is %NULL. If no matching tag toggles are found,
 * returns %FALSE, otherwise %TRUE. Does not return toggles
 * located at @iter, only toggles after @iter. Sets @iter to
 * the location of the toggle, or to the end of the buffer
 * if no toggle is found.
 *
 * Return value: whether we found a tag toggle after @iter
 **/
gboolean
gtk_text_iter_forward_to_tag_toggle (GtkTextIter *iter,
                                     GtkTextTag  *tag)
{
  GtkTextLine *next_line;
  GtkTextLine *current_line;
  GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, FALSE);

  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return FALSE;

  check_invariants (iter);

  current_line = real->line;
  next_line = _gtk_text_line_next_could_contain_tag (current_line,
                                                     real->tree, tag);

  while (_gtk_text_iter_forward_indexable_segment (iter))
    {
      /* If we went forward to a line that couldn't contain a toggle
         for the tag, then skip forward to a line that could contain
         it. This potentially skips huge hunks of the tree, so we
         aren't a purely linear search. */
      if (real->line != current_line)
        {
          if (next_line == NULL)
            {
              /* End of search. Set to end of buffer. */
              _gtk_text_btree_get_end_iter (real->tree, iter);
              return FALSE;
            }

          if (real->line != next_line)
            iter_set_from_byte_offset (real, next_line, 0);

          current_line = real->line;
          next_line = _gtk_text_line_next_could_contain_tag (current_line,
                                                             real->tree,
                                                             tag);
        }

      if (gtk_text_iter_toggles_tag (iter, tag))
        {
          /* If there's a toggle here, it isn't indexable so
             any_segment can't be the indexable segment. */
          g_assert (real->any_segment != real->segment);
          return TRUE;
        }
    }

  /* Check end iterator for tags */
  if (gtk_text_iter_toggles_tag (iter, tag))
    {
      /* If there's a toggle here, it isn't indexable so
         any_segment can't be the indexable segment. */
      g_assert (real->any_segment != real->segment);
      return TRUE;
    }

  /* Reached end of buffer */
  return FALSE;
}

/**
 * gtk_text_iter_backward_to_tag_toggle:
 * @iter: a #GtkTextIter
 * @tag: (allow-none): a #GtkTextTag, or %NULL
 *
 * Moves backward to the next toggle (on or off) of the
 * #GtkTextTag @tag, or to the next toggle of any tag if
 * @tag is %NULL. If no matching tag toggles are found,
 * returns %FALSE, otherwise %TRUE. Does not return toggles
 * located at @iter, only toggles before @iter. Sets @iter
 * to the location of the toggle, or the start of the buffer
 * if no toggle is found.
 *
 * Return value: whether we found a tag toggle before @iter
 **/
gboolean
gtk_text_iter_backward_to_tag_toggle (GtkTextIter *iter,
                                      GtkTextTag  *tag)
{
  GtkTextLine *prev_line;
  GtkTextLine *current_line;
  GtkTextRealIter *real;

  g_return_val_if_fail (iter != NULL, FALSE);

  real = gtk_text_iter_make_real (iter);

  if (real == NULL)
    return FALSE;

  check_invariants (iter);

  current_line = real->line;
  prev_line = _gtk_text_line_previous_could_contain_tag (current_line,
                                                        real->tree, tag);


  /* If we're at segment start, go to the previous segment;
   * if mid-segment, snap to start of current segment.
   */
  if (is_segment_start (real))
    {
      if (!_gtk_text_iter_backward_indexable_segment (iter))
        return FALSE;
    }
  else
    {
      ensure_char_offsets (real);

      if (!gtk_text_iter_backward_chars (iter, real->segment_char_offset))
        return FALSE;
    }

  do
    {
      /* If we went backward to a line that couldn't contain a toggle
       * for the tag, then skip backward further to a line that
       * could contain it. This potentially skips huge hunks of the
       * tree, so we aren't a purely linear search.
       */
      if (real->line != current_line)
        {
          if (prev_line == NULL)
            {
              /* End of search. Set to start of buffer. */
              _gtk_text_btree_get_iter_at_char (real->tree, iter, 0);
              return FALSE;
            }

          if (real->line != prev_line)
            {
              /* Set to last segment in prev_line (could do this
               * more quickly)
               */
              iter_set_from_byte_offset (real, prev_line, 0);

              while (!at_last_indexable_segment (real))
                _gtk_text_iter_forward_indexable_segment (iter);
            }

          current_line = real->line;
          prev_line = _gtk_text_line_previous_could_contain_tag (current_line,
                                                                real->tree,
                                                                tag);
        }

      if (gtk_text_iter_toggles_tag (iter, tag))
        {
          /* If there's a toggle here, it isn't indexable so
           * any_segment can't be the indexable segment.
           */
          g_assert (real->any_segment != real->segment);
          return TRUE;
        }
    }
  while (_gtk_text_iter_backward_indexable_segment (iter));

  /* Reached front of buffer */
  return FALSE;
}

static gboolean
matches_pred (GtkTextIter *iter,
              GtkTextCharPredicate pred,
              gpointer user_data)
{
  gint ch;

  ch = gtk_text_iter_get_char (iter);

  return (*pred) (ch, user_data);
}

/**
 * gtk_text_iter_forward_find_char:
 * @iter: a #GtkTextIter
 * @pred: a function to be called on each character
 * @user_data: user data for @pred
 * @limit: (allow-none): search limit, or %NULL for none 
 * 
 * Advances @iter, calling @pred on each character. If
 * @pred returns %TRUE, returns %TRUE and stops scanning.
 * If @pred never returns %TRUE, @iter is set to @limit if
 * @limit is non-%NULL, otherwise to the end iterator.
 * 
 * Return value: whether a match was found
 **/
gboolean
gtk_text_iter_forward_find_char (GtkTextIter         *iter,
                                 GtkTextCharPredicate pred,
                                 gpointer             user_data,
                                 const GtkTextIter   *limit)
{
  g_return_val_if_fail (iter != NULL, FALSE);
  g_return_val_if_fail (pred != NULL, FALSE);

  if (limit &&
      gtk_text_iter_compare (iter, limit) >= 0)
    return FALSE;
  
  while ((limit == NULL ||
          !gtk_text_iter_equal (limit, iter)) &&
         gtk_text_iter_forward_char (iter))
    {      
      if (matches_pred (iter, pred, user_data))
        return TRUE;
    }

  return FALSE;
}

/**
 * gtk_text_iter_backward_find_char:
 * @iter: a #GtkTextIter
 * @pred: function to be called on each character
 * @user_data: user data for @pred
 * @limit: (allow-none): search limit, or %NULL for none
 * 
 * Same as gtk_text_iter_forward_find_char(), but goes backward from @iter.
 * 
 * Return value: whether a match was found
 **/
gboolean
gtk_text_iter_backward_find_char (GtkTextIter         *iter,
                                  GtkTextCharPredicate pred,
                                  gpointer             user_data,
                                  const GtkTextIter   *limit)
{
  g_return_val_if_fail (iter != NULL, FALSE);
  g_return_val_if_fail (pred != NULL, FALSE);

  if (limit &&
      gtk_text_iter_compare (iter, limit) <= 0)
    return FALSE;
  
  while ((limit == NULL ||
          !gtk_text_iter_equal (limit, iter)) &&
         gtk_text_iter_backward_char (iter))
    {
      if (matches_pred (iter, pred, user_data))
        return TRUE;
    }

  return FALSE;
}

static void
forward_chars_with_skipping (GtkTextIter *iter,
                             gint         count,
                             gboolean     skip_invisible,
                             gboolean     skip_nontext)
{

  gint i;

  g_return_if_fail (count >= 0);

  i = count;

  while (i > 0)
    {
      gboolean ignored = FALSE;

      if (skip_nontext &&
          gtk_text_iter_get_char (iter) == GTK_TEXT_UNKNOWN_CHAR)
        ignored = TRUE;

      if (!ignored &&
          skip_invisible &&
          _gtk_text_btree_char_is_invisible (iter))
        ignored = TRUE;

      gtk_text_iter_forward_char (iter);

      if (!ignored)
        --i;
    }
}

static gboolean
lines_match (const GtkTextIter *start,
             const gchar **lines,
             gboolean visible_only,
             gboolean slice,
             GtkTextIter *match_start,
             GtkTextIter *match_end)
{
  GtkTextIter next;
  gchar *line_text;
  const gchar *found;
  gint offset;

  if (*lines == NULL || **lines == '\0')
    {
      if (match_start)
        *match_start = *start;

      if (match_end)
        *match_end = *start;
      return TRUE;
    }

  next = *start;
  gtk_text_iter_forward_line (&next);

  /* No more text in buffer, but *lines is nonempty */
  if (gtk_text_iter_equal (start, &next))
    {
      return FALSE;
    }

  if (slice)
    {
      if (visible_only)
        line_text = gtk_text_iter_get_visible_slice (start, &next);
      else
        line_text = gtk_text_iter_get_slice (start, &next);
    }
  else
    {
      if (visible_only)
        line_text = gtk_text_iter_get_visible_text (start, &next);
      else
        line_text = gtk_text_iter_get_text (start, &next);
    }

  if (match_start) /* if this is the first line we're matching */
    found = strstr (line_text, *lines);
  else
    {
      /* If it's not the first line, we have to match from the
       * start of the line.
       */
      if (strncmp (line_text, *lines, strlen (*lines)) == 0)
        found = line_text;
      else
        found = NULL;
    }

  if (found == NULL)
    {
      g_free (line_text);
      return FALSE;
    }

  /* Get offset to start of search string */
  offset = g_utf8_strlen (line_text, found - line_text);

  next = *start;

  /* If match start needs to be returned, set it to the
   * start of the search string.
   */
  if (match_start)
    {
      *match_start = next;

      forward_chars_with_skipping (match_start, offset,
                                   visible_only, !slice);
    }

  /* Go to end of search string */
  offset += g_utf8_strlen (*lines, -1);

  forward_chars_with_skipping (&next, offset,
                               visible_only, !slice);

  g_free (line_text);

  ++lines;

  if (match_end)
    *match_end = next;

  /* pass NULL for match_start, since we don't need to find the
   * start again.
   */
  return lines_match (&next, lines, visible_only, slice, NULL, match_end);
}

/* strsplit () that retains the delimiter as part of the string. */
static gchar **
strbreakup (const char *string,
            const char *delimiter,
            gint        max_tokens)
{
  GSList *string_list = NULL, *slist;
  gchar **str_array, *s;
  guint i, n = 1;

  g_return_val_if_fail (string != NULL, NULL);
  g_return_val_if_fail (delimiter != NULL, NULL);

  if (max_tokens < 1)
    max_tokens = G_MAXINT;

  s = strstr (string, delimiter);
  if (s)
    {
      guint delimiter_len = strlen (delimiter);

      do
        {
          guint len;
          gchar *new_string;

          len = s - string + delimiter_len;
          new_string = g_new (gchar, len + 1);
          strncpy (new_string, string, len);
          new_string[len] = 0;
          string_list = g_slist_prepend (string_list, new_string);
          n++;
          string = s + delimiter_len;
          s = strstr (string, delimiter);
        }
      while (--max_tokens && s);
    }
  if (*string)
    {
      n++;
      string_list = g_slist_prepend (string_list, g_strdup (string));
    }

  str_array = g_new (gchar*, n);

  i = n - 1;

  str_array[i--] = NULL;
  for (slist = string_list; slist; slist = slist->next)
    str_array[i--] = slist->data;

  g_slist_free (string_list);

  return str_array;
}

/**
 * gtk_text_iter_forward_search:
 * @iter: start of search
 * @str: a search string
 * @flags: flags affecting how the search is done
 * @match_start: (allow-none): return location for start of match, or %NULL
 * @match_end: (allow-none): return location for end of match, or %NULL
 * @limit: (allow-none): bound for the search, or %NULL for the end of the buffer
 *
 * Searches forward for @str. Any match is returned by setting
 * @match_start to the first character of the match and @match_end to the
 * first character after the match. The search will not continue past
 * @limit. Note that a search is a linear or O(n) operation, so you
 * may wish to use @limit to avoid locking up your UI on large
 * buffers.
 * 
 * If the #GTK_TEXT_SEARCH_VISIBLE_ONLY flag is present, the match may
 * have invisible text interspersed in @str. i.e. @str will be a
 * possibly-noncontiguous subsequence of the matched range. similarly,
 * if you specify #GTK_TEXT_SEARCH_TEXT_ONLY, the match may have
 * pixbufs or child widgets mixed inside the matched range. If these
 * flags are not given, the match must be exact; the special 0xFFFC
 * character in @str will match embedded pixbufs or child widgets.
 *
 * Return value: whether a match was found
 **/
gboolean
gtk_text_iter_forward_search (const GtkTextIter *iter,
                              const gchar       *str,
                              GtkTextSearchFlags flags,
                              GtkTextIter       *match_start,
                              GtkTextIter       *match_end,
                              const GtkTextIter *limit)
{
  gchar **lines = NULL;
  GtkTextIter match;
  gboolean retval = FALSE;
  GtkTextIter search;
  gboolean visible_only;
  gboolean slice;
  
  g_return_val_if_fail (iter != NULL, FALSE);
  g_return_val_if_fail (str != NULL, FALSE);

  if (limit &&
      gtk_text_iter_compare (iter, limit) >= 0)
    return FALSE;
  
  if (*str == '\0')
    {
      /* If we can move one char, return the empty string there */
      match = *iter;
      
      if (gtk_text_iter_forward_char (&match))
        {
          if (limit &&
              gtk_text_iter_equal (&match, limit))
            return FALSE;
          
          if (match_start)
            *match_start = match;
          if (match_end)
            *match_end = match;
          return TRUE;
        }
      else
        return FALSE;
    }

  visible_only = (flags & GTK_TEXT_SEARCH_VISIBLE_ONLY) != 0;
  slice = (flags & GTK_TEXT_SEARCH_TEXT_ONLY) == 0;
  
  /* locate all lines */

  lines = strbreakup (str, "\n", -1);

  search = *iter;

  do
    {
      /* This loop has an inefficient worst-case, where
       * gtk_text_iter_get_text () is called repeatedly on
       * a single line.
       */
      GtkTextIter end;

      if (limit &&
          gtk_text_iter_compare (&search, limit) >= 0)
        break;
      
      if (lines_match (&search, (const gchar**)lines,
                       visible_only, slice, &match, &end))
        {
          if (limit == NULL ||
              (limit &&
               gtk_text_iter_compare (&end, limit) <= 0))
            {
              retval = TRUE;
              
              if (match_start)
                *match_start = match;
              
              if (match_end)
                *match_end = end;
            }
          
          break;
        }
    }
  while (gtk_text_iter_forward_line (&search));

  g_strfreev ((gchar**)lines);

  return retval;
}

static gboolean
vectors_equal_ignoring_trailing (gchar **vec1,
                                 gchar **vec2)
{
  /* Ignores trailing chars in vec2's last line */

  gchar **i1, **i2;

  i1 = vec1;
  i2 = vec2;

  while (*i1 && *i2)
    {
      if (strcmp (*i1, *i2) != 0)
        {
          if (*(i2 + 1) == NULL) /* if this is the last line */
            {
              gint len1 = strlen (*i1);
              gint len2 = strlen (*i2);

              if (len2 >= len1 &&
                  strncmp (*i1, *i2, len1) == 0)
                {
                  /* We matched ignoring the trailing stuff in vec2 */
                  return TRUE;
                }
              else
                {
                  return FALSE;
                }
            }
          else
            {
              return FALSE;
            }
        }
      ++i1;
      ++i2;
    }

  if (*i1 || *i2)
    {
      return FALSE;
    }
  else
    return TRUE;
}

typedef struct _LinesWindow LinesWindow;

struct _LinesWindow
{
  gint n_lines;
  gchar **lines;
  GtkTextIter first_line_start;
  GtkTextIter first_line_end;
  gboolean slice;
  gboolean visible_only;
};

static void
lines_window_init (LinesWindow       *win,
                   const GtkTextIter *start)
{
  gint i;
  GtkTextIter line_start;
  GtkTextIter line_end;

  /* If we start on line 1, there are 2 lines to search (0 and 1), so
   * n_lines can be 2.
   */
  if (gtk_text_iter_is_start (start) ||
      gtk_text_iter_get_line (start) + 1 < win->n_lines)
    {
      /* Already at the end, or not enough lines to match */
      win->lines = g_new0 (gchar*, 1);
      *win->lines = NULL;
      return;
    }

  line_start = *start;
  line_end = *start;

  /* Move to start iter to start of line */
  gtk_text_iter_set_line_offset (&line_start, 0);

  if (gtk_text_iter_equal (&line_start, &line_end))
    {
      /* we were already at the start; so go back one line */
      gtk_text_iter_backward_line (&line_start);
    }

  win->first_line_start = line_start;
  win->first_line_end = line_end;

  win->lines = g_new0 (gchar*, win->n_lines + 1);

  i = win->n_lines - 1;
  while (i >= 0)
    {
      gchar *line_text;

      if (win->slice)
        {
          if (win->visible_only)
            line_text = gtk_text_iter_get_visible_slice (&line_start, &line_end);
          else
            line_text = gtk_text_iter_get_slice (&line_start, &line_end);
        }
      else
        {
          if (win->visible_only)
            line_text = gtk_text_iter_get_visible_text (&line_start, &line_end);
          else
            line_text = gtk_text_iter_get_text (&line_start, &line_end);
        }

      win->lines[i] = line_text;

      line_end = line_start;
      gtk_text_iter_backward_line (&line_start);

      --i;
    }
}

static gboolean
lines_window_back (LinesWindow *win)
{
  GtkTextIter new_start;
  gchar *line_text;

  new_start = win->first_line_start;

  if (!gtk_text_iter_backward_line (&new_start))
    return FALSE;
  else
    {
      win->first_line_start = new_start;
      win->first_line_end = new_start;

      gtk_text_iter_forward_line (&win->first_line_end);
    }

  if (win->slice)
    {
      if (win->visible_only)
        line_text = gtk_text_iter_get_visible_slice (&win->first_line_start,
                                                     &win->first_line_end);
      else
        line_text = gtk_text_iter_get_slice (&win->first_line_start,
                                             &win->first_line_end);
    }
  else
    {
      if (win->visible_only)
        line_text = gtk_text_iter_get_visible_text (&win->first_line_start,
                                                    &win->first_line_end);
      else
        line_text = gtk_text_iter_get_text (&win->first_line_start,
                                            &win->first_line_end);
    }

  /* Move lines to make room for first line. */
  g_memmove (win->lines + 1, win->lines, win->n_lines * sizeof (gchar*));

  *win->lines = line_text;

  /* Free old last line and NULL-terminate */
  g_free (win->lines[win->n_lines]);
  win->lines[win->n_lines] = NULL;

  return TRUE;
}

static void
lines_window_free (LinesWindow *win)
{
  g_strfreev (win->lines);
}

/**
 * gtk_text_iter_backward_search:
 * @iter: a #GtkTextIter where the search begins
 * @str: search string
 * @flags: bitmask of flags affecting the search
 * @match_start: (allow-none): return location for start of match, or %NULL
 * @match_end: (allow-none): return location for end of match, or %NULL
 * @limit: (allow-none): location of last possible @match_start, or %NULL for start of buffer
 *
 * Same as gtk_text_iter_forward_search(), but moves backward.
 *
 * Return value: whether a match was found
 **/
gboolean
gtk_text_iter_backward_search (const GtkTextIter *iter,
                               const gchar       *str,
                               GtkTextSearchFlags flags,
                               GtkTextIter       *match_start,
                               GtkTextIter       *match_end,
                               const GtkTextIter *limit)
{
  gchar **lines = NULL;
  gchar **l;
  gint n_lines;
  LinesWindow win;
  gboolean retval = FALSE;
  gboolean visible_only;
  gboolean slice;
  
  g_return_val_if_fail (iter != NULL, FALSE);
  g_return_val_if_fail (str != NULL, FALSE);

  if (limit &&
      gtk_text_iter_compare (limit, iter) > 0)
    return FALSE;
  
  if (*str == '\0')
    {
      /* If we can move one char, return the empty string there */
      GtkTextIter match = *iter;

      if (limit && gtk_text_iter_equal (limit, &match))
        return FALSE;
      
      if (gtk_text_iter_backward_char (&match))
        {
          if (match_start)
            *match_start = match;
          if (match_end)
            *match_end = match;
          return TRUE;
        }
      else
        return FALSE;
    }

  visible_only = (flags & GTK_TEXT_SEARCH_VISIBLE_ONLY) != 0;
  slice = (flags & GTK_TEXT_SEARCH_TEXT_ONLY) == 0;
  
  /* locate all lines */

  lines = strbreakup (str, "\n", -1);

  l = lines;
  n_lines = 0;
  while (*l)
    {
      ++n_lines;
      ++l;
    }

  win.n_lines = n_lines;
  win.slice = slice;
  win.visible_only = visible_only;

  lines_window_init (&win, iter);

  if (*win.lines == NULL)
    goto out;

  do
    {
      gchar *first_line_match;

      if (limit &&
          gtk_text_iter_compare (limit, &win.first_line_end) > 0)
        {
          /* We're now before the search limit, abort. */
          goto out;
        }
      
      /* If there are multiple lines, the first line will
       * end in '\n', so this will only match at the
       * end of the first line, which is correct.
       */
      first_line_match = g_strrstr (*win.lines, *lines);

      if (first_line_match &&
          vectors_equal_ignoring_trailing (lines + 1, win.lines + 1))
        {
          /* Match! */
          gint offset;
          GtkTextIter next;
          GtkTextIter start_tmp;
          
          /* Offset to start of search string */
          offset = g_utf8_strlen (*win.lines, first_line_match - *win.lines);

          next = win.first_line_start;
          start_tmp = next;
          forward_chars_with_skipping (&start_tmp, offset,
                                       visible_only, !slice);

          if (limit &&
              gtk_text_iter_compare (limit, &start_tmp) > 0)
            goto out; /* match was bogus */
          
          if (match_start)
            *match_start = start_tmp;

          /* Go to end of search string */
          l = lines;
          while (*l)
            {
              offset += g_utf8_strlen (*l, -1);
              ++l;
            }

          forward_chars_with_skipping (&next, offset,
                                       visible_only, !slice);

          if (match_end)
            *match_end = next;

          retval = TRUE;
          goto out;
        }
    }
  while (lines_window_back (&win));

 out:
  lines_window_free (&win);
  g_strfreev (lines);
  
  return retval;
}

/*
 * Comparisons
 */

/**
 * gtk_text_iter_equal:
 * @lhs: a #GtkTextIter
 * @rhs: another #GtkTextIter
 * 
 * Tests whether two iterators are equal, using the fastest possible
 * mechanism. This function is very fast; you can expect it to perform
 * better than e.g. getting the character offset for each iterator and
 * comparing the offsets yourself. Also, it's a bit faster than
 * gtk_text_iter_compare().
 * 
 * Return value: %TRUE if the iterators point to the same place in the buffer
 **/
gboolean
gtk_text_iter_equal (const GtkTextIter *lhs,
                     const GtkTextIter *rhs)
{
  GtkTextRealIter *real_lhs;
  GtkTextRealIter *real_rhs;

  real_lhs = (GtkTextRealIter*)lhs;
  real_rhs = (GtkTextRealIter*)rhs;

  check_invariants (lhs);
  check_invariants (rhs);

  if (real_lhs->line != real_rhs->line)
    return FALSE;
  else if (real_lhs->line_byte_offset >= 0 &&
           real_rhs->line_byte_offset >= 0)
    return real_lhs->line_byte_offset == real_rhs->line_byte_offset;
  else
    {
      /* the ensure_char_offsets () calls do nothing if the char offsets
         are already up-to-date. */
      ensure_char_offsets (real_lhs);
      ensure_char_offsets (real_rhs);
      return real_lhs->line_char_offset == real_rhs->line_char_offset;
    }
}

/**
 * gtk_text_iter_compare:
 * @lhs: a #GtkTextIter
 * @rhs: another #GtkTextIter
 * 
 * A qsort()-style function that returns negative if @lhs is less than
 * @rhs, positive if @lhs is greater than @rhs, and 0 if they're equal.
 * Ordering is in character offset order, i.e. the first character in the buffer
 * is less than the second character in the buffer.
 * 
 * Return value: -1 if @lhs is less than @rhs, 1 if @lhs is greater, 0 if they are equal
 **/
gint
gtk_text_iter_compare (const GtkTextIter *lhs,
                       const GtkTextIter *rhs)
{
  GtkTextRealIter *real_lhs;
  GtkTextRealIter *real_rhs;

  real_lhs = gtk_text_iter_make_surreal (lhs);
  real_rhs = gtk_text_iter_make_surreal (rhs);

  if (real_lhs == NULL ||
      real_rhs == NULL)
    return -1; /* why not */

  check_invariants (lhs);
  check_invariants (rhs);
  
  if (real_lhs->line == real_rhs->line)
    {
      gint left_index, right_index;

      if (real_lhs->line_byte_offset >= 0 &&
          real_rhs->line_byte_offset >= 0)
        {
          left_index = real_lhs->line_byte_offset;
          right_index = real_rhs->line_byte_offset;
        }
      else
        {
          /* the ensure_char_offsets () calls do nothing if
             the offsets are already up-to-date. */
          ensure_char_offsets (real_lhs);
          ensure_char_offsets (real_rhs);
          left_index = real_lhs->line_char_offset;
          right_index = real_rhs->line_char_offset;
        }

      if (left_index < right_index)
        return -1;
      else if (left_index > right_index)
        return 1;
      else
        return 0;
    }
  else
    {
      gint line1, line2;

      line1 = gtk_text_iter_get_line (lhs);
      line2 = gtk_text_iter_get_line (rhs);
      if (line1 < line2)
        return -1;
      else if (line1 > line2)
        return 1;
      else
        return 0;
    }
}

/**
 * gtk_text_iter_in_range:
 * @iter: a #GtkTextIter
 * @start: start of range
 * @end: end of range
 * 
 * Checks whether @iter falls in the range [@start, @end).
 * @start and @end must be in ascending order.
 * 
 * Return value: %TRUE if @iter is in the range
 **/
gboolean
gtk_text_iter_in_range (const GtkTextIter *iter,
                        const GtkTextIter *start,
                        const GtkTextIter *end)
{
  g_return_val_if_fail (iter != NULL, FALSE);
  g_return_val_if_fail (start != NULL, FALSE);
  g_return_val_if_fail (end != NULL, FALSE);
  g_return_val_if_fail (gtk_text_iter_compare (start, end) <= 0, FALSE);
  
  return gtk_text_iter_compare (iter, start) >= 0 &&
    gtk_text_iter_compare (iter, end) < 0;
}

/**
 * gtk_text_iter_order:
 * @first: a #GtkTextIter
 * @second: another #GtkTextIter
 *
 * Swaps the value of @first and @second if @second comes before
 * @first in the buffer. That is, ensures that @first and @second are
 * in sequence. Most text buffer functions that take a range call this
 * automatically on your behalf, so there's no real reason to call it yourself
 * in those cases. There are some exceptions, such as gtk_text_iter_in_range(),
 * that expect a pre-sorted range.
 * 
 **/
void
gtk_text_iter_order (GtkTextIter *first,
                     GtkTextIter *second)
{
  g_return_if_fail (first != NULL);
  g_return_if_fail (second != NULL);

  if (gtk_text_iter_compare (first, second) > 0)
    {
      GtkTextIter tmp;

      tmp = *first;
      *first = *second;
      *second = tmp;
    }
}

/*
 * Init iterators from the BTree
 */

void
_gtk_text_btree_get_iter_at_char (GtkTextBTree *tree,
                                  GtkTextIter *iter,
                                  gint char_index)
{
  GtkTextRealIter *real = (GtkTextRealIter*)iter;
  gint real_char_index;
  gint line_start;
  GtkTextLine *line;

  g_return_if_fail (iter != NULL);
  g_return_if_fail (tree != NULL);

  line = _gtk_text_btree_get_line_at_char (tree, char_index,
                                           &line_start, &real_char_index);

  iter_init_from_char_offset (iter, tree, line, real_char_index - line_start);

  real->cached_char_index = real_char_index;

  check_invariants (iter);
}

void
_gtk_text_btree_get_iter_at_line_char (GtkTextBTree *tree,
                                       GtkTextIter  *iter,
                                       gint          line_number,
                                       gint          char_on_line)
{
  GtkTextRealIter *real = (GtkTextRealIter*)iter;
  GtkTextLine *line;
  gint real_line;

  g_return_if_fail (iter != NULL);
  g_return_if_fail (tree != NULL);

  line = _gtk_text_btree_get_line_no_last (tree, line_number, &real_line);
  
  iter_init_from_char_offset (iter, tree, line, char_on_line);

  /* We might as well cache this, since we know it. */
  real->cached_line_number = real_line;

  check_invariants (iter);
}

void
_gtk_text_btree_get_iter_at_line_byte (GtkTextBTree   *tree,
                                       GtkTextIter    *iter,
                                       gint            line_number,
                                       gint            byte_index)
{
  GtkTextRealIter *real = (GtkTextRealIter*)iter;
  GtkTextLine *line;
  gint real_line;

  g_return_if_fail (iter != NULL);
  g_return_if_fail (tree != NULL);

  line = _gtk_text_btree_get_line_no_last (tree, line_number, &real_line);

  iter_init_from_byte_offset (iter, tree, line, byte_index);

  /* We might as well cache this, since we know it. */
  real->cached_line_number = real_line;

  check_invariants (iter);
}

void
_gtk_text_btree_get_iter_at_line      (GtkTextBTree   *tree,
                                       GtkTextIter    *iter,
                                       GtkTextLine    *line,
                                       gint            byte_offset)
{
  g_return_if_fail (iter != NULL);
  g_return_if_fail (tree != NULL);
  g_return_if_fail (line != NULL);

  iter_init_from_byte_offset (iter, tree, line, byte_offset);

  check_invariants (iter);
}

gboolean
_gtk_text_btree_get_iter_at_first_toggle (GtkTextBTree   *tree,
                                          GtkTextIter    *iter,
                                          GtkTextTag     *tag)
{
  GtkTextLine *line;

  g_return_val_if_fail (iter != NULL, FALSE);
  g_return_val_if_fail (tree != NULL, FALSE);

  line = _gtk_text_btree_first_could_contain_tag (tree, tag);

  if (line == NULL)
    {
      /* Set iter to last in tree */
      _gtk_text_btree_get_end_iter (tree, iter);
      check_invariants (iter);
      return FALSE;
    }
  else
    {
      iter_init_from_byte_offset (iter, tree, line, 0);

      if (!gtk_text_iter_toggles_tag (iter, tag))
        gtk_text_iter_forward_to_tag_toggle (iter, tag);

      check_invariants (iter);
      return TRUE;
    }
}

gboolean
_gtk_text_btree_get_iter_at_last_toggle  (GtkTextBTree   *tree,
                                          GtkTextIter    *iter,
                                          GtkTextTag     *tag)
{
  g_return_val_if_fail (iter != NULL, FALSE);
  g_return_val_if_fail (tree != NULL, FALSE);

  _gtk_text_btree_get_end_iter (tree, iter);
  gtk_text_iter_backward_to_tag_toggle (iter, tag);
  check_invariants (iter);
  
  return TRUE;
}

gboolean
_gtk_text_btree_get_iter_at_mark_name (GtkTextBTree *tree,
                                       GtkTextIter *iter,
                                       const gchar *mark_name)
{
  GtkTextMark *mark;

  g_return_val_if_fail (iter != NULL, FALSE);
  g_return_val_if_fail (tree != NULL, FALSE);

  mark = _gtk_text_btree_get_mark_by_name (tree, mark_name);

  if (mark == NULL)
    return FALSE;
  else
    {
      _gtk_text_btree_get_iter_at_mark (tree, iter, mark);
      check_invariants (iter);
      return TRUE;
    }
}

void
_gtk_text_btree_get_iter_at_mark (GtkTextBTree *tree,
                                  GtkTextIter *iter,
                                  GtkTextMark *mark)
{
  GtkTextLineSegment *seg;

  g_return_if_fail (iter != NULL);
  g_return_if_fail (tree != NULL);
  g_return_if_fail (GTK_IS_TEXT_MARK (mark));

  seg = mark->segment;

  iter_init_from_segment (iter, tree,
                          seg->body.mark.line, seg);
  g_assert (seg->body.mark.line == _gtk_text_iter_get_text_line (iter));
  check_invariants (iter);
}

void
_gtk_text_btree_get_iter_at_child_anchor (GtkTextBTree       *tree,
                                          GtkTextIter        *iter,
                                          GtkTextChildAnchor *anchor)
{
  GtkTextLineSegment *seg;

  g_return_if_fail (iter != NULL);
  g_return_if_fail (tree != NULL);
  g_return_if_fail (GTK_IS_TEXT_CHILD_ANCHOR (anchor));
  
  seg = anchor->segment;  

  g_assert (seg->body.child.line != NULL);
  
  iter_init_from_segment (iter, tree,
                          seg->body.child.line, seg);
  g_assert (seg->body.child.line == _gtk_text_iter_get_text_line (iter));
  check_invariants (iter);
}

void
_gtk_text_btree_get_end_iter         (GtkTextBTree   *tree,
                                      GtkTextIter    *iter)
{
  g_return_if_fail (iter != NULL);
  g_return_if_fail (tree != NULL);

  _gtk_text_btree_get_iter_at_char (tree,
                                   iter,
                                   _gtk_text_btree_char_count (tree));
  check_invariants (iter);
}

void
_gtk_text_iter_check (const GtkTextIter *iter)
{
  const GtkTextRealIter *real = (const GtkTextRealIter*)iter;
  gint line_char_offset, line_byte_offset, seg_char_offset, seg_byte_offset;
  GtkTextLineSegment *byte_segment = NULL;
  GtkTextLineSegment *byte_any_segment = NULL;
  GtkTextLineSegment *char_segment = NULL;
  GtkTextLineSegment *char_any_segment = NULL;
  gboolean segments_updated;

  /* This function checks our class invariants for the Iter class. */

  g_assert (sizeof (GtkTextIter) == sizeof (GtkTextRealIter));

  if (real->chars_changed_stamp !=
      _gtk_text_btree_get_chars_changed_stamp (real->tree))
    g_error ("iterator check failed: invalid iterator");

  if (real->line_char_offset < 0 && real->line_byte_offset < 0)
    g_error ("iterator check failed: both char and byte offsets are invalid");

  segments_updated = (real->segments_changed_stamp ==
                      _gtk_text_btree_get_segments_changed_stamp (real->tree));

#if 0
  printf ("checking iter, segments %s updated, byte %d char %d\n",
          segments_updated ? "are" : "aren't",
          real->line_byte_offset,
          real->line_char_offset);
#endif

  if (segments_updated)
    {
      if (real->segment_char_offset < 0 && real->segment_byte_offset < 0)
        g_error ("iterator check failed: both char and byte segment offsets are invalid");

      if (real->segment->char_count == 0)
        g_error ("iterator check failed: segment is not indexable.");

      if (real->line_char_offset >= 0 && real->segment_char_offset < 0)
        g_error ("segment char offset is not properly up-to-date");

      if (real->line_byte_offset >= 0 && real->segment_byte_offset < 0)
        g_error ("segment byte offset is not properly up-to-date");

      if (real->segment_byte_offset >= 0 &&
          real->segment_byte_offset >= real->segment->byte_count)
        g_error ("segment byte offset is too large.");

      if (real->segment_char_offset >= 0 &&
          real->segment_char_offset >= real->segment->char_count)
        g_error ("segment char offset is too large.");
    }

  if (real->line_byte_offset >= 0)
    {
      _gtk_text_line_byte_locate (real->line, real->line_byte_offset,
                                  &byte_segment, &byte_any_segment,
                                  &seg_byte_offset, &line_byte_offset);

      if (line_byte_offset != real->line_byte_offset)
        g_error ("wrong byte offset was stored in iterator");

      if (segments_updated)
        {
          if (real->segment != byte_segment)
            g_error ("wrong segment was stored in iterator");

          if (real->any_segment != byte_any_segment)
            g_error ("wrong any_segment was stored in iterator");

          if (seg_byte_offset != real->segment_byte_offset)
            g_error ("wrong segment byte offset was stored in iterator");

          if (byte_segment->type == &gtk_text_char_type)
            {
              const gchar *p;
              p = byte_segment->body.chars + seg_byte_offset;
              
              if (!gtk_text_byte_begins_utf8_char (p))
                g_error ("broken iterator byte index pointed into the middle of a character");
            }
        }
    }

  if (real->line_char_offset >= 0)
    {
      _gtk_text_line_char_locate (real->line, real->line_char_offset,
                                  &char_segment, &char_any_segment,
                                  &seg_char_offset, &line_char_offset);

      if (line_char_offset != real->line_char_offset)
        g_error ("wrong char offset was stored in iterator");

      if (segments_updated)
        {          
          if (real->segment != char_segment)
            g_error ("wrong segment was stored in iterator");

          if (real->any_segment != char_any_segment)
            g_error ("wrong any_segment was stored in iterator");

          if (seg_char_offset != real->segment_char_offset)
            g_error ("wrong segment char offset was stored in iterator");

          if (char_segment->type == &gtk_text_char_type)
            {
              const gchar *p;
              p = g_utf8_offset_to_pointer (char_segment->body.chars,
                                            seg_char_offset);

              /* hmm, not likely to happen eh */
              if (!gtk_text_byte_begins_utf8_char (p))
                g_error ("broken iterator char offset pointed into the middle of a character");
            }
        }
    }

  if (real->line_char_offset >= 0 && real->line_byte_offset >= 0)
    {
      if (byte_segment != char_segment)
        g_error ("char and byte offsets did not point to the same segment");

      if (byte_any_segment != char_any_segment)
        g_error ("char and byte offsets did not point to the same any segment");

      /* Make sure the segment offsets are equivalent, if it's a char
         segment. */
      if (char_segment->type == &gtk_text_char_type)
        {
          gint byte_offset = 0;
          gint char_offset = 0;
          while (char_offset < seg_char_offset)
            {
              const char * start = char_segment->body.chars + byte_offset;
              byte_offset += g_utf8_next_char (start) - start;
              char_offset += 1;
            }

          if (byte_offset != seg_byte_offset)
            g_error ("byte offset did not correspond to char offset");

          char_offset =
            g_utf8_strlen (char_segment->body.chars, seg_byte_offset);

          if (char_offset != seg_char_offset)
            g_error ("char offset did not correspond to byte offset");

          if (!gtk_text_byte_begins_utf8_char (char_segment->body.chars + seg_byte_offset))
            g_error ("byte index for iterator does not index the start of a character");
        }
    }

  if (real->cached_line_number >= 0)
    {
      gint should_be;

      should_be = _gtk_text_line_get_number (real->line);
      if (real->cached_line_number != should_be)
        g_error ("wrong line number was cached");
    }

  if (real->cached_char_index >= 0)
    {
      if (real->line_char_offset >= 0) /* only way we can check it
                                          efficiently, not a real
                                          invariant. */
        {
          gint char_index;

          char_index = _gtk_text_line_char_index (real->line);
          char_index += real->line_char_offset;

          if (real->cached_char_index != char_index)
            g_error ("wrong char index was cached");
        }
    }

  if (_gtk_text_line_is_last (real->line, real->tree))
    g_error ("Iterator was on last line (past the end iterator)");
}

#define __GTK_TEXT_ITER_C__
#include "gtkaliasdef.c"