summaryrefslogtreecommitdiff
path: root/usr.bin/vim/fileio.c
blob: fc37d542d6c46f6f1bb0f53ab9e21f25df2009bc (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
/*	$OpenBSD: fileio.c,v 1.3 1996/10/14 03:55:11 downsj Exp $	*/
/* vi:set ts=4 sw=4:
 *
 * VIM - Vi IMproved		by Bram Moolenaar
 *
 * Do ":help uganda"  in Vim to read copying and usage conditions.
 * Do ":help credits" in Vim to see a list of people who contributed.
 */

/*
 * fileio.c: read from and write to a file
 */

#if defined MSDOS  ||  defined WIN32
# include <io.h>		/* for lseek(), must be before vim.h */
#endif

#include "vim.h"
#include "globals.h"
#include "proto.h"
#include "option.h"
#ifdef HAVE_FCNTL_H
# include <fcntl.h>
#endif

#ifdef LATTICE
# include <proto/dos.h>		/* for Lock() and UnLock() */
#endif

#define BUFSIZE		8192			/* size of normal write buffer */
#define SBUFSIZE	256				/* size of emergency write buffer */

#ifdef VIMINFO
static void check_marks_read __ARGS((void));
#endif
static void msg_add_fname __ARGS((BUF *, char_u *));
static int msg_add_textmode __ARGS((int));
static void msg_add_lines __ARGS((int, long, long));
static void msg_add_eol __ARGS((void));
static int  write_buf __ARGS((int, char_u *, int));

static linenr_t	write_no_eol_lnum = 0; 	/* non-zero lnum when last line of
										   next binary write should not have
										   an end-of-line */

	void
filemess(buf, name, s)
	BUF			*buf;
	char_u		*name;
	char_u		*s;
{
	msg_add_fname(buf, name);		/* put file name in IObuff with quotes */
	STRCAT(IObuff, s);
	/*
	 * For the first message may have to start a new line.
	 * For further ones overwrite the previous one, reset msg_scroll before
	 * calling filemess().
	 */
	msg_start();
	msg_outtrans(IObuff);
	stop_highlight();
	msg_clr_eos();
	flushbuf();
}

/*
 * Read lines from file 'fname' into the buffer after line 'from'.
 *
 * 1. We allocate blocks with lalloc, as big as possible.
 * 2. Each block is filled with characters from the file with a single read().
 * 3. The lines are inserted in the buffer with ml_append().
 *
 * (caller must check that fname != NULL)
 *
 * lines_to_skip is the number of lines that must be skipped
 * lines_to_read is the number of lines that are appended
 * When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM.
 *
 * return FAIL for failure, OK otherwise
 */
	int
readfile(fname, sfname, from, newfile, lines_to_skip, lines_to_read, filtering)
	char_u		   *fname;
	char_u		   *sfname;
	linenr_t		from;
	int				newfile;
	linenr_t		lines_to_skip;
	linenr_t		lines_to_read;
	int				filtering;
{
	int 				fd;
	register char_u 	c;
	register linenr_t	lnum = from;
	register char_u 	*ptr = NULL;			/* pointer into read buffer */
	register char_u		*buffer = NULL;			/* read buffer */
	char_u				*new_buffer = NULL;		/* init to shut up gcc */
	char_u				*line_start = NULL;		/* init to shut up gcc */
	colnr_t				len;
	register long		size;
	register char_u		*p;
	long				filesize = 0;
	int					split = 0;				/* number of split lines */
#define UNKNOWN		0x0fffffff					/* file size is unknown */
	linenr_t			linecnt;
	int 				error = FALSE;			/* errors encountered */
	int					tx_error = FALSE;		/* textmode, but no CR */
	long				linerest = 0;			/* remaining chars in line */
	int					firstpart = TRUE;		/* reading first part */
#ifdef UNIX
	int					perm;
#endif
	int					textmode;				/* accept CR-LF linebreak */
	struct stat			st;
	int					file_readonly;
	linenr_t			skip_count = lines_to_skip;
	linenr_t			read_count = lines_to_read;
	int					msg_save = msg_scroll;
	linenr_t			read_no_eol_lnum = 0; 	/* non-zero lnum when last
												   line of last read was
												   missing the eol */


#ifdef AUTOCMD
	write_no_eol_lnum = 0;		/* in case it was set by the previous read */
#endif

	/*
	 * If there is no file name yet, use the one for the read file.
	 * b_notedited is set to reflect this.
	 * Don't do this for a read from a filter.
	 * Only do this when 'cpoptions' contains the 'f' flag.
	 */
	if (curbuf->b_filename == NULL && !filtering &&
										vim_strchr(p_cpo, CPO_FNAMER) != NULL)
	{
		if (setfname(fname, sfname, FALSE) == OK)
			curbuf->b_notedited = TRUE;
	}

	if (shortmess(SHM_OVER) || curbuf->b_help)
		msg_scroll = FALSE;		/* overwrite previous file message */
	else
		msg_scroll = TRUE;		/* don't overwrite previous file message */
	if (sfname == NULL)
		sfname = fname;
	/*
	 * For Unix: Use the short filename whenever possible.
	 * Avoids problems with networks and when directory names are changed.
	 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
	 * another directory, which we don't detect.
	 */
#if defined(UNIX) || defined(__EMX__)
	if (!did_cd)
		fname = sfname;
#endif

#ifdef UNIX
	/*
	 * On Unix it is possible to read a directory, so we have to
	 * check for it before the open().
	 */
	perm = getperm(fname);
# ifdef _POSIX_SOURCE
	if (perm >= 0 && !S_ISREG(perm)	 				/* not a regular file ... */
#  ifdef S_ISFIFO
				  && !S_ISFIFO(perm)				/* ... or fifo or socket */
#  endif
										   )
# else
	if (perm >= 0 && (perm & S_IFMT) != S_IFREG		/* not a regular file ... */
#  ifdef S_IFIFO
				  && (perm & S_IFMT) != S_IFIFO		/* ... or fifo ... */
#  endif
#  ifdef S_IFSOCK
				  && (perm & S_IFMT) != S_IFSOCK	/* ... or socket */
#  endif
											)
# endif
	{
# ifdef _POSIX_SOURCE
		if (S_ISDIR(perm))
# else
		if ((perm & S_IFMT) == S_IFDIR)
# endif
			filemess(curbuf, fname, (char_u *)"is a directory");
		else
			filemess(curbuf, fname, (char_u *)"is not a file");
		msg_scroll = msg_save;
		return FAIL;
	}
#endif

	/*
	 * When opening a new file we take the readonly flag from the file.
	 * Default is r/w, can be set to r/o below.
	 * Don't reset it when in readonly mode
	 */
	if (newfile && !readonlymode)			/* default: set file not readonly */
		curbuf->b_p_ro = FALSE;

	if (newfile)
	{
		if (stat((char *)fname, &st) >= 0)	/* remember time of file */
		{
			curbuf->b_mtime = st.st_mtime;
			curbuf->b_mtime_read = st.st_mtime;
#ifdef UNIX
			/*
			 * Set the protection bits of the swap file equal to the original
			 * file. This makes it possible for others to read the name of the
			 * original file from the swapfile.
			 */
			if (curbuf->b_ml.ml_mfp->mf_fname != NULL)
				(void)setperm(curbuf->b_ml.ml_mfp->mf_fname,
												  (st.st_mode & 0777) | 0600);
#endif
		}
		else
		{
			curbuf->b_mtime = 0;
			curbuf->b_mtime_read = 0;
		}
	}

/*
 * for UNIX: check readonly with perm and access()
 * for MSDOS and Amiga: check readonly by trying to open the file for writing
 */
	file_readonly = FALSE;
#if defined(UNIX) || defined(DJGPP) || defined(__EMX__)
	if (
# ifdef UNIX
		!(perm & 0222) ||
# endif
							access((char *)fname, W_OK))
		file_readonly = TRUE;
	fd = open((char *)fname, O_RDONLY | O_EXTRA);
#else
	if (!newfile || readonlymode || (fd =
								   open((char *)fname, O_RDWR | O_EXTRA)) < 0)
	{
		file_readonly = TRUE;
		fd = open((char *)fname, O_RDONLY | O_EXTRA);	/* try to open ro */
	}
#endif

	if (fd < 0)					 /* cannot open at all */
	{
#ifndef UNIX
		int		isdir_f;
#endif
		msg_scroll = msg_save;
#ifndef UNIX
	/*
	 * On MSDOS and Amiga we can't open a directory, check here.
	 */
		isdir_f = (mch_isdir(fname));
		/* replace with short name now, for the messages */
		if (!did_cd)
			fname = sfname;
		if (isdir_f)
			filemess(curbuf, fname, (char_u *)"is a directory");
		else
#endif
			if (newfile)
			{
#ifdef UNIX
				if (perm < 0)
#endif
				{
					filemess(curbuf, fname, (char_u *)"[New File]");
#ifdef AUTOCMD
					apply_autocmds(EVENT_BUFNEWFILE, fname, fname);
#endif
					return OK;		/* a new file is not an error */
				}
#ifdef UNIX
				else
					filemess(curbuf, fname, (char_u *)"[Permission Denied]");
#endif
			}

		return FAIL;
	}

	/*
	 * Only set the 'ro' flag for readonly files the first time they are
	 * loaded.
	 * Help files always get readonly mode
	 */
	if ((newfile && file_readonly) || curbuf->b_help)
		curbuf->b_p_ro = TRUE;

	if (newfile)
		curbuf->b_p_eol = TRUE;

#ifndef UNIX
	/* replace with short name now, for the messages */
	if (!did_cd)
		fname = sfname;
#endif
	++no_wait_return;							/* don't wait for return yet */

	/*
	 * Set '[ mark to the line above where the lines go (line 1 if zero).
	 */
	curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
	curbuf->b_op_start.col = 0;

#ifdef AUTOCMD
	{
		int	m = msg_scroll;
		int n = msg_scrolled;
		BUF	*old_curbuf = curbuf;

		/*
		 * The file must be closed again, the autocommands may want to change
		 * the file before reading it.
		 */
		close(fd);			/* ignore errors */

		/*
		 * The output from the autocommands should not overwrite anything and
		 * should not be overwritten: Set msg_scroll, restore its value if no
		 * output was done.
		 */
		msg_scroll = TRUE;
		if (filtering)
			apply_autocmds(EVENT_FILTERREADPRE, NULL, fname);
		else if (newfile)
			apply_autocmds(EVENT_BUFREADPRE, NULL, fname);
		else
			apply_autocmds(EVENT_FILEREADPRE, fname, fname);
		if (msg_scrolled == n)
			msg_scroll = m;

		/*
		 * Don't allow the autocommands to change the current buffer.
		 * Try to re-open the file.
		 */
		if (curbuf != old_curbuf ||
						   (fd = open((char *)fname, O_RDONLY | O_EXTRA)) < 0)
		{
			--no_wait_return;
			msg_scroll = msg_save;
			if (fd < 0)
				EMSG("*ReadPre autocommands made the file unreadable");
			else
				EMSG("*ReadPre autocommands must not change current buffer");
			return FAIL;
		}
	}
#endif

	if (!recoverymode && !filtering)
		filemess(curbuf, fname, (char_u *)"");	/* show that we are busy */

	msg_scroll = FALSE;							/* overwrite the file message */

	/*
	 * Set textmode and linecnt now, before the "retry" caused by 'textauto'
	 * and after the autocommands, which may change them.
	 */
	textmode = curbuf->b_p_tx;
	linecnt = curbuf->b_ml.ml_line_count;

retry:
	while (!error && !got_int)
	{
		/*
		 * We allocate as much space for the file as we can get, plus
		 * space for the old line plus room for one terminating NUL.
		 * The amount is limited by the fact that read() only can read
		 * upto max_unsigned characters (and other things).
		 */
#if SIZEOF_INT <= 2
		if (linerest >= 0x7ff0)
		{
			++split;
			*ptr = NL;				/* split line by inserting a NL */
			size = 1;
		}
		else
#endif
		{
#if SIZEOF_INT > 2
			size = 0x10000L;				/* use buffer >= 64K */
#else
			size = 0x7ff0L - linerest;		/* limit buffer to 32K */
#endif

			for ( ; size >= 10; size >>= 1)
			{
				if ((new_buffer = lalloc((long_u)(size + linerest + 1), FALSE)) != NULL)
					break;
			}
			if (new_buffer == NULL)
			{
				do_outofmem_msg();
				error = TRUE;
				break;
			}
			if (linerest)		/* copy characters from the previous buffer */
				vim_memmove(new_buffer, ptr - linerest, (size_t)linerest);
			vim_free(buffer);
			buffer = new_buffer;
			ptr = buffer + linerest;
			line_start = buffer;
			
			if ((size = read(fd, (char *)ptr, (size_t)size)) <= 0)
			{
				if (size < 0)				/* read error */
					error = TRUE;
				break;
			}
			filesize += size;				/* count the number of characters */

			/*
			 * when reading the first part of a file: guess EOL type
			 */
			if (firstpart && p_ta)
			{
				for (p = ptr; p < ptr + size; ++p)
					if (*p == NL)
					{
						if (p > ptr && p[-1] == CR)	/* found CR-NL */
							textmode = TRUE;
						else						/* found a single NL */
							textmode = FALSE;
							/* if editing a new file: may set p_tx */
						if (newfile)
							curbuf->b_p_tx = textmode;
						break;
					}
			}
		}

		firstpart = FALSE;

		/*
		 * This loop is executed once for every character read.
		 * Keep it fast!
		 */
		--ptr;
		while (++ptr, --size >= 0)
		{
			if ((c = *ptr) != NUL && c != NL)	/* catch most common case */
				continue;
			if (c == NUL)
				*ptr = NL;		/* NULs are replaced by newlines! */
			else
			{
				if (skip_count == 0)
				{
					*ptr = NUL;		/* end of line */
					len = ptr - line_start + 1;
					if (textmode)
					{
						if (ptr[-1] == CR)	/* remove CR */
						{
							ptr[-1] = NUL;
							--len;
						}
						/*
						 * Reading in textmode, but no CR-LF found!
						 * When 'textauto' set, delete all the lines read so
						 * far and start all over again.
						 * Otherwise give an error message later.
						 */
						else if (!tx_error)
						{
							if (p_ta && lseek(fd, 0L, SEEK_SET) == 0)
							{
								while (lnum > from)
									ml_delete(lnum--, FALSE);
								textmode = FALSE;
								if (newfile)
									curbuf->b_p_tx = FALSE;
								linerest = 0;
								filesize = 0;
								skip_count = lines_to_skip;
								read_count = lines_to_read;
								goto retry;
							}
							else
								tx_error = TRUE;
						}
					}
					if (ml_append(lnum, line_start, len, newfile) == FAIL)
					{
						error = TRUE;
						break;
					}
					++lnum;
					if (--read_count == 0)
					{
						error = TRUE;		/* break loop */
						line_start = ptr;	/* nothing left to write */
						break;
					}
				}
				else
					--skip_count;
				line_start = ptr + 1;
			}
		}
		linerest = ptr - line_start;
		mch_breakcheck();
	}

	/* not an error, max. number of lines reached */
	if (error && read_count == 0)
		error = FALSE;

	/*
	 * If we get EOF in the middle of a line, note the fact and
	 * complete the line ourselves.
	 * In textmode ignore a trailing CTRL-Z, unless 'binary' set.
	 */
	if (!error && !got_int && linerest != 0 &&
			!(!curbuf->b_p_bin && textmode &&
					*line_start == Ctrl('Z') && ptr == line_start + 1))
	{
		if (newfile)				/* remember for when writing */
			curbuf->b_p_eol = FALSE;
		*ptr = NUL;
		if (ml_append(lnum, line_start,
						(colnr_t)(ptr - line_start + 1), newfile) == FAIL)
			error = TRUE;
		else
			read_no_eol_lnum = ++lnum;
	}
	if (lnum != from && !newfile)	/* added at least one line */
		CHANGED;

	close(fd);						/* errors are ignored */
	vim_free(buffer);

	--no_wait_return;				/* may wait for return now */

	/* in recovery mode everything but autocommands are skipped */
	if (!recoverymode)
	{

		/* need to delete the last line, which comes from the empty buffer */
		if (newfile && !(curbuf->b_ml.ml_flags & ML_EMPTY))
		{
			ml_delete(curbuf->b_ml.ml_line_count, FALSE);
			--linecnt;
		}
		linecnt = curbuf->b_ml.ml_line_count - linecnt;
		if (filesize == 0)
			linecnt = 0;
		if (!newfile)
			mark_adjust(from + 1, MAXLNUM, (long)linecnt, 0L);

		if (got_int)
		{
			filemess(curbuf, fname, e_interr);
			msg_scroll = msg_save;
#ifdef VIMINFO
			check_marks_read();
#endif /* VIMINFO */
			return OK;			/* an interrupt isn't really an error */
		}

		if (!filtering)
		{
			msg_add_fname(curbuf, fname);	/* fname in IObuff with quotes */
			c = FALSE;

#ifdef UNIX
# ifdef S_ISFIFO
			if (S_ISFIFO(perm))						/* fifo or socket */
			{
				STRCAT(IObuff, "[fifo/socket]");
				c = TRUE;
			}
# else
#  ifdef S_IFIFO
			if ((perm & S_IFMT) == S_IFIFO)			/* fifo */
			{
				STRCAT(IObuff, "[fifo]");
				c = TRUE;
			}
#  endif
#  ifdef S_IFSOCK
			if ((perm & S_IFMT) == S_IFSOCK)		/* or socket */
			{
				STRCAT(IObuff, "[socket]");
				c = TRUE;
			}
#  endif
# endif
#endif
			if (curbuf->b_p_ro)
			{
				STRCAT(IObuff, shortmess(SHM_RO) ? "[RO]" : "[readonly]");
				c = TRUE;
			}
			if (read_no_eol_lnum)
			{
				msg_add_eol();
				c = TRUE;
			}
			if (tx_error)
			{
				STRCAT(IObuff, "[CR missing]");
				c = TRUE;
			}
			if (split)
			{
				STRCAT(IObuff, "[long lines split]");
				c = TRUE;
			}
			if (error)
			{
				STRCAT(IObuff, "[READ ERRORS]");
				c = TRUE;
			}
			if (msg_add_textmode(textmode))
				c = TRUE;
			msg_add_lines(c, (long)linecnt, filesize);
			msg_trunc(IObuff);
		}

		if (error && newfile)	/* with errors we should not write the file */
			curbuf->b_p_ro = TRUE;

		u_clearline();		/* cannot use "U" command after adding lines */

		if (from < curbuf->b_ml.ml_line_count)
		{
			curwin->w_cursor.lnum = from + 1;	/* cursor at first new line */
			beginline(TRUE);					/* on first non-blank */
		}

		/*
		 * Set '[ and '] marks to the newly read lines.
		 */
		curbuf->b_op_start.lnum = from + 1;
		curbuf->b_op_start.col = 0;
		curbuf->b_op_end.lnum = from + linecnt;
		curbuf->b_op_end.col = 0;
	}
	msg_scroll = msg_save;

#ifdef AUTOCMD
	{
		int	m = msg_scroll;
		int n = msg_scrolled;

		/*
		 * Trick: We remember if the last line of the read didn't have
		 * an eol for when writing it again.  This is required for
		 * ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work.
		 */
		write_no_eol_lnum = read_no_eol_lnum;

		/*
		 * The output from the autocommands should not overwrite anything and
		 * should not be overwritten: Set msg_scroll, restore its value if no
		 * output was done.
		 */
		msg_scroll = TRUE;
		if (filtering)
			apply_autocmds(EVENT_FILTERREADPOST, NULL, fname);
		else if (newfile)
			apply_autocmds(EVENT_BUFREADPOST, NULL, fname);
		else
			apply_autocmds(EVENT_FILEREADPOST, fname, fname);
		if (msg_scrolled == n)
			msg_scroll = m;
	}
#endif

#ifdef VIMINFO
	check_marks_read();
#endif /* VIMINFO */

	if (recoverymode && error)
		return FAIL;
	return OK;
}

#ifdef VIMINFO
	static void
check_marks_read()
{
	if (!curbuf->b_marks_read && get_viminfo_parameter('\'') > 0)
	{
		read_viminfo(NULL, FALSE, TRUE, FALSE);
		curbuf->b_marks_read = TRUE;
	}
}
#endif /* VIMINFO */

/*
 * buf_write() - write to file 'fname' lines 'start' through 'end'
 *
 * We do our own buffering here because fwrite() is so slow.
 *
 * If forceit is true, we don't care for errors when attempting backups (jw).
 * In case of an error everything possible is done to restore the original file.
 * But when forceit is TRUE, we risk loosing it.
 * When reset_changed is TRUE and start == 1 and end ==
 * curbuf->b_ml.ml_line_count, reset curbuf->b_changed.
 *
 * This function must NOT use NameBuff (because it's called by autowrite()).
 *
 * return FAIL for failure, OK otherwise
 */
	int
buf_write(buf, fname, sfname, start, end, append, forceit,
													  reset_changed, filtering)
	BUF				*buf;
	char_u			*fname;
	char_u			*sfname;
	linenr_t		start, end;
	int				append;
	int				forceit;
	int				reset_changed;
	int				filtering;
{
	int 				fd;
	char_u			   *backup = NULL;
	char_u			   *ffname;
#ifdef AUTOCMD
	BUF				   *save_buf;
#endif
	register char_u	   *s;
	register char_u	   *ptr;
	register char_u		c;
	register int		len;
	register linenr_t	lnum;
	long				nchars;
	char_u				*errmsg = NULL;
	char_u				*buffer;
	char_u				smallbuf[SBUFSIZE];
	char_u				*backup_ext;
	int					bufsize;
	long 				perm = -1;			/* file permissions */
	int					retval = OK;
	int					newfile = FALSE;	/* TRUE if file doesn't exist yet */
	int					msg_save = msg_scroll;
	int					overwriting;		/* TRUE if writing over original */
	int					no_eol = FALSE;		/* no end-of-line written */
#if defined(UNIX) || defined(__EMX__XX) /*XXX fix me sometime? */
	struct stat			st_old;
	int					made_writable = FALSE;	/* 'w' bit has been set */
#endif
#ifdef AMIGA
	BPTR				flock;
#endif
											/* writing everything */
	int					whole = (start == 1 && end == buf->b_ml.ml_line_count);
#ifdef AUTOCMD
	linenr_t			old_line_count = buf->b_ml.ml_line_count;
#endif

	if (fname == NULL || *fname == NUL)		/* safety check */
		return FAIL;

	/*
	 * If there is no file name yet, use the one for the written file.
	 * b_notedited is set to reflect this (in case the write fails).
	 * Don't do this when the write is for a filter command.
	 * Only do this when 'cpoptions' contains the 'f' flag.
	 */
	if (reset_changed && whole && buf == curbuf &&
								   curbuf->b_filename == NULL && !filtering &&
										vim_strchr(p_cpo, CPO_FNAMEW) != NULL)
	{
		if (setfname(fname, sfname, FALSE) == OK)
			curbuf->b_notedited = TRUE;
	}

	if (sfname == NULL)
		sfname = fname;
	/*
	 * For Unix: Use the short filename whenever possible.
	 * Avoids problems with networks and when directory names are changed.
	 * Don't do this for MS-DOS, a "cd" in a sub-shell may have moved us to
	 * another directory, which we don't detect
	 */
	ffname = fname;							/* remember full fname */
#ifdef UNIX
	if (!did_cd)
		fname = sfname;
#endif

		/* make sure we have a valid backup extension to use */
	if (*p_bex == NUL)
		backup_ext = (char_u *)".bak";
	else
		backup_ext = p_bex;

	if (buf->b_filename != NULL && fnamecmp(ffname, buf->b_filename) == 0)
		overwriting = TRUE;
	else
		overwriting = FALSE;

	/*
	 * Disallow writing from .exrc and .vimrc in current directory for
	 * security reasons.
	 */
	if (secure)
	{
		secure = 2;
		emsg(e_curdir);
		return FAIL;
	}

	if (exiting)
		settmode(0);				/* when exiting allow typahead now */

	++no_wait_return;				/* don't wait for return yet */

	/*
	 * Set '[ and '] marks to the lines to be written.
	 */
	buf->b_op_start.lnum = start;
	buf->b_op_start.col = 0;
	buf->b_op_end.lnum = end;
	buf->b_op_end.col = 0;

#ifdef AUTOCMD
	/*
	 * Apply PRE aucocommands.
	 * Set curbuf to the buffer to be written.
	 * Careful: The autocommands may call buf_write() recursively!
	 */
	save_buf = curbuf;
	curbuf = buf;
	curwin->w_buffer = buf;
	if (append)
		apply_autocmds(EVENT_FILEAPPENDPRE, fname, fname);
	else if (filtering)
		apply_autocmds(EVENT_FILTERWRITEPRE, NULL, fname);
	else if (reset_changed && whole)
		apply_autocmds(EVENT_BUFWRITEPRE, fname, fname);
	else
		apply_autocmds(EVENT_FILEWRITEPRE, fname, fname);
	/*
	 * If the autocommands deleted or unloaded the buffer, give an error
	 * message.
	 */
	if (!buf_valid(buf) || buf->b_ml.ml_mfp == NULL)
	{
		--no_wait_return;
		msg_scroll = msg_save;
		EMSG("Autocommands deleted or unloaded buffer to be written");
		return FAIL;
	}
	/*
	 * If the autocommands didn't change the current buffer, go back to the
	 * original current buffer, if it still exists.
	 */
	if (curbuf == buf && buf_valid(save_buf))
	{
		curbuf = save_buf;
		curwin->w_buffer = save_buf;
	}
	
	/*
	 * The autocommands may have changed the number of lines in the file.
	 * When writing the whole file, adjust the end.
	 * When writing part of the file, assume that the autocommands only
	 * changed the number of lines that are to be written (tricky!).
	 */
	if (buf->b_ml.ml_line_count != old_line_count)
	{
		if (whole)											/* writing all */
			end = buf->b_ml.ml_line_count;
		else if (buf->b_ml.ml_line_count > old_line_count)	/* more lines */
			end += buf->b_ml.ml_line_count - old_line_count;
		else												/* less lines */
		{
			end -= old_line_count - buf->b_ml.ml_line_count;
			if (end < start)
			{
				--no_wait_return;
				msg_scroll = msg_save;
				EMSG("Autocommand changed number of lines in unexpected way");
				return FAIL;
			}
		}
	}
#endif

	if (shortmess(SHM_OVER))
		msg_scroll = FALSE;			/* overwrite previous file message */
	else
		msg_scroll = TRUE;			/* don't overwrite previous file message */
	if (!filtering)
		filemess(buf,
#ifndef UNIX
				did_cd ? fname : sfname,
#else
				fname,
#endif
					(char_u *)"");	/* show that we are busy */
	msg_scroll = FALSE;				/* always overwrite the file message now */

	buffer = alloc(BUFSIZE);
	if (buffer == NULL)				/* can't allocate big buffer, use small
									 * one (to be able to write when out of
									 * memory) */
	{
		buffer = smallbuf;
		bufsize = SBUFSIZE;
	}
	else
		bufsize = BUFSIZE;

#if defined(UNIX) && !defined(ARCHIE)
		/* get information about original file (if there is one) */
	st_old.st_dev = st_old.st_ino = 0;
	if (stat((char *)fname, &st_old))
		newfile = TRUE;
	else
	{
#ifdef _POSIX_SOURCE
		if (!S_ISREG(st_old.st_mode))      		/* not a file */
#else
		if ((st_old.st_mode & S_IFMT) != S_IFREG)	/* not a file */
#endif
		{
#ifdef _POSIX_SOURCE
			if (S_ISDIR(st_old.st_mode))
#else
			if ((st_old.st_mode & S_IFMT) == S_IFDIR)
#endif
				errmsg = (char_u *)"is a directory";
			else
				errmsg = (char_u *)"is not a file";
			goto fail;
		}
		if (buf->b_mtime_read != 0 &&
						  buf->b_mtime_read != st_old.st_mtime && overwriting)
		{
			msg_scroll = TRUE;		/* don't overwrite messages here */
			(void)set_highlight('e');	/* set highlight for error messages */
			msg_highlight = TRUE;
			/* don't use emsg() here, don't want to flush the buffers */
			MSG("WARNING: The file has been changed since reading it!!!");
			if (ask_yesno((char_u *)"Do you really want to write to it",
																 TRUE) == 'n')
			{
				retval = FAIL;
				goto fail;
			}
			msg_scroll = FALSE;		/* always overwrite the file message now */
		}
		perm = st_old.st_mode;
	}
/*
 * If we are not appending, the file exists, and the 'writebackup', 'backup'
 * or 'patchmode' option is set, try to make a backup copy of the file.
 */
	if (!append && perm >= 0 && (p_wb || p_bk || *p_pm != NUL) &&
						  (fd = open((char *)fname, O_RDONLY | O_EXTRA)) >= 0)
	{
		int				bfd, buflen;
		char_u			copybuf[BUFSIZE + 1], *wp;
		int				some_error = FALSE;
		struct stat		st_new;
		char_u			*dirp;
		char_u			*rootname;
#ifndef SHORT_FNAME
		int				did_set_shortname;
#endif

		/*
		 * Try to make the backup in each directory in the 'bdir' option.
		 *
		 * Unix semantics has it, that we may have a writable file, 
		 * that cannot be recreated with a simple open(..., O_CREAT, ) e.g:
		 *  - the directory is not writable, 
		 *  - the file may be a symbolic link, 
		 *  - the file may belong to another user/group, etc.
		 *
		 * For these reasons, the existing writable file must be truncated
		 * and reused. Creation of a backup COPY will be attempted.
		 */
		dirp = p_bdir;
		while (*dirp)
		{
			st_new.st_dev = st_new.st_ino = 0;
			st_new.st_gid = 0;

			/*
			 * Isolate one directory name, using an entry in 'bdir'.
			 */
			(void)copy_option_part(&dirp, copybuf, BUFSIZE, ",");
			rootname = get_file_in_dir(fname, copybuf);
			if (rootname == NULL)
			{
				some_error = TRUE;			/* out of memory */
				goto nobackup;
			}


#ifndef SHORT_FNAME
			did_set_shortname = FALSE;
#endif

			/*
			 * May try twice if 'shortname' not set.
			 */
			for (;;)
			{
				/*
				 * Make backup file name.
				 */
				backup = buf_modname(buf, rootname, backup_ext);
				if (backup == NULL)
				{
					some_error = TRUE;			/* out of memory */
					vim_free(rootname);
					goto nobackup;
				}

				/*
				 * Check if backup file already exists.
				 */
				if (!stat((char *)backup, &st_new))
				{
					/*
					 * Check if backup file is same as original file.
					 * May happen when modname gave the same file back.
					 * E.g. silly link, or filename-length reached.
					 * If we don't check here, we either ruin the file when
					 * copying or erase it after writing. jw.
					 */
					if (st_new.st_dev == st_old.st_dev &&
										   st_new.st_ino == st_old.st_ino)
					{
						vim_free(backup);
						backup = NULL;	/* there is no backup file to delete */
#ifndef SHORT_FNAME
						/*
						 * may try again with 'shortname' set
						 */
						if (!(buf->b_shortname || buf->b_p_sn))
						{
							buf->b_shortname = TRUE;
							did_set_shortname = TRUE;
							continue;
						}
							/* setting shortname didn't help */
						if (did_set_shortname)
							buf->b_shortname = FALSE;
#endif
						break;
					}

					/*
					 * If we are not going to keep the backup file, don't
					 * delete an existing one, try to use another name.
					 * Change one character, just before the extension.
					 */
					if (!p_bk)
					{
						wp = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
						if (wp < backup)		/* empty file name ??? */
							wp = backup;
						*wp = 'z';
						while (*wp > 'a' && !stat((char *)backup, &st_new))
							--*wp;
						/* They all exist??? Must be something wrong. */
						if (*wp == 'a')
						{
							vim_free(backup);
							backup = NULL;
						}
					}
				}
				break;
			}
			vim_free(rootname);

			/*
			 * Try to create the backup file
			 */
			if (backup != NULL)
			{
				/* remove old backup, if present */
				vim_remove(backup);
				bfd = open((char *)backup, O_WRONLY | O_CREAT | O_EXTRA, 0666);
				if (bfd < 0)
				{
					vim_free(backup);
					backup = NULL;
				}
				else
				{
					/* set file protection same as original file, but strip
					 * s-bit */
					(void)setperm(backup, perm & 0777);

					/*
					 * Try to set the group of the backup same as the original
					 * file. If this fails, set the protection bits for the
					 * group same as the protection bits for others.
					 */
					if (st_new.st_gid != st_old.st_gid &&
#ifdef HAVE_FCHOWN	/* sequent-ptx lacks fchown() */
										  fchown(bfd, -1, st_old.st_gid) != 0)
#else
										chown(backup, -1, st_old.st_gid) != 0)
#endif
						setperm(backup, (perm & 0707) | ((perm & 07) << 3));

					/* copy the file. */
					while ((buflen = read(fd, (char *)copybuf, BUFSIZE)) > 0)
					{
						if (write_buf(bfd, copybuf, buflen) == FAIL)
						{
							errmsg = (char_u *)"Can't write to backup file (use ! to override)";
							break;
						}
					}
					if (close(bfd) < 0 && errmsg == NULL)
						errmsg = (char_u *)"Close error for backup file (use ! to override)";
					if (buflen < 0)
						errmsg = (char_u *)"Can't read file for backup (use ! to override)";
					break;
				}
			}
		}
nobackup:
		close(fd);				/* ignore errors for closing read file */

		if (backup == NULL && errmsg == NULL)
			errmsg = (char_u *)"Cannot create backup file (use ! to override)";
		/* ignore errors when forceit is TRUE */
		if ((some_error || errmsg) && !forceit)
		{
			retval = FAIL;
			goto fail;
		}
		errmsg = NULL;
	}
	/* When using ":w!" and the file was read-only: make it writable */
	if (forceit && (st_old.st_uid == getuid()) && perm >= 0 && !(perm & 0200))
 	{
		perm |= 0200;	
		(void)setperm(fname, perm);
		made_writable = TRUE;
	}

#else /* end of UNIX, start of the rest */

/*
 * If we are not appending, the file exists, and the 'writebackup' or
 * 'backup' option is set, make a backup.
 * Do not make any backup, if "writebackup" and "backup" are 
 * both switched off. This helps when editing large files on
 * almost-full disks. (jw)
 */
	perm = getperm(fname);
	if (perm < 0)
		newfile = TRUE;
	else if (mch_isdir(fname))
	{
		errmsg = (char_u *)"is a directory";
		goto fail;
	}
	if (!append && perm >= 0 && (p_wb || p_bk || *p_pm != NUL))
	{
		char_u			*dirp;
		char_u			*p;
		char_u			*rootname;

		/*
		 * Form the backup file name - change path/fo.o.h to path/fo.o.h.bak
		 * Try all directories in 'backupdir', first one that works is used.
		 */
		dirp = p_bdir;
		while (*dirp)
		{
			/*
			 * Isolate one directory name and make the backup file name.
			 */
			(void)copy_option_part(&dirp, IObuff, IOSIZE, ",");
			rootname = get_file_in_dir(fname, IObuff);
			if (rootname == NULL)
				backup = NULL;
			else
			{
				backup = buf_modname(buf, rootname, backup_ext);
				vim_free(rootname);
			}

			if (backup != NULL)
			{
				/*
				 * If we are not going to keep the backup file, don't
				 * delete an existing one, try to use another name.
				 * Change one character, just before the extension.
				 */
				if (!p_bk && getperm(backup) >= 0)
				{
					p = backup + STRLEN(backup) - 1 - STRLEN(backup_ext);
					if (p < backup)		/* empty file name ??? */
						p = backup;
					*p = 'z';
					while (*p > 'a' && getperm(backup) >= 0)
						--*p;
					/* They all exist??? Must be something wrong! */
					if (*p == 'a')
					{
						vim_free(backup);
						backup = NULL;
					}
				}
			}
			if (backup != NULL)
			{

				/*
				 * Delete any existing backup and move the current version to
				 * the backup.  For safety, we don't remove the backup until
				 * the write has finished successfully. And if the 'backup'
				 * option is set, leave it around.
				 */
#ifdef AMIGA
				/*
				 * With MSDOS-compatible filesystems (crossdos, messydos) it is
				 * possible that the name of the backup file is the same as the
				 * original file. To avoid the chance of accidently deleting the
				 * original file (horror!) we lock it during the remove.
				 * This should not happen with ":w", because startscript()
				 * should detect this problem and set buf->b_shortname,
				 * causing modname to return a correct ".bak" filename. This
				 * problem does exist with ":w filename", but then the
				 * original file will be somewhere else so the backup isn't
				 * really important. If autoscripting is off the rename may
				 * fail.
				 */
				flock = Lock((UBYTE *)fname, (long)ACCESS_READ);
#endif
				vim_remove(backup);
#ifdef AMIGA
				if (flock)
					UnLock(flock);
#endif
				/*
				 * If the renaming of the original file to the backup file
				 * works, quit here.
				 */
				if (vim_rename(fname, backup) == 0)
					break;

				vim_free(backup);	/* don't do the rename below */
				backup = NULL;
			}
		}
		if (backup == NULL && !forceit)
		{
			errmsg = (char_u *)"Can't make backup file (use ! to override)";
			goto fail;
		}
	}
#endif /* UNIX */

	/* When using ":w!" and writing to the current file, readonly makes no
	 * sense, reset it */
	if (forceit && overwriting)
		buf->b_p_ro = FALSE;

	/*
	 * If the original file is being overwritten, there is a small chance that
	 * we crash in the middle of writing. Therefore the file is preserved now.
	 * This makes all block numbers positive so that recovery does not need
	 * the original file.
	 * Don't do this if there is a backup file and we are exiting.
	 */
	if (reset_changed && !newfile && !otherfile(ffname) &&
											!(exiting && backup != NULL))
		ml_preserve(buf, FALSE);

	/* 
	 * We may try to open the file twice: If we can't write to the
	 * file and forceit is TRUE we delete the existing file and try to create
	 * a new one. If this still fails we may have lost the original file!
	 * (this may happen when the user reached his quotum for number of files).
	 * Appending will fail if the file does not exist and forceit is FALSE.
	 */
	while ((fd = open((char *)fname, O_WRONLY | O_EXTRA | (append ?
					(forceit ? (O_APPEND | O_CREAT) : O_APPEND) :
					(O_CREAT | O_TRUNC)), 0666)) < 0)
 	{
		/*
		 * A forced write will try to create a new file if the old one is
		 * still readonly. This may also happen when the directory is
		 * read-only. In that case the vim_remove() will fail.
		 */
		if (!errmsg)
		{
			errmsg = (char_u *)"Can't open file for writing";
			if (forceit)
			{
#ifdef UNIX
				/* we write to the file, thus it should be marked
													writable after all */
				perm |= 0200;		
				made_writable = TRUE;
				if (st_old.st_uid != getuid() || st_old.st_gid != getgid())
					perm &= 0777;
#endif /* UNIX */
				if (!append)		/* don't remove when appending */
					vim_remove(fname);
				continue;
			}
		}
/*
 * If we failed to open the file, we don't need a backup. Throw it away.
 * If we moved or removed the original file try to put the backup in its place.
 */
 		if (backup != NULL)
		{
#ifdef UNIX
			struct stat st;

			/*
			 * There is a small chance that we removed the original, try
			 * to move the copy in its place.
			 * This may not work if the vim_rename() fails.
			 * In that case we leave the copy around.
			 */
			 							/* file does not exist */
			if (stat((char *)fname, &st) < 0)
										/* put the copy in its place */
				vim_rename(backup, fname);
										/* original file does exist */
			if (stat((char *)fname, &st) >= 0)
				vim_remove(backup);	/* throw away the copy */
#else
										/* try to put the original file back */
 			vim_rename(backup, fname);
#endif
		}
 		goto fail;
 	}
	errmsg = NULL;

	if (end > buf->b_ml.ml_line_count)
		end = buf->b_ml.ml_line_count;
	len = 0;
	s = buffer;
	nchars = 0;
	if (buf->b_ml.ml_flags & ML_EMPTY)
		start = end + 1;
	for (lnum = start; lnum <= end; ++lnum)
	{
		/*
		 * The next while loop is done once for each character written.
		 * Keep it fast!
		 */
		ptr = ml_get_buf(buf, lnum, FALSE) - 1;
		while ((c = *++ptr) != NUL)
		{
			if (c == NL)
				*s = NUL;		/* replace newlines with NULs */
			else
				*s = c;
			++s;
			if (++len != bufsize)
				continue;
			if (write_buf(fd, buffer, bufsize) == FAIL)
			{
				end = 0;				/* write error: break loop */
				break;
			}
			nchars += bufsize;
			s = buffer;
			len = 0;
		}
			/* write failed or last line has no EOL: stop here */
		if (end == 0 || (lnum == end && buf->b_p_bin &&
												(lnum == write_no_eol_lnum ||
						 (lnum == buf->b_ml.ml_line_count && !buf->b_p_eol))))
		{
			++lnum;				/* written the line, count it */
			no_eol = TRUE;
			break;
		}
		if (buf->b_p_tx)		/* write CR-NL */
		{
			*s = CR;
			++s;
			if (++len == bufsize)
			{
				if (write_buf(fd, buffer, bufsize) == FAIL)
				{
					end = 0;				/* write error: break loop */
					break;
				}
				nchars += bufsize;
				s = buffer;
				len = 0;
			}
		}
		*s = NL;
		++s;
		if (++len == bufsize && end)
		{
			if (write_buf(fd, buffer, bufsize) == FAIL)
			{
				end = 0;				/* write error: break loop */
				break;
			}
			nchars += bufsize;
			s = buffer;
			len = 0;
		}
	}
	if (len && end)
	{
		if (write_buf(fd, buffer, len) == FAIL)
			end = 0;				/* write error */
		nchars += len;
	}

	if (close(fd) != 0)
	{
		errmsg = (char_u *)"Close failed";
		goto fail;
	}
#ifdef UNIX
	if (made_writable)
		perm &= ~0200;			/* reset 'w' bit for security reasons */
#endif
	if (perm >= 0)
		(void)setperm(fname, perm);	/* set permissions of new file same as old file */

	if (end == 0)
	{
		errmsg = (char_u *)"write error (file system full?)";
		/*
		 * If we have a backup file, try to put it in place of the new file,
		 * because it is probably corrupt. This avoids loosing the original
		 * file when trying to make a backup when writing the file a second
		 * time.
		 * For unix this means copying the backup over the new file.
		 * For others this means renaming the backup file.
		 * If this is OK, don't give the extra warning message.
		 */
		if (backup != NULL)
		{
#ifdef UNIX
			char_u		copybuf[BUFSIZE + 1];
			int			bfd, buflen;

			if ((bfd = open((char *)backup, O_RDONLY | O_EXTRA)) >= 0)
			{
				if ((fd = open((char *)fname,
						  O_WRONLY | O_CREAT | O_TRUNC | O_EXTRA, 0666)) >= 0)
				{
					/* copy the file. */
					while ((buflen = read(bfd, (char *)copybuf, BUFSIZE)) > 0)
						if (write_buf(fd, copybuf, buflen) == FAIL)
							break;
					if (close(fd) >= 0 && buflen == 0)	/* success */
						end = 1;
				}
				close(bfd);		/* ignore errors for closing read file */
			}
#else
			if (vim_rename(backup, fname) == 0)
				end = 1;
#endif
		}
		goto fail;
	}

	lnum -= start;			/* compute number of written lines */
	--no_wait_return;		/* may wait for return now */

#ifndef UNIX
	/* use shortname now, for the messages */
	if (!did_cd)
		fname = sfname;
#endif
	if (!filtering)
	{
		msg_add_fname(buf, fname);		/* put fname in IObuff with quotes */
		c = FALSE;
		if (newfile)
		{
			STRCAT(IObuff, shortmess(SHM_NEW) ? "[New]" : "[New File]");
			c = TRUE;
		}
		if (no_eol)
		{
			msg_add_eol();
			c = TRUE;
		}
		if (msg_add_textmode(buf->b_p_tx))		/* may add [textmode] */
			c = TRUE;
		msg_add_lines(c, (long)lnum, nchars);	/* add line/char count */
		if (!shortmess(SHM_WRITE))
			STRCAT(IObuff, shortmess(SHM_WRI) ? " [w]" : " written");

		msg_trunc(IObuff);
	}

	if (reset_changed && whole)			/* when written everything */
	{
		UNCHANGED(buf);
		u_unchanged(buf);
	}

	/*
	 * If written to the current file, update the timestamp of the swap file
	 * and reset the 'notedited' flag. Also sets buf->b_mtime.
	 */
	if (!exiting && overwriting)
	{
		ml_timestamp(buf);
		buf->b_notedited = FALSE;
	}

	/*
	 * If we kept a backup until now, and we are in patch mode, then we make
	 * the backup file our 'original' file.
	 */
	if (*p_pm)
	{
	    char *org = (char *)buf_modname(buf, fname, p_pm);

		if (backup != NULL)
		{
		    struct stat st;

			/*
			 * If the original file does not exist yet
			 * the current backup file becomes the original file
			 */
		    if (org == NULL)
				EMSG("patchmode: can't save original file");
			else if (stat(org, &st) < 0)
			{
			    vim_rename(backup, (char_u *)org);
				vim_free(backup);			/* don't delete the file */
				backup = NULL;
			}
		}
	    /*
		 * If there is no backup file, remember that a (new) file was
		 * created.
		 */
	    else
		{
		    int empty_fd;

			if (org == NULL || (empty_fd =
									  open(org, O_CREAT | O_EXTRA, 0666)) < 0)
			  EMSG("patchmode: can't touch empty original file");
		    else
			  close(empty_fd);
		}
	    if (org != NULL)
		{
		    setperm((char_u *)org, getperm(fname) & 0777);
			vim_free(org);
		}
	}

	/*
	 * Remove the backup unless 'backup' option is set
	 */
	if (!p_bk && backup != NULL && vim_remove(backup) != 0)
		EMSG("Can't delete backup file");
	
	goto nofail;

fail:
	--no_wait_return;		/* may wait for return now */
nofail:

	vim_free(backup);
	if (buffer != smallbuf)
		vim_free(buffer);

	if (errmsg != NULL)
	{
		/* can't use emsg() here, do something alike */
		if (p_eb)
			beep_flush();			/* also includes flush_buffers() */
		else
			flush_buffers(FALSE);	/* flush internal buffers */
		(void)set_highlight('e');	/* set highlight mode for error messages */
		start_highlight();
		filemess(buf,
#ifndef UNIX
						did_cd ? fname : sfname,
#else
						fname,
#endif
													errmsg);
		retval = FAIL;
		if (end == 0)
		{
			MSG_OUTSTR("\nWARNING: Original file may be lost or damaged\n");
			MSG_OUTSTR("don't quit the editor until the file is successfully written!");
		}
	}
	msg_scroll = msg_save;

#ifdef AUTOCMD
	write_no_eol_lnum = 0;		/* in case it was set by the previous read */

	/*
	 * Apply POST autocommands.
	 * Careful: The autocommands may call buf_write() recursively!
	 */
	save_buf = curbuf;
	curbuf = buf;
	curwin->w_buffer = buf;
	if (append)
		apply_autocmds(EVENT_FILEAPPENDPOST, fname, fname);
	else if (filtering)
		apply_autocmds(EVENT_FILTERWRITEPOST, NULL, fname);
	else if (reset_changed && whole)
		apply_autocmds(EVENT_BUFWRITEPOST, fname, fname);
	else
		apply_autocmds(EVENT_FILEWRITEPOST, fname, fname);
	/*
	 * If the autocommands didn't change the current buffer, go back to the
	 * original current buffer, if it still exists.
	 */
	if (curbuf == buf && buf_valid(save_buf))
	{
		curbuf = save_buf;
		curwin->w_buffer = save_buf;
	}
#endif

	return retval;
}

