-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
fileio.c
3855 lines (3536 loc) · 117 KB
/
fileio.c
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
// fileio.c: read from and write to a file
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <iconv.h>
#include <inttypes.h>
#include <limits.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <time.h>
#include <uv.h>
#include "auto/config.h"
#include "nvim/ascii_defs.h"
#include "nvim/autocmd.h"
#include "nvim/buffer.h"
#include "nvim/buffer_defs.h"
#include "nvim/buffer_updates.h"
#include "nvim/change.h"
#include "nvim/cursor.h"
#include "nvim/diff.h"
#include "nvim/drawscreen.h"
#include "nvim/edit.h"
#include "nvim/eval.h"
#include "nvim/ex_cmds_defs.h"
#include "nvim/ex_eval.h"
#include "nvim/fileio.h"
#include "nvim/fold.h"
#include "nvim/func_attr.h"
#include "nvim/garray.h"
#include "nvim/garray_defs.h"
#include "nvim/getchar.h"
#include "nvim/gettext.h"
#include "nvim/globals.h"
#include "nvim/highlight.h"
#include "nvim/iconv_defs.h"
#include "nvim/log.h"
#include "nvim/macros_defs.h"
#include "nvim/mbyte.h"
#include "nvim/memfile.h"
#include "nvim/memline.h"
#include "nvim/memory.h"
#include "nvim/message.h"
#include "nvim/move.h"
#include "nvim/option.h"
#include "nvim/option_vars.h"
#include "nvim/optionstr.h"
#include "nvim/os/fs.h"
#include "nvim/os/fs_defs.h"
#include "nvim/os/input.h"
#include "nvim/os/os.h"
#include "nvim/os/time.h"
#include "nvim/path.h"
#include "nvim/pos_defs.h"
#include "nvim/regexp.h"
#include "nvim/sha256.h"
#include "nvim/shada.h"
#include "nvim/state_defs.h"
#include "nvim/strings.h"
#include "nvim/types_defs.h"
#include "nvim/ui.h"
#include "nvim/undo.h"
#include "nvim/vim_defs.h"
#ifdef BACKSLASH_IN_FILENAME
# include "nvim/charset.h"
#endif
#ifdef HAVE_DIRFD_AND_FLOCK
# include <dirent.h>
# include <sys/file.h>
#endif
#ifdef OPEN_CHR_FILES
# include "nvim/charset.h"
#endif
// For compatibility with libuv < 1.20.0 (tested on 1.18.0)
#ifndef UV_FS_COPYFILE_FICLONE
# define UV_FS_COPYFILE_FICLONE 0
#endif
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "fileio.c.generated.h"
#endif
static const char *e_auchangedbuf = N_("E812: Autocommands changed buffer or buffer name");
void filemess(buf_T *buf, char *name, char *s, int attr)
{
int prev_msg_col = msg_col;
if (msg_silent != 0) {
return;
}
add_quoted_fname(IObuff, IOSIZE - 100, buf, name);
// Avoid an over-long translation to cause trouble.
xstrlcat(IObuff, s, IOSIZE);
// For the first message may have to start a new line.
// For further ones overwrite the previous one, reset msg_scroll before
// calling filemess().
int msg_scroll_save = msg_scroll;
if (shortmess(SHM_OVERALL) && !msg_listdo_overwrite && !exiting && p_verbose == 0) {
msg_scroll = false;
}
if (!msg_scroll) { // wait a bit when overwriting an error msg
msg_check_for_delay(false);
}
msg_start();
if (prev_msg_col != 0 && msg_col == 0) {
msg_putchar('\r'); // overwrite any previous message.
}
msg_scroll = msg_scroll_save;
msg_scrolled_ign = true;
// may truncate the message to avoid a hit-return prompt
msg_outtrans(msg_may_trunc(false, IObuff), attr);
msg_clr_eos();
ui_flush();
msg_scrolled_ign = false;
}
/// Read lines from file "fname" into the buffer after line "from".
///
/// 1. We allocate blocks with try_malloc, 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, unless READ_STDIN is used)
///
/// "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.
///
/// flags:
/// READ_NEW starting to edit a new buffer
/// READ_FILTER reading filter output
/// READ_STDIN read from stdin instead of a file
/// READ_BUFFER read from curbuf instead of a file (converting after reading
/// stdin)
/// READ_NOFILE do not read a file, only trigger BufReadCmd
/// READ_DUMMY read into a dummy buffer (to check if file contents changed)
/// READ_KEEP_UNDO don't clear undo info or read it from a file
/// READ_FIFO read from fifo/socket instead of a file
///
/// @param eap can be NULL!
///
/// @return FAIL for failure, NOTDONE for directory (failure), or OK
int readfile(char *fname, char *sfname, linenr_T from, linenr_T lines_to_skip,
linenr_T lines_to_read, exarg_T *eap, int flags, bool silent)
{
int retval = FAIL; // jump to "theend" instead of returning
int fd = stdin_fd >= 0 ? stdin_fd : 0;
int newfile = (flags & READ_NEW);
int check_readonly;
int filtering = (flags & READ_FILTER);
int read_stdin = (flags & READ_STDIN);
int read_buffer = (flags & READ_BUFFER);
int read_fifo = (flags & READ_FIFO);
int set_options = newfile || read_buffer
|| (eap != NULL && eap->read_edit);
linenr_T read_buf_lnum = 1; // next line to read from curbuf
colnr_T read_buf_col = 0; // next char to read from this line
char c;
linenr_T lnum = from;
char *ptr = NULL; // pointer into read buffer
char *buffer = NULL; // read buffer
char *new_buffer = NULL; // init to shut up gcc
char *line_start = NULL; // init to shut up gcc
int wasempty; // buffer was empty before reading
colnr_T len;
ptrdiff_t size = 0;
uint8_t *p = NULL;
off_T filesize = 0;
bool skip_read = false;
context_sha256_T sha_ctx;
int read_undo_file = false;
int split = 0; // number of split lines
linenr_T linecnt;
bool error = false; // errors encountered
int ff_error = EOL_UNKNOWN; // file format with errors
ptrdiff_t linerest = 0; // remaining chars in line
int perm = 0;
#ifdef UNIX
int swap_mode = -1; // protection bits for swap file
#endif
int fileformat = 0; // end-of-line format
bool keep_fileformat = false;
FileInfo file_info;
linenr_T skip_count = 0;
linenr_T read_count = 0;
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
bool file_rewind = false;
int can_retry;
linenr_T conv_error = 0; // line nr with conversion error
linenr_T illegal_byte = 0; // line nr with illegal byte
bool keep_dest_enc = false; // don't retry when char doesn't fit
// in destination encoding
int bad_char_behavior = BAD_REPLACE;
// BAD_KEEP, BAD_DROP or character to
// replace with
char *tmpname = NULL; // name of 'charconvert' output file
int fio_flags = 0;
char *fenc; // fileencoding to use
bool fenc_alloced; // fenc_next is in allocated memory
char *fenc_next = NULL; // next item in 'fencs' or NULL
bool advance_fenc = false;
int real_size = 0;
iconv_t iconv_fd = (iconv_t)-1; // descriptor for iconv() or -1
bool did_iconv = false; // true when iconv() failed and trying
// 'charconvert' next
bool converted = false; // true if conversion done
bool notconverted = false; // true if conversion wanted but it wasn't possible
char conv_rest[CONV_RESTLEN];
int conv_restlen = 0; // nr of bytes in conv_rest[]
pos_T orig_start;
buf_T *old_curbuf;
char *old_b_ffname;
char *old_b_fname;
int using_b_ffname;
int using_b_fname;
static char *msg_is_a_directory = N_("is a directory");
au_did_filetype = false; // reset before triggering any autocommands
curbuf->b_no_eol_lnum = 0; // in case it was set by the previous read
// If there is no file name yet, use the one for the read file.
// BF_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_ffname == NULL
&& !filtering
&& fname != NULL
&& vim_strchr(p_cpo, CPO_FNAMER) != NULL
&& !(flags & READ_DUMMY)) {
if (set_rw_fname(fname, sfname) == FAIL) {
goto theend;
}
}
// Remember the initial values of curbuf, curbuf->b_ffname and
// curbuf->b_fname to detect whether they are altered as a result of
// executing nasty autocommands. Also check if "fname" and "sfname"
// point to one of these values.
old_curbuf = curbuf;
old_b_ffname = curbuf->b_ffname;
old_b_fname = curbuf->b_fname;
using_b_ffname = (fname == curbuf->b_ffname) || (sfname == curbuf->b_ffname);
using_b_fname = (fname == curbuf->b_fname) || (sfname == curbuf->b_fname);
// After reading a file the cursor line changes but we don't want to
// display the line.
ex_no_reprint = true;
// don't display the file info for another buffer now
need_fileinfo = false;
// For Unix: Use the short file name whenever possible.
// Avoids problems with networks and when directory names are changed.
// Don't do this for Windows, a "cd" in a sub-shell may have moved us to
// another directory, which we don't detect.
if (sfname == NULL) {
sfname = fname;
}
#if defined(UNIX)
fname = sfname;
#endif
// The BufReadCmd and FileReadCmd events intercept the reading process by
// executing the associated commands instead.
if (!filtering && !read_stdin && !read_buffer) {
orig_start = curbuf->b_op_start;
// 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;
if (newfile) {
if (apply_autocmds_exarg(EVENT_BUFREADCMD, NULL, sfname,
false, curbuf, eap)) {
retval = OK;
if (aborting()) {
retval = FAIL;
}
// The BufReadCmd code usually uses ":read" to get the text and
// perhaps ":file" to change the buffer name. But we should
// consider this to work like ":edit", thus reset the
// BF_NOTEDITED flag. Then ":write" will work to overwrite the
// same file.
if (retval == OK) {
curbuf->b_flags &= ~BF_NOTEDITED;
}
goto theend;
}
} else if (apply_autocmds_exarg(EVENT_FILEREADCMD, sfname, sfname,
false, NULL, eap)) {
retval = aborting() ? FAIL : OK;
goto theend;
}
curbuf->b_op_start = orig_start;
if (flags & READ_NOFILE) {
// Return NOTDONE instead of FAIL so that BufEnter can be triggered
// and other operations don't fail.
retval = NOTDONE;
goto theend;
}
}
if (((shortmess(SHM_OVER) && !msg_listdo_overwrite) || curbuf->b_help) && p_verbose == 0) {
msg_scroll = false; // overwrite previous file message
} else {
msg_scroll = true; // don't overwrite previous file message
}
// If the name is too long we might crash further on, quit here.
if (fname != NULL && *fname != NUL) {
size_t namelen = strlen(fname);
// If the name is too long we might crash further on, quit here.
if (namelen >= MAXPATHL) {
filemess(curbuf, fname, _("Illegal file name"), 0);
msg_end();
msg_scroll = msg_save;
goto theend;
}
// If the name ends in a path separator, we can't open it. Check here,
// because reading the file may actually work, but then creating the
// swap file may destroy it! Reported on MS-DOS and Win 95.
if (after_pathsep(fname, fname + namelen)) {
if (!silent) {
filemess(curbuf, fname, _(msg_is_a_directory), 0);
}
msg_end();
msg_scroll = msg_save;
retval = NOTDONE;
goto theend;
}
}
if (!read_buffer && !read_stdin && !read_fifo) {
perm = os_getperm(fname);
// On Unix it is possible to read a directory, so we have to
// check for it before os_open().
#ifdef OPEN_CHR_FILES
# define IS_CHR_DEV(perm, fname) S_ISCHR(perm) && is_dev_fd_file(fname)
#else
# define IS_CHR_DEV(perm, fname) false
#endif
if (perm >= 0 && !S_ISREG(perm) // not a regular file ...
&& !S_ISFIFO(perm) // ... or fifo
&& !S_ISSOCK(perm) // ... or socket
&& !(IS_CHR_DEV(perm, fname))
// ... or a character special file named /dev/fd/<n>
) {
if (S_ISDIR(perm)) {
if (!silent) {
filemess(curbuf, fname, _(msg_is_a_directory), 0);
}
retval = NOTDONE;
} else {
filemess(curbuf, fname, _("is not a file"), 0);
}
msg_end();
msg_scroll = msg_save;
goto theend;
}
}
// Set default or forced 'fileformat' and 'binary'.
set_file_options(set_options, eap);
// 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
// Only set/reset b_p_ro when BF_CHECK_RO is set.
check_readonly = (newfile && (curbuf->b_flags & BF_CHECK_RO));
if (check_readonly && !readonlymode) {
curbuf->b_p_ro = false;
}
if (newfile && !read_stdin && !read_buffer && !read_fifo) {
// Remember time of file.
if (os_fileinfo(fname, &file_info)) {
buf_store_file_info(curbuf, &file_info);
curbuf->b_mtime_read = curbuf->b_mtime;
curbuf->b_mtime_read_ns = curbuf->b_mtime_ns;
#ifdef UNIX
// Use the protection bits of the original file for the swap file.
// This makes it possible for others to read the name of the
// edited file from the swapfile, but only if they can read the
// edited file.
// Remove the "write" and "execute" bits for group and others
// (they must not write the swapfile).
// Add the "read" and "write" bits for the user, otherwise we may
// not be able to write to the file ourselves.
// Setting the bits is done below, after creating the swap file.
swap_mode = ((int)file_info.stat.st_mode & 0644) | 0600;
#endif
} else {
curbuf->b_mtime = 0;
curbuf->b_mtime_ns = 0;
curbuf->b_mtime_read = 0;
curbuf->b_mtime_read_ns = 0;
curbuf->b_orig_size = 0;
curbuf->b_orig_mode = 0;
}
// Reset the "new file" flag. It will be set again below when the
// file doesn't exist.
curbuf->b_flags &= ~(BF_NEW | BF_NEW_W);
}
// Check readonly.
bool file_readonly = false;
if (!read_buffer && !read_stdin) {
if (!newfile || readonlymode || !(perm & 0222)
|| !os_file_is_writable(fname)) {
file_readonly = true;
}
fd = os_open(fname, O_RDONLY, 0);
}
if (fd < 0) { // cannot open at all
msg_scroll = msg_save;
if (!newfile) {
goto theend;
}
if (perm == UV_ENOENT) { // check if the file exists
// Set the 'new-file' flag, so that when the file has
// been created by someone else, a ":w" will complain.
curbuf->b_flags |= BF_NEW;
// Create a swap file now, so that other Vims are warned
// that we are editing this file. Don't do this for a
// "nofile" or "nowrite" buffer type.
if (!bt_dontwrite(curbuf)) {
check_need_swap(newfile);
// SwapExists autocommand may mess things up
if (curbuf != old_curbuf
|| (using_b_ffname
&& (old_b_ffname != curbuf->b_ffname))
|| (using_b_fname
&& (old_b_fname != curbuf->b_fname))) {
emsg(_(e_auchangedbuf));
goto theend;
}
}
if (!silent) {
if (dir_of_file_exists(fname)) {
filemess(curbuf, sfname, _("[New]"), 0);
} else {
filemess(curbuf, sfname, _("[New DIRECTORY]"), 0);
}
}
// Even though this is a new file, it might have been
// edited before and deleted. Get the old marks.
check_marks_read();
// Set forced 'fileencoding'.
if (eap != NULL) {
set_forced_fenc(eap);
}
apply_autocmds_exarg(EVENT_BUFNEWFILE, sfname, sfname,
false, curbuf, eap);
// remember the current fileformat
save_file_ff(curbuf);
if (!aborting()) { // autocmds may abort script processing
retval = OK; // a new file is not an error
}
goto theend;
}
#if defined(UNIX) && defined(EOVERFLOW)
filemess(curbuf, sfname, ((fd == UV_EFBIG) ? _("[File too big]")
:
// libuv only returns -errno
// in Unix and in Windows
// open() does not set
// EOVERFLOW
(fd == -EOVERFLOW) ? _("[File too big]")
: _("[Permission Denied]")), 0);
#else
filemess(curbuf, sfname, ((fd == UV_EFBIG) ? _("[File too big]")
: _("[Permission Denied]")), 0);
#endif
curbuf->b_p_ro = true; // must use "w!" now
goto theend;
}
// Only set the 'ro' flag for readonly files the first time they are
// loaded. Help files always get readonly mode
if ((check_readonly && file_readonly) || curbuf->b_help) {
curbuf->b_p_ro = true;
}
if (set_options) {
// Don't change 'eol' if reading from buffer as it will already be
// correctly set when reading stdin.
if (!read_buffer) {
curbuf->b_p_eof = false;
curbuf->b_start_eof = false;
curbuf->b_p_eol = true;
curbuf->b_start_eol = true;
}
curbuf->b_p_bomb = false;
curbuf->b_start_bomb = false;
}
// Create a swap file now, so that other Vims are warned that we are
// editing this file.
// Don't do this for a "nofile" or "nowrite" buffer type.
if (!bt_dontwrite(curbuf)) {
check_need_swap(newfile);
if (!read_stdin
&& (curbuf != old_curbuf
|| (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
|| (using_b_fname && (old_b_fname != curbuf->b_fname)))) {
emsg(_(e_auchangedbuf));
if (!read_buffer) {
close(fd);
}
goto theend;
}
#ifdef UNIX
// Set swap file protection bits after creating it.
if (swap_mode > 0 && curbuf->b_ml.ml_mfp != NULL
&& curbuf->b_ml.ml_mfp->mf_fname != NULL) {
const char *swap_fname = curbuf->b_ml.ml_mfp->mf_fname;
// If the group-read bit is set but not the world-read bit, then
// the group must be equal to the group of the original file. If
// we can't make that happen then reset the group-read bit. This
// avoids making the swap file readable to more users when the
// primary group of the user is too permissive.
if ((swap_mode & 044) == 040) {
FileInfo swap_info;
if (os_fileinfo(swap_fname, &swap_info)
&& file_info.stat.st_gid != swap_info.stat.st_gid
&& os_fchown(curbuf->b_ml.ml_mfp->mf_fd, (uv_uid_t)(-1),
(uv_gid_t)file_info.stat.st_gid)
== -1) {
swap_mode &= 0600;
}
}
(void)os_setperm(swap_fname, swap_mode);
}
#endif
}
// If "Quit" selected at ATTENTION dialog, don't load the file.
if (swap_exists_action == SEA_QUIT) {
if (!read_buffer && !read_stdin) {
close(fd);
}
goto theend;
}
no_wait_return++; // don't wait for return yet
// Set '[ mark to the line above where the lines go (line 1 if zero).
orig_start = curbuf->b_op_start;
curbuf->b_op_start.lnum = ((from == 0) ? 1 : from);
curbuf->b_op_start.col = 0;
int try_mac = (vim_strchr(p_ffs, 'm') != NULL);
int try_dos = (vim_strchr(p_ffs, 'd') != NULL);
int try_unix = (vim_strchr(p_ffs, 'x') != NULL);
if (!read_buffer) {
int m = msg_scroll;
int n = msg_scrolled;
// The file must be closed again, the autocommands may want to change
// the file before reading it.
if (!read_stdin) {
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_exarg(EVENT_FILTERREADPRE, NULL, sfname,
false, curbuf, eap);
} else if (read_stdin) {
apply_autocmds_exarg(EVENT_STDINREADPRE, NULL, sfname,
false, curbuf, eap);
} else if (newfile) {
apply_autocmds_exarg(EVENT_BUFREADPRE, NULL, sfname,
false, curbuf, eap);
} else {
apply_autocmds_exarg(EVENT_FILEREADPRE, sfname, sfname,
false, NULL, eap);
}
// autocommands may have changed it
try_mac = (vim_strchr(p_ffs, 'm') != NULL);
try_dos = (vim_strchr(p_ffs, 'd') != NULL);
try_unix = (vim_strchr(p_ffs, 'x') != NULL);
curbuf->b_op_start = orig_start;
if (msg_scrolled == n) {
msg_scroll = m;
}
if (aborting()) { // autocmds may abort script processing
no_wait_return--;
msg_scroll = msg_save;
curbuf->b_p_ro = true; // must use "w!" now
goto theend;
}
// Don't allow the autocommands to change the current buffer.
// Try to re-open the file.
//
// Don't allow the autocommands to change the buffer name either
// (cd for example) if it invalidates fname or sfname.
if (!read_stdin && (curbuf != old_curbuf
|| (using_b_ffname && (old_b_ffname != curbuf->b_ffname))
|| (using_b_fname && (old_b_fname != curbuf->b_fname))
|| (fd = os_open(fname, O_RDONLY, 0)) < 0)) {
no_wait_return--;
msg_scroll = msg_save;
if (fd < 0) {
emsg(_("E200: *ReadPre autocommands made the file unreadable"));
} else {
emsg(_("E201: *ReadPre autocommands must not change current buffer"));
}
curbuf->b_p_ro = true; // must use "w!" now
goto theend;
}
}
// Autocommands may add lines to the file, need to check if it is empty
wasempty = (curbuf->b_ml.ml_flags & ML_EMPTY);
if (!recoverymode && !filtering && !(flags & READ_DUMMY) && !silent) {
if (!read_stdin && !read_buffer) {
filemess(curbuf, sfname, "", 0);
}
}
msg_scroll = false; // overwrite the file message
// Set linecnt now, before the "retry" caused by a wrong guess for
// fileformat, and after the autocommands, which may change them.
linecnt = curbuf->b_ml.ml_line_count;
// "++bad=" argument.
if (eap != NULL && eap->bad_char != 0) {
bad_char_behavior = eap->bad_char;
if (set_options) {
curbuf->b_bad_char = eap->bad_char;
}
} else {
curbuf->b_bad_char = 0;
}
// Decide which 'encoding' to use or use first.
if (eap != NULL && eap->force_enc != 0) {
fenc = enc_canonize(eap->cmd + eap->force_enc);
fenc_alloced = true;
keep_dest_enc = true;
} else if (curbuf->b_p_bin) {
fenc = ""; // binary: don't convert
fenc_alloced = false;
} else if (curbuf->b_help) {
// Help files are either utf-8 or latin1. Try utf-8 first, if this
// fails it must be latin1.
// It is needed when the first line contains non-ASCII characters.
// That is only in *.??x files.
fenc_next = "latin1";
fenc = "utf-8";
fenc_alloced = false;
} else if (*p_fencs == NUL) {
fenc = curbuf->b_p_fenc; // use format from buffer
fenc_alloced = false;
} else {
fenc_next = p_fencs; // try items in 'fileencodings'
fenc = next_fenc(&fenc_next, &fenc_alloced);
}
// Jump back here to retry reading the file in different ways.
// Reasons to retry:
// - encoding conversion failed: try another one from "fenc_next"
// - BOM detected and fenc was set, need to setup conversion
// - "fileformat" check failed: try another
//
// Variables set for special retry actions:
// "file_rewind" Rewind the file to start reading it again.
// "advance_fenc" Advance "fenc" using "fenc_next".
// "skip_read" Re-use already read bytes (BOM detected).
// "did_iconv" iconv() conversion failed, try 'charconvert'.
// "keep_fileformat" Don't reset "fileformat".
//
// Other status indicators:
// "tmpname" When != NULL did conversion with 'charconvert'.
// Output file has to be deleted afterwards.
// "iconv_fd" When != -1 did conversion with iconv().
retry:
if (file_rewind) {
if (read_buffer) {
read_buf_lnum = 1;
read_buf_col = 0;
} else if (read_stdin || vim_lseek(fd, 0, SEEK_SET) != 0) {
// Can't rewind the file, give up.
error = true;
goto failed;
}
// Delete the previously read lines.
while (lnum > from) {
ml_delete(lnum--, false);
}
file_rewind = false;
if (set_options) {
curbuf->b_p_bomb = false;
curbuf->b_start_bomb = false;
}
conv_error = 0;
}
// When retrying with another "fenc" and the first time "fileformat"
// will be reset.
if (keep_fileformat) {
keep_fileformat = false;
} else {
if (eap != NULL && eap->force_ff != 0) {
fileformat = get_fileformat_force(curbuf, eap);
try_unix = try_dos = try_mac = false;
} else if (curbuf->b_p_bin) {
fileformat = EOL_UNIX; // binary: use Unix format
} else if (*p_ffs ==
NUL) {
fileformat = get_fileformat(curbuf); // use format from buffer
} else {
fileformat = EOL_UNKNOWN; // detect from file
}
}
if (iconv_fd != (iconv_t)-1) {
// aborted conversion with iconv(), close the descriptor
iconv_close(iconv_fd);
iconv_fd = (iconv_t)-1;
}
if (advance_fenc) {
// Try the next entry in 'fileencodings'.
advance_fenc = false;
if (eap != NULL && eap->force_enc != 0) {
// Conversion given with "++cc=" wasn't possible, read
// without conversion.
notconverted = true;
conv_error = 0;
if (fenc_alloced) {
xfree(fenc);
}
fenc = "";
fenc_alloced = false;
} else {
if (fenc_alloced) {
xfree(fenc);
}
if (fenc_next != NULL) {
fenc = next_fenc(&fenc_next, &fenc_alloced);
} else {
fenc = "";
fenc_alloced = false;
}
}
if (tmpname != NULL) {
os_remove(tmpname); // delete converted file
XFREE_CLEAR(tmpname);
}
}
// Conversion may be required when the encoding of the file is different
// from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4.
fio_flags = 0;
converted = need_conversion(fenc);
if (converted) {
// "ucs-bom" means we need to check the first bytes of the file
// for a BOM.
if (strcmp(fenc, ENC_UCSBOM) == 0) {
fio_flags = FIO_UCSBOM;
} else {
// Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be
// done. This is handled below after read(). Prepare the
// fio_flags to avoid having to parse the string each time.
// Also check for Unicode to Latin1 conversion, because iconv()
// appears not to handle this correctly. This works just like
// conversion to UTF-8 except how the resulting character is put in
// the buffer.
fio_flags = get_fio_flags(fenc);
}
// Try using iconv() if we can't convert internally.
if (fio_flags == 0
&& !did_iconv) {
iconv_fd = (iconv_t)my_iconv_open("utf-8", fenc);
}
// Use the 'charconvert' expression when conversion is required
// and we can't do it internally or with iconv().
if (fio_flags == 0 && !read_stdin && !read_buffer && *p_ccv != NUL
&& !read_fifo && iconv_fd == (iconv_t)-1) {
did_iconv = false;
// Skip conversion when it's already done (retry for wrong
// "fileformat").
if (tmpname == NULL) {
tmpname = readfile_charconvert(fname, fenc, &fd);
if (tmpname == NULL) {
// Conversion failed. Try another one.
advance_fenc = true;
if (fd < 0) {
// Re-opening the original file failed!
emsg(_("E202: Conversion made file unreadable!"));
error = true;
goto failed;
}
goto retry;
}
}
} else {
if (fio_flags == 0 && iconv_fd == (iconv_t)-1) {
// Conversion wanted but we can't.
// Try the next conversion in 'fileencodings'
advance_fenc = true;
goto retry;
}
}
}
// Set "can_retry" when it's possible to rewind the file and try with
// another "fenc" value. It's false when no other "fenc" to try, reading
// stdin or fixed at a specific encoding.
can_retry = (*fenc != NUL && !read_stdin && !keep_dest_enc && !read_fifo);
if (!skip_read) {
linerest = 0;
filesize = 0;
skip_count = lines_to_skip;
read_count = lines_to_read;
conv_restlen = 0;
read_undo_file = (newfile && (flags & READ_KEEP_UNDO) == 0
&& curbuf->b_ffname != NULL
&& curbuf->b_p_udf
&& !filtering
&& !read_fifo
&& !read_stdin
&& !read_buffer);
if (read_undo_file) {
sha256_start(&sha_ctx);
}
}
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
// up to max_unsigned characters (and other things).
{
if (!skip_read) {
// Use buffer >= 64K. Add linerest to double the size if the
// line gets very long, to avoid a lot of copying. But don't
// read more than 1 Mbyte at a time, so we can be interrupted.
size = 0x10000 + linerest;
if (size > 0x100000) {
size = 0x100000;
}
}
// Protect against the argument of lalloc() going negative.
if (size < 0 || size + linerest + 1 < 0 || linerest >= MAXCOL) {
split++;
*ptr = NL; // split line by inserting a NL
size = 1;
} else if (!skip_read) {
for (; size >= 10; size /= 2) {
new_buffer = verbose_try_malloc((size_t)size + (size_t)linerest + 1);
if (new_buffer) {
break;
}
}
if (new_buffer == NULL) {
error = true;
break;
}
if (linerest) { // copy characters from the previous buffer
memmove(new_buffer, ptr - linerest, (size_t)linerest);
}
xfree(buffer);
buffer = new_buffer;
ptr = buffer + linerest;
line_start = buffer;
// May need room to translate into.
// For iconv() we don't really know the required space, use a
// factor ICONV_MULT.
// latin1 to utf-8: 1 byte becomes up to 2 bytes
// utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes
// become up to 4 bytes, size must be multiple of 2
// ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be
// multiple of 2
// ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be
// multiple of 4
real_size = (int)size;
if (iconv_fd != (iconv_t)-1) {
size = size / ICONV_MULT;
} else if (fio_flags & FIO_LATIN1) {
size = size / 2;
} else if (fio_flags & (FIO_UCS2 | FIO_UTF16)) {
size = (size * 2 / 3) & ~1;
} else if (fio_flags & FIO_UCS4) {
size = (size * 2 / 3) & ~3;
} else if (fio_flags == FIO_UCSBOM) {
size = size / ICONV_MULT; // worst case
}
if (conv_restlen > 0) {
// Insert unconverted bytes from previous line.
memmove(ptr, conv_rest, (size_t)conv_restlen);
ptr += conv_restlen;
size -= conv_restlen;
}
if (read_buffer) {
// Read bytes from curbuf. Used for converting text read
// from stdin.
if (read_buf_lnum > from) {
size = 0;
} else {
int ni;
int tlen = 0;
while (true) {
p = (uint8_t *)ml_get(read_buf_lnum) + read_buf_col;
int n = (int)strlen((char *)p);
if (tlen + n + 1 > size) {
// Filled up to "size", append partial line.
// Change NL to NUL to reverse the effect done
// below.
n = (int)(size - tlen);
for (ni = 0; ni < n; ni++) {
if (p[ni] == NL) {
ptr[tlen++] = NUL;
} else {
ptr[tlen++] = (char)p[ni];
}
}
read_buf_col += n;
break;
}
// Append whole line and new-line. Change NL
// to NUL to reverse the effect done below.
for (ni = 0; ni < n; ni++) {
if (p[ni] == NL) {
ptr[tlen++] = NUL;
} else {
ptr[tlen++] = (char)p[ni];
}
}
ptr[tlen++] = NL;
read_buf_col = 0;
if (++read_buf_lnum > from) {
// When the last line didn't have an
// end-of-line don't add it now either.
if (!curbuf->b_p_eol) {
tlen--;
}
size = tlen;
break;
}
}
}
} else {
// Read bytes from the file.
size_t read_size = (size_t)size;
size = read_eintr(fd, ptr, read_size);
}