summaryrefslogtreecommitdiff
path: root/src/textconv.c
blob: 2a7b0ed330d035851d6a1753bf7c0e0bc2bda7da (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
/* String conversion support for graphics terminals.

Copyright (C) 2023-2024 Free Software Foundation, Inc.

This file is part of GNU Emacs.

GNU Emacs is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.

GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */

/* String conversion support.

   Many input methods require access to text surrounding the cursor.
   They may then request that the text editor remove or substitute
   that text for something else, for example when providing the
   ability to ``undo'' or ``edit'' previously composed text.  This is
   most commonly seen in input methods for CJK languages for X Windows,
   and is extensively used throughout Android by input methods for all
   kinds of scripts.

   In addition, these input methods may also need to make detailed
   edits to the content of a buffer.  That is also handled here.  */

#include <config.h>

#include "textconv.h"
#include "buffer.h"
#include "syntax.h"
#include "blockinput.h"
#include "keyboard.h"



/* Define debugging macros.  */

#if defined HAVE_ANDROID && !defined ANDROID_STUBIFY
#if 0
#include <android/log.h>

#define TEXTCONV_DEBUG(fmt, ...)					\
  __android_log_print (ANDROID_LOG_VERBOSE, "EmacsInputConnection",	\
		       "%s: " fmt, __func__, ## __VA_ARGS__)
#endif /* 0 */
#endif /* defined HAVE_ANDROID && !defined ANDROID_STUBIFY */

#ifndef TEXTCONV_DEBUG
#define TEXTCONV_DEBUG(...) ((void) 0)
#endif /* TEXTCONV_DEBUG */



/* The window system's text conversion interface.  NULL when the
   window system has not set up text conversion.  */

static struct textconv_interface *text_interface;

/* How many times text conversion has been disabled.  */

static int suppress_conversion_count;

/* Flags used to determine what must be sent after a batch edit
   ends.  */

enum textconv_batch_edit_flags
  {
    PENDING_POINT_CHANGE   = 1,
    PENDING_COMPOSE_CHANGE = 2,
  };



/* Copy the portion of the current buffer's text described by BEG,
   BEG_BYTE, END, END_BYTE to the char * buffer BUFFER, which should
   be at least END_BYTE - BEG_BYTEs long.  */

static void
copy_buffer_text (ptrdiff_t beg, ptrdiff_t beg_byte,
		  ptrdiff_t end, ptrdiff_t end_byte,
		  char *buffer)
{
  ptrdiff_t beg0, end0, beg1, end1, size;

  if (beg_byte < GPT_BYTE && GPT_BYTE < end_byte)
    {
      /* Two regions, before and after the gap.  */
      beg0 = beg_byte;
      end0 = GPT_BYTE;
      beg1 = GPT_BYTE + GAP_SIZE - BEG_BYTE;
      end1 = end_byte + GAP_SIZE - BEG_BYTE;
    }
  else
    {
      /* The only region.  */
      beg0 = beg_byte;
      end0 = end_byte;
      beg1 = -1;
      end1 = -1;
    }

  size = end0 - beg0;
  memcpy (buffer, BYTE_POS_ADDR (beg0), size);
  if (beg1 != -1)
    memcpy (buffer + size, BEG_ADDR + beg1, end1 - beg1);
}



/* Conversion query.  */

/* Return the position of the active mark, or -1 if there is no mark
   or it is not active.  */

static ptrdiff_t
get_mark (void)
{
  if (!NILP (BVAR (current_buffer, mark_active))
      && XMARKER (BVAR (current_buffer, mark))->buffer)
    return marker_position (BVAR (current_buffer,
				  mark));

  return -1;
}

/* Like Fselect_window.  However, if WINDOW is a minibuffer window
   but not the active minibuffer window, select its frame's selected
   window instead.  */

static void
select_window (Lisp_Object window, Lisp_Object norecord)
{
  struct window *w;

  w = XWINDOW (window);

  if (MINI_WINDOW_P (w)
      && WINDOW_LIVE_P (window)
      && !EQ (window, Factive_minibuffer_window ()))
    window = WINDOW_XFRAME (w)->selected_window;

  Fselect_window (window, norecord);
}

/* Perform the text conversion operation specified in QUERY and return
   the results.

   Find the text between QUERY->position from point on frame F's
   selected window and QUERY->factor times QUERY->direction from that
   position.  Return it in QUERY->text.

   If QUERY->position is TYPE_MINIMUM (EMACS_INT) or EMACS_INT_MAX,
   start at the window's last point or mark, whichever is greater or
   smaller.

   Then, either delete that text from the buffer if QUERY->operation
   is TEXTCONV_SUBSTITUTION, or return 0.

   If FLAGS & TEXTCONV_SKIP_CONVERSION_REGION, then first move point
   past the conversion region in the specified direction if it is
   inside.

   Value is 0 if QUERY->operation was not TEXTCONV_SUBSTITUTION
   or if deleting the text was successful, and 1 otherwise.  */

int
textconv_query (struct frame *f, struct textconv_callback_struct *query,
		int flags)
{
  specpdl_ref count;
  ptrdiff_t pos, pos_byte, end, end_byte, start;
  ptrdiff_t temp, temp1, mark;
  char *buffer;
  struct window *w;

  /* Save the excursion, as there will be extensive changes to the
     selected window.  */
  count = SPECPDL_INDEX ();
  record_unwind_protect_excursion ();

  /* Inhibit quitting.  */
  specbind (Qinhibit_quit, Qt);

  /* Temporarily switch to F's selected window at the time of the last
     redisplay.  */
  select_window ((WINDOW_LIVE_P (f->old_selected_window)
		  ? f->old_selected_window
		  : f->selected_window), Qt);
  w = XWINDOW (selected_window);

  /* Now find the appropriate text bounds for QUERY.  First, move
     point QUERY->position steps forward or backwards.  */

  pos = PT;

  /* If QUERY->position is EMACS_INT_MAX, use the last mark or the
     ephemeral last point, whichever is greater.

     The opposite applies for EMACS_INT_MIN.  */

  mark = get_mark ();

  if (query->position == EMACS_INT_MAX)
    {
      pos = (mark == -1
	     ? w->ephemeral_last_point
	     : max (w->ephemeral_last_point, mark));
      goto escape1;
    }
  else if (query->position == TYPE_MINIMUM (EMACS_INT))
    {
      pos = (mark == -1
	     ? w->ephemeral_last_point
	     : min (w->ephemeral_last_point, mark));
      goto escape1;
    }

  /* Next, if POS lies within the conversion region and the caller
     asked for it to be moved away, move it away from the conversion
     region.  */

  if (flags & TEXTCONV_SKIP_CONVERSION_REGION
      && MARKERP (f->conversion.compose_region_start))
    {
      start = marker_position (f->conversion.compose_region_start);
      end = marker_position (f->conversion.compose_region_end);

      if (pos >= start && pos < end)
	{
	  switch (query->direction)
	    {
	    case TEXTCONV_FORWARD_CHAR:
	    case TEXTCONV_FORWARD_WORD:
	    case TEXTCONV_CARET_DOWN:
	    case TEXTCONV_NEXT_LINE:
	    case TEXTCONV_LINE_START:
	      pos = end;
	      break;

	    default:
	      pos = max (BEGV, start - 1);
	      break;
	    }
	}
    }

  /* If pos is outside the accessible part of the buffer or if it
     overflows, move back to point or to the extremes of the
     accessible region.  */

  if (ckd_add (&pos, pos, query->position))
    pos = PT;

 escape1:

  if (pos < BEGV)
    pos = BEGV;

  if (pos > ZV)
    pos = ZV;

  /* Move to pos.  */
  set_point (pos);
  pos = PT;
  pos_byte = PT_BYTE;

  /* Now scan forward or backwards according to what is in QUERY.  */

  switch (query->direction)
    {
    case TEXTCONV_FORWARD_CHAR:
      /* Move forward by query->factor characters.  */
      if (ckd_add (&end, pos, query->factor) || end > ZV)
	end = ZV;

      end_byte = CHAR_TO_BYTE (end);
      break;

    case TEXTCONV_BACKWARD_CHAR:
      /* Move backward by query->factor characters.  */
      if (ckd_sub (&end, pos, query->factor) || end < BEGV)
	end = BEGV;

      end_byte = CHAR_TO_BYTE (end);
      break;

    case TEXTCONV_FORWARD_WORD:
      /* Move forward by query->factor words.  */
      end = scan_words (pos, (EMACS_INT) query->factor);

      if (!end)
	{
	  end = ZV;
	  end_byte = ZV_BYTE;
	}
      else
	end_byte = CHAR_TO_BYTE (end);

      break;

    case TEXTCONV_BACKWARD_WORD:
      /* Move backwards by query->factor words.  */
      end = scan_words (pos, 0 - (EMACS_INT) query->factor);

      if (!end)
	{
	  end = BEGV;
	  end_byte = BEGV_BYTE;
	}
      else
	end_byte = CHAR_TO_BYTE (end);

      break;

    case TEXTCONV_CARET_UP:
      /* Move upwards one visual line, keeping the column intact.  */
      Fvertical_motion (Fcons (Fcurrent_column (), make_fixnum (-1)),
			Qnil, Qnil);
      end = PT;
      end_byte = PT_BYTE;
      break;

    case TEXTCONV_CARET_DOWN:
      /* Move downwards one visual line, keeping the column
	 intact.  */
      Fvertical_motion (Fcons (Fcurrent_column (), make_fixnum (1)),
			Qnil, Qnil);
      end = PT;
      end_byte = PT_BYTE;
      break;

    case TEXTCONV_NEXT_LINE:
      /* Move one line forward.  */
      scan_newline (pos, pos_byte, ZV, ZV_BYTE,
		    query->factor, false);
      end = PT;
      end_byte = PT_BYTE;
      break;

    case TEXTCONV_PREVIOUS_LINE:
      /* Move one line backwards.  */
      scan_newline (pos, pos_byte, BEGV, BEGV_BYTE,
		    0 - (EMACS_INT) query->factor, false);
      end = PT;
      end_byte = PT_BYTE;
      break;

    case TEXTCONV_LINE_START:
      /* Move to the beginning of the line.  */
      Fbeginning_of_line (Qnil);
      end = PT;
      end_byte = PT_BYTE;
      break;

    case TEXTCONV_LINE_END:
      /* Move to the end of the line.  */
      Fend_of_line (Qnil);
      end = PT;
      end_byte = PT_BYTE;
      break;

    case TEXTCONV_ABSOLUTE_POSITION:
      /* How to implement this is unclear.  */
      SET_PT (query->factor);
      end = PT;
      end_byte = PT_BYTE;
      break;

    default:
      unbind_to (count, Qnil);
      return 1;
    }

  /* Sort end and pos.  */

  if (end < pos)
    {
      eassert (end_byte < pos_byte);
      temp = pos_byte;
      temp1 = pos;
      pos_byte = end_byte;
      pos = end;
      end = temp1;
      end_byte = temp;
    }

  /* Return the string first.  */
  buffer = xmalloc (end_byte - pos_byte);
  copy_buffer_text (pos, pos_byte, end, end_byte, buffer);
  query->text.text = buffer;
  query->text.length = end - pos;
  query->text.bytes = end_byte - pos_byte;

  /* Next, perform any operation specified.  */

  switch (query->operation)
    {
    case TEXTCONV_SUBSTITUTION:
      if (safe_del_range (pos, end))
	{
	  /* Undo any changes to the excursion.  */
	  unbind_to (count, Qnil);
	  return 1;
	}

    default:
      break;
    }

  /* Undo any changes to the excursion.  */
  unbind_to (count, Qnil);
  return 0;
}

/* Update the overlay displaying the conversion area on frame F after
   a change to the conversion region.  */

static void
sync_overlay (struct frame *f)
{
  if (MARKERP (f->conversion.compose_region_start)
      && !NILP (Vtext_conversion_face))
    {
      if (NILP (f->conversion.compose_region_overlay))
	{
	  f->conversion.compose_region_overlay
	    = Fmake_overlay (f->conversion.compose_region_start,
			     f->conversion.compose_region_end, Qnil,
			     Qt, Qnil);
	  Foverlay_put (f->conversion.compose_region_overlay,
			Qface, Vtext_conversion_face);
	}

      Fmove_overlay (f->conversion.compose_region_overlay,
		     f->conversion.compose_region_start,
		     f->conversion.compose_region_end, Qnil);
    }
  else if (!NILP (f->conversion.compose_region_overlay))
    {
      Fdelete_overlay (f->conversion.compose_region_overlay);
      f->conversion.compose_region_overlay = Qnil;
    }
}

/* Record a change to the current buffer as a result of an
   asynchronous text conversion operation.

   Consult the doc string of `text-conversion-edits' for the meaning
   of BEG, END, and EPHEMERAL.  */

static void
record_buffer_change (ptrdiff_t beg, ptrdiff_t end,
		      Lisp_Object ephemeral)
{
  Lisp_Object buffer, beg_marker, end_marker;

  XSETBUFFER (buffer, current_buffer);

  /* Make markers for both BEG and END.  */
  beg_marker = build_marker (current_buffer, beg,
			     CHAR_TO_BYTE (beg));

  /* If BEG and END are identical, make sure to keep the markers
     eq.  */

  if (beg == end)
    end_marker = beg_marker;
  else
    {
      end_marker = build_marker (current_buffer, end,
				 CHAR_TO_BYTE (end));

      /* Otherwise, make sure the marker extends past inserted
	 text.  */
      Fset_marker_insertion_type (end_marker, Qt);
    }

  Vtext_conversion_edits
    = Fcons (list4 (buffer, beg_marker, end_marker,
		    ephemeral),
	     Vtext_conversion_edits);
}

/* Reset text conversion state of frame F.  Delete any overlays or
   markers inside.  */

void
reset_frame_state (struct frame *f)
{
  struct text_conversion_action *last, *next;

  /* Make the composition region markers point elsewhere.  */

  if (!NILP (f->conversion.compose_region_start))
    {
      Fset_marker (f->conversion.compose_region_start, Qnil, Qnil);
      Fset_marker (f->conversion.compose_region_end, Qnil, Qnil);
      f->conversion.compose_region_start = Qnil;
      f->conversion.compose_region_end = Qnil;
    }

  /* Delete the composition region overlay.  */

  if (!NILP (f->conversion.compose_region_overlay))
    Fdelete_overlay (f->conversion.compose_region_overlay);

  /* Delete each text conversion action queued up.  */

  next = f->conversion.actions;
  while (next)
    {
      last = next;
      next = next->next;

      /* Say that the conversion is finished.  */
      if (text_interface && text_interface->notify_conversion)
	text_interface->notify_conversion (last->counter);

      xfree (last);
    }
  f->conversion.actions = NULL;

  /* Clear batch edit state.  */
  f->conversion.batch_edit_count = 0;
  f->conversion.batch_edit_flags = 0;
}

/* Return whether or not there are pending edits from an input method
   on any frame.  */

bool
detect_conversion_events (void)
{
  Lisp_Object tail, frame;

  FOR_EACH_FRAME (tail, frame)
    {
      /* See if there's a pending edit on this frame.  */
      if (XFRAME (frame)->conversion.actions
	  && ((XFRAME (frame)->conversion.actions->operation
	       != TEXTCONV_BARRIER)
	      || (kbd_fetch_ptr == kbd_store_ptr)))
	return true;
    }

  return false;
}

/* Restore the selected window WINDOW.  */

static void
restore_selected_window (Lisp_Object window)
{
  /* FIXME: not sure what to do if WINDOW has been deleted.  */
  select_window (window, Qt);
}

/* Commit the given text in the composing region.  If there is no
   composing region, then insert the text after frame F's selected
   window's last point instead, unless the mark is active.  Finally,
   remove the composing region.

   If the mark is active, delete the text between mark and point.

   Then, move point to POSITION relative to TEXT.  If POSITION is
   greater than zero, it is relative to the character at the end of
   TEXT; otherwise, it is relative to the start of TEXT.  */

static void
really_commit_text (struct frame *f, EMACS_INT position,
		    Lisp_Object text)
{
  specpdl_ref count;
  ptrdiff_t wanted, start, end, mark;
  struct window *w;

  /* If F's old selected window is no longer alive, fail.  */

  if (!WINDOW_LIVE_P (f->old_selected_window))
    return;

  count = SPECPDL_INDEX ();
  record_unwind_protect (restore_selected_window,
			 selected_window);

  /* Temporarily switch to F's selected window at the time of the last
     redisplay.  */
  select_window (f->old_selected_window, Qt);

  /* Now detect whether or not there is a composing or active region.
     If there is, then replace it with TEXT.  Don't do that
     otherwise.  */

  mark = get_mark ();
  if (MARKERP (f->conversion.compose_region_start) || mark != -1)
    {
      /* Replace its contents.  Set START and END to the start and end
	 of the composing region if it exists.  */

      if (MARKERP (f->conversion.compose_region_start))
	{
	  start = marker_position (f->conversion.compose_region_start);
	  end = marker_position (f->conversion.compose_region_end);
	}
      else
	{
	  /* Otherwise, set it to the start and end of the region.  */
	  start = min (mark, PT);
	  end = max (mark, PT);
	}

      /* If it transpires that the start of the compose region is not
	 point, move point there.  */

      if (start != PT)
	set_point (start);

      /* Now delete whatever needs to go.  */

      del_range_1 (start, end, true, false);
      record_buffer_change (start, start, Qt);

      /* Don't record changes if TEXT is empty.  */

      if (SCHARS (text))
	{
	  /* Insert the new text.  Make sure to inherit text
	     properties from the surroundings: if this doesn't happen,
	     CC Mode fontification can get thrown off and become very
	     slow.  */

	  insert_from_string (text, 0, 0, SCHARS (text),
			      SBYTES (text), true);
	  record_buffer_change (start, PT, text);
	}

      /* Move to the position specified in POSITION.  */

      if (position <= 0)
	{
	  /* If POSITION is less than zero, it is relative to the
	     start of the text that was inserted.  */
	  wanted = start;

	  if (INT_ADD_WRAPV (wanted, position, &wanted)
	      || wanted < BEGV)
	    wanted = BEGV;

	  if (wanted > ZV)
	    wanted = ZV;

	  set_point (wanted);
	}
      else
	{
	  /* Otherwise, it is relative to the last character in
	     TEXT.  */
	  wanted = PT;

	  if (INT_ADD_WRAPV (wanted, position - 1, &wanted)
	      || wanted > ZV)
	    wanted = ZV;

	  if (wanted < BEGV)
	    wanted = BEGV;

	  set_point (wanted);
	}

      /* Make the composition region markers point elsewhere.  */

      if (!NILP (f->conversion.compose_region_start))
	{
	  Fset_marker (f->conversion.compose_region_start, Qnil, Qnil);
	  Fset_marker (f->conversion.compose_region_end, Qnil, Qnil);
	  f->conversion.compose_region_start = Qnil;
	  f->conversion.compose_region_end = Qnil;
	}

      /* Delete the composition region overlay.  */

      if (!NILP (f->conversion.compose_region_overlay))
	Fdelete_overlay (f->conversion.compose_region_overlay);
    }
  else
    {
      /* Otherwise, move the text and point to an appropriate
	 location.  */
      wanted = PT;

      /* Don't record changes if TEXT is empty.  */

      if (SCHARS (text))
	{
	  /* Insert the new text.  Make sure to inherit text
	     properties from the surroundings: if this doesn't happen,
	     CC Mode fontification can get thrown off and become very
	     slow.  */

	  insert_from_string (text, 0, 0, SCHARS (text),
			      SBYTES (text), true);

	  record_buffer_change (wanted, PT, text);
	}

      if (position <= 0)
	{
	  if (INT_ADD_WRAPV (wanted, position, &wanted)
	      || wanted < BEGV)
	    wanted = BEGV;

	  if (wanted > ZV)
	    wanted = ZV;

	  set_point (wanted);
	}
      else
	{
	  wanted = PT;

	  if (INT_ADD_WRAPV (wanted, position - 1, &wanted)
	      || wanted > ZV)
	    wanted = ZV;

	  if (wanted < BEGV)
	    wanted = BEGV;

	  set_point (wanted);
	}
    }

  /* This should deactivate the mark.  */
  call0 (Qdeactivate_mark);

  /* Print some debugging information.  */
  TEXTCONV_DEBUG ("text inserted: %s, point now: %zd",
		  SSDATA (text), PT);

  /* Update the ephemeral last point.  */
  w = XWINDOW (selected_window);
  w->ephemeral_last_point = PT;
  unbind_to (count, Qnil);
}

/* Remove the composition region on the frame F, while leaving its
   contents intact.  If UPDATE, also notify the input method of the
   change.  */

static void
really_finish_composing_text (struct frame *f, bool update)
{
  if (!NILP (f->conversion.compose_region_start))
    {
      Fset_marker (f->conversion.compose_region_start, Qnil, Qnil);
      Fset_marker (f->conversion.compose_region_end, Qnil, Qnil);
      f->conversion.compose_region_start = Qnil;
      f->conversion.compose_region_end = Qnil;

      if (update && text_interface
	  && text_interface->compose_region_changed)
	(*text_interface->compose_region_changed) (f);
    }

  /* Delete the composition region overlay.  */

  if (!NILP (f->conversion.compose_region_overlay))
    Fdelete_overlay (f->conversion.compose_region_overlay);

  TEXTCONV_DEBUG ("conversion region removed");
}

/* Set the composing text on frame F to TEXT.  Then, move point to an
   appropriate position relative to POSITION, and call
   `compose_region_changed' in the text conversion interface should
   point not have been changed relative to F's old selected window's
   last point.  */

static void
really_set_composing_text (struct frame *f, ptrdiff_t position,
			   Lisp_Object text)
{
  specpdl_ref count;
  ptrdiff_t start, wanted, end;
  struct window *w;

  /* If F's old selected window is no longer live, fail.  */

  if (!WINDOW_LIVE_P (f->old_selected_window))
    return;

  count = SPECPDL_INDEX ();
  record_unwind_protect (restore_selected_window,
			 selected_window);

  /* Temporarily switch to F's selected window at the time of the last
     redisplay.  */
  w = XWINDOW (f->old_selected_window);
  select_window (f->old_selected_window, Qt);

  /* Now set up the composition region if necessary.  */

  if (!MARKERP (f->conversion.compose_region_start))
    {
      /* Set START and END.  */
      start = PT;
      wanted = end = get_mark ();

      /* If END is -1, set it to start.  */

      if (end == -1)
	end = start;
      else
	{
	  /* Now sort start and end.  */
	  start = min (start, end);
	  end  = max (PT, wanted);
	}

      /* If END is not the same as start, delete the text in
	 between.  */

      if (end != start)
	{
	  del_range_1 (start, end, true, false);
	  set_point (start);
	  record_buffer_change (start, start, Qt);
	}

      /* Now set the markers which denote the composition region.  */
      f->conversion.compose_region_start
	= build_marker (current_buffer, PT, PT_BYTE);
      f->conversion.compose_region_end
	= build_marker (current_buffer, PT, PT_BYTE);

      Fset_marker_insertion_type (f->conversion.compose_region_end,
				  Qt);
    }
  else
    {
      /* Delete the text between the start of the composing region and
	 its end.  */
      start = marker_position (f->conversion.compose_region_start);
      end = marker_position (f->conversion.compose_region_end);
      del_range_1 (start, end, true, false);
      set_point (start);

      if (start != end)
	record_buffer_change (start, start, Qt);
    }

  /* Insert the new text.  Make sure to inherit text properties from
     the surroundings: if this doesn't happen, CC Mode fontification
     can get thrown off and become very slow.  */

  insert_from_string (text, 0, 0, SCHARS (text),
		      SBYTES (text), true);

  if (start != PT)
    record_buffer_change (start, PT, Qt);

  /* Now move point to an appropriate location.  */
  if (position <= 0)
    {
      wanted = start;

      if (INT_SUBTRACT_WRAPV (wanted, position, &wanted)
	  || wanted < BEGV)
	wanted = BEGV;

      if (wanted > ZV)
	wanted = ZV;
    }
  else
    {
      end = marker_position (f->conversion.compose_region_end);
      wanted = end;

      /* end should be PT after the edit.  */
      eassert (end == PT);

      if (INT_ADD_WRAPV (wanted, position - 1, &wanted)
	  || wanted > ZV)
	wanted = ZV;

      if (wanted < BEGV)
	wanted = BEGV;
    }

  set_point (wanted);

  /* This should deactivate the mark.  */
  call0 (Qdeactivate_mark);

  /* Move the composition overlay.  */
  sync_overlay (f);

  /* If TEXT is empty, remove the composing region.  This goes against
     the documentation, but is ultimately what programs expect.  */

  if (!SCHARS (text))
    really_finish_composing_text (f, false);

  /* If PT hasn't changed, the conversion region definitely has.
     Otherwise, redisplay will update the input method instead.  */

  if (PT == w->ephemeral_last_point
      && text_interface
      && text_interface->compose_region_changed)
    {
      if (f->conversion.batch_edit_count > 0)
	f->conversion.batch_edit_flags |= PENDING_COMPOSE_CHANGE;
      else
	text_interface->compose_region_changed (f);
    }

  /* Update the ephemeral last point.  */
  w = XWINDOW (selected_window);
  w->ephemeral_last_point = PT;

  if (SCHARS (text))
    TEXTCONV_DEBUG ("conversion region set to: %td %td",
		    marker_position (f->conversion.compose_region_start),
		    marker_position (f->conversion.compose_region_end));
  else
    TEXTCONV_DEBUG ("conversion region removed; PT is now: %td", PT);

  unbind_to (count, Qnil);
}

/* Set the composing region of frame F to START by END.  Make it if
   it is not already set.  */

static void
really_set_composing_region (struct frame *f, ptrdiff_t start,
			     ptrdiff_t end)
{
  specpdl_ref count;
  struct window *w;

  /* If F's old selected window is no longer live, fail.  */

  if (!WINDOW_LIVE_P (f->old_selected_window))
    return;

  /* If MAX (0, start) == end, then this should behave the same as
     really_finish_composing_text.  */

  if (max (0, start) == max (0, end))
    {
      really_finish_composing_text (f, false);
      return;
    }

  count = SPECPDL_INDEX ();
  record_unwind_protect (restore_selected_window,
			 selected_window);

  /* Temporarily switch to F's selected window at the time of the last
     redisplay.  */
  select_window (f->old_selected_window, Qt);

  /* Now set up the composition region if necessary.  */

  if (!MARKERP (f->conversion.compose_region_start))
    {
      f->conversion.compose_region_start = Fmake_marker ();
      f->conversion.compose_region_end = Fmake_marker ();
      Fset_marker_insertion_type (f->conversion.compose_region_end,
				  Qt);
    }

  Fset_marker (f->conversion.compose_region_start,
	       make_fixnum (start), Qnil);
  Fset_marker (f->conversion.compose_region_end,
	       make_fixnum (end), Qnil);
  sync_overlay (f);

  TEXTCONV_DEBUG ("composing region set to: %td, %td; point is: %td",
		  start, end, PT);

  /* Update the ephemeral last point.  */
  w = XWINDOW (selected_window);
  w->ephemeral_last_point = PT;

  unbind_to (count, Qnil);
}

/* Delete LEFT and RIGHT chars around point or the active mark,
   whichever is larger, in frame F's selected window, avoiding the
   composing region if necessary.  */

static void
really_delete_surrounding_text (struct frame *f, ptrdiff_t left,
				ptrdiff_t right)
{
  specpdl_ref count;
  ptrdiff_t start, end, a, b, a1, b1, lstart, rstart;
  struct window *w;
  Lisp_Object text;

  /* If F's old selected window is no longer live, fail.  */

  if (!WINDOW_LIVE_P (f->old_selected_window))
    return;

  count = SPECPDL_INDEX ();
  record_unwind_protect (restore_selected_window,
			 selected_window);

  /* Temporarily switch to F's selected window at the time of the last
     redisplay.  */
  select_window (f->old_selected_window, Qt);

  /* Figure out where to start deleting from.  */

  a = get_mark ();

  if (a != -1 && a != PT)
    lstart = rstart = max (a, PT);
  else
    lstart = rstart = PT;

  /* Avoid the composing text.  This behavior is identical to how
     Android's BaseInputConnection actually implements avoiding the
     composing span.  */

  if (MARKERP (f->conversion.compose_region_start))
    {
      a = marker_position (f->conversion.compose_region_start);
      b = marker_position (f->conversion.compose_region_end);

      a1 = min (a, b);
      b1 = max (a, b);

      lstart = min (lstart, min (PT, a1));
      rstart = max (rstart, max (PT, b1));
    }

  if (lstart == rstart)
    {
      start = max (BEGV, lstart - left);
      end = min (ZV, rstart + right);

      text = del_range_1 (start, end, true, true);
      record_buffer_change (start, start, text);
    }
  else
    {
      /* Don't record a deletion if the text which was deleted lies
	 after point.  */

      start = rstart;
      end = min (ZV, rstart + right);
      text = del_range_1 (start, end, true, true);
      record_buffer_change (start, start, Qnil);

      /* Now delete what must be deleted on the left.  */

      start = max (BEGV, lstart - left);
      end = lstart;
      text = del_range_1 (start, end, true, true);
      record_buffer_change (start, start, text);
    }

  TEXTCONV_DEBUG ("deleted surrounding text: %td, %td; PT is now %td",
		  left, right, PT);

  /* if the mark is now equal to start, deactivate it.  */

  if (get_mark () == PT)
    call0 (Qdeactivate_mark);

  /* Update the ephemeral last point.  */
  w = XWINDOW (selected_window);
  w->ephemeral_last_point = PT;

  unbind_to (count, Qnil);
}

/* Update the interface with frame F's new point and mark.  If a batch
   edit is in progress, schedule the update for when it finishes
   instead.  */

static void
really_request_point_update (struct frame *f)
{
  /* If F's old selected window is no longer live, fail.  */

  if (!WINDOW_LIVE_P (f->old_selected_window))
    return;

  if (f->conversion.batch_edit_count > 0)
    f->conversion.batch_edit_flags |= PENDING_POINT_CHANGE;
  else if (text_interface && text_interface->point_changed)
    text_interface->point_changed (f,
				   XWINDOW (f->old_selected_window),
				   current_buffer);
}

/* Set point in frame F's selected window to POSITION.  If MARK is not
   at POSITION, activate the mark and set MARK to that as well.

   If point was not changed, signal an update through the text input
   interface, which is necessary for the IME to acknowledge that the
   change has completed.  */

static void
really_set_point_and_mark (struct frame *f, ptrdiff_t point,
			   ptrdiff_t mark)
{
  specpdl_ref count;
  struct window *w;

  /* If F's old selected window is no longer live, fail.  */

  if (!WINDOW_LIVE_P (f->old_selected_window))
    return;

  count = SPECPDL_INDEX ();
  record_unwind_protect (restore_selected_window,
			 selected_window);

  /* Temporarily switch to F's selected window at the time of the last
     redisplay.  */
  select_window (f->old_selected_window, Qt);

  if (point == PT)
    {
      if (f->conversion.batch_edit_count > 0)
	f->conversion.batch_edit_flags |= PENDING_POINT_CHANGE;
      else if (text_interface && text_interface->point_changed)
	text_interface->point_changed (f,
				       XWINDOW (f->old_selected_window),
				       current_buffer);
    }
  else
    /* Set the point.  */
    Fgoto_char (make_fixnum (point));

  if (mark == point
      && !NILP (BVAR (current_buffer, mark_active)))
    call0 (Qdeactivate_mark);
  else
    call1 (Qpush_mark, make_fixnum (mark));

  /* Update the ephemeral last point.  */
  w = XWINDOW (selected_window);
  w->ephemeral_last_point = PT;

  TEXTCONV_DEBUG ("set point and mark: %td %td",
		  PT, get_mark ());

  unbind_to (count, Qnil);
}

/* Remove the composing region.  Replace the text between START and
   END in F's selected window with TEXT, then set point to POSITION
   relative to it.  If the mark is active, deactivate it.  */

static void
really_replace_text (struct frame *f, ptrdiff_t start, ptrdiff_t end,
		     Lisp_Object text, ptrdiff_t position)
{
  specpdl_ref count;
  ptrdiff_t new_start, new_end, wanted;
  struct window *w;

  /* If F's old selected window is no longer alive, fail.  */

  if (!WINDOW_LIVE_P (f->old_selected_window))
    return;

  count = SPECPDL_INDEX ();
  record_unwind_protect (restore_selected_window,
			 selected_window);

  /* Make the composition region markers point elsewhere.  */

  if (!NILP (f->conversion.compose_region_start))
    {
      Fset_marker (f->conversion.compose_region_start, Qnil, Qnil);
      Fset_marker (f->conversion.compose_region_end, Qnil, Qnil);
      f->conversion.compose_region_start = Qnil;
      f->conversion.compose_region_end = Qnil;

      /* Notify the IME of an update to the composition region,
	 inasmuch as the point might not change if START and END are
	 identical and TEXT is empty, among other circumstances.  */

      if (text_interface
	  && text_interface->compose_region_changed)
	(*text_interface->compose_region_changed) (f);
    }

  /* Delete the composition region overlay.  */

  if (!NILP (f->conversion.compose_region_overlay))
    Fdelete_overlay (f->conversion.compose_region_overlay);

  /* Temporarily switch to F's selected window at the time of the last
     redisplay.  */
  select_window (f->old_selected_window, Qt);

  /* Sort START and END by magnitude.  */
  new_start = min (start, end);
  new_end   = max (start, end);

  /* Now constrain both to the accessible region.  */

  if (new_start < BEGV)
    new_start = BEGV;
  else if (new_start > ZV)
    new_start = ZV;

  if (new_end < BEGV)
    new_end = BEGV;
  else if (new_end > ZV)
    new_end = ZV;

  start = new_start;
  end   = new_end;

  /* This should deactivate the mark.  */
  call0 (Qdeactivate_mark);

  /* Go to start.  */
  set_point (start);

  /* Now delete the text in between, and save PT before TEXT is
     inserted.  */
  del_range_1 (start, end, true, false);
  record_buffer_change (start, start, Qt);
  wanted = PT;

  /* So long as TEXT isn't empty, insert it now.  */

  if (SCHARS (text))
    {
      /* Insert the new text.  Make sure to inherit text properties
	 from the surroundings: if this doesn't happen, CC Mode
	 fontification might grow confused and become very slow.  */

      insert_from_string (text, 0, 0, SCHARS (text),
			  SBYTES (text), true);
      record_buffer_change (start, PT, text);
    }

  /* Now, move point to the position designated by POSITION.  */

  if (position <= 0)
    {
      if (INT_ADD_WRAPV (wanted, position, &wanted)
	  || wanted < BEGV)
	wanted = BEGV;

      if (wanted > ZV)
	wanted = ZV;

      set_point (wanted);
    }
  else
    {
      wanted = PT;

      if (INT_ADD_WRAPV (wanted, position - 1, &wanted)
	  || wanted > ZV)
	wanted = ZV;

      if (wanted < BEGV)
	wanted = BEGV;

      set_point (wanted);
    }

  /* Print some debugging information.  */
  TEXTCONV_DEBUG ("text inserted: %s, point now: %zd",
		  SSDATA (text), PT);

  /* Update the ephemeral last point.  */
  w = XWINDOW (selected_window);
  w->ephemeral_last_point = PT;
  unbind_to (count, Qnil);
}

/* Complete the edit specified by the counter value inside *TOKEN.  */

static void
complete_edit (void *token)
{
  if (text_interface && text_interface->notify_conversion)
    text_interface->notify_conversion (*(unsigned long *) token);
}

/* Context for complete_edit_check.  */

struct complete_edit_check_context
{
  /* The window.  */
  struct window *w;

  /* Whether or not editing was successful.  */
  bool check;
};

/* Convert PTR to CONTEXT.  If CONTEXT->check is false, then update
   CONTEXT->w's ephemeral last point and give it to the input method,
   the assumption being that an editing operation signaled.  */

static void
complete_edit_check (void *ptr)
{
  struct complete_edit_check_context *context;
  struct frame *f;

  context = ptr;

  if (!context->check)
    {
      /* Figure out the new position of point.  */
      context->w->ephemeral_last_point
	= window_point (context->w);

      /* See if the frame is still alive.  */

      f = WINDOW_XFRAME (context->w);

      if (!FRAME_LIVE_P (f))
	return;

      if (text_interface && text_interface->point_changed)
	{
	  if (f->conversion.batch_edit_count > 0)
	    f->conversion.batch_edit_flags |= PENDING_POINT_CHANGE;
	  else
	    text_interface->point_changed (f, context->w, NULL);
	}
    }
}

/* Process and free the text conversion ACTION.  F must be the frame
   on which ACTION will be performed.

   Value is the window which was used, or NULL.  */

static struct window *
handle_pending_conversion_events_1 (struct frame *f,
				    struct text_conversion_action *action)
{
  Lisp_Object data;
  enum text_conversion_operation operation;
  struct buffer *buffer UNINIT;
  struct window *w;
  specpdl_ref count;
  unsigned long token;
  struct complete_edit_check_context context;

  /* Next, process this action and free it.  */

  data = action->data;
  operation = action->operation;
  token = action->counter;
  xfree (action);

  /* Text conversion events can still arrive immediately after
     `conversion_disabled_p' becomes true.  In that case, process all
     events, but don't perform any associated actions.  */

  if (conversion_disabled_p ())
    return NULL;

  /* check is a flag used by complete_edit_check to determine whether
     or not the editing operation completed successfully.  */
  context.check = false;

  /* Make sure completion is signaled.  */
  count = SPECPDL_INDEX ();
  record_unwind_protect_ptr (complete_edit, &token);
  w = NULL;

  if (WINDOW_LIVE_P (f->old_selected_window))
    {
      w = XWINDOW (f->old_selected_window);
      buffer = XBUFFER (WINDOW_BUFFER (w));
      context.w = w;

      /* Notify the input method of any editing failures.  */
      record_unwind_protect_ptr (complete_edit_check, &context);
    }

  switch (operation)
    {
    case TEXTCONV_START_BATCH_EDIT:
      f->conversion.batch_edit_count++;
      break;

    case TEXTCONV_END_BATCH_EDIT:
      if (f->conversion.batch_edit_count > 0)
	f->conversion.batch_edit_count--;

      if (!WINDOW_LIVE_P (f->old_selected_window))
	break;

      if (f->conversion.batch_edit_flags & PENDING_POINT_CHANGE)
	text_interface->point_changed (f, w, buffer);

      if (f->conversion.batch_edit_flags & PENDING_COMPOSE_CHANGE)
	text_interface->compose_region_changed (f);

      f->conversion.batch_edit_flags = 0;
      break;

    case TEXTCONV_COMMIT_TEXT:
      really_commit_text (f, XFIXNUM (XCAR (data)), XCDR (data));
      break;

    case TEXTCONV_FINISH_COMPOSING_TEXT:
      really_finish_composing_text (f, !NILP (data));
      break;

    case TEXTCONV_SET_COMPOSING_TEXT:
      really_set_composing_text (f, XFIXNUM (XCAR (data)),
				 XCDR (data));
      break;

    case TEXTCONV_SET_COMPOSING_REGION:
      really_set_composing_region (f, XFIXNUM (XCAR (data)),
				   XFIXNUM (XCDR (data)));
      break;

    case TEXTCONV_SET_POINT_AND_MARK:
      really_set_point_and_mark (f, XFIXNUM (XCAR (data)),
				 XFIXNUM (XCDR (data)));
      break;

    case TEXTCONV_DELETE_SURROUNDING_TEXT:
      really_delete_surrounding_text (f, XFIXNUM (XCAR (data)),
				      XFIXNUM (XCDR (data)));
      break;

    case TEXTCONV_REQUEST_POINT_UPDATE:
      really_request_point_update (f);
      break;

    case TEXTCONV_BARRIER:
      if (kbd_fetch_ptr != kbd_store_ptr)
	emacs_abort ();

      /* Once a barrier is hit, synchronize F's selected window's
	 `ephemeral_last_point' with its current point.  The reason
	 for this is because otherwise a previous keyboard event may
	 have taken place without redisplay happening in between.  */

      if (w)
	w->ephemeral_last_point = window_point (w);
      break;

    case TEXTCONV_REPLACE_TEXT:
      really_replace_text (f, XFIXNUM (XCAR (data)),
			   XFIXNUM (XCAR (XCDR (data))),
			   XCAR (XCDR (XCDR (data))),
			   XFIXNUM (XCAR (XCDR (XCDR (XCDR (data))))));
      break;
    }

  /* Signal success.  */
  context.check = true;
  unbind_to (count, Qnil);

  return w;
}

/* Decrement the variable pointed to by *PTR.  */

static void
decrement_inside (void *ptr)
{
  int *i;

  i = ptr;
  (*i)--;
}

/* Process any outstanding text conversion events.
   This may run Lisp or signal.  */

void
handle_pending_conversion_events (void)
{
  struct frame *f;
  Lisp_Object tail, frame;
  struct text_conversion_action *action, *next;
  bool handled;
  static int inside;
  specpdl_ref count;
  ptrdiff_t last_point;
  struct window *w;

  handled = false;

  /* Reset Vtext_conversion_edits.  Do not do this if called
     reentrantly.  */

  if (!inside)
    Vtext_conversion_edits = Qnil;

  inside++;

  count = SPECPDL_INDEX ();
  record_unwind_protect_ptr (decrement_inside, &inside);

  FOR_EACH_FRAME (tail, frame)
    {
      f = XFRAME (frame);
      last_point = -1;
      w = NULL;

      /* Test if F has any outstanding conversion events.  Then
	 process them in bottom to up order.  */
      while (true)
	{
	  /* Update the input method if handled &&
	     w->ephemeral_last_point != last_point.  */
	  if (w && (last_point != w->ephemeral_last_point))
	    {
	      if (handled
		  && last_point != -1
		  && text_interface
		  && text_interface->point_changed)
		{
		  if (f->conversion.batch_edit_count > 0)
		    f->conversion.batch_edit_flags |= PENDING_POINT_CHANGE;
		  else
		    text_interface->point_changed (f, NULL, NULL);
		}

	      last_point = w->ephemeral_last_point;
	    }

	  /* Reload action.  This needs to be reentrant as buffer
	     modification functions can call `read-char'.  */
	  action = f->conversion.actions;

	  /* If there are no more actions, break.  */

	  if (!action)
	    break;

	  /* If action is a barrier event and the keyboard buffer is
	     not yet empty, break out of the loop.  */

	  if (action->operation == TEXTCONV_BARRIER
	      && kbd_store_ptr != kbd_fetch_ptr)
	    break;

	  /* Unlink this action.  */
	  next = action->next;
	  f->conversion.actions = next;

	  /* Handle and free the action.  */
	  w = handle_pending_conversion_events_1 (f, action);
	  handled = true;
	}
    }

  unbind_to (count, Qnil);
}

/* Start a ``batch edit'' in frame F.  During a batch edit,
   point_changed will not be called until the batch edit ends.

   Process the actual operation in the event loop in keyboard.c; then,
   call `notify_conversion' in the text conversion interface with
   COUNTER.  */

void
start_batch_edit (struct frame *f, unsigned long counter)
{
  struct text_conversion_action *action, **last;

  action = xmalloc (sizeof *action);
  action->operation = TEXTCONV_START_BATCH_EDIT;
  action->data = Qnil;
  action->next = NULL;
  action->counter = counter;
  for (last = &f->conversion.actions; *last; last = &(*last)->next)
    ;;
  *last = action;
  input_pending = true;
}

/* End a ``batch edit''.  It is ok to call this function even if a
   batch edit has not yet started, in which case it does nothing.

   COUNTER means the same as in `start_batch_edit'.  */

void
end_batch_edit (struct frame *f, unsigned long counter)
{
  struct text_conversion_action *action, **last;

  action = xmalloc (sizeof *action);
  action->operation = TEXTCONV_END_BATCH_EDIT;
  action->data = Qnil;
  action->next = NULL;
  action->counter = counter;
  for (last = &f->conversion.actions; *last; last = &(*last)->next)
    ;;
  *last = action;
  input_pending = true;
}

/* Insert the specified STRING into frame F's selected-window's
   buffer's composition region, and set point to POSITION relative to
   STRING.

   If there is no composition region, use the active region instead.
   If that doesn't exist either, insert STRING after point.

   COUNTER means the same as in `start_batch_edit'.  */

void
commit_text (struct frame *f, Lisp_Object string,
	     ptrdiff_t position, unsigned long counter)
{
  struct text_conversion_action *action, **last;

  action = xmalloc (sizeof *action);
  action->operation = TEXTCONV_COMMIT_TEXT;
  action->data = Fcons (make_fixnum (position), string);
  action->next = NULL;
  action->counter = counter;
  for (last = &f->conversion.actions; *last; last = &(*last)->next)
    ;;
  *last = action;
  input_pending = true;
}

/* Remove the composition region and its overlay from frame F's
   selected-window's current buffer.  Leave the text being composed
   intact.

   If UPDATE, call `compose_region_changed' after the region is
   removed.

   COUNTER means the same as in `start_batch_edit'.  */

void
finish_composing_text (struct frame *f, unsigned long counter,
		       bool update)
{
  struct text_conversion_action *action, **last;

  action = xmalloc (sizeof *action);
  action->operation = TEXTCONV_FINISH_COMPOSING_TEXT;
  action->data = update ? Qt : Qnil;
  action->next = NULL;
  action->counter = counter;
  for (last = &f->conversion.actions; *last; last = &(*last)->next)
    ;;
  *last = action;
  input_pending = true;
}

/* Insert the given STRING and make it the currently active
   composition.

   If there is currently no composing or active region, then the new
   value of point is used as the composing region.

   Then, the composing or active region is replaced with the text in
   the specified string.

   Finally, move point to new_point, which is relative to either the
   start or the end of OBJECT depending on whether or not it is less
   than zero.

   COUNTER means the same as in `start_batch_edit'.  */

void
set_composing_text (struct frame *f, Lisp_Object object,
		    ptrdiff_t new_point, unsigned long counter)
{
  struct text_conversion_action *action, **last;

  action = xmalloc (sizeof *action);
  action->operation = TEXTCONV_SET_COMPOSING_TEXT;
  action->data = Fcons (make_fixnum (new_point),
			object);
  action->next = NULL;
  action->counter = counter;
  for (last = &f->conversion.actions; *last; last = &(*last)->next)
    ;;
  *last = action;
  input_pending = true;
}

/* Make the region between START and END the currently active
   ``composing region'' on frame F.

   The ``composing region'' is a region of text in the buffer that is
   about to undergo editing by the input method.  */

void
set_composing_region (struct frame *f, ptrdiff_t start,
		      ptrdiff_t end, unsigned long counter)
{
  struct text_conversion_action *action, **last;

  if (start > MOST_POSITIVE_FIXNUM)
    start = MOST_POSITIVE_FIXNUM;

  if (end > MOST_POSITIVE_FIXNUM)
    end = MOST_POSITIVE_FIXNUM;

  action = xmalloc (sizeof *action);
  action->operation = TEXTCONV_SET_COMPOSING_REGION;
  action->data = Fcons (make_fixnum (start),
			make_fixnum (end));
  action->next = NULL;
  action->counter = counter;
  for (last = &f->conversion.actions; *last; last = &(*last)->next)
    ;;
  *last = action;
  input_pending = true;
}

/* Move point in frame F's selected-window's buffer to POINT and maybe
   push MARK.

   COUNTER means the same as in `start_batch_edit'.  */

void
textconv_set_point_and_mark (struct frame *f, ptrdiff_t point,
			     ptrdiff_t mark, unsigned long counter)
{
  struct text_conversion_action *action, **last;

  if (point > MOST_POSITIVE_FIXNUM)
    point = MOST_POSITIVE_FIXNUM;

  action = xmalloc (sizeof *action);
  action->operation = TEXTCONV_SET_POINT_AND_MARK;
  action->data = Fcons (make_fixnum (point),
			make_fixnum (mark));
  action->next = NULL;
  action->counter = counter;
  for (last = &f->conversion.actions; *last; last = &(*last)->next)
    ;;
  *last = action;
  input_pending = true;
}

/* Delete LEFT and RIGHT characters around point in frame F's old
   selected window.  */

void
delete_surrounding_text (struct frame *f, ptrdiff_t left,
			 ptrdiff_t right, unsigned long counter)
{
  struct text_conversion_action *action, **last;

  action = xmalloc (sizeof *action);
  action->operation = TEXTCONV_DELETE_SURROUNDING_TEXT;
  action->data = Fcons (make_fixnum (left),
			make_fixnum (right));
  action->next = NULL;
  action->counter = counter;
  for (last = &f->conversion.actions; *last; last = &(*last)->next)
    ;;
  *last = action;
  input_pending = true;
}

/* Request an immediate call to TEXT_INTERFACE->point_changed with the
   new details of frame F's region unless a batch edit is in
   progress.  */

void
request_point_update (struct frame *f, unsigned long counter)
{
  struct text_conversion_action *action, **last;

  action = xmalloc (sizeof *action);
  action->operation = TEXTCONV_REQUEST_POINT_UPDATE;
  action->data = Qnil;
  action->next = NULL;
  action->counter = counter;
  for (last = &f->conversion.actions; *last; last = &(*last)->next)
    ;;
  *last = action;
  input_pending = true;
}

/* Request that text conversion on frame F pause until the keyboard
   buffer becomes empty.

   Use this function to ensure that edits associated with a keyboard
   event complete before the text conversion edits after the barrier
   take place.  */

void
textconv_barrier (struct frame *f, unsigned long counter)
{
  struct text_conversion_action *action, **last;

  action = xmalloc (sizeof *action);
  action->operation = TEXTCONV_BARRIER;
  action->data = Qnil;
  action->next = NULL;
  action->counter = counter;
  for (last = &f->conversion.actions; *last; last = &(*last)->next)
    ;;
  *last = action;
  input_pending = true;
}

/* Remove the composing region.  Replace the text between START and
   END within F's selected window with TEXT; deactivate the mark if it
   is active.  Subsequently, set point to POSITION relative to TEXT,
   much as `commit_text' would.  */

void
replace_text (struct frame *f, ptrdiff_t start, ptrdiff_t end,
	      Lisp_Object text, ptrdiff_t position,
	      unsigned long counter)
{
  struct text_conversion_action *action, **last;

  action = xmalloc (sizeof *action);
  action->operation = TEXTCONV_REPLACE_TEXT;
  action->data = list4 (make_fixnum (start), make_fixnum (end),
			text, make_fixnum (position));
  action->next = NULL;
  action->counter = counter;
  for (last = &f->conversion.actions; *last; last = &(*last)->next)
    ;;
  *last = action;
  input_pending = true;
}

/* Return N characters of text around point in frame F's old selected
   window.

   If N is -1, return the text between point and mark instead, given
   that the mark is active.

   Set *START_RETURN to the position of the first character returned,
   *START_OFFSET to the offset of the lesser of mark and point within
   that text, *END_OFFSET to the greater of mark and point within that
   text, and *LENGTH to the actual number of characters returned,
   *BYTES to the actual number of bytes returned, and *MARK_ACTIVE to
   whether or not the mark is active.

   Value is NULL upon failure, and a malloced string upon success.  */

char *
get_extracted_text (struct frame *f, ptrdiff_t n,
		    ptrdiff_t *start_return,
		    ptrdiff_t *start_offset,
		    ptrdiff_t *end_offset, ptrdiff_t *length,
		    ptrdiff_t *bytes, bool *mark_active)
{
  specpdl_ref count;
  ptrdiff_t start, end, start_byte, end_byte, mark;
  char *buffer;

  if (!WINDOW_LIVE_P (f->old_selected_window))
    return NULL;

  /* Save the excursion, as there will be extensive changes to the
     selected window.  */
  count = SPECPDL_INDEX ();
  record_unwind_protect_excursion ();

  /* Inhibit quitting.  */
  specbind (Qinhibit_quit, Qt);

  /* Temporarily switch to F's selected window at the time of the last
     redisplay.  */
  select_window (f->old_selected_window, Qt);
  buffer = NULL;

  /* Figure out the bounds of the text to return.  */
  if (n != -1)
    {
      /* Make sure n is at least 4, leaving two characters around
	 PT.  */
      n = max (4, n);

      start = PT - n / 2;
      end = PT + n - n / 2;
    }
  else
    {
      if (!NILP (BVAR (current_buffer, mark_active))
	  && XMARKER (BVAR (current_buffer, mark))->buffer)
	{
	  start = marker_position (BVAR (current_buffer, mark));
	  end = PT;

	  /* Sort start and end.  start_byte is used to hold a
	     temporary value.  */

	  if (start > end)
	    {
	      start_byte = end;
	      end = start;
	      start = start_byte;
	    }
	}
      else
	goto finish;
    }

  start = max (start, BEGV);
  end = min (end, ZV);

  /* Detect overflow.  */

  if (!(start <= PT && PT <= end))
    goto finish;

  /* Convert the character positions to byte positions.  */
  start_byte = CHAR_TO_BYTE (start);
  end_byte = CHAR_TO_BYTE (end);

  /* Extract the text from the buffer.  */
  buffer = xmalloc (end_byte - start_byte);
  copy_buffer_text (start, start_byte, end, end_byte, buffer);

  /* Get the mark.  If it's not active, use PT.  */

  mark = get_mark ();
  *mark_active = true;

  if (mark == -1)
    {
      mark = PT;
      *mark_active = false;
    }

  /* Return the offsets.  */
  *start_return = start;
  *start_offset = min (mark - start, PT - start);
  *end_offset = max (mark - start, PT - start);
  *length = end - start;
  *bytes = end_byte - start_byte;

  TEXTCONV_DEBUG ("get_extracted_text: PT, mark, start: %td, %td, %td",
		  PT, mark, start);

 finish:
  unbind_to (count, Qnil);
  return buffer;
}

/* Return the text between the positions pt - LEFT and pt + RIGHT,
   where pt is the position of point in frame F's selected window.  If
   the mark is active, return the range of text relative to the bounds
   of the region instead.

   Set *LENGTH to the number of characters returned, *BYTES to the
   number of bytes returned, *OFFSET to the character position of the
   returned text, and *START_RETURN and *END_RETURN to the mark and
   point relative to that position.  */

char *
get_surrounding_text (struct frame *f, ptrdiff_t left,
		      ptrdiff_t right, ptrdiff_t *length,
		      ptrdiff_t *bytes, ptrdiff_t *offset,
		      ptrdiff_t *start_return,
		      ptrdiff_t *end_return)
{
  specpdl_ref count;
  ptrdiff_t start, end, start_byte, end_byte, mark, temp;
  char *buffer;

  if (!WINDOW_LIVE_P (f->old_selected_window))
    return NULL;

  /* Save the excursion, as there will be extensive changes to the
     selected window.  */
  count = SPECPDL_INDEX ();
  record_unwind_protect_excursion ();

  /* Inhibit quitting.  */
  specbind (Qinhibit_quit, Qt);

  /* Temporarily switch to F's selected window at the time of the last
     redisplay.  */
  select_window (f->old_selected_window, Qt);
  buffer = NULL;

  /* Figure out the bounds of the text to return.  */

  /* First, obtain start and end.  */
  end = get_mark ();
  start = PT;

  /* If the mark is not active, make it start and end.  */

  if (end == -1)
    end = start;

  /* Now sort start and end.  */

  if (end < start)
    {
      temp = start;
      start = end;
      end = temp;
    }

  /* And subtract left and right.  */

  if (INT_SUBTRACT_WRAPV (start, left, &start)
      || INT_ADD_WRAPV (end, right, &end))
    goto finish;

  start = max (start, BEGV);
  end = min (end, ZV);

  /* Detect overflow.  */

  if (!(start <= PT && PT <= end))
    goto finish;

  /* Convert the character positions to byte positions.  */
  start_byte = CHAR_TO_BYTE (start);
  end_byte = CHAR_TO_BYTE (end);

  /* Extract the text from the buffer.  */
  buffer = xmalloc (end_byte - start_byte);
  copy_buffer_text (start, start_byte, end, end_byte, buffer);

  /* Get the mark.  If it's not active, use PT.  */

  mark = get_mark ();

  if (mark == -1)
    mark = PT;

  /* Return the offsets.  Unlike `get_extracted_text', this need not
     sort mark and point.  */

  *offset = start;
  *start_return = mark - start;
  *end_return = PT - start;
  *length = end - start;
  *bytes = end_byte - start_byte;

 finish:
  unbind_to (count, Qnil);
  return buffer;
}

/* Return whether or not text conversion is temporarily disabled.
   `reset' should always call this to determine whether or not to
   disable the input method.  */

bool
conversion_disabled_p (void)
{
  return suppress_conversion_count > 0;
}



/* Window system interface.  These are called from the rest of
   Emacs.  */

/* Notice that frame F's selected window has been set from redisplay.
   Reset F's input method state.  */

void
report_selected_window_change (struct frame *f)
{
  struct window *w;

  reset_frame_state (f);

  if (!text_interface)
    return;

  /* When called from window.c, F's selected window has already been
     redisplayed, but w->last_point has not yet been updated.  Update
     it here to avoid race conditions when the IM asks for the initial
     selection position immediately after.  */

  if (WINDOWP (f->selected_window))
    {
      w = XWINDOW (f->selected_window);
      w->ephemeral_last_point = window_point (w);
    }

  text_interface->reset (f);
}

/* Notice that point in frame F's selected window's current buffer has
   changed.

   F is the frame whose selected window was changed, WINDOW is the
   window in question, and BUFFER is that window's buffer.

   Tell the text conversion interface about the change; it will likely
   pass the information on to the system input method.  */

void
report_point_change (struct frame *f, struct window *window,
		     struct buffer *buffer)
{
  if (!text_interface || !text_interface->point_changed)
    return;

  if (f->conversion.batch_edit_count > 0)
    f->conversion.batch_edit_flags |= PENDING_POINT_CHANGE;
  else
    text_interface->point_changed (f, window, buffer);
}

/* Temporarily disable text conversion.  Must be paired with a
   corresponding call to resume_text_conversion.  */

void
disable_text_conversion (void)
{
  Lisp_Object tail, frame;
  struct frame *f;

  suppress_conversion_count++;

  if (!text_interface || suppress_conversion_count > 1)
    return;

  /* Loop through and reset the input method on each window system
     frame.  It should call conversion_disabled_p and then DTRT.  */

  FOR_EACH_FRAME (tail, frame)
    {
      f = XFRAME (frame);
      reset_frame_state (f);

      if (FRAME_WINDOW_P (f) && FRAME_VISIBLE_P (f))
	text_interface->reset (f);
    }
}

/* Undo the effect of the last call to `disable_text_conversion'.  */

void
resume_text_conversion (void)
{
  Lisp_Object tail, frame;
  struct frame *f;

  suppress_conversion_count--;
  eassert (suppress_conversion_count >= 0);

  if (!text_interface || suppress_conversion_count)
    return;

  /* Loop through and reset the input method on each window system
     frame.  It should call conversion_disabled_p and then DTRT.  */

  FOR_EACH_FRAME (tail, frame)
    {
      f = XFRAME (frame);
      reset_frame_state (f);

      if (FRAME_WINDOW_P (f) && FRAME_VISIBLE_P (f))
	text_interface->reset (f);
    }
}

/* Register INTERFACE as the text conversion interface.  */

void
register_textconv_interface (struct textconv_interface *interface)
{
  text_interface = interface;
}



/* List of buffers whose text conversion state will be reset after a
   key sequence is read.  */
static Lisp_Object postponed_buffers;

/* Reset the text conversion style of each frame whose selected buffer
   is contained inside `postponed_buffers'.  Set `postponed_buffers'
   to nil.  */

void
check_postponed_buffers (void)
{
  Lisp_Object buffer, tail, frame;
  struct buffer *b;
  struct frame *f;

  buffer = postponed_buffers;
  postponed_buffers = Qnil;

  if (!text_interface->reset)
    return;

  FOR_EACH_TAIL (buffer)
    {
      b = XBUFFER (XCAR (buffer));

      /* Continue if this is a dead buffer.  */

      if (!BUFFER_LIVE_P (b))
	continue;

      /* If no windows are displaying B anymore, continue.  */

      if (!buffer_window_count (b))
	continue;

      /* Look for frames which have B selected.  */

      FOR_EACH_FRAME (tail, frame)
	{
	  f = XFRAME (frame);

	  if (WINDOW_LIVE_P (f->old_selected_window)
	      && FRAME_WINDOW_P (f)
	      /* N.B. that the same frame can't be reset twice as long
		 as the list of buffers remains unique.  */
	      && EQ (XWINDOW (f->old_selected_window)->contents,
		     XCAR (buffer)))
	    {
	      block_input ();
	      reset_frame_state (f);
	      text_interface->reset (f);
	      unblock_input ();
	    }
	}
    }
}

/* Lisp interface.  */

DEFUN ("set-text-conversion-style", Fset_text_conversion_style,
       Sset_text_conversion_style, 1, 2, 0,
       doc: /* Set the current buffer's text conversion style to VALUE.

After setting `text-conversion-style', force input methods
editing in a selected window displaying this buffer on any frame
to stop themselves.

This can lead to a significant amount of time being taken by the input
method resetting itself, so you should not use this function lightly;
instead, set `text-conversion-style' before your buffer is displayed,
and let redisplay manage the input method appropriately.

If a key sequence is currently being read (either through the command
loop or by a call to `read-key-sequence') and AFTER-KEY-SEQUENCE is
non-nil, don't perform changes to the input method until the key
sequence is read.  This is useful within a function bound to
`input-decode-map' or `local-function-key-map', as it prevents the
input method from being redundantly enabled according to VALUE if the
replacement key sequence returned starts a new key sequence and makes
`read-key-sequence' disable text conversion again.  */)
  (Lisp_Object value, Lisp_Object after_key_sequence)
{
  Lisp_Object tail, frame;
  struct frame *f;
  Lisp_Object buffer;

  bset_text_conversion_style (current_buffer, value);

  if (!text_interface)
    return Qnil;

  /* If there are any selected windows displaying this buffer, reset
     text conversion on their associated frames.  */

  if (buffer_window_count (current_buffer))
    {
      buffer = Fcurrent_buffer ();

      /* Postpone changes to the actual text conversion state if
	 AFTER_KEY_SEQUENCE is non-nil and a key sequence is being
	 read.  */

      if (reading_key_sequence && !NILP (after_key_sequence))
	{
	  if (NILP (Fmemq (buffer, postponed_buffers)))
	    /* `check_postponed_buffers' will hopefully be called soon
	       enough to avoid postponed_buffers growing
	       indefinitely.  */
	    postponed_buffers = Fcons (buffer, postponed_buffers);
	  return Qnil;
	}

      FOR_EACH_FRAME (tail, frame)
	{
	  f = XFRAME (frame);

	  if (WINDOW_LIVE_P (f->old_selected_window)
	      && FRAME_WINDOW_P (f)
	      && (EQ (XWINDOW (f->old_selected_window)->contents,
		      buffer)
		  /* Always reset the text conversion style of the
		     selected frame.  */
		  || (f == SELECTED_FRAME ())))
	    {
	      block_input ();
	      reset_frame_state (f);
	      text_interface->reset (f);
	      unblock_input ();
	    }
	}
    }

  return Qnil;
}



void
syms_of_textconv (void)
{
  DEFSYM (Qaction, "action");
  DEFSYM (Qtext_conversion, "text-conversion");
  DEFSYM (Qpush_mark, "push-mark");
  DEFSYM (Qunderline, "underline");
  DEFSYM (Qoverriding_text_conversion_style,
	  "overriding-text-conversion-style");

  DEFVAR_LISP ("text-conversion-edits", Vtext_conversion_edits,
    doc: /* List of buffers that were last edited as result of text conversion.

This list can be used while handling a `text-conversion' event to
determine which changes have taken place.

Each element of the list describes a single edit in a buffer, and
is of the form:

    (BUFFER BEG END EPHEMERAL)

If an insertion or an edit to the buffer text is described, then BEG
and END are markers which denote the bounds of the text that was
changed or inserted.  If a deletion is described, then BEG and END are
the same object.

If EPHEMERAL is t, then the input method is preparing to make further
edits to the text, so any actions that would otherwise be taken, such
as indenting or automatically filling text, should not take place.

Otherwise, it is either a string containing text that was inserted,
text deleted before point, or nil if text was deleted after point.

The list contents are ordered in the reverse order of editing, i.e.
the latest edit first, so you must iterate through the list in reverse.  */);
  Vtext_conversion_edits = Qnil;

  DEFVAR_LISP ("overriding-text-conversion-style",
	       Voverriding_text_conversion_style,
    doc: /* Non-buffer local version of `text-conversion-style'.

If this variable is the symbol `lambda', it means to consult the
buffer-local value of `text-conversion-style' to determine whether or
not to activate the input method.  Otherwise, the value is used in
preference to any buffer-local value of `text-conversion-style'.  */);
  Voverriding_text_conversion_style = Qlambda;

  DEFVAR_LISP ("text-conversion-face", Vtext_conversion_face,
    doc: /* Face in which to display temporary edits by an input method.
The value nil means to display no indication of a temporary edit.  */);
  Vtext_conversion_face = Qunderline;

  defsubr (&Sset_text_conversion_style);

  postponed_buffers = Qnil;
  staticpro (&postponed_buffers);
}