/*
 * Put file name into IObuff with quotes.
 */
	static void
msg_add_fname(buf, fname)
	BUF		*buf;
	char_u	*fname;
{
		/* careful: home_replace calls vim_getenv(), which also uses IObuff! */
	home_replace(buf, fname, IObuff + 1, IOSIZE - 1);
	IObuff[0] = '"';
	STRCAT(IObuff, "\" ");
}

/*
 * Append message for text mode to IObuff.
 * Return TRUE if something appended.
 */
	static int
msg_add_textmode(textmode)
	int		textmode;
{
#ifdef USE_CRNL
	if (!textmode)
	{
		STRCAT(IObuff, shortmess(SHM_TEXT) ? "[notx]" : "[notextmode]");
		return TRUE;
	}
#else
	if (textmode)
	{
		STRCAT(IObuff, shortmess(SHM_TEXT) ? "[tx]" : "[textmode]");
		return TRUE;
	}
#endif
	return FALSE;
}

/*
 * Append line and character count to IObuff.
 */
	static void
msg_add_lines(insert_space, lnum, nchars)
	int		insert_space;
	long	lnum;
	long	nchars;
{
	char_u	*p;

	p = IObuff + STRLEN(IObuff);

	if (insert_space)
		*p++ = ' ';
	if (shortmess(SHM_LINES))
		sprintf((char *)p, "%ldL, %ldC", lnum, nchars);
	else
		sprintf((char *)p, "%ld line%s, %ld character%s",
			lnum, plural(lnum),
			nchars, plural(nchars));
}

