robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
aa1d8a2702
master
1// fileio.c: read from and write to a file 2 3#include <assert.h> 4#include <errno.h> 5#include <fcntl.h> 6#include <iconv.h> 7#include <inttypes.h> 8#include <limits.h> 9#include <stdbool.h> 10#include <stddef.h> 11#include <stdio.h> 12#include <string.h> 13#include <sys/stat.h> 14#include <sys/types.h> 15#include <time.h> 16#include <uv.h> 17 18#include "auto/config.h" 19#include "nvim/ascii_defs.h" 20#include "nvim/autocmd.h" 21#include "nvim/autocmd_defs.h" 22#include "nvim/buffer.h" 23#include "nvim/buffer_defs.h" 24#include "nvim/buffer_updates.h" 25#include "nvim/change.h" 26#include "nvim/context.h" 27#include "nvim/cursor.h" 28#include "nvim/dialog.h" 29#include "nvim/diff.h" 30#include "nvim/drawscreen.h" 31#include "nvim/errors.h" 32#include "nvim/eval.h" 33#include "nvim/eval/vars.h" 34#include "nvim/ex_cmds_defs.h" 35#include "nvim/ex_eval.h" 36#include "nvim/fileio.h" 37#include "nvim/fold.h" 38#include "nvim/garray.h" 39#include "nvim/garray_defs.h" 40#include "nvim/gettext_defs.h" 41#include "nvim/globals.h" 42#include "nvim/highlight_defs.h" 43#include "nvim/iconv_defs.h" 44#include "nvim/input.h" 45#include "nvim/insert.h" 46#include "nvim/log.h" 47#include "nvim/macros_defs.h" 48#include "nvim/mbyte.h" 49#include "nvim/mbyte_defs.h" 50#include "nvim/mcursor.h" 51#include "nvim/memfile.h" 52#include "nvim/memfile_defs.h" 53#include "nvim/memline.h" 54#include "nvim/memline_defs.h" 55#include "nvim/memory.h" 56#include "nvim/message.h" 57#include "nvim/move.h" 58#include "nvim/option.h" 59#include "nvim/option_defs.h" 60#include "nvim/option_vars.h" 61#include "nvim/os/fs.h" 62#include "nvim/os/fs_defs.h" 63#include "nvim/os/input.h" 64#include "nvim/os/os.h" 65#include "nvim/os/os_defs.h" 66#include "nvim/os/time.h" 67#include "nvim/path.h" 68#include "nvim/pos_defs.h" 69#include "nvim/regexp.h" 70#include "nvim/regexp_defs.h" 71#include "nvim/sha256.h" 72#include "nvim/shada.h" 73#include "nvim/state_defs.h" 74#include "nvim/strings.h" 75#include "nvim/types_defs.h" 76#include "nvim/ui.h" 77#include "nvim/undo.h" 78#include "nvim/undo_defs.h" 79#include "nvim/vim_defs.h" 80 81#ifdef BACKSLASH_IN_FILENAME 82# include "nvim/charset.h" 83#endif 84 85#ifdef HAVE_DIRFD_AND_FLOCK 86# include <dirent.h> 87# include <sys/file.h> 88#endif 89 90#ifdef MSWIN 91# include "nvim/os/os_win_console.h" 92#endif 93 94#ifdef OPEN_CHR_FILES 95# include "nvim/charset.h" 96#endif 97 98// For compatibility with libuv < 1.20.0 (tested on 1.18.0) 99#ifndef UV_FS_COPYFILE_FICLONE 100# define UV_FS_COPYFILE_FICLONE 0 101#endif 102 103#include "fileio.c.generated.h" 104 105static const char * e_auchangedbuf = N_ ("E812: Autocommands changed buffer or buffer name" ); 106 107// Bitmask with 0x80 set in each byte of a uint64_t word, used to detect 108// non-ASCII bytes (high bit set) in multiple bytes at once. 109#define NONASCII_MASK (((uint64_t)(-1) / 0xFF) * 0x80) 110 111/// Shows a message about file `name`, e.g. `"foo.txt" [New]`. 112/// 113/// @param s Info appended to the filename, e.g. "[New]". 114/// @param msg_id Emit as a progress-message with this id, or NULL for a plain message. 115/// Caller must emit a non-"running" status for `msg_id`, later. 116static void filemess (buf_T * buf ,char * name ,char * s ,const char * msg_id ) 117{ 118int prev_msg_col = msg_col ; 119 120if (msg_silent != 0 ) { 121return ; 122 } 123 124add_quoted_fname (IObuff ,IOSIZE - 100 ,buf ,name ); 125 126// Avoid an over-long translation to cause trouble. 127xstrlcat (IObuff ,s ,IOSIZE ); 128 129// For the first message may have to start a new line. 130// For further ones overwrite the previous one, reset msg_scroll before 131// calling filemess(). 132int msg_scroll_save = msg_scroll ; 133if (shortmess (kShmOverall )&& !msg_listdo_overwrite && !exiting && p_verbose == 0 ) { 134msg_scroll = false; 135 } 136if (!msg_scroll ) {// wait a bit when overwriting an error msg 137msg_check_for_delay (false); 138 } 139msg_start (); 140if (prev_msg_col != 0 && msg_col == 0 ) { 141msg_putchar ('\r' );// overwrite any previous message. 142 } 143msg_scroll = msg_scroll_save ; 144msg_scrolled_ign = true; 145// may truncate the message to avoid a hit-return prompt 146if (msg_id != NULL ) { 147msg_progress (IObuff , (char * )msg_id ,"running" ,0 , false, true, false); 148 }else { 149msg_outtrans (msg_may_trunc (false,IObuff ),0 , false); 150 } 151msg_clr_eos (); 152msg_scrolled_ign = false; 153} 154 155/// Shows the "busy" message for writing file `name`, as a progress-message. #39280 156/// Caller must end the progress by emitting a non-"running" status to the same `msg_id`. 157void filemess_progress (buf_T * buf ,char * name ,const char * msg_id ) 158{ 159filemess (buf ,name ,"" ,msg_id ); 160} 161 162/// Read lines from file "fname" into the buffer after line "from". 163/// 164/// 1. We allocate blocks with try_malloc, as big as possible. 165/// 2. Each block is filled with characters from the file with a single read(). 166/// 3. The lines are inserted in the buffer with ml_append(). 167/// 168/// (caller must check that fname != NULL, unless READ_STDIN is used) 169/// 170/// "lines_to_skip" is the number of lines that must be skipped 171/// "lines_to_read" is the number of lines that are appended 172/// When not recovering lines_to_skip is 0 and lines_to_read MAXLNUM. 173/// 174/// flags: 175/// READ_NEW starting to edit a new buffer 176/// READ_FILTER reading filter output 177/// READ_STDIN read from stdin instead of a file 178/// READ_BUFFER read from curbuf instead of a file (converting after reading 179/// stdin) 180/// READ_NOFILE do not read a file, only trigger BufReadCmd 181/// READ_DUMMY read into a dummy buffer (to check if file contents changed) 182/// READ_KEEP_UNDO don't clear undo info or read it from a file 183/// READ_FIFO read from fifo/socket instead of a file 184/// 185/// @param eap can be NULL! 186/// 187/// @return FAIL for failure, NOTDONE for directory (failure), or OK 188int readfile (char * fname ,char * sfname ,linenr_T from ,linenr_T lines_to_skip , 189linenr_T lines_to_read ,exarg_T * eap ,int flags ,bool silent ) 190{ 191int retval = FAIL ;// jump to "theend" instead of returning 192int fd = stdin_fd >=0 ?stdin_fd :0 ; 193bool newfile = (flags & READ_NEW ); 194bool filtering = (flags & READ_FILTER ); 195bool read_stdin = (flags & READ_STDIN ); 196bool read_buffer = (flags & READ_BUFFER ); 197bool read_fifo = (flags & READ_FIFO ); 198bool set_options = newfile || read_buffer || (eap != NULL && eap -> read_edit ); 199linenr_T read_buf_lnum = 1 ;// next line to read from curbuf 200colnr_T read_buf_col = 0 ;// next char to read from this line 201char c ; 202linenr_T lnum = from ; 203char * ptr = NULL ;// pointer into read buffer 204char * buffer = NULL ;// read buffer 205char * new_buffer = NULL ;// init to shut up gcc 206char * line_start = NULL ;// init to shut up gcc 207int wasempty ;// buffer was empty before reading 208colnr_T len ; 209ptrdiff_t size = 0 ; 210uint8_t * p = NULL ; 211off_T filesize = 0 ; 212bool skip_read = false; 213context_sha256_T sha_ctx ; 214bool read_undo_file = false; 215int split = 0 ;// number of split lines 216linenr_T linecnt ; 217bool error = false;// errors encountered 218int ff_error = EOL_UNKNOWN ;// file format with errors 219ptrdiff_t linerest = 0 ;// remaining chars in line 220int perm = 0 ; 221#ifdef UNIX 222int swap_mode = -1 ;// protection bits for swap file 223#endif 224int fileformat = 0 ;// end-of-line format 225bool keep_fileformat = false; 226FileInfo file_info ; 227linenr_T skip_count = 0 ; 228linenr_T read_count = 0 ; 229int msg_save = msg_scroll ; 230linenr_T read_no_eol_lnum = 0 ;// non-zero lnum when last line of 231// last read was missing the eol 232bool file_rewind = false; 233linenr_T conv_error = 0 ;// line nr with conversion error 234linenr_T illegal_byte = 0 ;// line nr with illegal byte 235bool keep_dest_enc = false;// don't retry when char doesn't fit 236// in destination encoding 237int bad_char_behavior = BAD_REPLACE ; 238// BAD_KEEP, BAD_DROP or character to 239// replace with 240char * tmpname = NULL ;// name of 'charconvert' output file 241int fio_flags = 0 ; 242char * fenc ;// fileencoding to use 243bool fenc_alloced ;// fenc_next is in allocated memory 244char * fenc_next = NULL ;// next item in 'fencs' or NULL 245bool advance_fenc = false; 246int real_size = 0 ; 247iconv_t iconv_fd = (iconv_t )- 1 ;// descriptor for iconv() or -1 248bool did_iconv = false;// true when iconv() failed and trying 249// 'charconvert' next 250bool converted = false;// true if conversion done 251bool notconverted = false;// true if conversion wanted but it wasn't possible 252char conv_rest [CONV_RESTLEN ]; 253int conv_restlen = 0 ;// nr of bytes in conv_rest[] 254pos_T orig_start ; 255buf_T * old_curbuf ; 256char * old_b_ffname ; 257char * old_b_fname ; 258int using_b_ffname ; 259int using_b_fname ; 260static char * msg_is_a_directory = N_ ("is a directory" ); 261 262curbuf -> b_au_did_filetype = false;// reset before triggering any autocommands 263 264curbuf -> b_no_eol_lnum = 0 ;// in case it was set by the previous read 265 266// If there is no file name yet, use the one for the read file. 267// BF_NOTEDITED is set to reflect this. 268// Don't do this for a read from a filter. 269// Only do this when 'cpoptions' contains the 'f' flag. 270if (curbuf -> b_ffname == NULL 271&& !filtering 272&& fname != NULL 273&& vim_strchr (p_cpo ,kCpoFnamer )!= NULL 274&& !(flags & READ_DUMMY )) { 275if (set_rw_fname (fname ,sfname )== FAIL ) { 276 gototheend ; 277 } 278 } 279 280// Remember the initial values of curbuf, curbuf->b_ffname and 281// curbuf->b_fname to detect whether they are altered as a result of 282// executing nasty autocommands. Also check if "fname" and "sfname" 283// point to one of these values. 284old_curbuf = curbuf ; 285old_b_ffname = curbuf -> b_ffname ; 286old_b_fname = curbuf -> b_fname ; 287using_b_ffname = (fname == curbuf -> b_ffname )|| (sfname == curbuf -> b_ffname ); 288using_b_fname = (fname == curbuf -> b_fname )|| (sfname == curbuf -> b_fname ); 289 290// don't display the file info for another buffer now 291need_fileinfo = false; 292 293// For Unix: Use the short file name whenever possible. 294// Avoids problems with networks and when directory names are changed. 295// Don't do this for Windows, a "cd" in a sub-shell may have moved us to 296// another directory, which we don't detect. 297if (sfname == NULL ) { 298sfname = fname ; 299 } 300#ifdef UNIX 301fname = sfname ; 302#endif 303 304// The BufReadCmd and FileReadCmd events intercept the reading process by 305// executing the associated commands instead. 306if (!filtering && !read_stdin && !read_buffer ) { 307orig_start = curbuf -> b_op_start ; 308 309// Set '[ mark to the line above where the lines go (line 1 if zero). 310curbuf -> b_op_start .lnum = ((from == 0 ) ?1 :from ); 311curbuf -> b_op_start .col = 0 ; 312 313if (newfile ) { 314if (apply_autocmds_exarg (EVENT_BUFREADCMD ,NULL ,sfname , 315 false,curbuf ,eap )) { 316retval = OK ; 317if (aborting ()) { 318retval = FAIL ; 319 } 320 321// The BufReadCmd code usually uses ":read" to get the text and 322// perhaps ":file" to change the buffer name. But we should 323// consider this to work like ":edit", thus reset the 324// BF_NOTEDITED flag. Then ":write" will work to overwrite the 325// same file. 326if (retval == OK && !curbuf -> b_au_did_filetype && * curbuf -> b_p_ft != NUL ) { 327apply_autocmds (EVENT_FILETYPE ,curbuf -> b_p_ft ,curbuf -> b_fname , true,curbuf ); 328if (aborting ()) { 329retval = FAIL ; 330 } 331 } 332if (retval == OK ) { 333curbuf -> b_flags &= ~BF_NOTEDITED ; 334 } 335 gototheend ; 336 } 337 }else if (apply_autocmds_exarg (EVENT_FILEREADCMD ,sfname ,sfname , 338 false,NULL ,eap )) { 339retval = aborting () ?FAIL :OK ; 340 gototheend ; 341 } 342 343curbuf -> b_op_start = orig_start ; 344 345if (flags & READ_NOFILE ) { 346// Return NOTDONE instead of FAIL so that BufEnter can be triggered 347// and other operations don't fail. 348retval = NOTDONE ; 349 gototheend ; 350 } 351 } 352 353if (((shortmess (kShmOver )&& !msg_listdo_overwrite )|| curbuf -> b_help )&& p_verbose == 0 ) { 354msg_scroll = false;// overwrite previous file message 355 }else { 356msg_scroll = true;// don't overwrite previous file message 357 } 358// If the name is too long we might crash further on, quit here. 359if (fname != NULL && * fname != NUL ) { 360size_t fnamelen = strlen (fname ); 361 362// If the name is too long we might crash further on, quit here. 363if (fnamelen >=MAXPATHL ) { 364filemess (curbuf ,fname ,_ ("Illegal file name" ),NULL ); 365msg_end (); 366msg_scroll = msg_save ; 367 gototheend ; 368 } 369 370// If the name ends in a path separator, we can't open it. Check here, 371// because reading the file may actually work, but then creating the 372// swap file may destroy it! Reported on MS-DOS and Win 95. 373if (after_pathsep (fname ,fname + fnamelen )) { 374if (!silent ) { 375filemess (curbuf ,fname ,_ (msg_is_a_directory ),NULL ); 376 } 377msg_end (); 378msg_scroll = msg_save ; 379retval = NOTDONE ; 380 gototheend ; 381 } 382 } 383 384if (!read_stdin && fname != NULL ) { 385perm = os_getperm (fname ); 386 } 387 388#ifdef OPEN_CHR_FILES 389# define IS_CHR_DEV (perm ,fname ) S_ISCHR(perm) && is_dev_fd_file(fname) 390#else 391# define IS_CHR_DEV (perm ,fname ) false 392#endif 393 394if (!read_stdin && !read_buffer && !read_fifo ) { 395if (perm >=0 && !S_ISREG (perm )// not a regular file ... 396&& !S_ISFIFO (perm )// ... or fifo 397&& !S_ISSOCK (perm )// ... or socket 398&& !(IS_CHR_DEV (perm ,fname )) 399// ... or a character special file named /dev/fd/<n> 400 ) { 401// On Unix it is possible to read a directory, so we have to 402// check for it before os_open(). 403if (S_ISDIR (perm )) { 404if (!silent ) { 405filemess (curbuf ,fname ,_ (msg_is_a_directory ),NULL ); 406 } 407retval = NOTDONE ; 408 }else { 409filemess (curbuf ,fname ,_ ("is not a file" ),NULL ); 410 } 411msg_end (); 412msg_scroll = msg_save ; 413 gototheend ; 414 } 415 } 416 417// Set default or forced 'fileformat' and 'binary'. 418set_file_options (set_options ,eap ); 419 420// When opening a new file we take the readonly flag from the file. 421// Default is r/w, can be set to r/o below. 422// Don't reset it when in readonly mode 423// Only set/reset b_p_ro when BF_CHECK_RO is set. 424bool check_readonly = (newfile && (curbuf -> b_flags & BF_CHECK_RO )); 425if (check_readonly && !readonlymode ) { 426curbuf -> b_p_ro = false; 427 } 428 429if (newfile && !read_stdin && !read_buffer && !read_fifo ) { 430// Remember time of file. 431if (os_fileinfo (fname ,& file_info )) { 432buf_store_file_info (curbuf ,& file_info ); 433curbuf -> b_mtime_read = curbuf -> b_mtime ; 434curbuf -> b_mtime_read_ns = curbuf -> b_mtime_ns ; 435#ifdef UNIX 436// Use the protection bits of the original file for the swap file. 437// This makes it possible for others to read the name of the 438// edited file from the swapfile, but only if they can read the 439// edited file. 440// Remove the "write" and "execute" bits for group and others 441// (they must not write the swapfile). 442// Add the "read" and "write" bits for the user, otherwise we may 443// not be able to write to the file ourselves. 444// Setting the bits is done below, after creating the swap file. 445swap_mode = ((int )file_info .stat .st_mode & 0644 ) |0600 ; 446#endif 447 }else { 448curbuf -> b_mtime = 0 ; 449curbuf -> b_mtime_ns = 0 ; 450curbuf -> b_mtime_read = 0 ; 451curbuf -> b_mtime_read_ns = 0 ; 452curbuf -> b_orig_size = 0 ; 453curbuf -> b_orig_mode = 0 ; 454 } 455 456// Reset the "new file" flag. It will be set again below when the 457// file doesn't exist. 458curbuf -> b_flags &= ~(BF_NEW |BF_NEW_W ); 459 } 460 461// Check readonly. 462bool file_readonly = false; 463if (!read_buffer && !read_stdin ) { 464if (!newfile || readonlymode || !(perm & 0222 ) 465|| !os_file_is_writable (fname )) { 466file_readonly = true; 467 } 468fd = os_open (fname ,O_RDONLY ,0 ); 469 } 470 471if (fd < 0 ) {// cannot open at all 472msg_scroll = msg_save ; 473if (!newfile ) { 474 gototheend ; 475 } 476if (perm == UV_ENOENT ) {// check if the file exists 477// Set the 'new-file' flag, so that when the file has 478// been created by someone else, a ":w" will complain. 479curbuf -> b_flags |=BF_NEW ; 480 481// Create a swap file now, so that other Vims are warned 482// that we are editing this file. Don't do this for a 483// "nofile" or "nowrite" buffer type. 484if (!bt_dontwrite (curbuf )) { 485check_need_swap (newfile ); 486// SwapExists autocommand may mess things up 487if (curbuf != old_curbuf 488|| (using_b_ffname 489&& (old_b_ffname != curbuf -> b_ffname )) 490|| (using_b_fname 491&& (old_b_fname != curbuf -> b_fname ))) { 492emsg (_ (e_auchangedbuf )); 493 gototheend ; 494 } 495 } 496if (!silent ) { 497if (dir_of_file_exists (fname )) { 498filemess (curbuf ,sfname ,_ ("[New]" ),NULL ); 499 }else { 500filemess (curbuf ,sfname ,_ ("[New DIRECTORY]" ),NULL ); 501 } 502 } 503// Even though this is a new file, it might have been 504// edited before and deleted. Get the old marks. 505check_marks_read (); 506// Set forced 'fileencoding'. 507if (eap != NULL ) { 508set_forced_fenc (eap ); 509 } 510apply_autocmds_exarg (EVENT_BUFNEWFILE ,sfname ,sfname , 511 false,curbuf ,eap ); 512// remember the current fileformat 513save_file_ff (curbuf ); 514 515if (!aborting ()) {// autocmds may abort script processing 516retval = OK ;// a new file is not an error 517 } 518 gototheend ; 519 } 520#if defined(UNIX )&& defined(EOVERFLOW ) 521filemess (curbuf ,sfname , 522 ((fd == UV_EFBIG ) 523 ?_ ("[File too big]" ) 524// libuv only returns -errno in Unix; Windows open() does not set EOVERFLOW. 525 : (fd == - EOVERFLOW ) ?_ ("[File too big]" ) :_ ("[Permission Denied]" )), 526NULL ); 527#else 528filemess (curbuf ,sfname , ((fd == UV_EFBIG ) ?_ ("[File too big]" ) :_ ("[Permission Denied]" )), 529NULL ); 530#endif 531curbuf -> b_p_ro = true;// must use "w!" now 532 533 gototheend ; 534 } 535 536// Only set the 'ro' flag for readonly files the first time they are 537// loaded. Help files always get readonly mode 538if ((check_readonly && file_readonly )|| curbuf -> b_help ) { 539curbuf -> b_p_ro = true; 540 } 541 542if (set_options ) { 543// Don't change 'eol' if reading from buffer as it will already be 544// correctly set when reading stdin. 545if (!read_buffer ) { 546curbuf -> b_p_eof = false; 547curbuf -> b_start_eof = false; 548curbuf -> b_p_eol = true; 549curbuf -> b_start_eol = true; 550 } 551curbuf -> b_p_bomb = false; 552curbuf -> b_start_bomb = false; 553 } 554 555// Create a swap file now, so that other Vims are warned that we are 556// editing this file. 557// Don't do this for a "nofile" or "nowrite" buffer type. 558if (!bt_dontwrite (curbuf )) { 559check_need_swap (newfile ); 560if (!read_stdin 561&& (curbuf != old_curbuf 562|| (using_b_ffname && (old_b_ffname != curbuf -> b_ffname )) 563|| (using_b_fname && (old_b_fname != curbuf -> b_fname )))) { 564emsg (_ (e_auchangedbuf )); 565if (!read_buffer ) { 566close (fd ); 567 } 568 gototheend ; 569 } 570#ifdef UNIX 571// Set swap file protection bits after creating it. 572if (swap_mode > 0 && curbuf -> b_ml .ml_mfp != NULL 573&& curbuf -> b_ml .ml_mfp -> mf_fname != NULL ) { 574const char * swap_fname = curbuf -> b_ml .ml_mfp -> mf_fname ; 575 576// If the group-read bit is set but not the world-read bit, then 577// the group must be equal to the group of the original file. If 578// we can't make that happen then reset the group-read bit. This 579// avoids making the swap file readable to more users when the 580// primary group of the user is too permissive. 581if ((swap_mode & 044 )== 040 ) { 582FileInfo swap_info ; 583 584if (os_fileinfo (swap_fname ,& swap_info ) 585&& file_info .stat .st_gid != swap_info .stat .st_gid 586&& os_fchown (curbuf -> b_ml .ml_mfp -> mf_fd , (uv_uid_t )(-1 ), 587 (uv_gid_t )file_info .stat .st_gid ) 588== -1 ) { 589swap_mode &=0600 ; 590 } 591 } 592 593os_setperm (swap_fname ,swap_mode ); 594 } 595#endif 596 } 597 598// If "Quit" selected at ATTENTION dialog, don't load the file. 599if (swap_exists_action == SEA_QUIT ) { 600if (!read_buffer && !read_stdin ) { 601close (fd ); 602 } 603 gototheend ; 604 } 605 606no_wait_return ++ ;// don't wait for return yet 607 608// Set '[ mark to the line above where the lines go (line 1 if zero). 609orig_start = curbuf -> b_op_start ; 610curbuf -> b_op_start .lnum = ((from == 0 ) ?1 :from ); 611curbuf -> b_op_start .col = 0 ; 612 613int try_mac = (vim_strchr (p_ffs ,'m' )!= NULL ); 614int try_dos = (vim_strchr (p_ffs ,'d' )!= NULL ); 615int try_unix = (vim_strchr (p_ffs ,'x' )!= NULL ); 616 617if (!read_buffer ) { 618int m = msg_scroll ; 619int n = msg_scrolled ; 620 621// The file must be closed again, the autocommands may want to change 622// the file before reading it. 623if (!read_stdin ) { 624close (fd );// ignore errors 625 } 626 627// The output from the autocommands should not overwrite anything and 628// should not be overwritten: Set msg_scroll, restore its value if no 629// output was done. 630msg_scroll = true; 631if (filtering ) { 632apply_autocmds_exarg (EVENT_FILTERREADPRE ,NULL ,sfname , 633 false,curbuf ,eap ); 634 }else if (read_stdin ) { 635apply_autocmds_exarg (EVENT_STDINREADPRE ,NULL ,sfname , 636 false,curbuf ,eap ); 637 }else if (newfile ) { 638apply_autocmds_exarg (EVENT_BUFREADPRE ,NULL ,sfname , 639 false,curbuf ,eap ); 640 }else { 641apply_autocmds_exarg (EVENT_FILEREADPRE ,sfname ,sfname , 642 false,NULL ,eap ); 643 } 644 645// autocommands may have changed it 646try_mac = (vim_strchr (p_ffs ,'m' )!= NULL ); 647try_dos = (vim_strchr (p_ffs ,'d' )!= NULL ); 648try_unix = (vim_strchr (p_ffs ,'x' )!= NULL ); 649curbuf -> b_op_start = orig_start ; 650 651if (msg_scrolled == n ) { 652msg_scroll = m ; 653 } 654 655if (aborting ()) {// autocmds may abort script processing 656no_wait_return -- ; 657msg_scroll = msg_save ; 658curbuf -> b_p_ro = true;// must use "w!" now 659 gototheend ; 660 } 661// Don't allow the autocommands to change the current buffer. 662// Try to re-open the file. 663// 664// Don't allow the autocommands to change the buffer name either 665// (cd for example) if it invalidates fname or sfname. 666if (!read_stdin && (curbuf != old_curbuf 667|| (using_b_ffname && (old_b_ffname != curbuf -> b_ffname )) 668|| (using_b_fname && (old_b_fname != curbuf -> b_fname )) 669|| (fd = os_open (fname ,O_RDONLY ,0 ))< 0 )) { 670no_wait_return -- ; 671msg_scroll = msg_save ; 672if (fd < 0 ) { 673emsg (_ ("E200: *ReadPre autocommands made the file unreadable" )); 674 }else { 675emsg (_ ("E201: *ReadPre autocommands must not change current buffer" )); 676 } 677curbuf -> b_p_ro = true;// must use "w!" now 678 gototheend ; 679 } 680 } 681 682// Autocommands may add lines to the file, need to check if it is empty 683wasempty = (curbuf -> b_ml .ml_flags & ML_EMPTY ); 684 685if (!recoverymode && !filtering && !(flags & READ_DUMMY )&& !silent ) { 686if (!read_stdin && !read_buffer ) { 687filemess (curbuf ,sfname ,"" ,NULL ); 688 } 689 } 690 691msg_scroll = false;// overwrite the file message 692 693// Set linecnt now, before the "retry" caused by a wrong guess for 694// fileformat, and after the autocommands, which may change them. 695linecnt = curbuf -> b_ml .ml_line_count ; 696 697// "++bad=" argument. 698if (eap != NULL && eap -> bad_char != 0 ) { 699bad_char_behavior = eap -> bad_char ; 700if (set_options ) { 701curbuf -> b_bad_char = eap -> bad_char ; 702 } 703 }else { 704curbuf -> b_bad_char = 0 ; 705 } 706 707// Decide which 'encoding' to use or use first. 708if (eap != NULL && eap -> force_enc != 0 ) { 709fenc = enc_canonize (eap -> cmd + eap -> force_enc ); 710fenc_alloced = true; 711keep_dest_enc = true; 712 }else if (curbuf -> b_p_bin ) { 713fenc = "" ;// binary: don't convert 714fenc_alloced = false; 715 }else if (curbuf -> b_help ) { 716// Help files are either utf-8 or latin1. Try utf-8 first, if this 717// fails it must be latin1. 718// It is needed when the first line contains non-ASCII characters. 719// That is only in *.??x files. 720fenc_next = "latin1" ; 721fenc = "utf-8" ; 722 723fenc_alloced = false; 724 }else if (* p_fencs == NUL ) { 725fenc = curbuf -> b_p_fenc ;// use format from buffer 726fenc_alloced = false; 727 }else { 728fenc_next = p_fencs ;// try items in 'fileencodings' 729fenc = next_fenc (& fenc_next ,& fenc_alloced ); 730 } 731 732// Jump back here to retry reading the file in different ways. 733// Reasons to retry: 734// - encoding conversion failed: try another one from "fenc_next" 735// - BOM detected and fenc was set, need to setup conversion 736// - "fileformat" check failed: try another 737// 738// Variables set for special retry actions: 739// "file_rewind" Rewind the file to start reading it again. 740// "advance_fenc" Advance "fenc" using "fenc_next". 741// "skip_read" Re-use already read bytes (BOM detected). 742// "did_iconv" iconv() conversion failed, try 'charconvert'. 743// "keep_fileformat" Don't reset "fileformat". 744// 745// Other status indicators: 746// "tmpname" When != NULL did conversion with 'charconvert'. 747// Output file has to be deleted afterwards. 748// "iconv_fd" When != -1 did conversion with iconv(). 749retry : 750 751if (file_rewind ) { 752if (read_buffer ) { 753read_buf_lnum = 1 ; 754read_buf_col = 0 ; 755 }else if (read_stdin || vim_lseek (fd ,0 ,SEEK_SET )!= 0 ) { 756// Can't rewind the file, give up. 757error = true; 758 gotofailed ; 759 } 760// Delete the previously read lines. 761while (lnum > from ) { 762ml_delete (lnum -- ); 763 } 764file_rewind = false; 765if (set_options ) { 766curbuf -> b_p_bomb = false; 767curbuf -> b_start_bomb = false; 768 } 769conv_error = 0 ; 770 } 771 772// When retrying with another "fenc" and the first time "fileformat" 773// will be reset. 774if (keep_fileformat ) { 775keep_fileformat = false; 776 }else { 777if (eap != NULL && eap -> force_ff != 0 ) { 778fileformat = get_fileformat_force (curbuf ,eap ); 779try_unix = try_dos = try_mac = false; 780 }else if (curbuf -> b_p_bin ) { 781fileformat = EOL_UNIX ;// binary: use Unix format 782 }else if (* p_ffs == 783NUL ) { 784fileformat = get_fileformat (curbuf );// use format from buffer 785 }else { 786fileformat = EOL_UNKNOWN ;// detect from file 787 } 788 } 789 790if (iconv_fd != (iconv_t )- 1 ) { 791// aborted conversion with iconv(), close the descriptor 792iconv_close (iconv_fd ); 793iconv_fd = (iconv_t )- 1 ; 794 } 795 796if (advance_fenc ) { 797// Try the next entry in 'fileencodings'. 798advance_fenc = false; 799 800if (eap != NULL && eap -> force_enc != 0 ) { 801// Conversion given with "++cc=" wasn't possible, read 802// without conversion. 803notconverted = true; 804conv_error = 0 ; 805if (fenc_alloced ) { 806xfree (fenc ); 807 } 808fenc = "" ; 809fenc_alloced = false; 810 }else { 811if (fenc_alloced ) { 812xfree (fenc ); 813 } 814if (fenc_next != NULL ) { 815fenc = next_fenc (& fenc_next ,& fenc_alloced ); 816 }else { 817fenc = "" ; 818fenc_alloced = false; 819 } 820 } 821if (tmpname != NULL ) { 822os_remove (tmpname );// delete converted file 823XFREE_CLEAR (tmpname ); 824 } 825 } 826 827// Conversion may be required when the encoding of the file is different 828// from 'encoding' or 'encoding' is UTF-16, UCS-2 or UCS-4. 829fio_flags = 0 ; 830converted = need_conversion (fenc ); 831if (converted ) { 832// "ucs-bom" means we need to check the first bytes of the file 833// for a BOM. 834if (strcmp (fenc ,ENC_UCSBOM )== 0 ) { 835fio_flags = FIO_UCSBOM ; 836 }else { 837// Check if UCS-2/4 or Latin1 to UTF-8 conversion needs to be 838// done. This is handled below after read(). Prepare the 839// fio_flags to avoid having to parse the string each time. 840// Also check for Unicode to Latin1 conversion, because iconv() 841// appears not to handle this correctly. This works just like 842// conversion to UTF-8 except how the resulting character is put in 843// the buffer. 844fio_flags = get_fio_flags (fenc ); 845 } 846 847// Try using iconv() if we can't convert internally. 848if (fio_flags == 0 849&& !did_iconv ) { 850iconv_fd = (iconv_t )my_iconv_open ("utf-8" ,fenc ); 851 } 852 853// Use the 'charconvert' expression when conversion is required 854// and we can't do it internally or with iconv(). 855if (fio_flags == 0 && !read_stdin && !read_buffer && p_ccv .type != kCallbackNone 856&& !read_fifo && iconv_fd == (iconv_t )- 1 ) { 857did_iconv = false; 858// Skip conversion when it's already done (retry for wrong 859// "fileformat"). 860if (tmpname == NULL ) { 861tmpname = readfile_charconvert (fname ,fenc ,& fd ); 862if (tmpname == NULL ) { 863// Conversion failed. Try another one. 864advance_fenc = true; 865if (fd < 0 ) { 866// Re-opening the original file failed! 867emsg (_ ("E202: Conversion made file unreadable!" )); 868error = true; 869 gotofailed ; 870 } 871 gotoretry ; 872 } 873 } 874 }else { 875if (fio_flags == 0 && iconv_fd == (iconv_t )- 1 ) { 876// Conversion wanted but we can't. 877// Try the next conversion in 'fileencodings' 878advance_fenc = true; 879 gotoretry ; 880 } 881 } 882 } 883 884// Set "can_retry" when it's possible to rewind the file and try with 885// another "fenc" value. It's false when no other "fenc" to try, reading 886// stdin or fixed at a specific encoding. 887bool can_retry = (* fenc != NUL && !read_stdin && !keep_dest_enc && !read_fifo ); 888 889if (!skip_read ) { 890linerest = 0 ; 891filesize = 0 ; 892skip_count = lines_to_skip ; 893read_count = lines_to_read ; 894conv_restlen = 0 ; 895read_undo_file = (newfile && (flags & READ_KEEP_UNDO )== 0 896&& curbuf -> b_ffname != NULL 897&& curbuf -> b_p_udf 898&& !filtering 899&& !read_fifo 900&& !read_stdin 901&& !read_buffer ); 902if (read_undo_file ) { 903sha256_start (& sha_ctx ); 904 } 905 } 906 907while (!error && !got_int ) { 908// We allocate as much space for the file as we can get, plus 909// space for the old line plus room for one terminating NUL. 910// The amount is limited by the fact that read() only can read 911// up to max_unsigned characters (and other things). 912 { 913if (!skip_read ) { 914// Use buffer >= 64K. Add linerest to double the size if the 915// line gets very long, to avoid a lot of copying. But don't 916// read more than 1 Mbyte at a time, so we can be interrupted. 917size = MIN (0x10000 + linerest ,0x100000 ); 918 } 919 920// Protect against the argument of lalloc() going negative. 921// Also split lines that are too long for colnr_T. After this check 922// passes, we read up to 'size' more bytes. We must ensure that even 923// after that read, the line length won't exceed MAXCOL - 1 (because 924// we add 1 for the NUL when casting to colnr_T). If this check fires, 925// we insert a synthetic newline immediately, so linerest doesn't grow. 926if (size < 0 || size + linerest + 1 < 0 || linerest >=MAXCOL - size ) { 927split ++ ; 928* ptr = NL ;// split line by inserting a NL 929size = 1 ; 930 }else if (!skip_read ) { 931for (;size >=10 ;size /=2 ) { 932new_buffer = verbose_try_malloc ((size_t )size + (size_t )linerest + 1 ); 933if (new_buffer ) { 934break ; 935 } 936 } 937if (new_buffer == NULL ) { 938error = true; 939break ; 940 } 941if (linerest ) {// copy characters from the previous buffer 942memmove (new_buffer ,ptr - linerest , (size_t )linerest ); 943 } 944xfree (buffer ); 945buffer = new_buffer ; 946ptr = buffer + linerest ; 947line_start = buffer ; 948 949// May need room to translate into. 950// For iconv() we don't really know the required space, use a 951// factor ICONV_MULT. 952// latin1 to utf-8: 1 byte becomes up to 2 bytes 953// utf-16 to utf-8: 2 bytes become up to 3 bytes, 4 bytes 954// become up to 4 bytes, size must be multiple of 2 955// ucs-2 to utf-8: 2 bytes become up to 3 bytes, size must be 956// multiple of 2 957// ucs-4 to utf-8: 4 bytes become up to 6 bytes, size must be 958// multiple of 4 959real_size = (int )size ; 960if (iconv_fd != (iconv_t )- 1 ) { 961size = size /ICONV_MULT ; 962 }else if (fio_flags & FIO_LATIN1 ) { 963size = size /2 ; 964 }else if (fio_flags & (FIO_UCS2 |FIO_UTF16 )) { 965size = (size * 2 /3 )& ~1 ; 966 }else if (fio_flags & FIO_UCS4 ) { 967size = (size * 2 /3 )& ~3 ; 968 }else if (fio_flags == FIO_UCSBOM ) { 969size = size /ICONV_MULT ;// worst case 970 } 971 972if (conv_restlen > 0 ) { 973// Insert unconverted bytes from previous line. 974memmove (ptr ,conv_rest , (size_t )conv_restlen ); 975ptr += conv_restlen ; 976size -= conv_restlen ; 977 } 978 979if (read_buffer ) { 980// Read bytes from curbuf. Used for converting text read 981// from stdin. 982if (read_buf_lnum > from ) { 983size = 0 ; 984 }else { 985int ni ; 986int tlen = 0 ; 987while (true) { 988p = (uint8_t * )ml_get (read_buf_lnum )+ read_buf_col ; 989int n = ml_get_len (read_buf_lnum )- read_buf_col ; 990if (tlen + n + 1 > size ) { 991// Filled up to "size", append partial line. 992// Change NL to NUL to reverse the effect done 993// below. 994n = (int )(size - tlen ); 995for (ni = 0 ;ni < n ;ni ++ ) { 996if (p [ni ]== NL ) { 997ptr [tlen ++ ]= NUL ; 998 }else { 999ptr [tlen ++ ]= (char )p [ni ]; 1000 } 1001 } 1002read_buf_col += n ; 1003break ; 1004 } 1005 1006// Append whole line and new-line. Change NL 1007// to NUL to reverse the effect done below. 1008for (ni = 0 ;ni < n ;ni ++ ) { 1009if (p [ni ]== NL ) { 1010ptr [tlen ++ ]= NUL ; 1011 }else { 1012ptr [tlen ++ ]= (char )p [ni ]; 1013 } 1014 } 1015ptr [tlen ++ ]= NL ; 1016read_buf_col = 0 ; 1017if (++ read_buf_lnum > from ) { 1018// When the last line didn't have an 1019// end-of-line don't add it now either. 1020if (!curbuf -> b_p_eol ) { 1021tlen -- ; 1022 } 1023size = tlen ; 1024break ; 1025 } 1026 } 1027 } 1028 }else { 1029// Read bytes from the file. 1030size_t read_size = (size_t )size ; 1031size = read_eintr (fd ,ptr ,read_size ); 1032 } 1033 1034if (size <=0 ) { 1035if (size < 0 ) {// read error 1036error = true; 1037 }else if (conv_restlen > 0 ) { 1038// Reached end-of-file but some trailing bytes could 1039// not be converted. Truncated file? 1040 1041// When we did a conversion report an error. 1042if (fio_flags != 0 || iconv_fd != (iconv_t )- 1 ) { 1043if (can_retry ) { 1044 gotorewind_retry ; 1045 } 1046if (conv_error == 0 ) { 1047conv_error = curbuf -> b_ml .ml_line_count 1048- linecnt + 1 ; 1049 } 1050 }else if (illegal_byte == 0 ) { 1051// Remember the first linenr with an illegal byte 1052illegal_byte = curbuf -> b_ml .ml_line_count 1053- linecnt + 1 ; 1054 } 1055if (bad_char_behavior == BAD_DROP ) { 1056* (ptr - conv_restlen )= NUL ; 1057conv_restlen = 0 ; 1058 }else { 1059// Replace the trailing bytes with the replacement 1060// character if we were converting; if we weren't, 1061// leave the UTF8 checking code to do it, as it 1062// works slightly differently. 1063if (bad_char_behavior != BAD_KEEP && (fio_flags != 0 || iconv_fd != (iconv_t )- 1 )) { 1064while (conv_restlen > 0 ) { 1065* (-- ptr )= (char )bad_char_behavior ; 1066conv_restlen -- ; 1067 } 1068 } 1069fio_flags = 0 ;// don't convert this 1070if (iconv_fd != (iconv_t )- 1 ) { 1071iconv_close (iconv_fd ); 1072iconv_fd = (iconv_t )- 1 ; 1073 } 1074 } 1075 } 1076 } 1077 } 1078 1079skip_read = false; 1080 1081// At start of file: Check for BOM. 1082// Also check for a BOM for other Unicode encodings, but not after 1083// converting with 'charconvert' or when a BOM has already been 1084// found. 1085if ((filesize == 0 ) 1086&& (fio_flags == FIO_UCSBOM 1087|| (!curbuf -> b_p_bomb 1088&& tmpname == NULL 1089&& (* fenc == 'u' || * fenc == NUL )))) { 1090char * ccname ; 1091int blen = 0 ; 1092 1093// no BOM detection in a short file or in binary mode 1094if (size < 2 || curbuf -> b_p_bin ) { 1095ccname = NULL ; 1096 }else { 1097ccname = check_for_bom (ptr , (int )size ,& blen , 1098fio_flags == FIO_UCSBOM ?FIO_ALL :get_fio_flags (fenc )); 1099 } 1100if (ccname != NULL ) { 1101// Remove BOM from the text 1102filesize += blen ; 1103size -= blen ; 1104memmove (ptr ,ptr + blen , (size_t )size ); 1105if (set_options ) { 1106curbuf -> b_p_bomb = true; 1107curbuf -> b_start_bomb = true; 1108 } 1109 } 1110 1111if (fio_flags == FIO_UCSBOM ) { 1112if (ccname == NULL ) { 1113// No BOM detected: retry with next encoding. 1114advance_fenc = true; 1115 }else { 1116// BOM detected: set "fenc" and jump back 1117if (fenc_alloced ) { 1118xfree (fenc ); 1119 } 1120fenc = ccname ; 1121fenc_alloced = false; 1122 } 1123// retry reading without getting new bytes or rewinding 1124skip_read = true; 1125 gotoretry ; 1126 } 1127 } 1128 1129// Include not converted bytes. 1130ptr -= conv_restlen ; 1131size += conv_restlen ; 1132conv_restlen = 0 ; 1133// Break here for a read error or end-of-file. 1134if (size <=0 ) { 1135break ; 1136 } 1137 1138if (iconv_fd != (iconv_t )- 1 ) { 1139// Attempt conversion of the read bytes to 'encoding' using iconv(). 1140const char * fromp = ptr ; 1141size_t from_size = (size_t )size ; 1142ptr += size ; 1143char * top = ptr ; 1144size_t to_size = (size_t )(real_size - size ); 1145 1146// If there is conversion error or not enough room try using 1147// another conversion. Except for when there is no 1148// alternative (help files). 1149while ((iconv (iconv_fd , (void * )& fromp ,& from_size , 1150& top ,& to_size ) 1151== (size_t )-1 && ICONV_ERRNO != ICONV_EINVAL ) 1152|| from_size > CONV_RESTLEN ) { 1153if (can_retry ) { 1154 gotorewind_retry ; 1155 } 1156if (conv_error == 0 ) { 1157conv_error = readfile_linenr (linecnt ,ptr ,top ); 1158 } 1159 1160// Deal with a bad byte and continue with the next. 1161fromp ++ ; 1162from_size -- ; 1163if (bad_char_behavior == BAD_KEEP ) { 1164* top ++ = * (fromp - 1 ); 1165to_size -- ; 1166 }else if (bad_char_behavior != BAD_DROP ) { 1167* top ++ = (char )bad_char_behavior ; 1168to_size -- ; 1169 } 1170 } 1171 1172if (from_size > 0 ) { 1173// Some remaining characters, keep them for the next 1174// round. 1175memmove (conv_rest ,fromp ,from_size ); 1176conv_restlen = (int )from_size ; 1177 } 1178 1179// move the linerest to before the converted characters 1180line_start = ptr - linerest ; 1181memmove (line_start ,buffer , (size_t )linerest ); 1182size = (top - ptr ); 1183 } 1184 1185if (fio_flags != 0 ) { 1186unsigned u8c ; 1187char * tail = NULL ; 1188 1189// Convert Unicode or Latin1 to UTF-8. 1190// Go from end to start through the buffer, because the number 1191// of bytes may increase. 1192// "dest" points to after where the UTF-8 bytes go, "p" points 1193// to after the next character to convert. 1194char * dest = ptr + real_size ; 1195if (fio_flags == FIO_LATIN1 || fio_flags == FIO_UTF8 ) { 1196p = (uint8_t * )ptr + size ; 1197if (fio_flags == FIO_UTF8 ) { 1198// Check for a trailing incomplete UTF-8 sequence 1199tail = ptr + size - 1 ; 1200while (tail > ptr && (* tail & 0xc0 )== 0x80 ) { 1201tail -- ; 1202 } 1203if (tail + utf_byte2len (* tail ) <=ptr + size ) { 1204tail = NULL ; 1205 }else { 1206p = (uint8_t * )tail ; 1207 } 1208 } 1209 }else if (fio_flags & (FIO_UCS2 |FIO_UTF16 )) { 1210// Check for a trailing byte 1211p = (uint8_t * )ptr + (size & ~1 ); 1212if (size & 1 ) { 1213tail = (char * )p ; 1214 } 1215if ((fio_flags & FIO_UTF16 )&& p > (uint8_t * )ptr ) { 1216// Check for a trailing leading word 1217if (fio_flags & FIO_ENDIAN_L ) { 1218u8c = (unsigned )(*-- p ) <<8 ; 1219u8c += *-- p ; 1220 }else { 1221u8c = *-- p ; 1222u8c += (unsigned )(*-- p ) <<8 ; 1223 } 1224if (u8c >=0xd800 && u8c <=0xdbff ) { 1225tail = (char * )p ; 1226 }else { 1227p += 2 ; 1228 } 1229 } 1230 }else {// FIO_UCS4 1231// Check for trailing 1, 2 or 3 bytes 1232p = (uint8_t * )ptr + (size & ~3 ); 1233if (size & 3 ) { 1234tail = (char * )p ; 1235 } 1236 } 1237 1238// If there is a trailing incomplete sequence move it to 1239// conv_rest[]. 1240if (tail != NULL ) { 1241conv_restlen = (int )((ptr + size )- tail ); 1242memmove (conv_rest ,tail , (size_t )conv_restlen ); 1243size -= conv_restlen ; 1244 } 1245 1246while (p > (uint8_t * )ptr ) { 1247if (fio_flags & FIO_LATIN1 ) { 1248u8c = *-- p ; 1249 }else if (fio_flags & (FIO_UCS2 |FIO_UTF16 )) { 1250if (fio_flags & FIO_ENDIAN_L ) { 1251u8c = (unsigned )(*-- p ) <<8 ; 1252u8c += *-- p ; 1253 }else { 1254u8c = *-- p ; 1255u8c += (unsigned )(*-- p ) <<8 ; 1256 } 1257if ((fio_flags & FIO_UTF16 ) 1258&& u8c >=0xdc00 && u8c <=0xdfff ) { 1259int u16c ; 1260 1261if (p == (uint8_t * )ptr ) { 1262// Missing leading word. 1263if (can_retry ) { 1264 gotorewind_retry ; 1265 } 1266if (conv_error == 0 ) { 1267conv_error = readfile_linenr (linecnt ,ptr , (char * )p ); 1268 } 1269if (bad_char_behavior == BAD_DROP ) { 1270continue ; 1271 } 1272if (bad_char_behavior != BAD_KEEP ) { 1273u8c = (unsigned )bad_char_behavior ; 1274 } 1275 } 1276 1277// found second word of double-word, get the first 1278// word and compute the resulting character 1279if (fio_flags & FIO_ENDIAN_L ) { 1280u16c = (*-- p <<8 ); 1281u16c += *-- p ; 1282 }else { 1283u16c = *-- p ; 1284u16c += (*-- p <<8 ); 1285 } 1286u8c = 0x10000 + (((unsigned )u16c & 0x3ff ) <<10 ) 1287+ (u8c & 0x3ff ); 1288 1289// Check if the word is indeed a leading word. 1290if (u16c < 0xd800 || u16c > 0xdbff ) { 1291if (can_retry ) { 1292 gotorewind_retry ; 1293 } 1294if (conv_error == 0 ) { 1295conv_error = readfile_linenr (linecnt ,ptr , (char * )p ); 1296 } 1297if (bad_char_behavior == BAD_DROP ) { 1298continue ; 1299 } 1300if (bad_char_behavior != BAD_KEEP ) { 1301u8c = (unsigned )bad_char_behavior ; 1302 } 1303 } 1304 } 1305 }else if (fio_flags & FIO_UCS4 ) { 1306if (fio_flags & FIO_ENDIAN_L ) { 1307u8c = (unsigned )(*-- p ) <<24 ; 1308u8c += (unsigned )(*-- p ) <<16 ; 1309u8c += (unsigned )(*-- p ) <<8 ; 1310u8c += *-- p ; 1311 }else {// big endian 1312u8c = *-- p ; 1313u8c += (unsigned )(*-- p ) <<8 ; 1314u8c += (unsigned )(*-- p ) <<16 ; 1315u8c += (unsigned )(*-- p ) <<24 ; 1316 } 1317// Replace characters over INT_MAX with Unicode replacement character 1318if (u8c > INT_MAX ) { 1319u8c = 0xfffd ; 1320 } 1321 }else {// UTF-8 1322if (*-- p < 0x80 ) { 1323u8c = * p ; 1324 }else { 1325len = utf_head_off (ptr , (char * )p ); 1326p -= len ; 1327u8c = (unsigned )utf_ptr2char ((char * )p ); 1328if (len == 0 ) { 1329// Not a valid UTF-8 character, retry with 1330// another fenc when possible, otherwise just 1331// report the error. 1332if (can_retry ) { 1333 gotorewind_retry ; 1334 } 1335if (conv_error == 0 ) { 1336conv_error = readfile_linenr (linecnt ,ptr , (char * )p ); 1337 } 1338if (bad_char_behavior == BAD_DROP ) { 1339continue ; 1340 } 1341if (bad_char_behavior != BAD_KEEP ) { 1342u8c = (unsigned )bad_char_behavior ; 1343 } 1344 } 1345 } 1346 } 1347assert (u8c <=INT_MAX ); 1348// produce UTF-8 1349dest -= utf_char2len ((int )u8c ); 1350utf_char2bytes ((int )u8c ,dest ); 1351 } 1352 1353// move the linerest to before the converted characters 1354line_start = dest - linerest ; 1355memmove (line_start ,buffer , (size_t )linerest ); 1356size = ((ptr + real_size )- dest ); 1357ptr = dest ; 1358 }else if (!curbuf -> b_p_bin ) { 1359bool incomplete_tail = false; 1360 1361// Reading UTF-8: Check if the bytes are valid UTF-8. 1362for (p = (uint8_t * )ptr ;;) { 1363// Skip ASCII bytes quickly using word-at-a-time check. 1364 { 1365uint8_t * ascii_end = (uint8_t * )ptr + size ; 1366while (ascii_end - p >= (ptrdiff_t )sizeof (uint64_t )) { 1367uint64_t word ; 1368memcpy (& word ,p ,sizeof (uint64_t )); 1369if (word & NONASCII_MASK ) { 1370break ; 1371 } 1372p += sizeof (uint64_t ); 1373 } 1374while (p < ascii_end && * p < 0x80 ) { 1375p ++ ; 1376 } 1377 } 1378 1379int todo = (int )(((uint8_t * )ptr + size )- p ); 1380if (todo <=0 ) { 1381break ; 1382 } 1383if (* p >=0x80 ) { 1384// A length of 1 means it's an illegal byte. Accept 1385// an incomplete character at the end though, the next 1386// read() will get the next bytes, we'll check it 1387// then. 1388int l = utf_ptr2len_len ((char * )p ,todo ); 1389if (l > todo && !incomplete_tail ) { 1390// Avoid retrying with a different encoding when 1391// a truncated file is more likely, or attempting 1392// to read the rest of an incomplete sequence when 1393// we have already done so. 1394if (p > (uint8_t * )ptr || filesize > 0 ) { 1395incomplete_tail = true; 1396 } 1397// Incomplete byte sequence, move it to conv_rest[] 1398// and try to read the rest of it, unless we've 1399// already done so. 1400if (p > (uint8_t * )ptr ) { 1401conv_restlen = todo ; 1402memmove (conv_rest ,p , (size_t )conv_restlen ); 1403size -= conv_restlen ; 1404break ; 1405 } 1406 } 1407if (l == 1 || l > todo ) { 1408// Illegal byte. If we can try another encoding 1409// do that, unless at EOF where a truncated 1410// file is more likely than a conversion error. 1411if (can_retry && !incomplete_tail ) { 1412break ; 1413 } 1414 1415// When we did a conversion report an error. 1416if (iconv_fd != (iconv_t )- 1 && conv_error == 0 ) { 1417conv_error = readfile_linenr (linecnt ,ptr , (char * )p ); 1418 } 1419 1420// Remember the first linenr with an illegal byte 1421if (conv_error == 0 && illegal_byte == 0 ) { 1422illegal_byte = readfile_linenr (linecnt ,ptr , (char * )p ); 1423 } 1424 1425// Drop, keep or replace the bad byte. 1426if (bad_char_behavior == BAD_DROP ) { 1427memmove (p ,p + 1 , (size_t )(todo - 1 )); 1428size -- ; 1429 }else { 1430if (bad_char_behavior != BAD_KEEP ) { 1431* p = (uint8_t )bad_char_behavior ; 1432 } 1433p ++ ; 1434 } 1435 }else { 1436p += l ; 1437 } 1438 } 1439 } 1440if (p < (uint8_t * )ptr + size && !incomplete_tail ) { 1441// Detected a UTF-8 error. 1442rewind_retry : 1443// Retry reading with another conversion. 1444if (p_ccv .type != kCallbackNone && iconv_fd != (iconv_t )- 1 ) { 1445// iconv() failed, try 'charconvert' 1446did_iconv = true; 1447 }else { 1448// use next item from 'fileencodings' 1449advance_fenc = true; 1450 } 1451file_rewind = true; 1452 gotoretry ; 1453 } 1454 } 1455 1456// count the number of characters (after conversion!) 1457filesize += size ; 1458 1459// when reading the first part of a file: guess EOL type 1460if (fileformat == EOL_UNKNOWN ) { 1461// First try finding a NL, for Dos and Unix 1462if (try_dos || try_unix ) { 1463// Reset the carriage return counter. 1464if (try_mac ) { 1465try_mac = 1 ; 1466 } 1467 1468for (p = (uint8_t * )ptr ;p < (uint8_t * )ptr + size ;p ++ ) { 1469if (* p == NL ) { 1470if (!try_unix 1471|| (try_dos && p > (uint8_t * )ptr && p [-1 ]== CAR )) { 1472fileformat = EOL_DOS ; 1473 }else { 1474fileformat = EOL_UNIX ; 1475 } 1476break ; 1477 }else if (* p == CAR && try_mac ) { 1478try_mac ++ ; 1479 } 1480 } 1481 1482// Don't give in to EOL_UNIX if EOL_MAC is more likely 1483if (fileformat == EOL_UNIX && try_mac ) { 1484// Need to reset the counters when retrying fenc. 1485try_mac = 1 ; 1486try_unix = 1 ; 1487for (;p >= (uint8_t * )ptr && * p != CAR ;p -- ) {} 1488if (p >= (uint8_t * )ptr ) { 1489for (p = (uint8_t * )ptr ;p < (uint8_t * )ptr + size ;p ++ ) { 1490if (* p == NL ) { 1491try_unix ++ ; 1492 }else if (* p == CAR ) { 1493try_mac ++ ; 1494 } 1495 } 1496if (try_mac > try_unix ) { 1497fileformat = EOL_MAC ; 1498 } 1499 } 1500 }else if (fileformat == EOL_UNKNOWN && try_mac == 1 ) { 1501// Looking for CR but found no end-of-line markers at all: 1502// use the default format. 1503fileformat = default_fileformat (); 1504 } 1505 } 1506 1507// No NL found: may use Mac format 1508if (fileformat == EOL_UNKNOWN && try_mac ) { 1509fileformat = EOL_MAC ; 1510 } 1511 1512// Still nothing found? Use first format in 'ffs' 1513if (fileformat == EOL_UNKNOWN ) { 1514fileformat = default_fileformat (); 1515 } 1516 1517// May set 'p_ff' if editing a new file. 1518if (set_options ) { 1519set_fileformat (fileformat ,OPT_LOCAL ); 1520 } 1521 } 1522 } 1523 1524// This loop is executed once for every character read. 1525// Keep it fast! 1526if (fileformat == EOL_MAC ) { 1527ptr -- ; 1528while (++ ptr ,-- size >=0 ) { 1529// catch most common case first 1530if ((c = * ptr )!= NUL && c != CAR && c != NL ) { 1531continue ; 1532 } 1533if (c == NUL ) { 1534* ptr = NL ;// NULs are replaced by newlines! 1535 }else if (c == NL ) { 1536* ptr = CAR ;// NLs are replaced by CRs! 1537 }else { 1538if (skip_count == 0 ) { 1539* ptr = NUL ;// end of line 1540len = (colnr_T )(ptr - line_start + 1 ); 1541if (ml_append (lnum ,line_start ,len ,newfile )== FAIL ) { 1542error = true; 1543break ; 1544 } 1545if (read_undo_file ) { 1546sha256_update (& sha_ctx , (uint8_t * )line_start , (size_t )len ); 1547 } 1548lnum ++ ; 1549if (-- read_count == 0 ) { 1550error = true;// break loop 1551line_start = ptr ;// nothing left to write 1552break ; 1553 } 1554 }else { 1555skip_count -- ; 1556 } 1557line_start = ptr + 1 ; 1558 } 1559 } 1560 }else { 1561// Use memchr() for SIMD-optimized newline scanning instead 1562// of scanning each byte individually. 1563char * end = ptr + size ; 1564 1565while (ptr < end ) { 1566char * nl = memchr (ptr ,NL , (size_t )(end - ptr )); 1567char * nul_scan ; 1568 1569if (nl == NULL ) { 1570// No more newlines in buffer. 1571// Replace any NUL bytes with NL in remaining data. 1572while ((nul_scan = memchr (ptr ,NUL , (size_t )(end - ptr )))!= NULL ) { 1573* nul_scan = NL ; 1574ptr = nul_scan + 1 ; 1575 } 1576ptr = end ; 1577break ; 1578 } 1579 1580// Replace NUL bytes with NL before the newline. 1581 { 1582char * scan = ptr ; 1583while ((nul_scan = memchr (scan ,NUL , (size_t )(nl - scan )))!= NULL ) { 1584* nul_scan = NL ; 1585scan = nul_scan + 1 ; 1586 } 1587 } 1588 1589// Process the newline. 1590ptr = nl ; 1591if (skip_count == 0 ) { 1592* ptr = NUL ;// end of line 1593len = (colnr_T )(ptr - line_start + 1 ); 1594if (fileformat == EOL_DOS ) { 1595if (ptr > line_start && ptr [-1 ]== CAR ) { 1596// remove CR before NL 1597ptr [-1 ]= NUL ; 1598len -- ; 1599 }else if (ff_error != EOL_DOS ) { 1600// Reading in Dos format, but no CR-LF found! 1601// When 'fileformats' includes "unix", delete all 1602// the lines read so far and start all over again. 1603// Otherwise give an error message later. 1604if (try_unix 1605&& !read_stdin 1606&& (read_buffer || vim_lseek (fd ,0 ,SEEK_SET )== 0 )) { 1607fileformat = EOL_UNIX ; 1608if (set_options ) { 1609set_fileformat (EOL_UNIX ,OPT_LOCAL ); 1610 } 1611file_rewind = true; 1612keep_fileformat = true; 1613 gotoretry ; 1614 } 1615ff_error = EOL_DOS ; 1616 } 1617 } 1618if (ml_append (lnum ,line_start ,len ,newfile )== FAIL ) { 1619error = true; 1620break ; 1621 } 1622if (read_undo_file ) { 1623sha256_update (& sha_ctx , (uint8_t * )line_start , (size_t )len ); 1624 } 1625lnum ++ ; 1626if (-- read_count == 0 ) { 1627error = true;// break loop 1628line_start = ptr ;// nothing left to write 1629break ; 1630 } 1631 }else { 1632skip_count -- ; 1633 } 1634line_start = ptr + 1 ; 1635ptr ++ ; 1636 } 1637size = -1 ; 1638 } 1639linerest = (ptr - line_start ); 1640os_breakcheck (); 1641 } 1642 1643failed : 1644// not an error, max. number of lines reached 1645if (error && read_count == 0 ) { 1646error = false; 1647 } 1648 1649// In Dos format ignore a trailing CTRL-Z, unless 'binary' is set. 1650// In old days the file length was in sector count and the CTRL-Z the 1651// marker where the file really ended. Assuming we write it to a file 1652// system that keeps file length properly the CTRL-Z should be dropped. 1653// Set the 'endoffile' option so the user can decide what to write later. 1654// In Unix format the CTRL-Z is just another character. 1655if (linerest != 0 1656&& !curbuf -> b_p_bin 1657&& fileformat == EOL_DOS 1658&& ptr [-1 ]== Ctrl_Z ) { 1659ptr -- ; 1660linerest -- ; 1661if (set_options ) { 1662curbuf -> b_p_eof = true; 1663 } 1664 } 1665 1666// If we get EOF in the middle of a line, note the fact and 1667// complete the line ourselves. 1668if (!error 1669&& !got_int 1670&& linerest != 0 ) { 1671// remember for when writing 1672if (set_options ) { 1673curbuf -> b_p_eol = false; 1674 } 1675* ptr = NUL ; 1676len = (colnr_T )(ptr - line_start + 1 ); 1677if (ml_append (lnum ,line_start ,len ,newfile )== FAIL ) { 1678error = true; 1679 }else { 1680if (read_undo_file ) { 1681sha256_update (& sha_ctx , (uint8_t * )line_start , (size_t )len ); 1682 } 1683read_no_eol_lnum = ++ lnum ; 1684 } 1685 } 1686 1687if (set_options ) { 1688// Remember the current file format. 1689save_file_ff (curbuf ); 1690// If editing a new file: set 'fenc' for the current buffer. 1691// Also for ":read ++edit file". 1692set_option_direct (kOptFileencoding ,CSTR_AS_OBJ (fenc ),OPT_LOCAL ,0 ); 1693 } 1694if (fenc_alloced ) { 1695xfree (fenc ); 1696 } 1697if (iconv_fd != (iconv_t )- 1 ) { 1698iconv_close (iconv_fd ); 1699 } 1700 1701if (!read_buffer && !read_stdin ) { 1702close (fd );// errors are ignored 1703 }else { 1704os_set_cloexec (fd ); 1705 } 1706xfree (buffer ); 1707 1708if (read_stdin ) { 1709close (fd ); 1710if (stdin_fd < 0 ) { 1711#ifndef MSWIN 1712// On Unix, use stderr for stdin, makes shell commands work. 1713vim_ignored = dup (2 ); 1714#else 1715// On Windows, use the console input handle (CONIN$) for stdin. 1716vim_ignored = os_open_conin_fd (); 1717#endif 1718 } 1719 } 1720 1721if (tmpname != NULL ) { 1722os_remove (tmpname );// delete converted file 1723xfree (tmpname ); 1724 } 1725no_wait_return -- ;// may wait for return now 1726 1727// In recovery mode everything but autocommands is skipped. 1728if (!recoverymode ) { 1729// need to delete the last line, which comes from the empty buffer 1730if (newfile && wasempty && !(curbuf -> b_ml .ml_flags & ML_EMPTY )) { 1731ml_delete (curbuf -> b_ml .ml_line_count ); 1732linecnt -- ; 1733 } 1734curbuf -> deleted_bytes = 0 ; 1735curbuf -> deleted_bytes2 = 0 ; 1736curbuf -> deleted_codepoints = 0 ; 1737curbuf -> deleted_codeunits = 0 ; 1738linecnt = curbuf -> b_ml .ml_line_count - linecnt ; 1739if (filesize == 0 ) { 1740linecnt = 0 ; 1741 } 1742if (newfile || read_buffer ) { 1743redraw_curbuf_later (UPD_NOT_VALID ); 1744// After reading the text into the buffer the diff info needs to 1745// be updated. 1746diff_invalidate (curbuf ); 1747// All folds in the window are invalid now. Mark them for update 1748// before triggering autocommands. 1749foldUpdateAll (curwin ); 1750 }else if (linecnt ) {// appended at least one line 1751appended_lines_mark (from ,linecnt ); 1752 } 1753 1754if (got_int ) { 1755if (!(flags & READ_DUMMY )) { 1756filemess (curbuf ,sfname ,_ (e_interr ),NULL ); 1757if (newfile ) { 1758curbuf -> b_p_ro = true;// must use "w!" now 1759 } 1760 } 1761msg_scroll = msg_save ; 1762check_marks_read (); 1763retval = OK ;// an interrupt isn't really an error 1764 gototheend ; 1765 } 1766 1767if (!filtering && !(flags & READ_DUMMY )&& !silent ) { 1768add_quoted_fname (IObuff ,IOSIZE ,curbuf ,sfname ); 1769c = false; 1770 1771int buflen = (int )strlen (IObuff ); 1772#ifdef UNIX 1773if (S_ISFIFO (perm )) {// fifo 1774buflen += snprintf (IObuff + buflen , (size_t )(IOSIZE - buflen ),_ ("[fifo]" )); 1775c = true; 1776 } 1777if (S_ISSOCK (perm )) {// or socket 1778buflen += snprintf (IObuff + buflen , (size_t )(IOSIZE - buflen ),_ ("[socket]" )); 1779c = true; 1780 } 1781# ifdef OPEN_CHR_FILES 1782if (S_ISCHR (perm )) {// or character special 1783buflen += snprintf (IObuff + buflen , (size_t )(IOSIZE - buflen ),_ ("[character special]" )); 1784c = true; 1785 } 1786# endif 1787#endif 1788if (curbuf -> b_p_ro ) { 1789buflen += snprintf (IObuff + buflen , (size_t )(IOSIZE - buflen ),"%s" , 1790shortmess (kShmRo ) ?_ ("[RO]" ) :_ ("[readonly]" )); 1791c = true; 1792 } 1793if (read_no_eol_lnum ) { 1794buflen += snprintf (IObuff + buflen , (size_t )(IOSIZE - buflen ),_ ("[noeol]" )); 1795c = true; 1796 } 1797if (ff_error == EOL_DOS ) { 1798buflen += snprintf (IObuff + buflen , (size_t )(IOSIZE - buflen ),_ ("[CR missing]" )); 1799c = true; 1800 } 1801if (split ) { 1802buflen += snprintf (IObuff + buflen , (size_t )(IOSIZE - buflen ),_ ("[long lines split]" )); 1803c = true; 1804 } 1805if (notconverted ) { 1806buflen += snprintf (IObuff + buflen , (size_t )(IOSIZE - buflen ),_ ("[NOT converted]" )); 1807c = true; 1808 }else if (converted ) { 1809buflen += snprintf (IObuff + buflen , (size_t )(IOSIZE - buflen ),_ ("[converted]" )); 1810c = true; 1811 } 1812if (conv_error != 0 ) { 1813snprintf (IObuff + buflen , (size_t )(IOSIZE - buflen ), 1814_ ("[CONVERSION ERROR in line %" PRId64 "]" ), (int64_t )conv_error ); 1815c = true; 1816 }else if (illegal_byte > 0 ) { 1817snprintf (IObuff + buflen , (size_t )(IOSIZE - buflen ), 1818_ ("[ILLEGAL BYTE in line %" PRId64 "]" ), (int64_t )illegal_byte ); 1819c = true; 1820 }else if (error ) { 1821snprintf (IObuff + buflen , (size_t )(IOSIZE - buflen ),_ ("[READ ERRORS]" )); 1822c = true; 1823 } 1824if (msg_add_fileformat (fileformat )) { 1825c = true; 1826 } 1827 1828msg_add_lines (c ,linecnt ,filesize ); 1829 1830XFREE_CLEAR (keep_msg ); 1831p = NULL ; 1832msg_scrolled_ign = true; 1833 1834if (!read_stdin && !read_buffer ) { 1835if (msg_col > 0 ) { 1836msg_putchar ('\r' );// overwrite previous message 1837 } 1838p = (uint8_t * )msg_trunc (IObuff , false,0 ); 1839 } 1840 1841if (read_stdin || read_buffer || restart_edit != 0 1842|| (msg_scrolled != 0 && !need_wait_return )) { 1843// Need to repeat the message after redrawing when: 1844// - When reading from stdin (the screen will be cleared next). 1845// - When restart_edit is set (otherwise there will be a delay before 1846// redrawing). 1847// - When the screen was scrolled but there is no wait-return prompt. 1848set_keep_msg ((char * )p ,0 ); 1849 } 1850msg_scrolled_ign = false; 1851 } 1852 1853// with errors writing the file requires ":w!" 1854if (newfile && (error 1855|| conv_error != 0 1856|| (illegal_byte > 0 && bad_char_behavior != BAD_KEEP ))) { 1857curbuf -> b_p_ro = true; 1858 } 1859 1860u_clearline (curbuf );// cannot use "U" command after adding lines 1861 1862// Cursor at first new line. 1863curwin -> w_cursor .lnum = from + 1 ; 1864check_cursor_lnum (curwin ); 1865beginline (BL_WHITE |BL_FIX );// on first non-blank 1866 1867if ((cmdmod .cmod_flags & CMOD_LOCKMARKS )== 0 ) { 1868// Set '[ and '] marks to the newly read lines. 1869curbuf -> b_op_start .lnum = from + 1 ; 1870curbuf -> b_op_start .col = 0 ; 1871curbuf -> b_op_end .lnum = from + linecnt ; 1872curbuf -> b_op_end .col = 0 ; 1873 } 1874 } 1875msg_scroll = msg_save ; 1876 1877// Get the marks before executing autocommands, so they can be used there. 1878check_marks_read (); 1879 1880// We remember if the last line of the read didn't have 1881// an eol even when 'binary' is off, to support turning 'fixeol' off, 1882// or writing the read again with 'binary' on. The latter is required 1883// for ":autocmd FileReadPost *.gz set bin|'[,']!gunzip" to work. 1884curbuf -> b_no_eol_lnum = read_no_eol_lnum ; 1885 1886// When reloading a buffer put the cursor at the first line that is 1887// different. 1888if (flags & READ_KEEP_UNDO ) { 1889u_find_first_changed (); 1890 } 1891 1892// When opening a new file locate undo info and read it. 1893if (read_undo_file ) { 1894uint8_t hash [UNDO_HASH_SIZE ]; 1895 1896sha256_finish (& sha_ctx ,hash ); 1897u_read_undo (NULL ,hash ,fname ); 1898 } 1899 1900if (!read_stdin && !read_fifo && (!read_buffer || sfname != NULL )) { 1901int m = msg_scroll ; 1902int n = msg_scrolled ; 1903 1904// Save the fileformat now, otherwise the buffer will be considered 1905// modified if the format/encoding was automatically detected. 1906if (set_options ) { 1907save_file_ff (curbuf ); 1908 } 1909 1910// The output from the autocommands should not overwrite anything and 1911// should not be overwritten: Set msg_scroll, restore its value if no 1912// output was done. 1913msg_scroll = true; 1914if (filtering ) { 1915apply_autocmds_exarg (EVENT_FILTERREADPOST ,NULL ,sfname , 1916 false,curbuf ,eap ); 1917 }else if (newfile || (read_buffer && sfname != NULL )) { 1918// 'filetype' detection is triggered by BufReadPost. 1919bool did_bufrp = apply_autocmds_exarg (EVENT_BUFREADPOST ,NULL ,sfname , false,curbuf ,eap ); 1920 1921if (!curbuf -> b_au_did_filetype && * curbuf -> b_p_ft != NUL ) { 1922// EVENT_FILETYPE was not triggered but the buffer already has a 1923// filetype. Trigger EVENT_FILETYPE using the existing filetype. 1924apply_autocmds (EVENT_FILETYPE ,curbuf -> b_p_ft ,curbuf -> b_fname , true,curbuf ); 1925 } 1926 1927if (!did_bufrp && * curbuf -> b_p_ft == NUL && augroup_exists ("filetypedetect" )) { 1928// BufReadPost was skipped, and 'filetype' is empty. Retry filetype-detection now. 1929apply_autocmds_group (EVENT_BUFREADPOST ,sfname ,NULL , true,augroup_find ("filetypedetect" ), 1930curbuf ,curwin ,NULL ,NULL , false); 1931 } 1932 }else { 1933apply_autocmds_exarg (EVENT_FILEREADPOST ,sfname ,sfname , 1934 false,NULL ,eap ); 1935 } 1936if (msg_scrolled == n ) { 1937msg_scroll = m ; 1938 } 1939if (aborting ()) {// autocmds may abort script processing 1940return FAIL ; 1941 } 1942 } 1943 1944if (!(recoverymode && error )) { 1945retval = OK ; 1946 } 1947 1948theend : 1949if (curbuf -> b_ml .ml_mfp != NULL 1950&& curbuf -> b_ml .ml_mfp -> mf_dirty == MF_DIRTY_YES_NOSYNC ) { 1951// OK to sync the swap file now 1952curbuf -> b_ml .ml_mfp -> mf_dirty = MF_DIRTY_YES ; 1953 } 1954 1955return retval ; 1956} 1957 1958#ifdef OPEN_CHR_FILES 1959/// Returns true if the file name argument is of the form "/dev/fd/\d\+", 1960/// which is the name of files used for process substitution output by 1961/// some shells on some operating systems, e.g., bash on SunOS. 1962/// Do not accept "/dev/fd/[012]", opening these may hang Vim. 1963/// 1964/// @param fname file name to check 1965bool is_dev_fd_file (char * fname ) 1966FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 1967{ 1968return strncmp (fname ,"/dev/fd/" ,8 )== 0 1969&& ascii_isdigit ((uint8_t )fname [8 ]) 1970&& * skipdigits (fname + 9 )== NUL 1971&& (fname [9 ]!= NUL 1972|| (fname [8 ]!= '0' && fname [8 ]!= '1' && fname [8 ]!= '2' )); 1973} 1974#endif 1975 1976/// From the current line count and characters read after that, estimate the 1977/// line number where we are now. 1978/// Used for error messages that include a line number. 1979/// 1980/// @param linecnt line count before reading more bytes 1981/// @param p start of more bytes read 1982/// @param endp end of more bytes read 1983static linenr_T readfile_linenr (linenr_T linecnt ,char * p ,const char * endp ) 1984{ 1985linenr_T lnum = curbuf -> b_ml .ml_line_count - linecnt + 1 ; 1986for (char * s = p ;s < endp ;s ++ ) { 1987if (* s == '\n' ) { 1988lnum ++ ; 1989 } 1990 } 1991return lnum ; 1992} 1993 1994/// Fill "*eap" to force the 'fileencoding', 'fileformat' and 'binary' to be 1995/// equal to the buffer "buf". Used for calling readfile(). 1996void prep_exarg (exarg_T * eap ,const buf_T * buf ) 1997FUNC_ATTR_NONNULL_ALL 1998{ 1999const size_t cmd_len = 15 + strlen (buf -> b_p_fenc ); 2000eap -> cmd = xmalloc (cmd_len ); 2001 2002snprintf (eap -> cmd ,cmd_len ,"e ++enc=%s" ,buf -> b_p_fenc ); 2003eap -> force_enc = 8 ; 2004eap -> bad_char = buf -> b_bad_char ; 2005eap -> force_ff = (unsigned char )(* buf -> b_p_ff ); 2006 2007eap -> force_bin = buf -> b_p_bin ?FORCE_BIN :FORCE_NOBIN ; 2008eap -> read_edit = false; 2009eap -> forceit = false; 2010} 2011 2012/// Set default or forced 'fileformat' and 'binary'. 2013void set_file_options (bool set_options ,exarg_T * eap ) 2014{ 2015// set default 'fileformat' 2016if (set_options ) { 2017if (eap != NULL && eap -> force_ff != 0 ) { 2018set_fileformat (get_fileformat_force (curbuf ,eap ),OPT_LOCAL ); 2019 }else if (* p_ffs != NUL ) { 2020set_fileformat (default_fileformat (),OPT_LOCAL ); 2021 } 2022 } 2023 2024// set or reset 'binary' 2025if (eap != NULL && eap -> force_bin != 0 ) { 2026int oldval = curbuf -> b_p_bin ; 2027 2028curbuf -> b_p_bin = (eap -> force_bin == FORCE_BIN ); 2029set_options_bin (oldval ,curbuf -> b_p_bin ,OPT_LOCAL ); 2030 } 2031} 2032 2033/// Set forced 'fileencoding'. 2034void set_forced_fenc (exarg_T * eap ) 2035{ 2036if (eap -> force_enc == 0 ) { 2037return ; 2038 } 2039 2040char * fenc = enc_canonize (eap -> cmd + eap -> force_enc ); 2041set_option_direct (kOptFileencoding ,CSTR_AS_OBJ (fenc ),OPT_LOCAL ,0 ); 2042xfree (fenc ); 2043} 2044 2045/// Find next fileencoding to use from 'fileencodings'. 2046/// "pp" points to fenc_next. It's advanced to the next item. 2047/// When there are no more items, an empty string is returned and *pp is set to 2048/// NULL. 2049/// When *pp is not set to NULL, the result is in allocated memory and "alloced" 2050/// is set to true. 2051static char * next_fenc (char ** pp ,bool * alloced ) 2052FUNC_ATTR_NONNULL_ALL FUNC_ATTR_NONNULL_RET 2053{ 2054char * r ; 2055 2056* alloced = false; 2057if (** pp == NUL ) { 2058* pp = NULL ; 2059return "" ; 2060 } 2061char * p = vim_strchr (* pp ,',' ); 2062if (p == NULL ) { 2063r = enc_canonize (* pp ); 2064* pp += strlen (* pp ); 2065 }else { 2066r = xmemdupz (* pp , (size_t )(p - * pp )); 2067* pp = p + 1 ; 2068p = enc_canonize (r ); 2069xfree (r ); 2070r = p ; 2071 } 2072* alloced = true; 2073return r ; 2074} 2075 2076/// Convert a file with the 'charconvert' expression. 2077/// This closes the file which is to be read, converts it and opens the 2078/// resulting file for reading. 2079/// 2080/// @param fname name of input file 2081/// @param fenc converted from 2082/// @param fdp in/out: file descriptor of file 2083/// 2084/// @return name of the resulting converted file (the caller should delete it after reading it). 2085/// Returns NULL if the conversion failed ("*fdp" is not set) . 2086static char * readfile_charconvert (char * fname ,char * fenc ,int * fdp ) 2087{ 2088char * errmsg = NULL ; 2089 2090char * tmpname = vim_tempname (); 2091if (tmpname == NULL ) { 2092errmsg = _ ("Can't find temp file for conversion" ); 2093 }else { 2094close (* fdp );// close the input file, ignore errors 2095* fdp = -1 ; 2096if (eval_charconvert (fenc ,"utf-8" , 2097fname ,tmpname )== FAIL ) { 2098errmsg = _ ("Conversion with 'charconvert' failed" ); 2099 } 2100if (errmsg == NULL && (* fdp = os_open (tmpname ,O_RDONLY ,0 ))< 0 ) { 2101errmsg = _ ("can't read output of 'charconvert'" ); 2102 } 2103 } 2104 2105if (errmsg != NULL ) { 2106// Don't use emsg(), it breaks mappings, the retry with 2107// another type of conversion might still work. 2108msg (errmsg ,0 ); 2109if (tmpname != NULL ) { 2110os_remove (tmpname );// delete converted file 2111XFREE_CLEAR (tmpname ); 2112 } 2113 } 2114 2115// If the input file is closed, open it (caller should check for error). 2116if (* fdp < 0 ) { 2117* fdp = os_open (fname ,O_RDONLY ,0 ); 2118 } 2119 2120return tmpname ; 2121} 2122 2123/// Set the name of the current buffer. Use when the buffer doesn't have a 2124/// name and a ":r" or ":w" command with a file name is used. 2125int set_rw_fname (char * fname ,char * sfname ) 2126{ 2127buf_T * buf = curbuf ; 2128 2129// It's like the unnamed buffer is deleted.... 2130if (curbuf -> b_p_bl ) { 2131apply_autocmds (EVENT_BUFDELETE ,NULL ,NULL , false,curbuf ); 2132 } 2133apply_autocmds (EVENT_BUFWIPEOUT ,NULL ,NULL , false,curbuf ); 2134if (aborting ()) {// autocmds may abort script processing 2135return FAIL ; 2136 } 2137if (curbuf != buf ) { 2138// We are in another buffer now, don't do the renaming. 2139emsg (_ (e_auchangedbuf )); 2140return FAIL ; 2141 } 2142 2143if (setfname (curbuf ,fname ,sfname , false)== OK ) { 2144curbuf -> b_flags |=BF_NOTEDITED ; 2145 } 2146 2147// ....and a new named one is created 2148apply_autocmds (EVENT_BUFNEW ,NULL ,NULL , false,curbuf ); 2149if (curbuf -> b_p_bl ) { 2150apply_autocmds (EVENT_BUFADD ,NULL ,NULL , false,curbuf ); 2151 } 2152if (aborting ()) {// autocmds may abort script processing 2153return FAIL ; 2154 } 2155 2156// Do filetype detection now if 'filetype' is empty. 2157if (* curbuf -> b_p_ft == NUL ) { 2158if (augroup_exists ("filetypedetect" )) { 2159do_doautocmd ("filetypedetect BufRead" , false,NULL ); 2160 } 2161do_modelines (0 ); 2162 } 2163 2164return OK ; 2165} 2166 2167/// Put file name into the specified buffer with quotes 2168/// 2169/// Replaces home directory at the start with `~`. 2170/// 2171/// @param[out] ret_buf Buffer to save results to. 2172/// @param[in] bufsize ret_buf size. 2173/// @param[in] buf buf_T file name is coming from. 2174/// @param[in] fname File name to write. 2175void add_quoted_fname (char * const ret_buf ,const size_t bufsize ,const buf_T * const buf , 2176const char * fname ) 2177FUNC_ATTR_NONNULL_ARG (1 ) 2178{ 2179if (fname == NULL ) { 2180fname = "-stdin-" ; 2181 } 2182size_t len = 0 ; 2183ret_buf [len ++ ]= '"' ; 2184len += home_replace (buf ,fname ,ret_buf + len ,bufsize - 4 , true); 2185xstrlcpy (ret_buf + len ,"\" " ,bufsize - len ); 2186} 2187 2188/// Append message for text mode to IObuff. 2189/// 2190/// @param eol_type line ending type 2191/// 2192/// @return true if something was appended. 2193bool msg_add_fileformat (int eol_type ) 2194{ 2195#ifndef USE_CRNL 2196if (eol_type == EOL_DOS ) { 2197xstrlcat (IObuff ,_ ("[dos]" ),IOSIZE ); 2198return true; 2199 } 2200#endif 2201if (eol_type == EOL_MAC ) { 2202xstrlcat (IObuff ,_ ("[mac]" ),IOSIZE ); 2203return true; 2204 } 2205#ifdef USE_CRNL 2206if (eol_type == EOL_UNIX ) { 2207xstrlcat (IObuff ,_ ("[unix]" ),IOSIZE ); 2208return true; 2209 } 2210#endif 2211return false; 2212} 2213 2214/// Append line and character count to IObuff. 2215void msg_add_lines (int insert_space ,linenr_T lnum ,off_T nchars ) 2216{ 2217size_t len = strlen (IObuff ); 2218 2219if (shortmess (kShmLines )) { 2220snprintf (IObuff + len ,IOSIZE - len , 2221_ ("%s%" PRId64 "L, %" PRId64 "B" ),// l10n: L as in line, B as in byte 2222insert_space ?" " :"" , (int64_t )lnum , (int64_t )nchars ); 2223 }else { 2224len += (size_t )snprintf (IObuff + len ,IOSIZE - len , 2225NGETTEXT ("%s%" PRId64 " line, " ,"%s%" PRId64 " lines, " ,lnum ), 2226insert_space ?" " :"" , (int64_t )lnum ); 2227snprintf (IObuff + len ,IOSIZE - len , 2228NGETTEXT ("%" PRId64 " byte" ,"%" PRId64 " bytes" ,nchars ), 2229 (int64_t )nchars ); 2230 } 2231} 2232 2233bool time_differs (const FileInfo * file_info ,int64_t mtime ,int64_t mtime_ns ) 2234FUNC_ATTR_CONST 2235{ 2236#if defined(__linux__ )|| defined(MSWIN ) 2237return file_info -> stat .st_mtim .tv_nsec != mtime_ns 2238// On a FAT filesystem, esp. under Linux, there are only 5 bits to store 2239// the seconds. Since the roundoff is done when flushing the inode, the 2240// time may change unexpectedly by one second!!! 2241|| file_info -> stat .st_mtim .tv_sec - mtime > 1 2242|| mtime - file_info -> stat .st_mtim .tv_sec > 1 ; 2243#else 2244return file_info -> stat .st_mtim .tv_nsec != mtime_ns 2245|| file_info -> stat .st_mtim .tv_sec != mtime ; 2246#endif 2247} 2248 2249/// Return true if file encoding "fenc" requires conversion from or to 2250/// 'encoding'. 2251/// 2252/// @param fenc file encoding to check 2253/// 2254/// @return true if conversion is required 2255bool need_conversion (const char * fenc ) 2256FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT 2257{ 2258bool same_encoding ; 2259int fenc_flags ; 2260 2261if (* fenc == NUL || strcmp (p_enc ,fenc )== 0 ) { 2262same_encoding = true; 2263fenc_flags = 0 ; 2264 }else { 2265// Ignore difference between "ansi" and "latin1", "ucs-4" and 2266// "ucs-4be", etc. 2267int enc_flags = get_fio_flags (p_enc ); 2268fenc_flags = get_fio_flags (fenc ); 2269same_encoding = (enc_flags != 0 && fenc_flags == enc_flags ); 2270 } 2271if (same_encoding ) { 2272// Specified file encoding matches UTF-8. 2273return false; 2274 } 2275 2276// Encodings differ. However, conversion is not needed when 'enc' is any 2277// Unicode encoding and the file is UTF-8. 2278return !(fenc_flags == FIO_UTF8 ); 2279} 2280 2281/// Return the FIO_ flags needed for the internal conversion if 'name' was 2282/// unicode or latin1, otherwise 0. If "name" is an empty string, 2283/// use 'encoding'. 2284/// 2285/// @param name string to check for encoding 2286int get_fio_flags (const char * name ) 2287{ 2288if (* name == NUL ) { 2289name = p_enc ; 2290 } 2291int prop = enc_canon_props (name ); 2292if (prop & ENC_UNICODE ) { 2293if (prop & ENC_2BYTE ) { 2294if (prop & ENC_ENDIAN_L ) { 2295return FIO_UCS2 |FIO_ENDIAN_L ; 2296 } 2297return FIO_UCS2 ; 2298 } 2299if (prop & ENC_4BYTE ) { 2300if (prop & ENC_ENDIAN_L ) { 2301return FIO_UCS4 |FIO_ENDIAN_L ; 2302 } 2303return FIO_UCS4 ; 2304 } 2305if (prop & ENC_2WORD ) { 2306if (prop & ENC_ENDIAN_L ) { 2307return FIO_UTF16 |FIO_ENDIAN_L ; 2308 } 2309return FIO_UTF16 ; 2310 } 2311return FIO_UTF8 ; 2312 } 2313if (prop & ENC_LATIN1 ) { 2314return FIO_LATIN1 ; 2315 } 2316// must be ENC_DBCS, requires iconv() 2317return 0 ; 2318} 2319 2320/// Check for a Unicode BOM (Byte Order Mark) at the start of p[size]. 2321/// "size" must be at least 2. 2322/// 2323/// @return the name of the encoding and set "*lenp" to the length or, 2324/// NULL when no BOM found. 2325static char * check_for_bom (const char * p_in ,int size ,int * lenp ,int flags ) 2326{ 2327const uint8_t * p = (const uint8_t * )p_in ; 2328char * name = NULL ; 2329int len = 2 ; 2330 2331if (p [0 ]== 0xef && p [1 ]== 0xbb && size >=3 && p [2 ]== 0xbf 2332&& (flags == FIO_ALL || flags == FIO_UTF8 || flags == 0 )) { 2333name = "utf-8" ;// EF BB BF 2334len = 3 ; 2335 }else if (p [0 ]== 0xff && p [1 ]== 0xfe ) { 2336if (size >=4 && p [2 ]== 0 && p [3 ]== 0 2337&& (flags == FIO_ALL || flags == (FIO_UCS4 |FIO_ENDIAN_L ))) { 2338name = "ucs-4le" ;// FF FE 00 00 2339len = 4 ; 2340 }else if (flags == (FIO_UCS2 |FIO_ENDIAN_L )) { 2341name = "ucs-2le" ;// FF FE 2342 }else if (flags == FIO_ALL 2343|| flags == (FIO_UTF16 |FIO_ENDIAN_L )) { 2344// utf-16le is preferred, it also works for ucs-2le text 2345name = "utf-16le" ;// FF FE 2346 } 2347 }else if (p [0 ]== 0xfe && p [1 ]== 0xff 2348&& (flags == FIO_ALL || flags == FIO_UCS2 || flags == 2349FIO_UTF16 )) { 2350// Default to utf-16, it works also for ucs-2 text. 2351if (flags == FIO_UCS2 ) { 2352name = "ucs-2" ;// FE FF 2353 }else { 2354name = "utf-16" ;// FE FF 2355 } 2356 }else if (size >=4 && p [0 ]== 0 && p [1 ]== 0 && p [2 ]== 0xfe 2357&& p [3 ]== 0xff && (flags == FIO_ALL || flags == FIO_UCS4 )) { 2358name = "ucs-4" ;// 00 00 FE FF 2359len = 4 ; 2360 } 2361 2362* lenp = len ; 2363return name ; 2364} 2365 2366/// Shorten filename of a buffer. 2367/// 2368/// @param force when true: Use full path from now on for files currently being 2369/// edited, both for file name and swap file name. Try to shorten the file 2370/// names a bit, if safe to do so. 2371/// when false: Only try to shorten absolute file names. 2372/// 2373/// For buffers that have buftype "nofile" or "scratch": never change the file 2374/// name. 2375/// 2376/// @return True if `b_fname` changed. 2377bool shorten_buf_fname (buf_T * buf ,char * dirname ,int force ) 2378{ 2379if (buf -> b_fname == NULL 2380|| bt_nofilename (buf ) 2381|| path_with_url (buf -> b_fname ) 2382|| !(force || buf -> b_sfname == NULL || path_is_absolute (buf -> b_sfname ))) { 2383return false; 2384 } 2385 2386char * p = path_shorten_fname (buf -> b_ffname ,dirname ); 2387bool shorten = p != NULL && * p != NUL ; 2388if (shorten && buf -> b_sfname != NULL && strcmp (p ,buf -> b_sfname )== 0 ) { 2389// Same name: keep the allocation. Callers (readfile()) alias `b_fname` across autocommands and 2390// check the pointer to detect a rename. Very cool... #41454 2391return false; 2392 } 2393 2394// Decide now, the old name may be freed below. 2395char * new_fname = shorten ?p :buf -> b_ffname ; 2396bool changed = new_fname == NULL || strcmp (new_fname ,buf -> b_fname )!= 0 ; 2397 2398if (buf -> b_sfname != buf -> b_ffname ) { 2399XFREE_CLEAR (buf -> b_sfname ); 2400 } 2401if (shorten ) { 2402buf -> b_sfname = xstrdup (p ); 2403buf -> b_fname = buf -> b_sfname ; 2404 }else { 2405buf -> b_fname = buf -> b_ffname ; 2406 } 2407return changed ; 2408} 2409 2410/// Shortens filenames for all buffers. Schedules a statusline redraw if any name changed. 2411void shorten_fnames (int force ) 2412{ 2413char dirname [MAXPATHL ]; 2414bool changed = false; 2415 2416os_dirname (dirname ,MAXPATHL ); 2417FOR_ALL_BUFFERS (buf ) { 2418changed |=shorten_buf_fname (buf ,dirname ,force ); 2419 2420// Always make the swap file name a full path, a "nofile" buffer may 2421// also have a swap file. 2422mf_fullname (buf -> b_ml .ml_mfp ); 2423 } 2424if (changed ) { 2425status_redraw_all (); 2426redraw_tabline = true; 2427 } 2428} 2429 2430/// Get new filename ended by given extension. 2431/// 2432/// @param fname The original filename. 2433/// If NULL, use current directory name and ext to 2434/// compute new filename. 2435/// @param ext The extension to add to the filename. 2436/// 4 chars max if prefixed with a dot, 3 otherwise. 2437/// @param prepend_dot If true, prefix ext with a dot. 2438/// Does nothing if ext already starts with a dot, or 2439/// if fname is NULL. 2440/// 2441/// @return [allocated] - A new filename, made up from: 2442/// * fname + ext, if fname not NULL. 2443/// * current dir + ext, if fname is NULL. 2444/// Result is guaranteed to: 2445/// * be ended by <ext>. 2446/// * have a basename with at most BASENAMELEN chars: 2447/// original basename is truncated if necessary. 2448/// * be different than original: basename chars are 2449/// replaced by "_" if necessary. If that can't be done 2450/// because truncated value of original filename was 2451/// made of all underscores, replace first "_" by "v". 2452/// - NULL, if fname is NULL and there was a problem trying 2453/// to get current directory. 2454char * modname (const char * fname ,const char * ext ,bool prepend_dot ) 2455FUNC_ATTR_NONNULL_ARG (2 ) 2456{ 2457char * retval ; 2458size_t fnamelen ; 2459size_t extlen = strlen (ext ); 2460 2461// If there is no file name we must get the name of the current directory 2462// (we need the full path in case :cd is used). 2463if (fname == NULL || * fname == NUL ) { 2464retval = xmalloc (MAXPATHL + extlen + 3 );// +3 for PATHSEP, "_" (Win), NUL 2465if (os_dirname (retval ,MAXPATHL )== FAIL 2466|| strlen (retval )== 0 ) { 2467xfree (retval ); 2468return NULL ; 2469 } 2470add_pathsep (retval ); 2471fnamelen = strlen (retval ); 2472prepend_dot = false;// nothing to prepend a dot to 2473 }else { 2474fnamelen = strlen (fname ); 2475retval = xmalloc (fnamelen + extlen + 3 ); 2476strcpy (retval ,fname );// NOLINT(runtime/printf) 2477 } 2478 2479// Search backwards until we hit a '/', '\' or ':'. 2480// Then truncate what is after the '/', '\' or ':' to BASENAMELEN characters. 2481char * ptr = NULL ; 2482for (ptr = retval + fnamelen ;ptr > retval ;MB_PTR_BACK (retval ,ptr )) { 2483if (vim_ispathsep (* ptr )) { 2484ptr ++ ; 2485break ; 2486 } 2487 } 2488 2489// the file name has at most BASENAMELEN characters. 2490size_t ptrlen = fnamelen - (size_t )(ptr - retval ); 2491if (ptrlen > (unsigned )BASENAMELEN ) { 2492ptrlen = BASENAMELEN ; 2493ptr [ptrlen ]= NUL ; 2494 } 2495 2496char * s = ptr + ptrlen ; 2497 2498// Append the extension. 2499// ext can start with '.' and cannot exceed 3 more characters. 2500strcpy (s ,ext );// NOLINT(runtime/printf) 2501 2502char * e ; 2503// Prepend the dot if needed. 2504if (prepend_dot && * (e = path_tail (retval ))!= '.' ) { 2505memmove (e + 1 ,e , ((fnamelen + extlen )- (size_t )(e - retval ))+ 1 );// +1 for NUL 2506* e = '.' ; 2507 } 2508 2509// Check that, after appending the extension, the file name is really 2510// different. 2511if (fname != NULL && strcmp (fname ,retval )== 0 ) { 2512// we search for a character that can be replaced by '_' 2513while (-- s >=ptr ) { 2514if (* s != '_' ) { 2515* s = '_' ; 2516break ; 2517 } 2518 } 2519if (s < ptr ) {// fname was "________.<ext>", how tricky! 2520* ptr = 'v' ; 2521 } 2522 } 2523return retval ; 2524} 2525 2526/// Like fgets(), but if the file line is too long, it is truncated and the 2527/// rest of the line is thrown away. 2528/// 2529/// @param[out] buf buffer to fill 2530/// @param size size of the buffer 2531/// @param fp file to read from 2532/// 2533/// @return true for EOF or error 2534bool vim_fgets (char * buf ,int size ,FILE * fp ) 2535FUNC_ATTR_NONNULL_ALL 2536{ 2537char * retval ; 2538 2539// safety check 2540if (size < 2 ) { 2541if (size == 1 ) { 2542buf [0 ]= NUL ; 2543 } 2544return true; 2545 } 2546 2547buf [size - 2 ]= NUL ; 2548 2549do { 2550errno = 0 ; 2551retval = fgets (buf ,size ,fp ); 2552 }while (retval == NULL && errno == EINTR && ferror (fp )); 2553 2554if (buf [size - 2 ]!= NUL && buf [size - 2 ]!= '\n' ) { 2555char tbuf [200 ]; 2556 2557buf [size - 1 ]= NUL ;// Truncate the line. 2558 2559// Now throw away the rest of the line: 2560do { 2561tbuf [sizeof (tbuf )- 2 ]= NUL ; 2562errno = 0 ; 2563retval = fgets (tbuf ,sizeof (tbuf ),fp ); 2564if (retval == NULL && (feof (fp )|| errno != EINTR )) { 2565break ; 2566 } 2567 }while (tbuf [sizeof (tbuf )- 2 ]!= NUL && tbuf [sizeof (tbuf )- 2 ]!= '\n' ); 2568 } 2569return retval == NULL ; 2570} 2571 2572/// Read 2 bytes from "fd" and turn them into an int, MSB first. 2573/// 2574/// @return -1 when encountering EOF. 2575int get2c (FILE * fd ) 2576{ 2577const int n = getc (fd ); 2578if (n == EOF ) { 2579return -1 ; 2580 } 2581const int c = getc (fd ); 2582if (c == EOF ) { 2583return -1 ; 2584 } 2585return (n <<8 )+ c ; 2586} 2587 2588/// Read 3 bytes from "fd" and turn them into an int, MSB first. 2589/// 2590/// @return -1 when encountering EOF. 2591int get3c (FILE * fd ) 2592{ 2593int n = getc (fd ); 2594if (n == EOF ) { 2595return -1 ; 2596 } 2597int c = getc (fd ); 2598if (c == EOF ) { 2599return -1 ; 2600 } 2601n = (n <<8 )+ c ; 2602c = getc (fd ); 2603if (c == EOF ) { 2604return -1 ; 2605 } 2606return (n <<8 )+ c ; 2607} 2608 2609/// Read 4 bytes from "fd" and turn them into an int, MSB first. 2610/// 2611/// @return -1 when encountering EOF. 2612int get4c (FILE * fd ) 2613{ 2614// Use unsigned rather than int otherwise result is undefined 2615// when left-shift sets the MSB. 2616unsigned n ; 2617 2618int c = getc (fd ); 2619if (c == EOF ) { 2620return -1 ; 2621 } 2622n = (unsigned )c ; 2623c = getc (fd ); 2624if (c == EOF ) { 2625return -1 ; 2626 } 2627n = (n <<8 )+ (unsigned )c ; 2628c = getc (fd ); 2629if (c == EOF ) { 2630return -1 ; 2631 } 2632n = (n <<8 )+ (unsigned )c ; 2633c = getc (fd ); 2634if (c == EOF ) { 2635return -1 ; 2636 } 2637n = (n <<8 )+ (unsigned )c ; 2638return (int )n ; 2639} 2640 2641/// Read 8 bytes from `fd` and turn them into a time_t, MSB first. 2642/// 2643/// @return -1 when encountering EOF. 2644time_t get8ctime (FILE * fd ) 2645{ 2646time_t n = 0 ; 2647 2648for (int i = 0 ;i < 8 ;i ++ ) { 2649const int c = getc (fd ); 2650if (c == EOF ) { 2651return -1 ; 2652 } 2653n = (n <<8 )+ c ; 2654 } 2655return n ; 2656} 2657 2658/// Reads a string of length "cnt" from "fd" into allocated memory. 2659/// 2660/// @return pointer to the string or NULL when unable to read that many bytes. 2661char * read_string (FILE * fd ,size_t cnt ) 2662{ 2663char * str = xmallocz (cnt ); 2664for (size_t i = 0 ;i < cnt ;i ++ ) { 2665int c = getc (fd ); 2666if (c == EOF ) { 2667xfree (str ); 2668return NULL ; 2669 } 2670str [i ]= (char )c ; 2671 } 2672return str ; 2673} 2674 2675/// Writes a number to file "fd", most significant bit first, in "len" bytes. 2676/// 2677/// @return false in case of an error. 2678bool put_bytes (FILE * fd ,uintmax_t number ,size_t len ) 2679{ 2680assert (len > 0 ); 2681for (size_t i = len - 1 ;i < len ;i -- ) { 2682if (putc ((int )(number >> (i * 8 )),fd )== EOF ) { 2683return false; 2684 } 2685 } 2686return true; 2687} 2688 2689/// Writes time_t to file "fd" in 8 bytes. 2690/// 2691/// @return FAIL when the write failed. 2692int put_time (FILE * fd ,time_t time_ ) 2693{ 2694uint8_t buf [8 ]; 2695time_to_bytes (time_ ,buf ); 2696return fwrite (buf ,sizeof (uint8_t ),ARRAY_SIZE (buf ),fd )== 1 ?OK :FAIL ; 2697} 2698 2699static int rename_with_tmp (const char * const from ,const char * const to ) 2700{ 2701// Find a name that doesn't exist and is in the same directory. 2702// Rename "from" to "tempname" and then rename "tempname" to "to". 2703if (strlen (from ) >=MAXPATHL - 5 ) { 2704return -1 ; 2705 } 2706 2707char tempname [MAXPATHL + 1 ]; 2708STRCPY (tempname ,from ); 2709for (int n = 123 ;n < 99999 ;n ++ ) { 2710char * tail = path_tail (tempname ); 2711snprintf (tail , (size_t )((MAXPATHL + 1 )- (tail - tempname )),"%d" ,n ); 2712 2713if (!os_path_exists (tempname )) { 2714if (os_rename (from ,tempname )== OK ) { 2715if (os_rename (tempname ,to )== OK ) { 2716return 0 ; 2717 } 2718// Strange, the second step failed. Try moving the 2719// file back and return failure. 2720os_rename (tempname ,from ); 2721return -1 ; 2722 } 2723// If it fails for one temp name it will most likely fail 2724// for any temp name, give up. 2725return -1 ; 2726 } 2727 } 2728return -1 ; 2729} 2730 2731/// os_rename() only works if both files are on the same file system, this 2732/// function will (attempts to?) copy the file across if rename fails -- webb 2733/// 2734/// @return -1 for failure, 0 for success 2735int vim_rename (const char * from ,const char * to ) 2736FUNC_ATTR_NONNULL_ALL 2737{ 2738bool use_tmp_file = false; 2739 2740// When the names are identical, there is nothing to do. When they refer 2741// to the same file (ignoring case and slash/backslash differences) but 2742// the file name differs we need to go through a temp file. 2743if (path_equal (from ,to ,kPathCmpLiteral )) { 2744if (p_fic && (strcmp (path_tail (from ),path_tail (to ))!= 0 )) { 2745use_tmp_file = true; 2746 }else { 2747return 0 ; 2748 } 2749 } 2750 2751// Fail if the "from" file doesn't exist. Avoids that "to" is deleted. 2752FileInfo from_info ; 2753if (!os_fileinfo (from ,& from_info )) { 2754return -1 ; 2755 } 2756 2757// It's possible for the source and destination to be the same file. 2758// This happens when "from" and "to" differ in case and are on a FAT32 2759// filesystem. In that case go through a temp file name. 2760FileInfo to_info ; 2761if (os_fileinfo (to ,& to_info )&& os_fileinfo_id_equal (& from_info ,& to_info )) { 2762use_tmp_file = true; 2763 } 2764 2765if (use_tmp_file ) { 2766return rename_with_tmp (from ,to ); 2767 } 2768 2769// First try a normal rename without removing "to". 2770if (os_rename (from ,to )== OK ) { 2771return 0 ; 2772 } 2773 2774// Retry after removing "to", e.g. when renaming a directory over a file. 2775if (os_remove (to )== 0 && os_rename (from ,to )== OK ) { 2776return 0 ; 2777 } 2778 2779// Rename() failed, try copying the file. 2780int ret = vim_copyfile (from ,to ); 2781if (ret != OK ) { 2782return -1 ; 2783 } 2784 2785if (os_fileinfo (from ,& from_info )) { 2786os_remove (from ); 2787 } 2788 2789return 0 ; 2790} 2791 2792/// Create the new file with same permissions as the original. 2793/// Return FAIL for failure, OK for success. 2794int vim_copyfile (const char * from ,const char * to ) 2795{ 2796char * errmsg = NULL ; 2797 2798#ifdef HAVE_READLINK 2799FileInfo from_info ; 2800if (os_fileinfo_link (from ,& from_info )&& S_ISLNK (from_info .stat .st_mode )) { 2801int ret = -1 ; 2802 2803char linkbuf [MAXPATHL + 1 ]; 2804ssize_t len = readlink (from ,linkbuf ,MAXPATHL ); 2805if (len > 0 ) { 2806linkbuf [len ]= NUL ; 2807 2808// Create link 2809ret = symlink (linkbuf ,to ); 2810 } 2811 2812return ret == 0 ?OK :FAIL ; 2813 } 2814#endif 2815 2816// For systems that support ACL: get the ACL from the original file. 2817vim_acl_T acl = os_get_acl (from ); 2818 2819if (os_copy (from ,to ,UV_FS_COPYFILE_EXCL )!= 0 ) { 2820os_free_acl (acl ); 2821return FAIL ; 2822 } 2823 2824os_set_acl (to ,acl ); 2825os_free_acl (acl ); 2826if (errmsg != NULL ) { 2827semsg (errmsg ,to ); 2828return FAIL ; 2829 } 2830return OK ; 2831} 2832 2833static bool already_warned = false; 2834 2835/// Check if any not hidden buffer has been changed. 2836/// Postpone the check if there are characters in the stuff buffer, a global 2837/// command is being executed, a mapping is being executed or an autocommand is 2838/// busy. 2839/// 2840/// @param focus called for GUI focus event 2841/// 2842/// @return true if some message was written (screen should be redrawn and cursor positioned). 2843int check_timestamps (int focus ) 2844{ 2845// Don't check timestamps while system() or another low-level function may 2846// cause us to lose and gain focus. 2847if (no_check_timestamps > 0 ) { 2848return false; 2849 } 2850 2851// Avoid doing a check twice. The OK/Reload dialog can cause a focus 2852// event and we would keep on checking if the file is steadily growing. 2853// Do check again after typing something. 2854if (focus && did_check_timestamps ) { 2855need_check_timestamps = true; 2856return false; 2857 } 2858 2859int didit = 0 ; 2860 2861if (!stuff_empty ()|| global_busy || !typebuf_typed () 2862|| autocmd_busy || curbuf -> b_ro_locked > 0 2863|| allbuf_lock > 0 ) { 2864need_check_timestamps = true;// check later 2865 }else { 2866no_wait_return ++ ; 2867did_check_timestamps = true; 2868already_warned = false; 2869FOR_ALL_BUFFERS (buf ) { 2870// Only check buffers in a window. 2871if (buf -> b_nwindows > 0 ) { 2872bufref_T bufref ; 2873set_bufref (& bufref ,buf ); 2874const int n = buf_check_timestamp (buf ); 2875didit = MAX (didit ,n ); 2876if (n > 0 && !bufref_valid (& bufref )) { 2877// Autocommands have removed the buffer, start at the first one again. 2878buf = firstbuf ; 2879continue ; 2880 } 2881 } 2882 } 2883no_wait_return -- ; 2884need_check_timestamps = false; 2885if (need_wait_return && didit == 2 ) { 2886// make sure msg isn't overwritten 2887msg_puts ("\n" ); 2888ui_flush (); 2889 } 2890 } 2891return didit ; 2892} 2893 2894/// Move all the lines from buffer "frombuf" to buffer "tobuf". 2895/// 2896/// @return OK or FAIL. 2897/// When FAIL "tobuf" is incomplete and/or "frombuf" is not empty. 2898static int move_lines (buf_T * frombuf ,buf_T * tobuf ) 2899{ 2900buf_T * tbuf = curbuf ; 2901int retval = OK ; 2902 2903// Copy the lines in "frombuf" to "tobuf". 2904curbuf = tobuf ; 2905for (linenr_T lnum = 1 ;lnum <=frombuf -> b_ml .ml_line_count ;lnum ++ ) { 2906char * p = xmemdupz (ml_get_buf (frombuf ,lnum ), (size_t )ml_get_buf_len (frombuf ,lnum )); 2907if (ml_append (lnum - 1 ,p ,0 , false)== FAIL ) { 2908xfree (p ); 2909retval = FAIL ; 2910break ; 2911 } 2912xfree (p ); 2913 } 2914 2915// Delete all the lines in "frombuf". 2916if (retval != FAIL ) { 2917curbuf = frombuf ; 2918for (linenr_T lnum = curbuf -> b_ml .ml_line_count ;lnum > 0 ;lnum -- ) { 2919if (ml_delete (lnum )== FAIL ) { 2920// Oops! We could try putting back the saved lines, but that 2921// might fail again... 2922retval = FAIL ; 2923break ; 2924 } 2925 } 2926 } 2927 2928curbuf = tbuf ; 2929return retval ; 2930} 2931 2932/// Check if buffer "buf" has been changed. 2933/// Also check if the file for a new buffer unexpectedly appeared. 2934/// 2935/// @return 1 if a changed buffer was found or, 2936/// 2 if a message has been displayed or, 2937/// 0 otherwise. 2938int buf_check_timestamp (buf_T * buf ) 2939FUNC_ATTR_NONNULL_ALL 2940{ 2941int retval = 0 ; 2942char * mesg = NULL ; 2943char * mesg2 = "" ; 2944bool helpmesg = false; 2945 2946enum { 2947RELOAD_NONE , 2948RELOAD_NORMAL , 2949RELOAD_DETECT , 2950 }reload = RELOAD_NONE ; 2951 2952bool can_reload = false; 2953uint64_t orig_size = buf -> b_orig_size ; 2954int orig_mode = buf -> b_orig_mode ; 2955static bool busy = false; 2956 2957bufref_T bufref ; 2958set_bufref (& bufref ,buf ); 2959 2960// If its a terminal, there is no file name, the buffer is not loaded, 2961// 'buftype' is set, we are in the middle of a save or being called 2962// recursively: ignore this buffer. 2963if (buf -> terminal 2964|| buf -> b_ffname == NULL 2965|| buf -> b_ml .ml_mfp == NULL 2966|| !bt_normal (buf ) 2967|| buf -> b_saving 2968|| busy ) { 2969return 0 ; 2970 } 2971 2972FileInfo file_info ; 2973bool file_info_ok ; 2974if (!(buf -> b_flags & BF_NOTEDITED ) 2975&& buf -> b_mtime != 0 2976&& (!(file_info_ok = os_fileinfo (buf -> b_ffname ,& file_info )) 2977|| time_differs (& file_info ,buf -> b_mtime ,buf -> b_mtime_ns ) 2978|| (int )file_info .stat .st_mode != buf -> b_orig_mode )) { 2979const int64_t prev_b_mtime = buf -> b_mtime ; 2980 2981retval = 1 ; 2982 2983// set b_mtime to stop further warnings (e.g., when executing 2984// FileChangedShell autocmd) 2985if (!file_info_ok ) { 2986// Check the file again later to see if it re-appears. 2987buf -> b_mtime = -1 ; 2988buf -> b_orig_size = 0 ; 2989buf -> b_orig_mode = 0 ; 2990 }else { 2991buf_store_file_info (buf ,& file_info ); 2992 } 2993 2994if (os_isdir (buf -> b_fname )) { 2995// Don't do anything for a directory. Might contain the file explorer. 2996 }else if ((buf -> b_p_ar >=0 ?buf -> b_p_ar :p_ar ) 2997&& !bufIsChanged (buf )&& file_info_ok ) { 2998// If 'autoread' is set, the buffer has no changes and the file still 2999// exists, reload the buffer. Use the buffer-local option value if it 3000// was set, the global option value otherwise. 3001reload = RELOAD_NORMAL ; 3002 }else { 3003char * reason ; 3004size_t reasonlen ; 3005 3006if (!file_info_ok ) { 3007reason = "deleted" ; 3008reasonlen = STRLEN_LITERAL ("deleted" ); 3009 }else if (bufIsChanged (buf )) { 3010reason = "conflict" ; 3011reasonlen = STRLEN_LITERAL ("conflict" ); 3012 }else if (orig_size != buf -> b_orig_size || buf_contents_changed (buf )) { 3013reason = "changed" ; 3014reasonlen = STRLEN_LITERAL ("changed" ); 3015 }else if (orig_mode != buf -> b_orig_mode ) { 3016reason = "mode" ; 3017reasonlen = STRLEN_LITERAL ("mode" ); 3018 }else { 3019reason = "time" ; 3020reasonlen = STRLEN_LITERAL ("time" ); 3021 } 3022 3023// Only give the warning if there are no FileChangedShell 3024// autocommands. 3025// Avoid being called recursively by setting "busy". 3026busy = true; 3027set_vim_var_string (VV_FCS_REASON ,reason , (int )reasonlen ); 3028set_vim_var_string (VV_FCS_CHOICE ,"" ,0 ); 3029allbuf_lock ++ ; 3030bool n = apply_autocmds (EVENT_FILECHANGEDSHELL ,buf -> b_fname ,buf -> b_fname , false,buf ); 3031allbuf_lock -- ; 3032busy = false; 3033if (n ) { 3034if (!bufref_valid (& bufref )) { 3035emsg (_ ("E246: FileChangedShell autocommand deleted buffer" )); 3036 } 3037char * s = get_vim_var_str (VV_FCS_CHOICE ); 3038if (strcmp (s ,"reload" )== 0 && * reason != 'd' ) { 3039reload = RELOAD_NORMAL ; 3040 }else if (strcmp (s ,"edit" )== 0 ) { 3041reload = RELOAD_DETECT ; 3042 }else if (strcmp (s ,"ask" )== 0 ) { 3043n = false; 3044 }else { 3045return 2 ; 3046 } 3047 } 3048if (!n ) { 3049if (* reason == 'd' ) { 3050// Only give the message once. 3051if (prev_b_mtime != -1 ) { 3052mesg = _ ("E211: File \"%s\" no longer available" ); 3053 } 3054 }else { 3055helpmesg = true; 3056can_reload = true; 3057 3058// Check if the file contents really changed to avoid 3059// giving a warning when only the timestamp was set (e.g., 3060// checked out of CVS). Always warn when the buffer was 3061// changed. 3062if (reason [2 ]== 'n' ) { 3063mesg = 3064_ ("W12: Warning: File \"%s\" has changed and the buffer was changed in Vim as well" ); 3065mesg2 = _ ("See \":help W12\" for more info." ); 3066 }else if (reason [1 ]== 'h' ) { 3067mesg = _ ("W11: Warning: File \"%s\" has changed since editing started" ); 3068mesg2 = _ ("See \":help W11\" for more info." ); 3069 }else if (* reason == 'm' ) { 3070mesg = _ ("W16: Warning: Mode of file \"%s\" has changed since editing started" ); 3071mesg2 = _ ("See \":help W16\" for more info." ); 3072 }else { 3073// Only timestamp changed, store it to avoid a warning 3074// in check_mtime() later. 3075buf -> b_mtime_read = buf -> b_mtime ; 3076buf -> b_mtime_read_ns = buf -> b_mtime_ns ; 3077 } 3078 } 3079 } 3080 } 3081 }else if ((buf -> b_flags & BF_NEW )&& !(buf -> b_flags & BF_NEW_W ) 3082&& os_path_exists (buf -> b_ffname )) { 3083retval = 1 ; 3084mesg = _ ("W13: Warning: File \"%s\" has been created after editing started" ); 3085buf -> b_flags |=BF_NEW_W ; 3086can_reload = true; 3087 } 3088 3089if (mesg != NULL ) { 3090char * path = home_replace_save (buf ,buf -> b_fname ); 3091if (!helpmesg ) { 3092mesg2 = "" ; 3093 } 3094// +2 for either '\n' or "; " and +1 for NUL 3095const size_t tbufsize = strlen (path )+ strlen (mesg )+ strlen (mesg2 )+ 3 ; 3096char * const tbuf = xmalloc (tbufsize ); 3097int tbuflen = snprintf (tbuf ,tbufsize ,mesg ,path ); 3098// Set warningmsg here, before the unimportant and output-specific 3099// mesg2 has been appended. 3100set_vim_var_string (VV_WARNINGMSG ,tbuf ,tbuflen ); 3101if (can_reload ) { 3102if (* mesg2 != NUL ) { 3103snprintf (tbuf + tbuflen ,tbufsize - (size_t )tbuflen ,"\n%s" ,mesg2 ); 3104 } 3105switch (do_dialog (VIM_WARNING ,_ ("Warning" ),tbuf , 3106_ ("&OK\n&Load File\nLoad File &and Options" ), 31071 ,NULL , true)) { 3108case 2 : 3109reload = RELOAD_NORMAL ; 3110break ; 3111case 3 : 3112reload = RELOAD_DETECT ; 3113break ; 3114 } 3115 }else if (State > MODE_NORMAL_BUSY || (State & MODE_CMDLINE )|| already_warned ) { 3116if (* mesg2 != NUL ) { 3117snprintf (tbuf + tbuflen ,tbufsize - (size_t )tbuflen ,"; %s" ,mesg2 ); 3118 } 3119emsg (tbuf ); 3120retval = 2 ; 3121 }else { 3122if (!autocmd_busy ) { 3123msg_start (); 3124msg_puts_hl (tbuf ,HLF_E , true); 3125if (* mesg2 != NUL ) { 3126msg_puts_hl (mesg2 ,HLF_W , true); 3127 } 3128msg_clr_eos (); 3129msg_end (); 3130if (emsg_silent == 0 && !in_assert_fails && !ui_has (kUIMessages )) { 3131msg_delay (1004 , true);// give the user some time to think about it 3132redraw_cmdline = false;// don't redraw and erase the message 3133 } 3134 } 3135already_warned = true; 3136 } 3137 3138xfree (tbuf ); 3139xfree (path ); 3140 } 3141 3142if (reload != RELOAD_NONE ) { 3143// Reload the buffer. 3144buf_reload (buf ,orig_mode ,reload == RELOAD_DETECT ); 3145if (bufref_valid (& bufref )&& buf -> b_p_udf && buf -> b_ffname != NULL ) { 3146uint8_t hash [UNDO_HASH_SIZE ]; 3147 3148// Any existing undo file is unusable, write it now. 3149u_compute_hash (buf ,hash ); 3150u_write_undo (NULL , false,buf ,hash ); 3151 } 3152 } 3153 3154// Trigger FileChangedShell when the file was changed in any way. 3155if (bufref_valid (& bufref )&& retval != 0 ) { 3156apply_autocmds (EVENT_FILECHANGEDSHELLPOST ,buf -> b_fname ,buf -> b_fname , false,buf ); 3157 } 3158return retval ; 3159} 3160 3161/// Reload a buffer that is already loaded. 3162/// Used when the file was changed outside of Vim. 3163/// "orig_mode" is buf->b_orig_mode before the need for reloading was detected. 3164/// buf->b_orig_mode may have been reset already. 3165void buf_reload (buf_T * buf ,int orig_mode ,bool reload_options ) 3166{ 3167exarg_T ea ; 3168int old_ro = buf -> b_p_ro ; 3169buf_T * savebuf ; 3170bufref_T bufref ; 3171int saved = OK ; 3172CtxSwitch aco = {0 }; 3173int flags = READ_NEW ; 3174 3175// Set curwin/curbuf for "buf" and save some things. 3176ctx_switch (& aco ,NULL ,NULL ,buf ,0 ); 3177 3178mc_buf_clear (buf );// Multicursor: file-reload invalidates the extmarks. 3179 3180// Unless reload_options is set, we only want to read the text from the 3181// file, not reset the syntax highlighting, clear marks, diff status, etc. 3182// Force the fileformat and encoding to be the same. 3183if (reload_options ) { 3184CLEAR_FIELD (ea ); 3185 }else { 3186prep_exarg (& ea ,buf ); 3187 } 3188 3189pos_T old_cursor = curwin -> w_cursor ; 3190linenr_T old_topline = curwin -> w_topline ; 3191 3192if (p_ur < 0 || curbuf -> b_ml .ml_line_count <=p_ur ) { 3193// Save all the text, so that the reload can be undone. 3194// Sync first so that this is a separate undo-able action. 3195u_sync (false); 3196saved = u_savecommon (curbuf ,0 ,curbuf -> b_ml .ml_line_count + 1 ,0 , true); 3197flags |=READ_KEEP_UNDO ; 3198 } 3199 3200// To behave like when a new file is edited (matters for 3201// BufReadPost autocommands) we first need to delete the current 3202// buffer contents. But if reading the file fails we should keep 3203// the old contents. Can't use memory only, the file might be 3204// too big. Use a hidden buffer to move the buffer contents to. 3205if (buf_is_empty (curbuf )|| saved == FAIL ) { 3206savebuf = NULL ; 3207 }else { 3208// Allocate a buffer without putting it in the buffer list. 3209savebuf = buflist_new (NULL ,NULL ,1 ,BLN_DUMMY ); 3210set_bufref (& bufref ,savebuf ); 3211if (savebuf != NULL && buf == curbuf ) { 3212// Open the memline. 3213curbuf = savebuf ; 3214curwin -> w_buffer = savebuf ; 3215saved = ml_open (curbuf ); 3216curbuf = buf ; 3217curwin -> w_buffer = buf ; 3218 } 3219if (savebuf == NULL || saved == FAIL || buf != curbuf 3220|| move_lines (buf ,savebuf )== FAIL ) { 3221semsg (_ ("E462: Could not prepare for reloading \"%s\"" ), 3222buf -> b_fname ); 3223saved = FAIL ; 3224 } 3225 } 3226 3227if (saved == OK ) { 3228curbuf -> b_flags |=BF_CHECK_RO ;// check for RO again 3229curbuf -> b_keep_filetype = true;// don't detect 'filetype' 3230if (readfile (buf -> b_ffname ,buf -> b_fname ,0 ,0 , 3231 (linenr_T )MAXLNUM ,& ea ,flags ,shortmess (kShmFileinfo ))!= OK ) { 3232if (!aborting ()) { 3233semsg (_ ("E321: Could not reload \"%s\"" ),buf -> b_fname ); 3234 } 3235if (savebuf != NULL && bufref_valid (& bufref )&& buf == curbuf ) { 3236// Put the text back from the save buffer. First 3237// delete any lines that readfile() added. 3238while (!buf_is_empty (curbuf )) { 3239if (ml_delete (buf -> b_ml .ml_line_count )== FAIL ) { 3240break ; 3241 } 3242 } 3243move_lines (savebuf ,buf ); 3244 } 3245 }else if (buf == curbuf ) {// "buf" still valid. 3246// Mark the buffer as unmodified and free undo info. 3247unchanged (buf , true, true); 3248if ((flags & READ_KEEP_UNDO )== 0 ) { 3249u_clearallandblockfree (buf ); 3250 }else { 3251// Mark all undo states as changed. 3252u_unchanged (curbuf ); 3253 } 3254buf_updates_unload (curbuf , true); 3255curbuf -> b_mod_set = true; 3256 } 3257 } 3258xfree (ea .cmd ); 3259 3260if (savebuf != NULL && bufref_valid (& bufref )) { 3261wipe_buffer (savebuf , false); 3262 } 3263 3264// Invalidate diff info if necessary. 3265diff_invalidate (curbuf ); 3266 3267// Restore the topline and cursor position and check it (lines may 3268// have been removed). 3269curwin -> w_topline = MIN (old_topline ,curbuf -> b_ml .ml_line_count ); 3270curwin -> w_cursor = old_cursor ; 3271check_cursor (curwin ); 3272update_topline (curwin ); 3273curbuf -> b_keep_filetype = false; 3274 3275// Update folds unless they are defined manually. 3276FOR_ALL_TAB_WINDOWS (tp ,wp ) { 3277if (wp -> w_buffer == curwin -> w_buffer 3278&& !foldmethodIsManual (wp )) { 3279foldUpdateAll (wp ); 3280 } 3281 } 3282 3283// If the mode didn't change and 'readonly' was set, keep the old 3284// value; the user probably used the ":view" command. But don't 3285// reset it, might have had a read error. 3286if (orig_mode == curbuf -> b_orig_mode ) { 3287curbuf -> b_p_ro |=old_ro ; 3288 } 3289 3290// Modelines must override settings done by autocommands. 3291do_modelines (0 ); 3292 3293// restore curwin/curbuf and a few other things 3294ctx_restore (& aco ); 3295// Careful: autocommands may have made "buf" invalid! 3296} 3297 3298void buf_store_file_info (buf_T * buf ,FileInfo * file_info ) 3299FUNC_ATTR_NONNULL_ALL 3300{ 3301buf -> b_mtime = file_info -> stat .st_mtim .tv_sec ; 3302buf -> b_mtime_ns = file_info -> stat .st_mtim .tv_nsec ; 3303buf -> b_orig_size = os_fileinfo_size (file_info ); 3304buf -> b_orig_mode = (int )file_info -> stat .st_mode ; 3305} 3306 3307/// Adjust the line with missing eol, used for the next write. 3308/// Used for do_filter(), when the input lines for the filter are deleted. 3309void write_lnum_adjust (linenr_T offset ) 3310{ 3311if (curbuf -> b_no_eol_lnum != 0 ) {// only if there is a missing eol 3312curbuf -> b_no_eol_lnum += offset ; 3313 } 3314} 3315 3316/// Path to Nvim's own temp dir. Ends in a slash. 3317static char * vim_tempdir = NULL ; 3318#ifdef HAVE_DIRFD_AND_FLOCK 3319static DIR * vim_tempdir_dp = NULL ;///< File descriptor of temp dir 3320#endif 3321 3322/// Creates a directory for private use by this instance of Nvim, trying each of 3323/// `TEMP_DIR_NAMES` until one succeeds. 3324/// 3325/// Only done once, the same directory is used for all temp files. 3326/// This method avoids security problems because of symlink attacks et al. 3327/// It's also a bit faster, because we only need to check for an existing 3328/// file when creating the directory and not for each temp file. 3329static void vim_mktempdir (void ) 3330{ 3331static const char * temp_dirs []= TEMP_DIR_NAMES ;// Try each of these until one succeeds. 3332char tmp [TEMP_FILE_PATH_MAXLEN ]; 3333char path [TEMP_FILE_PATH_MAXLEN ]; 3334char user [40 ]= {0 }; 3335 3336os_get_username (user ,sizeof (user )); 3337// Usernames may contain slashes! #19240 3338memchrsub (user ,'/' ,'_' ,sizeof (user )); 3339memchrsub (user ,'\\' ,'_' ,sizeof (user )); 3340 3341// Make sure the umask doesn't remove the executable bit. 3342// "repl" has been reported to use "0177". 3343mode_t umask_save = umask (0077 ); 3344for (size_t i = 0 ;i < ARRAY_SIZE (temp_dirs );i ++ ) { 3345// Expand environment variables, leave room for "/tmp/nvim.<user>/XXXXXX/999999999". 3346size_t tmplen = expand_env ((char * )temp_dirs [i ],tmp ,TEMP_FILE_PATH_MAXLEN - 64 ); 3347if (!os_isdir (tmp )) { 3348if (strequal ("$TMPDIR" ,temp_dirs [i ])) { 3349if (!os_env_exists ("TMPDIR" , true)) { 3350DLOG ("$TMPDIR is unset" ); 3351 }else { 3352WLOG ("$TMPDIR tempdir not a directory (or does not exist): \"%s\"" ,tmp ); 3353 } 3354 } 3355continue ; 3356 } 3357 3358// "/tmp/" exists, now try to create "/tmp/nvim.<user>/". 3359if (!after_pathsep (tmp ,tmp + tmplen )) { 3360tmplen += (size_t )vim_snprintf (tmp + tmplen ,sizeof (tmp )- tmplen ,PATHSEPSTR ); 3361assert (tmplen < sizeof (tmp )); 3362 } 3363tmplen += (size_t )vim_snprintf (tmp + tmplen ,sizeof (tmp )- tmplen , 3364"nvim.%s" ,user ); 3365assert (tmplen < sizeof (tmp )); 3366os_mkdir (tmp ,0700 );// Always create, to avoid a race. 3367bool owned = os_file_owned (tmp ); 3368bool isdir = os_isdir (tmp ); 3369#ifdef UNIX 3370int perm = os_getperm (tmp );// XDG_RUNTIME_DIR must be owned by the user, mode 0700. 3371bool valid = isdir && owned && 0700 == (perm & 0777 ); 3372#else 3373bool valid = isdir && owned ;// TODO(justinmk): Windows ACL? 3374#endif 3375if (valid ) { 3376if (!after_pathsep (tmp ,tmp + tmplen )) { 3377tmplen += (size_t )vim_snprintf (tmp + tmplen ,sizeof (tmp )- tmplen ,PATHSEPSTR ); 3378assert (tmplen < sizeof (tmp )); 3379 } 3380 }else { 3381if (!owned ) { 3382ELOG ("tempdir root not owned by current user (%s): %s" ,user ,tmp ); 3383 }else if (!isdir ) { 3384ELOG ("tempdir root not a directory: %s" ,tmp ); 3385 } 3386#ifdef UNIX 3387if (0700 != (perm & 0777 )) { 3388ELOG ("tempdir root has invalid permissions (%o): %s" ,perm ,tmp ); 3389 } 3390#endif 3391// If our "root" tempdir is invalid or fails, proceed without "<user>/". 3392// Else user1 could break user2 by creating "/tmp/nvim.user2/". 3393tmplen -= strlen (user ); 3394tmp [tmplen ]= NUL ; 3395 } 3396 3397// Now try to create "/tmp/nvim.<user>/XXXXXX". 3398// "XXXXXX" is mkdtemp "template", will be replaced with random alphanumeric chars. 3399tmplen += (size_t )vim_snprintf (tmp + tmplen ,sizeof (tmp )- tmplen ,"XXXXXX" ); 3400assert (tmplen < sizeof (tmp )); 3401 (void )tmplen ; 3402int r = os_mkdtemp (tmp ,path ); 3403if (r != 0 ) { 3404WLOG ("tempdir create failed: %s: %s" ,os_strerror (r ),tmp ); 3405continue ; 3406 } 3407 3408if (vim_settempdir (path )) { 3409// Successfully created and set temporary directory so stop trying. 3410break ; 3411 } 3412// Couldn't set `vim_tempdir` to `path` so remove created directory. 3413os_rmdir (path ); 3414 } 3415umask (umask_save ); 3416} 3417 3418/// Core part of "readdir()" function. 3419/// Retrieve the list of files/directories of "path" into "gap". 3420/// 3421/// @return OK for success, FAIL for failure. 3422int readdir_core (garray_T * gap ,const char * path ,void * context ,CheckItem checkitem ) 3423FUNC_ATTR_NONNULL_ARG (1 ,2 ) 3424{ 3425ga_init (gap , (int )sizeof (char * ),20 ); 3426 3427Directory dir ; 3428if (!os_scandir (& dir ,path )) { 3429smsg (0 ,_ (e_notopen ),path ); 3430return FAIL ; 3431 } 3432 3433while (true) { 3434const char * p = os_scandir_next (& dir ); 3435if (p == NULL ) { 3436break ; 3437 } 3438 3439bool ignore = (p [0 ]== '.' && (p [1 ]== NUL || (p [1 ]== '.' && p [2 ]== NUL ))); 3440if (!ignore && checkitem != NULL ) { 3441varnumber_T r = checkitem (context ,p ); 3442if (r < 0 ) { 3443break ; 3444 } 3445if (r == 0 ) { 3446ignore = true; 3447 } 3448 } 3449 3450if (!ignore ) { 3451ga_grow (gap ,1 ); 3452 ((char ** )gap -> ga_data )[gap -> ga_len ++ ]= xstrdup (p ); 3453 } 3454 } 3455 3456os_closedir (& dir ); 3457 3458if (gap -> ga_len > 0 ) { 3459sort_strings (gap -> ga_data ,gap -> ga_len ); 3460 } 3461 3462return OK ; 3463} 3464 3465/// Delete "name" and everything in it, recursively. 3466/// 3467/// @param name The path which should be deleted. 3468/// 3469/// @return 0 for success, -1 if some file was not deleted. 3470int delete_recursive (const char * name ) 3471FUNC_ATTR_NONNULL_ALL 3472{ 3473int result = 0 ; 3474 3475if (os_isrealdir (name )) { 3476char * exp = xstrdup (name ); 3477garray_T ga ; 3478if (readdir_core (& ga ,exp ,NULL ,NULL )== OK ) { 3479int len = snprintf (NameBuff ,MAXPATHL ,"%s/" ,exp ); 3480 3481for (int i = 0 ;i < ga .ga_len ;i ++ ) { 3482snprintf (NameBuff + len ,MAXPATHL - (size_t )len ,"%s" , ((char ** )ga .ga_data )[i ]); 3483if (delete_recursive (NameBuff )!= 0 ) { 3484// Remember the failure but continue deleting any further 3485// entries. 3486result = -1 ; 3487 } 3488 } 3489ga_clear_strings (& ga ); 3490if (os_rmdir (exp )!= 0 ) { 3491result = -1 ; 3492 } 3493 }else { 3494result = -1 ; 3495 } 3496xfree (exp ); 3497 }else { 3498// Delete symlink only. 3499result = os_remove (name )== 0 ?0 :-1 ; 3500 } 3501 3502return result ; 3503} 3504 3505#ifdef HAVE_DIRFD_AND_FLOCK 3506/// Open temporary directory and take file lock to prevent 3507/// to be auto-cleaned. 3508static void vim_opentempdir (void ) 3509{ 3510if (vim_tempdir_dp != NULL ) { 3511return ; 3512 } 3513 3514DIR * dp = opendir (vim_tempdir ); 3515if (dp == NULL ) { 3516return ; 3517 } 3518 3519vim_tempdir_dp = dp ; 3520flock (dirfd (vim_tempdir_dp ),LOCK_SH ); 3521} 3522 3523/// Close temporary directory - it automatically release file lock. 3524static void vim_closetempdir (void ) 3525{ 3526if (vim_tempdir_dp == NULL ) { 3527return ; 3528 } 3529 3530closedir (vim_tempdir_dp ); 3531vim_tempdir_dp = NULL ; 3532} 3533#endif 3534 3535/// Delete the temp directory and all files it contains. 3536void vim_deltempdir (void ) 3537{ 3538if (vim_tempdir == NULL ) { 3539return ; 3540 } 3541 3542#ifdef HAVE_DIRFD_AND_FLOCK 3543vim_closetempdir (); 3544#endif 3545// remove the trailing path separator 3546path_tail (vim_tempdir )[-1 ]= NUL ; 3547delete_recursive (vim_tempdir ); 3548XFREE_CLEAR (vim_tempdir ); 3549} 3550 3551/// Gets path to Nvim's own temp dir (ending with slash). 3552/// 3553/// Creates the directory on the first call. 3554char * vim_gettempdir (void ) 3555{ 3556static int notfound = 0 ; 3557if (vim_tempdir == NULL || !os_isdir (vim_tempdir )) { 3558if (vim_tempdir != NULL ) { 3559notfound ++ ; 3560if (notfound == 1 ) { 3561ELOG ("tempdir disappeared (antivirus or broken cleanup job?): %s" ,vim_tempdir ); 3562 } 3563if (notfound > 1 ) { 3564msg_schedule_semsg ("E5431: tempdir disappeared (%d times)" ,notfound ); 3565 } 3566XFREE_CLEAR (vim_tempdir ); 3567 } 3568vim_mktempdir (); 3569 } 3570return vim_tempdir ; 3571} 3572 3573/// Sets Nvim's own temporary directory name to `tempdir`. This directory must 3574/// already exist. Expands the name to a full path and put it in `vim_tempdir`. 3575/// This avoids that using `:cd` would confuse us. 3576/// 3577/// @param tempdir must be no longer than MAXPATHL. 3578/// 3579/// @return false if we run out of memory. 3580static bool vim_settempdir (char * tempdir ) 3581{ 3582char * buf = verbose_try_malloc (MAXPATHL + 2 ); 3583if (buf == NULL ) { 3584return false; 3585 } 3586 3587vim_FullName (tempdir ,buf ,MAXPATHL , 3588#ifdef MSWIN 3589 true 3590#else 3591 false 3592#endif 3593 ); 3594 3595size_t buflen = strlen (buf ); 3596if (!after_pathsep (buf ,buf + buflen )) { 3597strcpy (buf + buflen ,PATHSEPSTR );// NOLINT(runtime/printf) 3598buflen += STRLEN_LITERAL (PATHSEPSTR ); 3599 } 3600vim_tempdir = xmemdupz (buf ,buflen ); 3601#ifdef HAVE_DIRFD_AND_FLOCK 3602vim_opentempdir (); 3603#endif 3604xfree (buf ); 3605return true; 3606} 3607 3608/// Return a unique name that can be used for a temp file. 3609/// 3610/// @note The temp file is NOT created. 3611/// 3612/// @return pointer to the temp file name or NULL if Nvim can't create 3613/// temporary directory for its own temporary files. 3614char * vim_tempname (void ) 3615{ 3616// Temp filename counter. 3617static uint64_t temp_count ; 3618 3619char * tempdir = vim_gettempdir (); 3620if (!tempdir ) { 3621return NULL ; 3622 } 3623 3624// There is no need to check if the file exists, because we own the directory 3625// and nobody else creates a file in it. 3626char templ [TEMP_FILE_PATH_MAXLEN ]; 3627int itmplen = snprintf (templ ,TEMP_FILE_PATH_MAXLEN ,"%s%" PRIu64 ,tempdir ,temp_count ++ ); 3628return xmemdupz (templ , (size_t )itmplen ); 3629} 3630 3631/// Tries matching a filename with a "pattern" ("prog" is NULL), or use the 3632/// precompiled regprog "prog" ("pattern" is NULL). That avoids calling 3633/// vim_regcomp() often. 3634/// 3635/// Used for autocommands and 'wildignore'. 3636/// 3637/// @param pattern pattern to match with 3638/// @param prog pre-compiled regprog or NULL 3639/// @param fname full path of the file name 3640/// @param sfname short file name or NULL 3641/// @param tail tail of the path 3642/// @param allow_dirs Allow matching with dir 3643/// 3644/// @return true if there is a match, false otherwise 3645bool match_file_pat (char * pattern ,regprog_T ** prog ,char * fname ,char * sfname ,char * tail , 3646int allow_dirs ) 3647{ 3648regmatch_T regmatch ; 3649bool result = false; 3650 3651regmatch .rm_ic = p_fic ;// ignore case if 'fileignorecase' is set 3652regmatch .regprog = prog != NULL ?* prog :vim_regcomp (pattern ,RE_MAGIC ); 3653 3654// Try for a match with the pattern with: 3655// 1. the full file name, when the pattern has a '/'. 3656// 2. the short file name, when the pattern has a '/'. 3657// 3. the tail of the file name, when the pattern has no '/'. 3658if (regmatch .regprog != NULL 3659&& ((allow_dirs 3660&& (vim_regexec (& regmatch ,fname ,0 ) 3661|| (sfname != NULL 3662&& vim_regexec (& regmatch ,sfname ,0 )))) 3663|| (!allow_dirs && vim_regexec (& regmatch ,tail ,0 )))) { 3664result = true; 3665 } 3666 3667if (prog != NULL ) { 3668* prog = regmatch .regprog ; 3669 }else { 3670vim_regfree (regmatch .regprog ); 3671 } 3672return result ; 3673} 3674 3675/// Check if a file matches with a pattern in "list". 3676/// "list" is a comma-separated list of patterns, like 'wildignore'. 3677/// "sfname" is the short file name or NULL, "ffname" the long file name. 3678/// 3679/// @param list list of patterns to match 3680/// @param sfname short file name 3681/// @param ffname full file name 3682/// 3683/// @return true if there was a match 3684bool match_file_list (char * list ,char * sfname ,char * ffname ) 3685FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ARG (1 ,3 ) 3686{ 3687char * tail = path_tail (sfname ); 3688 3689// try all patterns in 'wildignore' 3690char * p = list ; 3691while (* p ) { 3692char buf [MAXPATHL ]; 3693copy_option_part (& p ,buf ,ARRAY_SIZE (buf ),"," ); 3694char allow_dirs ; 3695char * regpat = file_pat_to_reg_pat (buf ,NULL ,& allow_dirs , false); 3696if (regpat == NULL ) { 3697break ; 3698 } 3699bool match = match_file_pat (regpat ,NULL ,ffname ,sfname ,tail , (int )allow_dirs ); 3700xfree (regpat ); 3701if (match ) { 3702return true; 3703 } 3704 } 3705return false; 3706} 3707 3708/// Convert the given pattern "pat" which has shell style wildcards in it, into 3709/// a regular expression, and return the result in allocated memory. If there 3710/// is a directory path separator to be matched, then true is put in 3711/// allow_dirs, otherwise false is put there -- webb. 3712/// Handle backslashes before special characters, like "\*" and "\ ". 3713/// 3714/// @param pat_end first char after pattern or NULL 3715/// @param allow_dirs Result passed back out in here 3716/// @param no_bslash Don't use a backward slash as pathsep 3717/// (only makes a difference when BACKSLASH_IN_FILENAME in defined) 3718/// 3719/// @return NULL on failure. 3720char * file_pat_to_reg_pat (const char * pat ,const char * pat_end ,char * allow_dirs ,int no_bslash ) 3721FUNC_ATTR_NONNULL_ARG (1 ) 3722{ 3723if (allow_dirs != NULL ) { 3724* allow_dirs = false; 3725 } 3726 3727if (pat_end == NULL ) { 3728pat_end = pat + strlen (pat ); 3729 } 3730 3731if (pat_end == pat ) { 3732return xstrdup ("^$" ); 3733 } 3734 3735size_t size = 2 ;// '^' at start, '$' at end. 3736 3737for (const char * p = pat ;p < pat_end ;p ++ ) { 3738switch (* p ) { 3739case '*' : 3740case '.' : 3741case ',' : 3742case '{' : 3743case '}' : 3744case '~' : 3745size += 2 ;// extra backslash 3746break ; 3747#ifdef BACKSLASH_IN_FILENAME 3748case '\\' : 3749case '/' : 3750size += 4 ;// could become "[\/]" 3751break ; 3752#endif 3753default : 3754size ++ ; 3755break ; 3756 } 3757 } 3758char * reg_pat = xmalloc (size + 1 ); 3759 3760size_t i = 0 ; 3761 3762if (pat [0 ]== '*' ) { 3763while (pat [0 ]== '*' && pat < pat_end - 1 ) { 3764pat ++ ; 3765 } 3766 }else { 3767reg_pat [i ++ ]= '^' ; 3768 } 3769const char * endp = pat_end - 1 ; 3770bool add_dollar = true; 3771if (endp >=pat && * endp == '*' ) { 3772while (endp - pat > 0 && * endp == '*' ) { 3773endp -- ; 3774 } 3775add_dollar = false; 3776 } 3777int nested = 0 ; 3778for (const char * p = pat ;* p && nested >=0 && p <=endp ;p ++ ) { 3779switch (* p ) { 3780case '*' : 3781reg_pat [i ++ ]= '.' ; 3782reg_pat [i ++ ]= '*' ; 3783while (p [1 ]== '*' ) {// "**" matches like "*" 3784p ++ ; 3785 } 3786break ; 3787case '.' : 3788case '~' : 3789reg_pat [i ++ ]= '\\' ; 3790reg_pat [i ++ ]= * p ; 3791break ; 3792case '?' : 3793reg_pat [i ++ ]= '.' ; 3794break ; 3795case '\\' : 3796if (p [1 ]== NUL ) { 3797break ; 3798 } 3799#ifdef BACKSLASH_IN_FILENAME 3800if (!no_bslash ) { 3801// translate: 3802// "\x" to "\\x" e.g., "dir\file" 3803// "\*" to "\\.*" e.g., "dir\*.c" 3804// "\?" to "\\." e.g., "dir\??.c" 3805// "\+" to "\+" e.g., "fileX\+.c" 3806if ((vim_isfilec ((uint8_t )p [1 ])|| p [1 ]== '*' || p [1 ]== '?' ) 3807&& p [1 ]!= '+' ) { 3808reg_pat [i ++ ]= '[' ; 3809reg_pat [i ++ ]= '\\' ; 3810reg_pat [i ++ ]= '/' ; 3811reg_pat [i ++ ]= ']' ; 3812if (allow_dirs != NULL ) { 3813* allow_dirs = true; 3814 } 3815break ; 3816 } 3817 } 3818#endif 3819// Undo escaping from ExpandEscape(): 3820// foo\?bar -> foo?bar 3821// foo\%bar -> foo%bar 3822// foo\,bar -> foo,bar 3823// foo\ bar -> foo bar 3824// Don't unescape \, * and others that are also special in a 3825// regexp. 3826// An escaped { must be unescaped since we use magic not 3827// verymagic. Use "\\\{n,m\}"" to get "\{n,m}". 3828if (*++ p == '?' && (!BACKSLASH_IN_FILENAME_BOOL || no_bslash )) { 3829reg_pat [i ++ ]= '?' ; 3830 }else if (* p == ',' || * p == '%' || * p == '#' 3831|| ascii_isspace (* p )|| * p == '{' || * p == '}' ) { 3832reg_pat [i ++ ]= * p ; 3833 }else if (* p == '\\' && p [1 ]== '\\' && p [2 ]== '{' ) { 3834reg_pat [i ++ ]= '\\' ; 3835reg_pat [i ++ ]= '{' ; 3836p += 2 ; 3837 }else { 3838if (allow_dirs != NULL && vim_ispathsep (* p ) 3839&& (!BACKSLASH_IN_FILENAME_BOOL || (!no_bslash || * p != '\\' ))) { 3840* allow_dirs = true; 3841 } 3842reg_pat [i ++ ]= '\\' ; 3843reg_pat [i ++ ]= * p ; 3844 } 3845break ; 3846#ifdef BACKSLASH_IN_FILENAME 3847case '/' : 3848reg_pat [i ++ ]= '[' ; 3849reg_pat [i ++ ]= '\\' ; 3850reg_pat [i ++ ]= '/' ; 3851reg_pat [i ++ ]= ']' ; 3852if (allow_dirs != NULL ) { 3853* allow_dirs = true; 3854 } 3855break ; 3856#endif 3857case '{' : 3858reg_pat [i ++ ]= '\\' ; 3859reg_pat [i ++ ]= '(' ; 3860nested ++ ; 3861break ; 3862case '}' : 3863reg_pat [i ++ ]= '\\' ; 3864reg_pat [i ++ ]= ')' ; 3865nested -- ; 3866break ; 3867case ',' : 3868if (nested ) { 3869reg_pat [i ++ ]= '\\' ; 3870reg_pat [i ++ ]= '|' ; 3871 }else { 3872reg_pat [i ++ ]= ',' ; 3873 } 3874break ; 3875default : 3876if (allow_dirs != NULL && vim_ispathsep (* p )) { 3877* allow_dirs = true; 3878 } 3879reg_pat [i ++ ]= * p ; 3880break ; 3881 } 3882 } 3883if (add_dollar ) { 3884reg_pat [i ++ ]= '$' ; 3885 } 3886reg_pat [i ]= NUL ; 3887if (nested != 0 ) { 3888if (nested < 0 ) { 3889emsg (_ ("E219: Missing {." )); 3890 }else { 3891emsg (_ ("E220: Missing }." )); 3892 } 3893XFREE_CLEAR (reg_pat ); 3894 } 3895return reg_pat ; 3896} 3897 3898#ifdef EINTR 3899 3900// Type of buffer size argument of read() and write() is platform-dependent. 3901# ifdef MSWIN 3902# define BUFSIZE (x ) (unsigned)(x) 3903# else 3904# define BUFSIZE (x ) (x) 3905# endif 3906 3907/// Version of read() that retries when interrupted by EINTR (possibly 3908/// by a SIGWINCH). 3909ssize_t read_eintr (int fd ,void * buf ,size_t bufsize ) 3910{ 3911ssize_t ret ; 3912 3913while (true) { 3914ret = read (fd ,buf ,BUFSIZE (bufsize )); 3915if (ret >=0 || errno != EINTR ) { 3916break ; 3917 } 3918 } 3919return ret ; 3920} 3921 3922/// Version of write() that retries when interrupted by EINTR (possibly 3923/// by a SIGWINCH). 3924ssize_t write_eintr (int fd ,void * buf ,size_t bufsize ) 3925{ 3926ssize_t ret = 0 ; 3927 3928// Repeat the write() so long it didn't fail, other than being interrupted 3929// by a signal. 3930while ((size_t )ret < bufsize ) { 3931ssize_t wlen = write (fd , (char * )buf + ret ,BUFSIZE (bufsize - (size_t )ret )); 3932if (wlen < 0 ) { 3933if (errno != EINTR ) { 3934break ; 3935 } 3936 }else { 3937ret += wlen ; 3938 } 3939 } 3940return ret ; 3941} 3942 3943# undef BUFSIZE 3944 3945#endif