/*
 * Append message for missing line separator to IObuff.
 */
	static void
msg_add_eol()
{
	STRCAT(IObuff, shortmess(SHM_LAST) ? "[noeol]" : "[Incomplete last line]");
}

/*
 * write_buf: call write() to write a buffer
 *
 * return FAIL for failure, OK otherwise
 */
	static int
write_buf(fd, buf, len)
	int		fd;
	char_u	*buf;
	int		len;
{
	int		wlen;

	while (len)
	{
		wlen = write(fd, (char *)buf, (size_t)len);
		if (wlen <= 0)				/* error! */
			return FAIL;
		len -= wlen;
		buf += wlen;
	}
	return OK;
}

/*
 * add extention to filename - change path/fo.o.h to path/fo.o.h.ext or
 * fo_o_h.ext for MSDOS or when shortname option set.
 *
 * Assumed that fname is a valid name found in the filesystem we assure that
 * the return value is a different name and ends in 'ext'.
 * "ext" MUST be at most 4 characters long if it starts with a dot, 3
 * characters otherwise.
 * Space for the returned name is allocated, must be freed later.
 */

	char_u *
modname(fname, ext)
	char_u *fname, *ext;
{
	return buf_modname(curbuf, fname, ext);
}

	char_u *
buf_modname(buf, fname, ext)
	BUF		*buf;
	char_u *fname, *ext;
{
	char_u				*retval;
	register char_u 	*s;
	register char_u		*e;
	register char_u		*ptr;
	register int		fnamelen, extlen;

	extlen = STRLEN(ext);

	/*
	 * if there is no filename we must get the name of the current directory
	 * (we need the full path in case :cd is used)
	 */
	if (fname == NULL || *fname == NUL)
	{
		retval = alloc((unsigned)(MAXPATHL + extlen + 3));
		if (retval == NULL)
			return NULL;
		if (mch_dirname(retval, MAXPATHL) == FAIL ||
											 (fnamelen = STRLEN(retval)) == 0)
		{
			vim_free(retval);
			return NULL;
		}
		if (!ispathsep(retval[fnamelen - 1]))
		{
			retval[fnamelen++] = PATHSEP;
			retval[fnamelen] = NUL;
		}
	}
	else
	{
		fnamelen = STRLEN(fname);
		retval = alloc((unsigned)(fnamelen + extlen + 2));
		if (retval == NULL)
			return NULL;
		STRCPY(retval, fname);
	}

	/*
	 * search backwards until we hit a '/', '\' or ':' replacing all '.'
	 * by '_' for MSDOS or when shortname option set and ext starts with a dot.
	 * Then truncate what is after the '/', '\' or ':' to 8 characters for
	 * MSDOS and 26 characters for AMIGA, a lot more for UNIX.
	 */
	for (ptr = retval + fnamelen; ptr >= retval; ptr--)
	{
		if (*ext == '.'
#ifdef USE_LONG_FNAME
					&& (!USE_LONG_FNAME || buf->b_p_sn || buf->b_shortname)
#else
# ifndef SHORT_FNAME
					&& (buf->b_p_sn || buf->b_shortname)
# endif
#endif
																)
			if (*ptr == '.')	/* replace '.' by '_' */
				*ptr = '_';
		if (ispathsep(*ptr))
			break;
	}
	ptr++;

	/* the filename has at most BASENAMELEN characters. */
#ifndef SHORT_FNAME
	if (STRLEN(ptr) > (unsigned)BASENAMELEN)
		ptr[BASENAMELEN] = '\0';
#endif

	s = ptr + STRLEN(ptr);

	/*
	 * For 8.3 filenames we may have to reduce the length.
	 */
#ifdef USE_LONG_FNAME
	if (!USE_LONG_FNAME || buf->b_p_sn || buf->b_shortname)
#else
# ifndef SHORT_FNAME
	if (buf->b_p_sn || buf->b_shortname)
# endif
#endif
	{
		/*
		 * If there is no file name, and the extension starts with '.', put a
		 * '_' before the dot, because just ".ext" is invalid.
		 */
		if (fname == NULL || *fname == NUL)
		{
			if (*ext == '.')
				*s++ = '_';
		}
		/*
		 * If the extension starts with '.', truncate the base name at 8
		 * characters
		 */
		else if (*ext == '.')
		{
			if (s - ptr > (size_t)8)
			{
				s = ptr + 8;
				*s = '\0';
			}
		}
		/*
		 * If the extension doesn't start with '.', and the file name
		 * doesn't have an extension yet, append a '.'
		 */
		else if ((e = vim_strchr(ptr, '.')) == NULL)
			*s++ = '.';
		/*
		 * If If the extension doesn't start with '.', and there already is an
		 * extension, it may need to be tructated
		 */
		else if ((int)STRLEN(e) + extlen > 4)
			s = e + 4 - extlen;
	}
#ifdef OS2
	/*
	 * If there is no file name, and the extension starts with '.', put a
	 * '_' before the dot, because just ".ext" may be invalid if it's on a
	 * FAT partition, and on HPFS it doesn't matter.
	 */
	else if ((fname == NULL || *fname == NUL) && *ext == '.')
		*s++ = '_';
#endif

	/*
	 * Append the extention.
	 * ext can start with '.' and cannot exceed 3 more characters.
	 */
	STRCPY(s, ext);

	/*
	 * Check that, after appending the extension, the file name is really
	 * different.
	 */
	if (fname != NULL && STRCMP(fname, retval) == 0)
	{
		/* we search for a character that can be replaced by '_' */
		while (--s >= ptr)
		{
			if (*s != '_')
			{
				*s = '_';
				break;
			}
		}
		if (s < ptr)	/* fname was "________.<ext>" how tricky! */
			*ptr = 'v';
	}
	return retval;
}

/* vim_fgets();
 *
 * Like fgets(), but if the file line is too long, it is truncated and the
 * rest of the line is thrown away.  Returns TRUE for end-of-file.
 * Note: do not pass IObuff as the buffer since this is used to read and
 * discard the extra part of any long lines.
 */
	int
vim_fgets(buf, size, fp)
	char_u		*buf;
	int			size;
	FILE		*fp;
{
	char *eof;

	buf[size - 2] = NUL;
	eof = fgets((char *)buf, size, fp);
	if (buf[size - 2] != NUL && buf[size - 2] != '\n')
	{
		buf[size - 1] = NUL;		/* Truncate the line */

		/* Now throw away the rest of the line: */
		do
		{
			IObuff[IOSIZE - 2] = NUL;
			fgets((char *)IObuff, IOSIZE, fp);
		} while (IObuff[IOSIZE - 2] != NUL && IObuff[IOSIZE - 2] != '\n');
	}
	return (eof == NULL);
}

/*
 * rename() only works if both files are on the same file system, this
 * function will (attempts to?) copy the file across if rename fails -- webb
 * Return -1 for failure, 0 for success.
 */
	int
vim_rename(from, to)
	char_u *from;
	char_u *to;
{
	int		fd_in;
	int		fd_out;
	int		n;
	char 	*errmsg = NULL;

	/*
	 * First delete the "to" file, this is required on some systems to make
	 * the rename() work, on other systems it makes sure that we don't have
	 * two files when the rename() fails.
	 */
	vim_remove(to);

	/*
	 * First try a normal rename, return if it works.
	 */
	if (rename((char *)from, (char *)to) == 0)
		return 0;

	/*
	 * Rename() failed, try copying the file.
	 */
	fd_in = open((char *)from, O_RDONLY | O_EXTRA);
	if (fd_in == -1)
		return -1;
	fd_out = open((char *)to, O_CREAT | O_TRUNC | O_WRONLY | O_EXTRA, 0666);
	if (fd_out == -1)
	{
		close(fd_in);
		return -1;
	}
	while ((n = read(fd_in, (char *)IObuff, (size_t)IOSIZE)) > 0)
		if (write(fd_out, (char *)IObuff, (size_t)n) != n)
		{
			errmsg = "writing to";
			break;
		}
	close(fd_in);
	if (close(fd_out) < 0)
		errmsg = "closing";
	if (n < 0)
	{
		errmsg = "reading";
		to = from;
	}
	if (errmsg != NULL)
	{
		sprintf((char *)IObuff, "Error %s '%s'", errmsg, to);
		emsg(IObuff);
		return -1;
	}
	vim_remove(from);
	return 0;
}

/*
 * Check if any not hidden buffer has been changed.
 * Postpone the check if there are characters in the stuff buffer, a global
 * command is being executed, a mapping is being executed or an autocommand is
 * busy.
 */
	void
check_timestamps()
{
	BUF		*buf;

	if (!stuff_empty() || global_busy || !typebuf_typed()
#ifdef AUTOCMD
						|| autocmd_busy
#endif
										)
		need_check_timestamps = TRUE;			/* check later */
	else
	{
		++no_wait_return;
		for (buf = firstbuf; buf != NULL; buf = buf->b_next)
			buf_check_timestamp(buf);
		--no_wait_return;
		need_check_timestamps = FALSE;
	}
}

/*
 * Check if buffer "buf" has been changed.
 */
	void
buf_check_timestamp(buf)
	BUF		*buf;
{
	struct stat		st;
	char_u			*path;

	if (	buf->b_filename != NULL &&
			buf->b_ml.ml_mfp != NULL &&
			!buf->b_notedited &&
			buf->b_mtime != 0 &&
			stat((char *)buf->b_filename, &st) >= 0 &&
			buf->b_mtime != st.st_mtime)
	{
		path = home_replace_save(buf, buf->b_xfilename);
		if (path != NULL)
		{
			EMSG2("Warning: File \"%s\" has changed since editing started",
																path);
			buf->b_mtime = st.st_mtime;
			vim_free(path);
		}
	}
}

/*
 * Adjust the line with missing eol, used for the next write.
 * Used for do_filter(), when the input lines for the filter are deleted.
 */
	void
write_lnum_adjust(offset)
	linenr_t	offset;
{
	if (write_no_eol_lnum)				/* only if there is a missing eol */
		write_no_eol_lnum += offset;
}

#ifdef USE_TMPNAM
extern char		*tmpnam __ARGS((char *));
#else
extern char		*mktemp __ARGS((char *));
#endif

/*
 * vim_tempname(): Return a unique name that can be used for a temp file.
 *
 * The temp file is NOT created.
 *
 * The returned pointer is to allocated memory.
 * The returned pointer is NULL if no valid name was found.
 */
	char_u	*
vim_tempname(extra_char)
	int		extra_char;		/* character to use in the name instead of '?' */
{
#ifdef USE_TMPNAM
	char_u			itmp[L_tmpnam];		/* use tmpnam() */
#else
	char_u			itmp[TEMPNAMELEN];
#endif
	char_u			*p;

#if defined(TEMPDIRNAMES)
	static char		*(tempdirs[]) = {TEMPDIRNAMES};
	static int		first_dir = 0;
	int				first_try = TRUE;
	int				i;

	/*
	 * Try a few places to put the temp file.
	 * To avoid waisting time with non-existing environment variables and
	 * directories, they are skipped next time.
	 */
	for (i = first_dir; i < sizeof(tempdirs) / sizeof(char *); ++i)
	{
		/* expand $TMP, leave room for '/', "v?XXXXXX" and NUL */
		expand_env((char_u *)tempdirs[i], itmp, TEMPNAMELEN - 10);
		if (mch_isdir(itmp))			/* directory exists */
		{
			if (first_try)
				first_dir = i;			/* start here next time */
			first_try = FALSE;
#ifdef BACKSLASH_IN_FILENAME
			/*
			 * really want a backslash here, because the filename will
			 * probably be used in a command line
			 */
			STRCAT(itmp, "\\");	
#else
			STRCAT(itmp, PATHSEPSTR);
#endif
			STRCAT(itmp, TEMPNAME);
			if ((p = vim_strchr(itmp, '?')) != NULL)
				*p = extra_char;
			if (*mktemp((char *)itmp) == NUL)
				continue;
			return strsave(itmp);
		}
	}
	return NULL;
#else

# ifdef USE_TMPNAM
	/* tmpnam() will make its own name */
	if (*tmpnam((char *)itmp) == NUL)
# else
	STRCPY(itmp, TEMPNAME);
	if ((p = vim_strchr(itmp, '?')) != NULL)
		*p = extra_char;
	if (*mktemp((char *)itmp) == NUL)
# endif
		return NULL;
	return strsave(itmp);
#endif
}