1// This is an open source non-commercial project. Dear PVS-Studio, please check
2// it. PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com
3
4//
5// buffer.c: functions for dealing with the buffer structure
6//
7
8//
9// The buffer list is a double linked list of all buffers.
10// Each buffer can be in one of these states:
11// never loaded: BF_NEVERLOADED is set, only the file name is valid
12// not loaded: b_ml.ml_mfp == NULL, no memfile allocated
13// hidden: b_nwindows == 0, loaded but not displayed in a window
14// normal: loaded and displayed in a window
15//
16// Instead of storing file names all over the place, each file name is
17// stored in the buffer list. It can be referenced by a number.
18//
19// The current implementation remembers all file names ever used.
20//
21
22#include <stdbool.h>
23#include <string.h>
24#include <inttypes.h>
25#include <assert.h>
26
27#include "nvim/api/private/handle.h"
28#include "nvim/api/private/helpers.h"
29#include "nvim/api/vim.h"
30#include "nvim/ascii.h"
31#include "nvim/assert.h"
32#include "nvim/channel.h"
33#include "nvim/vim.h"
34#include "nvim/buffer.h"
35#include "nvim/change.h"
36#include "nvim/charset.h"
37#include "nvim/cursor.h"
38#include "nvim/diff.h"
39#include "nvim/digraph.h"
40#include "nvim/eval.h"
41#include "nvim/ex_cmds2.h"
42#include "nvim/ex_cmds.h"
43#include "nvim/ex_docmd.h"
44#include "nvim/ex_eval.h"
45#include "nvim/ex_getln.h"
46#include "nvim/fileio.h"
47#include "nvim/file_search.h"
48#include "nvim/fold.h"
49#include "nvim/getchar.h"
50#include "nvim/hashtab.h"
51#include "nvim/highlight.h"
52#include "nvim/indent.h"
53#include "nvim/indent_c.h"
54#include "nvim/main.h"
55#include "nvim/mark.h"
56#include "nvim/mbyte.h"
57#include "nvim/memline.h"
58#include "nvim/memory.h"
59#include "nvim/message.h"
60#include "nvim/misc1.h"
61#include "nvim/garray.h"
62#include "nvim/move.h"
63#include "nvim/option.h"
64#include "nvim/os_unix.h"
65#include "nvim/path.h"
66#include "nvim/quickfix.h"
67#include "nvim/regexp.h"
68#include "nvim/screen.h"
69#include "nvim/sign.h"
70#include "nvim/spell.h"
71#include "nvim/strings.h"
72#include "nvim/syntax.h"
73#include "nvim/ui.h"
74#include "nvim/undo.h"
75#include "nvim/version.h"
76#include "nvim/window.h"
77#include "nvim/shada.h"
78#include "nvim/os/os.h"
79#include "nvim/os/time.h"
80#include "nvim/os/input.h"
81#include "nvim/buffer_updates.h"
82
83typedef enum {
84 kBLSUnchanged = 0,
85 kBLSChanged = 1,
86 kBLSDeleted = 2,
87} BufhlLineStatus;
88
89#ifdef INCLUDE_GENERATED_DECLARATIONS
90# include "buffer.c.generated.h"
91#endif
92
93static char *msg_loclist = N_("[Location List]");
94static char *msg_qflist = N_("[Quickfix List]");
95static char *e_auabort = N_("E855: Autocommands caused command to abort");
96
97// Number of times free_buffer() was called.
98static int buf_free_count = 0;
99
100typedef enum {
101 kBffClearWinInfo = 1,
102 kBffInitChangedtick = 2,
103} BufFreeFlags;
104
105// Read data from buffer for retrying.
106static int
107read_buffer(
108 int read_stdin, // read file from stdin, otherwise fifo
109 exarg_T *eap, // for forced 'ff' and 'fenc' or NULL
110 int flags) // extra flags for readfile()
111{
112 int retval = OK;
113 linenr_T line_count;
114
115 //
116 // Read from the buffer which the text is already filled in and append at
117 // the end. This makes it possible to retry when 'fileformat' or
118 // 'fileencoding' was guessed wrong.
119 //
120 line_count = curbuf->b_ml.ml_line_count;
121 retval = readfile(
122 read_stdin ? NULL : curbuf->b_ffname,
123 read_stdin ? NULL : curbuf->b_fname,
124 (linenr_T)line_count, (linenr_T)0, (linenr_T)MAXLNUM, eap,
125 flags | READ_BUFFER);
126 if (retval == OK) {
127 // Delete the binary lines.
128 while (--line_count >= 0) {
129 ml_delete((linenr_T)1, false);
130 }
131 } else {
132 // Delete the converted lines.
133 while (curbuf->b_ml.ml_line_count > line_count) {
134 ml_delete(line_count, false);
135 }
136 }
137 // Put the cursor on the first line.
138 curwin->w_cursor.lnum = 1;
139 curwin->w_cursor.col = 0;
140
141 if (read_stdin) {
142 // Set or reset 'modified' before executing autocommands, so that
143 // it can be changed there.
144 if (!readonlymode && !BUFEMPTY()) {
145 changed();
146 } else if (retval != FAIL) {
147 unchanged(curbuf, false, true);
148 }
149
150 apply_autocmds_retval(EVENT_STDINREADPOST, NULL, NULL, false,
151 curbuf, &retval);
152 }
153 return retval;
154}
155
156// Open current buffer, that is: open the memfile and read the file into
157// memory.
158// Return FAIL for failure, OK otherwise.
159int open_buffer(
160 int read_stdin, // read file from stdin
161 exarg_T *eap, // for forced 'ff' and 'fenc' or NULL
162 int flags // extra flags for readfile()
163)
164{
165 int retval = OK;
166 bufref_T old_curbuf;
167 long old_tw = curbuf->b_p_tw;
168 int read_fifo = false;
169
170 /*
171 * The 'readonly' flag is only set when BF_NEVERLOADED is being reset.
172 * When re-entering the same buffer, it should not change, because the
173 * user may have reset the flag by hand.
174 */
175 if (readonlymode && curbuf->b_ffname != NULL
176 && (curbuf->b_flags & BF_NEVERLOADED))
177 curbuf->b_p_ro = true;
178
179 if (ml_open(curbuf) == FAIL) {
180 /*
181 * There MUST be a memfile, otherwise we can't do anything
182 * If we can't create one for the current buffer, take another buffer
183 */
184 close_buffer(NULL, curbuf, 0, false);
185
186 curbuf = NULL;
187 FOR_ALL_BUFFERS(buf) {
188 if (buf->b_ml.ml_mfp != NULL) {
189 curbuf = buf;
190 break;
191 }
192 }
193
194 /*
195 * if there is no memfile at all, exit
196 * This is OK, since there are no changes to lose.
197 */
198 if (curbuf == NULL) {
199 EMSG(_("E82: Cannot allocate any buffer, exiting..."));
200 getout(2);
201 }
202 EMSG(_("E83: Cannot allocate buffer, using other one..."));
203 enter_buffer(curbuf);
204 if (old_tw != curbuf->b_p_tw) {
205 check_colorcolumn(curwin);
206 }
207 return FAIL;
208 }
209
210 // The autocommands in readfile() may change the buffer, but only AFTER
211 // reading the file.
212 set_bufref(&old_curbuf, curbuf);
213 modified_was_set = false;
214
215 // mark cursor position as being invalid
216 curwin->w_valid = 0;
217
218 if (curbuf->b_ffname != NULL) {
219 int old_msg_silent = msg_silent;
220#ifdef UNIX
221 int save_bin = curbuf->b_p_bin;
222 int perm;
223
224 perm = os_getperm((const char *)curbuf->b_ffname);
225 if (perm >= 0 && (0
226# ifdef S_ISFIFO
227 || S_ISFIFO(perm)
228# endif
229# ifdef S_ISSOCK
230 || S_ISSOCK(perm)
231# endif
232# ifdef OPEN_CHR_FILES
233 || (S_ISCHR(perm)
234 && is_dev_fd_file(curbuf->b_ffname))
235# endif
236 )
237 ) {
238 read_fifo = true;
239 }
240 if (read_fifo) {
241 curbuf->b_p_bin = true;
242 }
243#endif
244 if (shortmess(SHM_FILEINFO)) {
245 msg_silent = 1;
246 }
247
248 retval = readfile(curbuf->b_ffname, curbuf->b_fname,
249 (linenr_T)0, (linenr_T)0, (linenr_T)MAXLNUM, eap,
250 flags | READ_NEW | (read_fifo ? READ_FIFO : 0));
251#ifdef UNIX
252 if (read_fifo) {
253 curbuf->b_p_bin = save_bin;
254 if (retval == OK) {
255 retval = read_buffer(false, eap, flags);
256 }
257 }
258#endif
259 msg_silent = old_msg_silent;
260
261 // Help buffer is filtered.
262 if (bt_help(curbuf)) {
263 fix_help_buffer();
264 }
265 } else if (read_stdin) {
266 int save_bin = curbuf->b_p_bin;
267
268 /*
269 * First read the text in binary mode into the buffer.
270 * Then read from that same buffer and append at the end. This makes
271 * it possible to retry when 'fileformat' or 'fileencoding' was
272 * guessed wrong.
273 */
274 curbuf->b_p_bin = true;
275 retval = readfile(NULL, NULL, (linenr_T)0,
276 (linenr_T)0, (linenr_T)MAXLNUM, NULL,
277 flags | (READ_NEW + READ_STDIN));
278 curbuf->b_p_bin = save_bin;
279 if (retval == OK) {
280 retval = read_buffer(true, eap, flags);
281 }
282 }
283
284 // if first time loading this buffer, init b_chartab[]
285 if (curbuf->b_flags & BF_NEVERLOADED) {
286 (void)buf_init_chartab(curbuf, false);
287 parse_cino(curbuf);
288 }
289
290 // Set/reset the Changed flag first, autocmds may change the buffer.
291 // Apply the automatic commands, before processing the modelines.
292 // So the modelines have priority over auto commands.
293
294 // When reading stdin, the buffer contents always needs writing, so set
295 // the changed flag. Unless in readonly mode: "ls | nvim -R -".
296 // When interrupted and 'cpoptions' contains 'i' set changed flag.
297 if ((got_int && vim_strchr(p_cpo, CPO_INTMOD) != NULL)
298 || modified_was_set // ":set modified" used in autocmd
299 || (aborting() && vim_strchr(p_cpo, CPO_INTMOD) != NULL)) {
300 changed();
301 } else if (retval != FAIL && !read_stdin && !read_fifo) {
302 unchanged(curbuf, false, true);
303 }
304 save_file_ff(curbuf); // keep this fileformat
305
306 // Set last_changedtick to avoid triggering a TextChanged autocommand right
307 // after it was added.
308 curbuf->b_last_changedtick = buf_get_changedtick(curbuf);
309 curbuf->b_last_changedtick_pum = buf_get_changedtick(curbuf);
310
311 // require "!" to overwrite the file, because it wasn't read completely
312 if (aborting()) {
313 curbuf->b_flags |= BF_READERR;
314 }
315
316 /* Need to update automatic folding. Do this before the autocommands,
317 * they may use the fold info. */
318 foldUpdateAll(curwin);
319
320 // need to set w_topline, unless some autocommand already did that.
321 if (!(curwin->w_valid & VALID_TOPLINE)) {
322 curwin->w_topline = 1;
323 curwin->w_topfill = 0;
324 }
325 apply_autocmds_retval(EVENT_BUFENTER, NULL, NULL, false, curbuf, &retval);
326
327 if (retval == FAIL) {
328 return FAIL;
329 }
330
331 /*
332 * The autocommands may have changed the current buffer. Apply the
333 * modelines to the correct buffer, if it still exists and is loaded.
334 */
335 if (bufref_valid(&old_curbuf) && old_curbuf.br_buf->b_ml.ml_mfp != NULL) {
336 aco_save_T aco;
337
338 // Go to the buffer that was opened.
339 aucmd_prepbuf(&aco, old_curbuf.br_buf);
340 do_modelines(0);
341 curbuf->b_flags &= ~(BF_CHECK_RO | BF_NEVERLOADED);
342
343 apply_autocmds_retval(EVENT_BUFWINENTER, NULL, NULL, false, curbuf,
344 &retval);
345
346 // restore curwin/curbuf and a few other things
347 aucmd_restbuf(&aco);
348 }
349
350 return retval;
351}
352
353/// Store "buf" in "bufref" and set the free count.
354///
355/// @param bufref Reference to be used for the buffer.
356/// @param buf The buffer to reference.
357void set_bufref(bufref_T *bufref, buf_T *buf)
358{
359 bufref->br_buf = buf;
360 bufref->br_fnum = buf == NULL ? 0 : buf->b_fnum;
361 bufref->br_buf_free_count = buf_free_count;
362}
363
364/// Return true if "bufref->br_buf" points to the same buffer as when
365/// set_bufref() was called and it is a valid buffer.
366/// Only goes through the buffer list if buf_free_count changed.
367/// Also checks if b_fnum is still the same, a :bwipe followed by :new might get
368/// the same allocated memory, but it's a different buffer.
369///
370/// @param bufref Buffer reference to check for.
371bool bufref_valid(bufref_T *bufref)
372{
373 return bufref->br_buf_free_count == buf_free_count
374 ? true
375 : buf_valid(bufref->br_buf) && bufref->br_fnum == bufref->br_buf->b_fnum;
376}
377
378/// Check that "buf" points to a valid buffer in the buffer list.
379///
380/// Can be slow if there are many buffers, prefer using bufref_valid().
381///
382/// @param buf The buffer to check for.
383bool buf_valid(buf_T *buf)
384 FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
385{
386 if (buf == NULL) {
387 return false;
388 }
389 // Assume that we more often have a recent buffer,
390 // start with the last one.
391 for (buf_T *bp = lastbuf; bp != NULL; bp = bp->b_prev) {
392 if (bp == buf) {
393 return true;
394 }
395 }
396 return false;
397}
398
399/// Close the link to a buffer.
400///
401/// @param win If not NULL, set b_last_cursor.
402/// @param buf
403/// @param action Used when there is no longer a window for the buffer.
404/// Possible values:
405/// 0 buffer becomes hidden
406/// DOBUF_UNLOAD buffer is unloaded
407/// DOBUF_DELETE buffer is unloaded and removed from buffer list
408/// DOBUF_WIPE buffer is unloaded and really deleted
409/// When doing all but the first one on the current buffer, the
410/// caller should get a new buffer very soon!
411/// The 'bufhidden' option can force freeing and deleting.
412/// @param abort_if_last
413/// If TRUE, do not close the buffer if autocommands cause
414/// there to be only one window with this buffer. e.g. when
415/// ":quit" is supposed to close the window but autocommands
416/// close all other windows.
417void close_buffer(win_T *win, buf_T *buf, int action, int abort_if_last)
418{
419 bool unload_buf = (action != 0);
420 bool del_buf = (action == DOBUF_DEL || action == DOBUF_WIPE);
421 bool wipe_buf = (action == DOBUF_WIPE);
422
423 bool is_curwin = (curwin != NULL && curwin->w_buffer == buf);
424 win_T *the_curwin = curwin;
425 tabpage_T *the_curtab = curtab;
426
427 // Force unloading or deleting when 'bufhidden' says so, but not for terminal
428 // buffers.
429 // The caller must take care of NOT deleting/freeing when 'bufhidden' is
430 // "hide" (otherwise we could never free or delete a buffer).
431 if (!buf->terminal) {
432 if (buf->b_p_bh[0] == 'd') { // 'bufhidden' == "delete"
433 del_buf = true;
434 unload_buf = true;
435 } else if (buf->b_p_bh[0] == 'w') { // 'bufhidden' == "wipe"
436 del_buf = true;
437 unload_buf = true;
438 wipe_buf = true;
439 } else if (buf->b_p_bh[0] == 'u') // 'bufhidden' == "unload"
440 unload_buf = true;
441 }
442
443 if (buf->terminal && (unload_buf || del_buf || wipe_buf)) {
444 // terminal buffers can only be wiped
445 unload_buf = true;
446 del_buf = true;
447 wipe_buf = true;
448 }
449
450 // Disallow deleting the buffer when it is locked (already being closed or
451 // halfway a command that relies on it). Unloading is allowed.
452 if (buf->b_locked > 0 && (del_buf || wipe_buf)) {
453 EMSG(_("E937: Attempt to delete a buffer that is in use"));
454 return;
455 }
456
457 if (win != NULL // Avoid bogus clang warning.
458 && win_valid_any_tab(win)) {
459 // Set b_last_cursor when closing the last window for the buffer.
460 // Remember the last cursor position and window options of the buffer.
461 // This used to be only for the current window, but then options like
462 // 'foldmethod' may be lost with a ":only" command.
463 if (buf->b_nwindows == 1) {
464 set_last_cursor(win);
465 }
466 buflist_setfpos(buf, win,
467 win->w_cursor.lnum == 1 ? 0 : win->w_cursor.lnum,
468 win->w_cursor.col, true);
469 }
470
471 bufref_T bufref;
472 set_bufref(&bufref, buf);
473
474 // When the buffer is no longer in a window, trigger BufWinLeave
475 if (buf->b_nwindows == 1) {
476 buf->b_locked++;
477 if (apply_autocmds(EVENT_BUFWINLEAVE, buf->b_fname, buf->b_fname, false,
478 buf) && !bufref_valid(&bufref)) {
479 // Autocommands deleted the buffer.
480 EMSG(_(e_auabort));
481 return;
482 }
483 buf->b_locked--;
484 if (abort_if_last && last_nonfloat(win)) {
485 // Autocommands made this the only window.
486 EMSG(_(e_auabort));
487 return;
488 }
489
490 // When the buffer becomes hidden, but is not unloaded, trigger
491 // BufHidden
492 if (!unload_buf) {
493 buf->b_locked++;
494 if (apply_autocmds(EVENT_BUFHIDDEN, buf->b_fname, buf->b_fname, false,
495 buf) && !bufref_valid(&bufref)) {
496 // Autocommands deleted the buffer.
497 EMSG(_(e_auabort));
498 return;
499 }
500 buf->b_locked--;
501 if (abort_if_last && last_nonfloat(win)) {
502 // Autocommands made this the only window.
503 EMSG(_(e_auabort));
504 return;
505 }
506 }
507 if (aborting()) { // autocmds may abort script processing
508 return;
509 }
510 }
511
512 // If the buffer was in curwin and the window has changed, go back to that
513 // window, if it still exists. This avoids that ":edit x" triggering a
514 // "tabnext" BufUnload autocmd leaves a window behind without a buffer.
515 if (is_curwin && curwin != the_curwin && win_valid_any_tab(the_curwin)) {
516 block_autocmds();
517 goto_tabpage_win(the_curtab, the_curwin);
518 unblock_autocmds();
519 }
520
521 int nwindows = buf->b_nwindows;
522
523 // decrease the link count from windows (unless not in any window)
524 if (buf->b_nwindows > 0) {
525 buf->b_nwindows--;
526 }
527
528 if (diffopt_hiddenoff() && !unload_buf && buf->b_nwindows == 0) {
529 diff_buf_delete(buf); // Clear 'diff' for hidden buffer.
530 }
531
532 /* Return when a window is displaying the buffer or when it's not
533 * unloaded. */
534 if (buf->b_nwindows > 0 || !unload_buf) {
535 return;
536 }
537
538 if (buf->terminal) {
539 terminal_close(buf->terminal, NULL);
540 }
541
542 // Always remove the buffer when there is no file name.
543 if (buf->b_ffname == NULL) {
544 del_buf = true;
545 }
546
547 /*
548 * Free all things allocated for this buffer.
549 * Also calls the "BufDelete" autocommands when del_buf is TRUE.
550 */
551 /* Remember if we are closing the current buffer. Restore the number of
552 * windows, so that autocommands in buf_freeall() don't get confused. */
553 bool is_curbuf = (buf == curbuf);
554
555 // When closing the current buffer stop Visual mode before freeing
556 // anything.
557 if (is_curbuf && VIsual_active
558#if defined(EXITFREE)
559 && !entered_free_all_mem
560#endif
561 ) {
562 end_visual_mode();
563 }
564
565 buf->b_nwindows = nwindows;
566
567 buf_freeall(buf, (del_buf ? BFA_DEL : 0) + (wipe_buf ? BFA_WIPE : 0));
568
569 if (!bufref_valid(&bufref)) {
570 // Autocommands may have deleted the buffer.
571 return;
572 }
573 if (aborting()) {
574 // Autocmds may abort script processing.
575 return;
576 }
577
578 /*
579 * It's possible that autocommands change curbuf to the one being deleted.
580 * This might cause the previous curbuf to be deleted unexpectedly. But
581 * in some cases it's OK to delete the curbuf, because a new one is
582 * obtained anyway. Therefore only return if curbuf changed to the
583 * deleted buffer.
584 */
585 if (buf == curbuf && !is_curbuf) {
586 return;
587 }
588
589 if (win != NULL // Avoid bogus clang warning.
590 && win_valid_any_tab(win)
591 && win->w_buffer == buf) {
592 win->w_buffer = NULL; // make sure we don't use the buffer now
593 }
594
595 // Autocommands may have opened or closed windows for this buffer.
596 // Decrement the count for the close we do here.
597 if (buf->b_nwindows > 0) {
598 buf->b_nwindows--;
599 }
600
601 // Change directories when the 'acd' option is set.
602 do_autochdir();
603
604 // Disable buffer-updates for the current buffer.
605 // No need to check `unload_buf`: in that case the function returned above.
606 buf_updates_unregister_all(buf);
607
608 /*
609 * Remove the buffer from the list.
610 */
611 if (wipe_buf) {
612 xfree(buf->b_ffname);
613 xfree(buf->b_sfname);
614 if (buf->b_prev == NULL) {
615 firstbuf = buf->b_next;
616 } else {
617 buf->b_prev->b_next = buf->b_next;
618 }
619 if (buf->b_next == NULL) {
620 lastbuf = buf->b_prev;
621 } else {
622 buf->b_next->b_prev = buf->b_prev;
623 }
624 free_buffer(buf);
625 } else {
626 if (del_buf) {
627 // Free all internal variables and reset option values, to make
628 // ":bdel" compatible with Vim 5.7.
629 free_buffer_stuff(buf, kBffClearWinInfo | kBffInitChangedtick);
630
631 // Make it look like a new buffer.
632 buf->b_flags = BF_CHECK_RO | BF_NEVERLOADED;
633
634 // Init the options when loaded again.
635 buf->b_p_initialized = false;
636 }
637 buf_clear_file(buf);
638 if (del_buf) {
639 buf->b_p_bl = false;
640 }
641 }
642}
643
644/// Make buffer not contain a file.
645void buf_clear_file(buf_T *buf)
646{
647 buf->b_ml.ml_line_count = 1;
648 unchanged(buf, true, true);
649 buf->b_p_eol = true;
650 buf->b_start_eol = true;
651 buf->b_p_bomb = false;
652 buf->b_start_bomb = false;
653 buf->b_ml.ml_mfp = NULL;
654 buf->b_ml.ml_flags = ML_EMPTY; // empty buffer
655}
656
657/// Clears the current buffer contents.
658void buf_clear(void)
659{
660 linenr_T line_count = curbuf->b_ml.ml_line_count;
661 while (!(curbuf->b_ml.ml_flags & ML_EMPTY)) {
662 ml_delete((linenr_T)1, false);
663 }
664 deleted_lines_mark(1, line_count); // prepare for display
665 ml_close(curbuf, true); // free memline_T
666 buf_clear_file(curbuf);
667}
668
669/// buf_freeall() - free all things allocated for a buffer that are related to
670/// the file. Careful: get here with "curwin" NULL when exiting.
671///
672/// @param flags BFA_DEL buffer is going to be deleted
673/// BFA_WIPE buffer is going to be wiped out
674/// BFA_KEEP_UNDO do not free undo information
675void buf_freeall(buf_T *buf, int flags)
676{
677 bool is_curbuf = (buf == curbuf);
678 int is_curwin = (curwin != NULL && curwin->w_buffer == buf);
679 win_T *the_curwin = curwin;
680 tabpage_T *the_curtab = curtab;
681
682 // Make sure the buffer isn't closed by autocommands.
683 buf->b_locked++;
684
685 bufref_T bufref;
686 set_bufref(&bufref, buf);
687
688 if ((buf->b_ml.ml_mfp != NULL)
689 && apply_autocmds(EVENT_BUFUNLOAD, buf->b_fname, buf->b_fname, false, buf)
690 && !bufref_valid(&bufref)) {
691 // Autocommands deleted the buffer.
692 return;
693 }
694 if ((flags & BFA_DEL)
695 && buf->b_p_bl
696 && apply_autocmds(EVENT_BUFDELETE, buf->b_fname, buf->b_fname, false, buf)
697 && !bufref_valid(&bufref)) {
698 // Autocommands may delete the buffer.
699 return;
700 }
701 if ((flags & BFA_WIPE)
702 && apply_autocmds(EVENT_BUFWIPEOUT, buf->b_fname, buf->b_fname, false,
703 buf)
704 && !bufref_valid(&bufref)) {
705 // Autocommands may delete the buffer.
706 return;
707 }
708 buf->b_locked--;
709
710 // If the buffer was in curwin and the window has changed, go back to that
711 // window, if it still exists. This avoids that ":edit x" triggering a
712 // "tabnext" BufUnload autocmd leaves a window behind without a buffer.
713 if (is_curwin && curwin != the_curwin && win_valid_any_tab(the_curwin)) {
714 block_autocmds();
715 goto_tabpage_win(the_curtab, the_curwin);
716 unblock_autocmds();
717 }
718 if (aborting()) { // autocmds may abort script processing
719 return;
720 }
721
722 /*
723 * It's possible that autocommands change curbuf to the one being deleted.
724 * This might cause curbuf to be deleted unexpectedly. But in some cases
725 * it's OK to delete the curbuf, because a new one is obtained anyway.
726 * Therefore only return if curbuf changed to the deleted buffer.
727 */
728 if (buf == curbuf && !is_curbuf) {
729 return;
730 }
731 diff_buf_delete(buf); // Can't use 'diff' for unloaded buffer.
732 // Remove any ownsyntax, unless exiting.
733 if (curwin != NULL && curwin->w_buffer == buf) {
734 reset_synblock(curwin);
735 }
736
737 // No folds in an empty buffer.
738 FOR_ALL_TAB_WINDOWS(tp, win) {
739 if (win->w_buffer == buf) {
740 clearFolding(win);
741 }
742 }
743
744 ml_close(buf, true); // close and delete the memline/memfile
745 buf->b_ml.ml_line_count = 0; // no lines in buffer
746 if ((flags & BFA_KEEP_UNDO) == 0) {
747 u_blockfree(buf); // free the memory allocated for undo
748 u_clearall(buf); // reset all undo information
749 }
750 syntax_clear(&buf->b_s); // reset syntax info
751 buf->b_flags &= ~BF_READERR; // a read error is no longer relevant
752}
753
754/*
755 * Free a buffer structure and the things it contains related to the buffer
756 * itself (not the file, that must have been done already).
757 */
758static void free_buffer(buf_T *buf)
759{
760 handle_unregister_buffer(buf);
761 buf_free_count++;
762 // b:changedtick uses an item in buf_T.
763 free_buffer_stuff(buf, kBffClearWinInfo);
764 if (buf->b_vars->dv_refcount > DO_NOT_FREE_CNT) {
765 tv_dict_add(buf->b_vars,
766 tv_dict_item_copy((dictitem_T *)(&buf->changedtick_di)));
767 }
768 unref_var_dict(buf->b_vars);
769 aubuflocal_remove(buf);
770 tv_dict_unref(buf->additional_data);
771 clear_fmark(&buf->b_last_cursor);
772 clear_fmark(&buf->b_last_insert);
773 clear_fmark(&buf->b_last_change);
774 for (size_t i = 0; i < NMARKS; i++) {
775 free_fmark(buf->b_namedm[i]);
776 }
777 for (int i = 0; i < buf->b_changelistlen; i++) {
778 free_fmark(buf->b_changelist[i]);
779 }
780 if (autocmd_busy) {
781 // Do not free the buffer structure while autocommands are executing,
782 // it's still needed. Free it when autocmd_busy is reset.
783 memset(&buf->b_namedm[0], 0, sizeof(buf->b_namedm));
784 memset(&buf->b_changelist[0], 0, sizeof(buf->b_changelist));
785 buf->b_next = au_pending_free_buf;
786 au_pending_free_buf = buf;
787 } else {
788 xfree(buf);
789 }
790}
791
792/// Free stuff in the buffer for ":bdel" and when wiping out the buffer.
793///
794/// @param buf Buffer pointer
795/// @param free_flags BufFreeFlags
796static void free_buffer_stuff(buf_T *buf, int free_flags)
797{
798 if (free_flags & kBffClearWinInfo) {
799 clear_wininfo(buf); // including window-local options
800 free_buf_options(buf, true);
801 ga_clear(&buf->b_s.b_langp);
802 }
803 {
804 // Avoid losing b:changedtick when deleting buffer: clearing variables
805 // implies using clear_tv() on b:changedtick and that sets changedtick to
806 // zero.
807 hashitem_T *const changedtick_hi = hash_find(
808 &buf->b_vars->dv_hashtab, (const char_u *)"changedtick");
809 assert(changedtick_hi != NULL);
810 hash_remove(&buf->b_vars->dv_hashtab, changedtick_hi);
811 }
812 vars_clear(&buf->b_vars->dv_hashtab); // free all internal variables
813 hash_init(&buf->b_vars->dv_hashtab);
814 if (free_flags & kBffInitChangedtick) {
815 buf_init_changedtick(buf);
816 }
817 uc_clear(&buf->b_ucmds); // clear local user commands
818 buf_delete_signs(buf, (char_u *)"*"); // delete any signs
819 bufhl_clear_all(buf); // delete any highligts
820 map_clear_int(buf, MAP_ALL_MODES, true, false); // clear local mappings
821 map_clear_int(buf, MAP_ALL_MODES, true, true); // clear local abbrevs
822 XFREE_CLEAR(buf->b_start_fenc);
823
824 buf_updates_unregister_all(buf);
825}
826
827/*
828 * Free the b_wininfo list for buffer "buf".
829 */
830static void clear_wininfo(buf_T *buf)
831{
832 wininfo_T *wip;
833
834 while (buf->b_wininfo != NULL) {
835 wip = buf->b_wininfo;
836 buf->b_wininfo = wip->wi_next;
837 if (wip->wi_optset) {
838 clear_winopt(&wip->wi_opt);
839 deleteFoldRecurse(&wip->wi_folds);
840 }
841 xfree(wip);
842 }
843}
844
845/*
846 * Go to another buffer. Handles the result of the ATTENTION dialog.
847 */
848void goto_buffer(exarg_T *eap, int start, int dir, int count)
849{
850 bufref_T old_curbuf;
851 set_bufref(&old_curbuf, curbuf);
852 swap_exists_action = SEA_DIALOG;
853
854 (void)do_buffer(*eap->cmd == 's' ? DOBUF_SPLIT : DOBUF_GOTO,
855 start, dir, count, eap->forceit);
856
857 if (swap_exists_action == SEA_QUIT && *eap->cmd == 's') {
858 cleanup_T cs;
859
860 // Reset the error/interrupt/exception state here so that
861 // aborting() returns false when closing a window.
862 enter_cleanup(&cs);
863
864 // Quitting means closing the split window, nothing else.
865 win_close(curwin, true);
866 swap_exists_action = SEA_NONE;
867 swap_exists_did_quit = true;
868
869 /* Restore the error/interrupt/exception state if not discarded by a
870 * new aborting error, interrupt, or uncaught exception. */
871 leave_cleanup(&cs);
872 } else {
873 handle_swap_exists(&old_curbuf);
874 }
875}
876
877/// Handle the situation of swap_exists_action being set.
878///
879/// It is allowed for "old_curbuf" to be NULL or invalid.
880///
881/// @param old_curbuf The buffer to check for.
882void handle_swap_exists(bufref_T *old_curbuf)
883{
884 cleanup_T cs;
885 long old_tw = curbuf->b_p_tw;
886 buf_T *buf;
887
888 if (swap_exists_action == SEA_QUIT) {
889 // Reset the error/interrupt/exception state here so that
890 // aborting() returns false when closing a buffer.
891 enter_cleanup(&cs);
892
893 // User selected Quit at ATTENTION prompt. Go back to previous
894 // buffer. If that buffer is gone or the same as the current one,
895 // open a new, empty buffer.
896 swap_exists_action = SEA_NONE; // don't want it again
897 swap_exists_did_quit = true;
898 close_buffer(curwin, curbuf, DOBUF_UNLOAD, false);
899 if (old_curbuf == NULL
900 || !bufref_valid(old_curbuf)
901 || old_curbuf->br_buf == curbuf) {
902 buf = buflist_new(NULL, NULL, 1L, BLN_CURBUF | BLN_LISTED);
903 } else {
904 buf = old_curbuf->br_buf;
905 }
906 if (buf != NULL) {
907 int old_msg_silent = msg_silent;
908
909 if (shortmess(SHM_FILEINFO)) {
910 msg_silent = 1; // prevent fileinfo message
911 }
912 enter_buffer(buf);
913 // restore msg_silent, so that the command line will be shown
914 msg_silent = old_msg_silent;
915
916 if (old_tw != curbuf->b_p_tw) {
917 check_colorcolumn(curwin);
918 }
919 }
920 // If "old_curbuf" is NULL we are in big trouble here...
921
922 /* Restore the error/interrupt/exception state if not discarded by a
923 * new aborting error, interrupt, or uncaught exception. */
924 leave_cleanup(&cs);
925 } else if (swap_exists_action == SEA_RECOVER) {
926 // Reset the error/interrupt/exception state here so that
927 // aborting() returns false when closing a buffer.
928 enter_cleanup(&cs);
929
930 // User selected Recover at ATTENTION prompt.
931 msg_scroll = true;
932 ml_recover();
933 MSG_PUTS("\n"); // don't overwrite the last message
934 cmdline_row = msg_row;
935 do_modelines(0);
936
937 /* Restore the error/interrupt/exception state if not discarded by a
938 * new aborting error, interrupt, or uncaught exception. */
939 leave_cleanup(&cs);
940 }
941 swap_exists_action = SEA_NONE; // -V519
942}
943
944/*
945 * do_bufdel() - delete or unload buffer(s)
946 *
947 * addr_count == 0: ":bdel" - delete current buffer
948 * addr_count == 1: ":N bdel" or ":bdel N [N ..]" - first delete
949 * buffer "end_bnr", then any other arguments.
950 * addr_count == 2: ":N,N bdel" - delete buffers in range
951 *
952 * command can be DOBUF_UNLOAD (":bunload"), DOBUF_WIPE (":bwipeout") or
953 * DOBUF_DEL (":bdel")
954 *
955 * Returns error message or NULL
956 */
957char_u *
958do_bufdel(
959 int command,
960 char_u *arg, // pointer to extra arguments
961 int addr_count,
962 int start_bnr, // first buffer number in a range
963 int end_bnr, // buffer nr or last buffer nr in a range
964 int forceit
965)
966{
967 int do_current = 0; // delete current buffer?
968 int deleted = 0; // number of buffers deleted
969 char_u *errormsg = NULL; // return value
970 int bnr; // buffer number
971 char_u *p;
972
973 if (addr_count == 0) {
974 (void)do_buffer(command, DOBUF_CURRENT, FORWARD, 0, forceit);
975 } else {
976 if (addr_count == 2) {
977 if (*arg) { // both range and argument is not allowed
978 return (char_u *)_(e_trailing);
979 }
980 bnr = start_bnr;
981 } else { // addr_count == 1
982 bnr = end_bnr;
983 }
984
985 for (; !got_int; os_breakcheck()) {
986 /*
987 * delete the current buffer last, otherwise when the
988 * current buffer is deleted, the next buffer becomes
989 * the current one and will be loaded, which may then
990 * also be deleted, etc.
991 */
992 if (bnr == curbuf->b_fnum) {
993 do_current = bnr;
994 } else if (do_buffer(command, DOBUF_FIRST, FORWARD, bnr,
995 forceit) == OK) {
996 deleted++;
997 }
998
999 /*
1000 * find next buffer number to delete/unload
1001 */
1002 if (addr_count == 2) {
1003 if (++bnr > end_bnr) {
1004 break;
1005 }
1006 } else { // addr_count == 1
1007 arg = skipwhite(arg);
1008 if (*arg == NUL) {
1009 break;
1010 }
1011 if (!ascii_isdigit(*arg)) {
1012 p = skiptowhite_esc(arg);
1013 bnr = buflist_findpat(arg, p, command == DOBUF_WIPE,
1014 false, false);
1015 if (bnr < 0) { // failed
1016 break;
1017 }
1018 arg = p;
1019 } else {
1020 bnr = getdigits_int(&arg, false, 0);
1021 }
1022 }
1023 }
1024 if (!got_int && do_current
1025 && do_buffer(command, DOBUF_FIRST,
1026 FORWARD, do_current, forceit) == OK) {
1027 deleted++;
1028 }
1029
1030 if (deleted == 0) {
1031 if (command == DOBUF_UNLOAD) {
1032 STRCPY(IObuff, _("E515: No buffers were unloaded"));
1033 } else if (command == DOBUF_DEL) {
1034 STRCPY(IObuff, _("E516: No buffers were deleted"));
1035 } else {
1036 STRCPY(IObuff, _("E517: No buffers were wiped out"));
1037 }
1038 errormsg = IObuff;
1039 } else if (deleted >= p_report) {
1040 if (command == DOBUF_UNLOAD) {
1041 if (deleted == 1) {
1042 MSG(_("1 buffer unloaded"));
1043 } else {
1044 smsg(_("%d buffers unloaded"), deleted);
1045 }
1046 } else if (command == DOBUF_DEL) {
1047 if (deleted == 1) {
1048 MSG(_("1 buffer deleted"));
1049 } else {
1050 smsg(_("%d buffers deleted"), deleted);
1051 }
1052 } else {
1053 if (deleted == 1) {
1054 MSG(_("1 buffer wiped out"));
1055 } else {
1056 smsg(_("%d buffers wiped out"), deleted);
1057 }
1058 }
1059 }
1060 }
1061
1062
1063 return errormsg;
1064}
1065
1066
1067
1068/*
1069 * Make the current buffer empty.
1070 * Used when it is wiped out and it's the last buffer.
1071 */
1072static int empty_curbuf(int close_others, int forceit, int action)
1073{
1074 int retval;
1075 buf_T *buf = curbuf;
1076
1077 if (action == DOBUF_UNLOAD) {
1078 EMSG(_("E90: Cannot unload last buffer"));
1079 return FAIL;
1080 }
1081
1082 bufref_T bufref;
1083 set_bufref(&bufref, buf);
1084
1085 if (close_others) {
1086 // Close any other windows on this buffer, then make it empty.
1087 close_windows(buf, true);
1088 }
1089
1090 setpcmark();
1091 retval = do_ecmd(0, NULL, NULL, NULL, ECMD_ONE,
1092 forceit ? ECMD_FORCEIT : 0, curwin);
1093
1094 // do_ecmd() may create a new buffer, then we have to delete
1095 // the old one. But do_ecmd() may have done that already, check
1096 // if the buffer still exists.
1097 if (buf != curbuf && bufref_valid(&bufref) && buf->b_nwindows == 0) {
1098 close_buffer(NULL, buf, action, false);
1099 }
1100
1101 if (!close_others) {
1102 need_fileinfo = false;
1103 }
1104
1105 return retval;
1106}
1107/*
1108 * Implementation of the commands for the buffer list.
1109 *
1110 * action == DOBUF_GOTO go to specified buffer
1111 * action == DOBUF_SPLIT split window and go to specified buffer
1112 * action == DOBUF_UNLOAD unload specified buffer(s)
1113 * action == DOBUF_DEL delete specified buffer(s) from buffer list
1114 * action == DOBUF_WIPE delete specified buffer(s) really
1115 *
1116 * start == DOBUF_CURRENT go to "count" buffer from current buffer
1117 * start == DOBUF_FIRST go to "count" buffer from first buffer
1118 * start == DOBUF_LAST go to "count" buffer from last buffer
1119 * start == DOBUF_MOD go to "count" modified buffer from current buffer
1120 *
1121 * Return FAIL or OK.
1122 */
1123int
1124do_buffer(
1125 int action,
1126 int start,
1127 int dir, // FORWARD or BACKWARD
1128 int count, // buffer number or number of buffers
1129 int forceit // true for :...!
1130)
1131{
1132 buf_T *buf;
1133 buf_T *bp;
1134 int unload = (action == DOBUF_UNLOAD || action == DOBUF_DEL
1135 || action == DOBUF_WIPE);
1136
1137 switch (start) {
1138 case DOBUF_FIRST: buf = firstbuf; break;
1139 case DOBUF_LAST: buf = lastbuf; break;
1140 default: buf = curbuf; break;
1141 }
1142 if (start == DOBUF_MOD) { // find next modified buffer
1143 while (count-- > 0) {
1144 do {
1145 buf = buf->b_next;
1146 if (buf == NULL) {
1147 buf = firstbuf;
1148 }
1149 } while (buf != curbuf && !bufIsChanged(buf));
1150 }
1151 if (!bufIsChanged(buf)) {
1152 EMSG(_("E84: No modified buffer found"));
1153 return FAIL;
1154 }
1155 } else if (start == DOBUF_FIRST && count) { // find specified buffer number
1156 while (buf != NULL && buf->b_fnum != count) {
1157 buf = buf->b_next;
1158 }
1159 } else {
1160 bp = NULL;
1161 while (count > 0 || (!unload && !buf->b_p_bl && bp != buf)) {
1162 /* remember the buffer where we start, we come back there when all
1163 * buffers are unlisted. */
1164 if (bp == NULL) {
1165 bp = buf;
1166 }
1167 if (dir == FORWARD) {
1168 buf = buf->b_next;
1169 if (buf == NULL) {
1170 buf = firstbuf;
1171 }
1172 } else {
1173 buf = buf->b_prev;
1174 if (buf == NULL) {
1175 buf = lastbuf;
1176 }
1177 }
1178 // don't count unlisted buffers
1179 if (unload || buf->b_p_bl) {
1180 count--;
1181 bp = NULL; // use this buffer as new starting point
1182 }
1183 if (bp == buf) {
1184 // back where we started, didn't find anything.
1185 EMSG(_("E85: There is no listed buffer"));
1186 return FAIL;
1187 }
1188 }
1189 }
1190
1191 if (buf == NULL) { // could not find it
1192 if (start == DOBUF_FIRST) {
1193 // don't warn when deleting
1194 if (!unload) {
1195 EMSGN(_(e_nobufnr), count);
1196 }
1197 } else if (dir == FORWARD) {
1198 EMSG(_("E87: Cannot go beyond last buffer"));
1199 } else {
1200 EMSG(_("E88: Cannot go before first buffer"));
1201 }
1202 return FAIL;
1203 }
1204
1205
1206 /*
1207 * delete buffer buf from memory and/or the list
1208 */
1209 if (unload) {
1210 int forward;
1211 bufref_T bufref;
1212 set_bufref(&bufref, buf);
1213
1214 /* When unloading or deleting a buffer that's already unloaded and
1215 * unlisted: fail silently. */
1216 if (action != DOBUF_WIPE && buf->b_ml.ml_mfp == NULL && !buf->b_p_bl) {
1217 return FAIL;
1218 }
1219
1220 if (!forceit && (buf->terminal || bufIsChanged(buf))) {
1221 if ((p_confirm || cmdmod.confirm) && p_write && !buf->terminal) {
1222 dialog_changed(buf, false);
1223 if (!bufref_valid(&bufref)) {
1224 // Autocommand deleted buffer, oops! It's not changed now.
1225 return FAIL;
1226 }
1227 // If it's still changed fail silently, the dialog already
1228 // mentioned why it fails.
1229 if (bufIsChanged(buf)) {
1230 return FAIL;
1231 }
1232 } else {
1233 if (buf->terminal) {
1234 if (p_confirm || cmdmod.confirm) {
1235 if (!dialog_close_terminal(buf)) {
1236 return FAIL;
1237 }
1238 } else {
1239 EMSG2(_("E89: %s will be killed(add ! to override)"),
1240 (char *)buf->b_fname);
1241 return FAIL;
1242 }
1243 } else {
1244 EMSGN(_("E89: No write since last change for buffer %" PRId64
1245 " (add ! to override)"),
1246 buf->b_fnum);
1247 return FAIL;
1248 }
1249 }
1250 }
1251
1252 // When closing the current buffer stop Visual mode.
1253 if (buf == curbuf && VIsual_active) {
1254 end_visual_mode();
1255 }
1256
1257 /*
1258 * If deleting the last (listed) buffer, make it empty.
1259 * The last (listed) buffer cannot be unloaded.
1260 */
1261 bp = NULL;
1262 FOR_ALL_BUFFERS(bp2) {
1263 if (bp2->b_p_bl && bp2 != buf) {
1264 bp = bp2;
1265 break;
1266 }
1267 }
1268 if (bp == NULL && buf == curbuf) {
1269 return empty_curbuf(true, forceit, action);
1270 }
1271
1272 /*
1273 * If the deleted buffer is the current one, close the current window
1274 * (unless it's the only window). Repeat this so long as we end up in
1275 * a window with this buffer.
1276 */
1277 while (buf == curbuf
1278 && !(curwin->w_closing || curwin->w_buffer->b_locked > 0)
1279 && (!ONE_WINDOW || first_tabpage->tp_next != NULL)) {
1280 if (win_close(curwin, false) == FAIL) {
1281 break;
1282 }
1283 }
1284
1285 /*
1286 * If the buffer to be deleted is not the current one, delete it here.
1287 */
1288 if (buf != curbuf) {
1289 close_windows(buf, false);
1290 if (buf != curbuf && bufref_valid(&bufref) && buf->b_nwindows <= 0) {
1291 close_buffer(NULL, buf, action, false);
1292 }
1293 return OK;
1294 }
1295
1296 // Deleting the current buffer: Need to find another buffer to go to.
1297 // There should be another, otherwise it would have been handled
1298 // above. However, autocommands may have deleted all buffers.
1299 // First use au_new_curbuf.br_buf, if it is valid.
1300 // Then prefer the buffer we most recently visited.
1301 // Else try to find one that is loaded, after the current buffer,
1302 // then before the current buffer.
1303 // Finally use any buffer.
1304 buf = NULL; // Selected buffer.
1305 bp = NULL; // Used when no loaded buffer found.
1306 if (au_new_curbuf.br_buf != NULL && bufref_valid(&au_new_curbuf)) {
1307 buf = au_new_curbuf.br_buf;
1308 } else if (curwin->w_jumplistlen > 0) {
1309 int jumpidx;
1310
1311 jumpidx = curwin->w_jumplistidx - 1;
1312 if (jumpidx < 0) {
1313 jumpidx = curwin->w_jumplistlen - 1;
1314 }
1315
1316 forward = jumpidx;
1317 while (jumpidx != curwin->w_jumplistidx) {
1318 buf = buflist_findnr(curwin->w_jumplist[jumpidx].fmark.fnum);
1319 if (buf != NULL) {
1320 if (buf == curbuf || !buf->b_p_bl) {
1321 buf = NULL; // skip current and unlisted bufs
1322 } else if (buf->b_ml.ml_mfp == NULL) {
1323 // skip unloaded buf, but may keep it for later
1324 if (bp == NULL) {
1325 bp = buf;
1326 }
1327 buf = NULL;
1328 }
1329 }
1330 if (buf != NULL) { // found a valid buffer: stop searching
1331 break;
1332 }
1333 // advance to older entry in jump list
1334 if (!jumpidx && curwin->w_jumplistidx == curwin->w_jumplistlen) {
1335 break;
1336 }
1337 if (--jumpidx < 0) {
1338 jumpidx = curwin->w_jumplistlen - 1;
1339 }
1340 if (jumpidx == forward) { // List exhausted for sure
1341 break;
1342 }
1343 }
1344 }
1345
1346 if (buf == NULL) { // No previous buffer, Try 2'nd approach
1347 forward = true;
1348 buf = curbuf->b_next;
1349 for (;; ) {
1350 if (buf == NULL) {
1351 if (!forward) { // tried both directions
1352 break;
1353 }
1354 buf = curbuf->b_prev;
1355 forward = false;
1356 continue;
1357 }
1358 // in non-help buffer, try to skip help buffers, and vv
1359 if (buf->b_help == curbuf->b_help && buf->b_p_bl) {
1360 if (buf->b_ml.ml_mfp != NULL) { // found loaded buffer
1361 break;
1362 }
1363 if (bp == NULL) { // remember unloaded buf for later
1364 bp = buf;
1365 }
1366 }
1367 if (forward) {
1368 buf = buf->b_next;
1369 } else {
1370 buf = buf->b_prev;
1371 }
1372 }
1373 }
1374 if (buf == NULL) { // No loaded buffer, use unloaded one
1375 buf = bp;
1376 }
1377 if (buf == NULL) { // No loaded buffer, find listed one
1378 FOR_ALL_BUFFERS(buf2) {
1379 if (buf2->b_p_bl && buf2 != curbuf) {
1380 buf = buf2;
1381 break;
1382 }
1383 }
1384 }
1385 if (buf == NULL) { // Still no buffer, just take one
1386 if (curbuf->b_next != NULL) {
1387 buf = curbuf->b_next;
1388 } else {
1389 buf = curbuf->b_prev;
1390 }
1391 }
1392 }
1393
1394 if (buf == NULL) {
1395 /* Autocommands must have wiped out all other buffers. Only option
1396 * now is to make the current buffer empty. */
1397 return empty_curbuf(false, forceit, action);
1398 }
1399
1400 /*
1401 * make buf current buffer
1402 */
1403 if (action == DOBUF_SPLIT) { // split window first
1404 // If 'switchbuf' contains "useopen": jump to first window containing
1405 // "buf" if one exists
1406 if ((swb_flags & SWB_USEOPEN) && buf_jump_open_win(buf)) {
1407 return OK;
1408 }
1409 // If 'switchbuf' contains "usetab": jump to first window in any tab
1410 // page containing "buf" if one exists
1411 if ((swb_flags & SWB_USETAB) && buf_jump_open_tab(buf)) {
1412 return OK;
1413 }
1414 if (win_split(0, 0) == FAIL) {
1415 return FAIL;
1416 }
1417 }
1418
1419 // go to current buffer - nothing to do
1420 if (buf == curbuf) {
1421 return OK;
1422 }
1423
1424 /*
1425 * Check if the current buffer may be abandoned.
1426 */
1427 if (action == DOBUF_GOTO && !can_abandon(curbuf, forceit)) {
1428 if ((p_confirm || cmdmod.confirm) && p_write) {
1429 bufref_T bufref;
1430 set_bufref(&bufref, buf);
1431 dialog_changed(curbuf, false);
1432 if (!bufref_valid(&bufref)) {
1433 // Autocommand deleted buffer, oops!
1434 return FAIL;
1435 }
1436 }
1437 if (bufIsChanged(curbuf)) {
1438 no_write_message();
1439 return FAIL;
1440 }
1441 }
1442
1443 // Go to the other buffer.
1444 set_curbuf(buf, action);
1445
1446 if (action == DOBUF_SPLIT) {
1447 RESET_BINDING(curwin); // reset 'scrollbind' and 'cursorbind'
1448 }
1449
1450 if (aborting()) { // autocmds may abort script processing
1451 return FAIL;
1452 }
1453
1454 return OK;
1455}
1456
1457
1458/*
1459 * Set current buffer to "buf". Executes autocommands and closes current
1460 * buffer. "action" tells how to close the current buffer:
1461 * DOBUF_GOTO free or hide it
1462 * DOBUF_SPLIT nothing
1463 * DOBUF_UNLOAD unload it
1464 * DOBUF_DEL delete it
1465 * DOBUF_WIPE wipe it out
1466 */
1467void set_curbuf(buf_T *buf, int action)
1468{
1469 buf_T *prevbuf;
1470 int unload = (action == DOBUF_UNLOAD || action == DOBUF_DEL
1471 || action == DOBUF_WIPE);
1472 long old_tw = curbuf->b_p_tw;
1473
1474 setpcmark();
1475 if (!cmdmod.keepalt) {
1476 curwin->w_alt_fnum = curbuf->b_fnum; // remember alternate file
1477 }
1478 buflist_altfpos(curwin); // remember curpos
1479
1480 // Don't restart Select mode after switching to another buffer.
1481 VIsual_reselect = false;
1482
1483 // close_windows() or apply_autocmds() may change curbuf and wipe out "buf"
1484 prevbuf = curbuf;
1485 bufref_T newbufref;
1486 bufref_T prevbufref;
1487 set_bufref(&prevbufref, prevbuf);
1488 set_bufref(&newbufref, buf);
1489
1490 // Autocommands may delete the curren buffer and/or the buffer we wan to go
1491 // to. In those cases don't close the buffer.
1492 if (!apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, false, curbuf)
1493 || (bufref_valid(&prevbufref) && bufref_valid(&newbufref)
1494 && !aborting())) {
1495 if (prevbuf == curwin->w_buffer) {
1496 reset_synblock(curwin);
1497 }
1498 if (unload) {
1499 close_windows(prevbuf, false);
1500 }
1501 if (bufref_valid(&prevbufref) && !aborting()) {
1502 win_T *previouswin = curwin;
1503 if (prevbuf == curbuf) {
1504 u_sync(false);
1505 }
1506 close_buffer(prevbuf == curwin->w_buffer ? curwin : NULL,
1507 prevbuf,
1508 unload
1509 ? action
1510 : (action == DOBUF_GOTO && !buf_hide(prevbuf)
1511 && !bufIsChanged(prevbuf)) ? DOBUF_UNLOAD : 0,
1512 false);
1513 if (curwin != previouswin && win_valid(previouswin)) {
1514 // autocommands changed curwin, Grr!
1515 curwin = previouswin;
1516 }
1517 }
1518 }
1519 /* An autocommand may have deleted "buf", already entered it (e.g., when
1520 * it did ":bunload") or aborted the script processing!
1521 * If curwin->w_buffer is null, enter_buffer() will make it valid again */
1522 if ((buf_valid(buf) && buf != curbuf
1523 && !aborting()
1524 ) || curwin->w_buffer == NULL
1525 ) {
1526 enter_buffer(buf);
1527 if (old_tw != curbuf->b_p_tw) {
1528 check_colorcolumn(curwin);
1529 }
1530 }
1531
1532 if (bufref_valid(&prevbufref) && prevbuf->terminal != NULL) {
1533 terminal_check_size(prevbuf->terminal);
1534 }
1535}
1536
1537/*
1538 * Enter a new current buffer.
1539 * Old curbuf must have been abandoned already! This also means "curbuf" may
1540 * be pointing to freed memory.
1541 */
1542void enter_buffer(buf_T *buf)
1543{
1544 // Copy buffer and window local option values. Not for a help buffer.
1545 buf_copy_options(buf, BCO_ENTER | BCO_NOHELP);
1546 if (!buf->b_help) {
1547 get_winopts(buf);
1548 } else {
1549 // Remove all folds in the window.
1550 clearFolding(curwin);
1551 }
1552 foldUpdateAll(curwin); // update folds (later).
1553
1554 // Get the buffer in the current window.
1555 curwin->w_buffer = buf;
1556 curbuf = buf;
1557 curbuf->b_nwindows++;
1558
1559 if (curwin->w_p_diff) {
1560 diff_buf_add(curbuf);
1561 }
1562
1563 curwin->w_s = &(curbuf->b_s);
1564
1565 // Cursor on first line by default.
1566 curwin->w_cursor.lnum = 1;
1567 curwin->w_cursor.col = 0;
1568 curwin->w_cursor.coladd = 0;
1569 curwin->w_set_curswant = true;
1570 curwin->w_topline_was_set = false;
1571
1572 // mark cursor position as being invalid
1573 curwin->w_valid = 0;
1574
1575 // Make sure the buffer is loaded.
1576 if (curbuf->b_ml.ml_mfp == NULL) { // need to load the file
1577 // If there is no filetype, allow for detecting one. Esp. useful for
1578 // ":ball" used in an autocommand. If there already is a filetype we
1579 // might prefer to keep it.
1580 if (*curbuf->b_p_ft == NUL) {
1581 did_filetype = false;
1582 }
1583
1584 open_buffer(false, NULL, 0);
1585 } else {
1586 if (!msg_silent) {
1587 need_fileinfo = true; // display file info after redraw
1588 }
1589 (void)buf_check_timestamp(curbuf, false); // check if file changed
1590 curwin->w_topline = 1;
1591 curwin->w_topfill = 0;
1592 apply_autocmds(EVENT_BUFENTER, NULL, NULL, false, curbuf);
1593 apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, false, curbuf);
1594 }
1595
1596 /* If autocommands did not change the cursor position, restore cursor lnum
1597 * and possibly cursor col. */
1598 if (curwin->w_cursor.lnum == 1 && inindent(0)) {
1599 buflist_getfpos();
1600 }
1601
1602 check_arg_idx(curwin); // check for valid arg_idx
1603 maketitle();
1604 // when autocmds didn't change it
1605 if (curwin->w_topline == 1 && !curwin->w_topline_was_set) {
1606 scroll_cursor_halfway(false); // redisplay at correct position
1607 }
1608
1609
1610 // Change directories when the 'acd' option is set.
1611 do_autochdir();
1612
1613 if (curbuf->b_kmap_state & KEYMAP_INIT) {
1614 (void)keymap_init();
1615 }
1616 // May need to set the spell language. Can only do this after the buffer
1617 // has been properly setup.
1618 if (!curbuf->b_help && curwin->w_p_spell && *curwin->w_s->b_p_spl != NUL) {
1619 (void)did_set_spelllang(curwin);
1620 }
1621
1622 redraw_later(NOT_VALID);
1623}
1624
1625// Change to the directory of the current buffer.
1626// Don't do this while still starting up.
1627void do_autochdir(void)
1628{
1629 if (p_acd) {
1630 if (starting == 0
1631 && curbuf->b_ffname != NULL
1632 && vim_chdirfile(curbuf->b_ffname) == OK) {
1633 post_chdir(kCdScopeGlobal, false);
1634 shorten_fnames(true);
1635 }
1636 }
1637}
1638
1639void no_write_message(void)
1640{
1641 EMSG(_("E37: No write since last change (add ! to override)"));
1642}
1643
1644void no_write_message_nobang(void)
1645{
1646 EMSG(_("E37: No write since last change"));
1647}
1648
1649//
1650// functions for dealing with the buffer list
1651//
1652
1653static int top_file_num = 1; ///< highest file number
1654
1655/// Initialize b:changedtick and changedtick_val attribute
1656///
1657/// @param[out] buf Buffer to intialize for.
1658static inline void buf_init_changedtick(buf_T *const buf)
1659 FUNC_ATTR_ALWAYS_INLINE FUNC_ATTR_NONNULL_ALL
1660{
1661 STATIC_ASSERT(sizeof("changedtick") <= sizeof(buf->changedtick_di.di_key),
1662 "buf->changedtick_di cannot hold large enough keys");
1663 buf->changedtick_di = (ChangedtickDictItem) {
1664 .di_flags = DI_FLAGS_RO|DI_FLAGS_FIX, // Must not include DI_FLAGS_ALLOC.
1665 .di_tv = (typval_T) {
1666 .v_type = VAR_NUMBER,
1667 .v_lock = VAR_FIXED,
1668 .vval.v_number = buf_get_changedtick(buf),
1669 },
1670 .di_key = "changedtick",
1671 };
1672 tv_dict_add(buf->b_vars, (dictitem_T *)&buf->changedtick_di);
1673}
1674
1675/// Add a file name to the buffer list.
1676/// If the same file name already exists return a pointer to that buffer.
1677/// If it does not exist, or if fname == NULL, a new entry is created.
1678/// If (flags & BLN_CURBUF) is true, may use current buffer.
1679/// If (flags & BLN_LISTED) is true, add new buffer to buffer list.
1680/// If (flags & BLN_DUMMY) is true, don't count it as a real buffer.
1681/// If (flags & BLN_NEW) is true, don't use an existing buffer.
1682/// If (flags & BLN_NOOPT) is true, don't copy options from the current buffer
1683/// if the buffer already exists.
1684/// This is the ONLY way to create a new buffer.
1685///
1686/// @param ffname full path of fname or relative
1687/// @param sfname short fname or NULL
1688/// @param lnum preferred cursor line
1689/// @param flags BLN_ defines
1690/// @param bufnr
1691///
1692/// @return pointer to the buffer
1693buf_T * buflist_new(char_u *ffname, char_u *sfname, linenr_T lnum, int flags)
1694{
1695 buf_T *buf;
1696
1697 fname_expand(curbuf, &ffname, &sfname); // will allocate ffname
1698
1699 /*
1700 * If file name already exists in the list, update the entry.
1701 */
1702 /* We can use inode numbers when the file exists. Works better
1703 * for hard links. */
1704 FileID file_id;
1705 bool file_id_valid = (sfname != NULL
1706 && os_fileid((char *)sfname, &file_id));
1707 if (ffname != NULL && !(flags & (BLN_DUMMY | BLN_NEW))
1708 && (buf = buflist_findname_file_id(ffname, &file_id,
1709 file_id_valid)) != NULL) {
1710 xfree(ffname);
1711 if (lnum != 0) {
1712 buflist_setfpos(buf, curwin, lnum, (colnr_T)0, false);
1713 }
1714 if ((flags & BLN_NOOPT) == 0) {
1715 // Copy the options now, if 'cpo' doesn't have 's' and not done already.
1716 buf_copy_options(buf, 0);
1717 }
1718 if ((flags & BLN_LISTED) && !buf->b_p_bl) {
1719 buf->b_p_bl = true;
1720 bufref_T bufref;
1721 set_bufref(&bufref, buf);
1722 if (!(flags & BLN_DUMMY)) {
1723 if (apply_autocmds(EVENT_BUFADD, NULL, NULL, false, buf)
1724 && !bufref_valid(&bufref)) {
1725 return NULL;
1726 }
1727 }
1728 }
1729 return buf;
1730 }
1731
1732 /*
1733 * If the current buffer has no name and no contents, use the current
1734 * buffer. Otherwise: Need to allocate a new buffer structure.
1735 *
1736 * This is the ONLY place where a new buffer structure is allocated!
1737 * (A spell file buffer is allocated in spell.c, but that's not a normal
1738 * buffer.)
1739 */
1740 buf = NULL;
1741 if ((flags & BLN_CURBUF) && curbuf_reusable()) {
1742 assert(curbuf != NULL);
1743 buf = curbuf;
1744 /* It's like this buffer is deleted. Watch out for autocommands that
1745 * change curbuf! If that happens, allocate a new buffer anyway. */
1746 if (curbuf->b_p_bl) {
1747 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, false, curbuf);
1748 }
1749 if (buf == curbuf) {
1750 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, false, curbuf);
1751 }
1752 if (aborting()) { // autocmds may abort script processing
1753 return NULL;
1754 }
1755 if (buf == curbuf) {
1756 // Make sure 'bufhidden' and 'buftype' are empty
1757 clear_string_option(&buf->b_p_bh);
1758 clear_string_option(&buf->b_p_bt);
1759 }
1760 }
1761 if (buf != curbuf || curbuf == NULL) {
1762 buf = xcalloc(1, sizeof(buf_T));
1763 // init b: variables
1764 buf->b_vars = tv_dict_alloc();
1765 buf->b_signcols_max = -1;
1766 init_var_dict(buf->b_vars, &buf->b_bufvar, VAR_SCOPE);
1767 buf_init_changedtick(buf);
1768 }
1769
1770 if (ffname != NULL) {
1771 buf->b_ffname = ffname;
1772 buf->b_sfname = vim_strsave(sfname);
1773 }
1774
1775 clear_wininfo(buf);
1776 buf->b_wininfo = xcalloc(1, sizeof(wininfo_T));
1777
1778 if (ffname != NULL && (buf->b_ffname == NULL || buf->b_sfname == NULL)) {
1779 XFREE_CLEAR(buf->b_ffname);
1780 XFREE_CLEAR(buf->b_sfname);
1781 if (buf != curbuf) {
1782 free_buffer(buf);
1783 }
1784 return NULL;
1785 }
1786
1787 if (buf == curbuf) {
1788 // free all things allocated for this buffer
1789 buf_freeall(buf, 0);
1790 if (buf != curbuf) { // autocommands deleted the buffer!
1791 return NULL;
1792 }
1793 if (aborting()) { // autocmds may abort script processing
1794 return NULL;
1795 }
1796 free_buffer_stuff(buf, kBffInitChangedtick); // delete local vars et al.
1797
1798 // Init the options.
1799 buf->b_p_initialized = false;
1800 buf_copy_options(buf, BCO_ENTER);
1801
1802 // need to reload lmaps and set b:keymap_name
1803 curbuf->b_kmap_state |= KEYMAP_INIT;
1804 } else {
1805 /*
1806 * put new buffer at the end of the buffer list
1807 */
1808 buf->b_next = NULL;
1809 if (firstbuf == NULL) { // buffer list is empty
1810 buf->b_prev = NULL;
1811 firstbuf = buf;
1812 } else { // append new buffer at end of list
1813 lastbuf->b_next = buf;
1814 buf->b_prev = lastbuf;
1815 }
1816 lastbuf = buf;
1817
1818 buf->b_fnum = top_file_num++;
1819 handle_register_buffer(buf);
1820 if (top_file_num < 0) { // wrap around (may cause duplicates)
1821 EMSG(_("W14: Warning: List of file names overflow"));
1822 if (emsg_silent == 0) {
1823 ui_flush();
1824 os_delay(3000L, true); // make sure it is noticed
1825 }
1826 top_file_num = 1;
1827 }
1828
1829 /*
1830 * Always copy the options from the current buffer.
1831 */
1832 buf_copy_options(buf, BCO_ALWAYS);
1833 }
1834
1835 buf->b_wininfo->wi_fpos.lnum = lnum;
1836 buf->b_wininfo->wi_win = curwin;
1837
1838 hash_init(&buf->b_s.b_keywtab);
1839 hash_init(&buf->b_s.b_keywtab_ic);
1840
1841 buf->b_fname = buf->b_sfname;
1842 if (!file_id_valid) {
1843 buf->file_id_valid = false;
1844 } else {
1845 buf->file_id_valid = true;
1846 buf->file_id = file_id;
1847 }
1848 buf->b_u_synced = true;
1849 buf->b_flags = BF_CHECK_RO | BF_NEVERLOADED;
1850 if (flags & BLN_DUMMY) {
1851 buf->b_flags |= BF_DUMMY;
1852 }
1853 buf_clear_file(buf);
1854 clrallmarks(buf); // clear marks
1855 fmarks_check_names(buf); // check file marks for this file
1856 buf->b_p_bl = (flags & BLN_LISTED) ? true : false; // init 'buflisted'
1857 kv_destroy(buf->update_channels);
1858 kv_init(buf->update_channels);
1859 kv_destroy(buf->update_callbacks);
1860 kv_init(buf->update_callbacks);
1861 if (!(flags & BLN_DUMMY)) {
1862 // Tricky: these autocommands may change the buffer list. They could also
1863 // split the window with re-using the one empty buffer. This may result in
1864 // unexpectedly losing the empty buffer.
1865 bufref_T bufref;
1866 set_bufref(&bufref, buf);
1867 if (apply_autocmds(EVENT_BUFNEW, NULL, NULL, false, buf)
1868 && !bufref_valid(&bufref)) {
1869 return NULL;
1870 }
1871 if ((flags & BLN_LISTED)
1872 && apply_autocmds(EVENT_BUFADD, NULL, NULL, false, buf)
1873 && !bufref_valid(&bufref)) {
1874 return NULL;
1875 }
1876 if (aborting()) {
1877 // Autocmds may abort script processing.
1878 return NULL;
1879 }
1880 }
1881
1882 return buf;
1883}
1884
1885/// Return true if the current buffer is empty, unnamed, unmodified and used in
1886/// only one window. That means it can be reused.
1887bool curbuf_reusable(void)
1888{
1889 return (curbuf != NULL
1890 && curbuf->b_ffname == NULL
1891 && curbuf->b_nwindows <= 1
1892 && (curbuf->b_ml.ml_mfp == NULL || BUFEMPTY())
1893 && !bt_quickfix(curbuf)
1894 && !curbufIsChanged());
1895}
1896
1897/*
1898 * Free the memory for the options of a buffer.
1899 * If "free_p_ff" is true also free 'fileformat', 'buftype' and
1900 * 'fileencoding'.
1901 */
1902void free_buf_options(buf_T *buf, int free_p_ff)
1903{
1904 if (free_p_ff) {
1905 clear_string_option(&buf->b_p_fenc);
1906 clear_string_option(&buf->b_p_ff);
1907 clear_string_option(&buf->b_p_bh);
1908 clear_string_option(&buf->b_p_bt);
1909 }
1910 clear_string_option(&buf->b_p_def);
1911 clear_string_option(&buf->b_p_inc);
1912 clear_string_option(&buf->b_p_inex);
1913 clear_string_option(&buf->b_p_inde);
1914 clear_string_option(&buf->b_p_indk);
1915 clear_string_option(&buf->b_p_fp);
1916 clear_string_option(&buf->b_p_fex);
1917 clear_string_option(&buf->b_p_kp);
1918 clear_string_option(&buf->b_p_mps);
1919 clear_string_option(&buf->b_p_fo);
1920 clear_string_option(&buf->b_p_flp);
1921 clear_string_option(&buf->b_p_isk);
1922 clear_string_option(&buf->b_p_keymap);
1923 keymap_ga_clear(&buf->b_kmap_ga);
1924 ga_clear(&buf->b_kmap_ga);
1925 clear_string_option(&buf->b_p_com);
1926 clear_string_option(&buf->b_p_cms);
1927 clear_string_option(&buf->b_p_nf);
1928 clear_string_option(&buf->b_p_syn);
1929 clear_string_option(&buf->b_s.b_syn_isk);
1930 clear_string_option(&buf->b_s.b_p_spc);
1931 clear_string_option(&buf->b_s.b_p_spf);
1932 vim_regfree(buf->b_s.b_cap_prog);
1933 buf->b_s.b_cap_prog = NULL;
1934 clear_string_option(&buf->b_s.b_p_spl);
1935 clear_string_option(&buf->b_p_sua);
1936 clear_string_option(&buf->b_p_ft);
1937 clear_string_option(&buf->b_p_cink);
1938 clear_string_option(&buf->b_p_cino);
1939 clear_string_option(&buf->b_p_cinw);
1940 clear_string_option(&buf->b_p_cpt);
1941 clear_string_option(&buf->b_p_cfu);
1942 clear_string_option(&buf->b_p_ofu);
1943 clear_string_option(&buf->b_p_gp);
1944 clear_string_option(&buf->b_p_mp);
1945 clear_string_option(&buf->b_p_efm);
1946 clear_string_option(&buf->b_p_ep);
1947 clear_string_option(&buf->b_p_path);
1948 clear_string_option(&buf->b_p_tags);
1949 clear_string_option(&buf->b_p_tc);
1950 clear_string_option(&buf->b_p_dict);
1951 clear_string_option(&buf->b_p_tsr);
1952 clear_string_option(&buf->b_p_qe);
1953 buf->b_p_ar = -1;
1954 buf->b_p_ul = NO_LOCAL_UNDOLEVEL;
1955 clear_string_option(&buf->b_p_lw);
1956 clear_string_option(&buf->b_p_bkc);
1957 clear_string_option(&buf->b_p_menc);
1958}
1959
1960
1961/// Get alternate file "n".
1962/// Set linenr to "lnum" or altfpos.lnum if "lnum" == 0.
1963/// Also set cursor column to altfpos.col if 'startofline' is not set.
1964/// if (options & GETF_SETMARK) call setpcmark()
1965/// if (options & GETF_ALT) we are jumping to an alternate file.
1966/// if (options & GETF_SWITCH) respect 'switchbuf' settings when jumping
1967///
1968/// Return FAIL for failure, OK for success.
1969int buflist_getfile(int n, linenr_T lnum, int options, int forceit)
1970{
1971 buf_T *buf;
1972 win_T *wp = NULL;
1973 pos_T *fpos;
1974 colnr_T col;
1975
1976 buf = buflist_findnr(n);
1977 if (buf == NULL) {
1978 if ((options & GETF_ALT) && n == 0) {
1979 EMSG(_(e_noalt));
1980 } else {
1981 EMSGN(_("E92: Buffer %" PRId64 " not found"), n);
1982 }
1983 return FAIL;
1984 }
1985
1986 // if alternate file is the current buffer, nothing to do
1987 if (buf == curbuf) {
1988 return OK;
1989 }
1990
1991 if (text_locked()) {
1992 text_locked_msg();
1993 return FAIL;
1994 }
1995 if (curbuf_locked()) {
1996 return FAIL;
1997 }
1998
1999 // altfpos may be changed by getfile(), get it now
2000 if (lnum == 0) {
2001 fpos = buflist_findfpos(buf);
2002 lnum = fpos->lnum;
2003 col = fpos->col;
2004 } else
2005 col = 0;
2006
2007 if (options & GETF_SWITCH) {
2008 // If 'switchbuf' contains "useopen": jump to first window containing
2009 // "buf" if one exists
2010 if (swb_flags & SWB_USEOPEN) {
2011 wp = buf_jump_open_win(buf);
2012 }
2013
2014 // If 'switchbuf' contains "usetab": jump to first window in any tab
2015 // page containing "buf" if one exists
2016 if (wp == NULL && (swb_flags & SWB_USETAB)) {
2017 wp = buf_jump_open_tab(buf);
2018 }
2019
2020 // If 'switchbuf' contains "split", "vsplit" or "newtab" and the
2021 // current buffer isn't empty: open new tab or window
2022 if (wp == NULL && (swb_flags & (SWB_VSPLIT | SWB_SPLIT | SWB_NEWTAB))
2023 && !BUFEMPTY()) {
2024 if (swb_flags & SWB_NEWTAB) {
2025 tabpage_new();
2026 } else if (win_split(0, (swb_flags & SWB_VSPLIT) ? WSP_VERT : 0)
2027 == FAIL) {
2028 return FAIL;
2029 }
2030 RESET_BINDING(curwin);
2031 }
2032 }
2033
2034 RedrawingDisabled++;
2035 if (GETFILE_SUCCESS(getfile(buf->b_fnum, NULL, NULL,
2036 (options & GETF_SETMARK), lnum, forceit))) {
2037 RedrawingDisabled--;
2038
2039 // cursor is at to BOL and w_cursor.lnum is checked due to getfile()
2040 if (!p_sol && col != 0) {
2041 curwin->w_cursor.col = col;
2042 check_cursor_col();
2043 curwin->w_cursor.coladd = 0;
2044 curwin->w_set_curswant = true;
2045 }
2046 return OK;
2047 }
2048 RedrawingDisabled--;
2049 return FAIL;
2050}
2051
2052// Go to the last known line number for the current buffer.
2053void buflist_getfpos(void)
2054{
2055 pos_T *fpos;
2056
2057 fpos = buflist_findfpos(curbuf);
2058
2059 curwin->w_cursor.lnum = fpos->lnum;
2060 check_cursor_lnum();
2061
2062 if (p_sol) {
2063 curwin->w_cursor.col = 0;
2064 } else {
2065 curwin->w_cursor.col = fpos->col;
2066 check_cursor_col();
2067 curwin->w_cursor.coladd = 0;
2068 curwin->w_set_curswant = true;
2069 }
2070}
2071
2072/*
2073 * Find file in buffer list by name (it has to be for the current window).
2074 * Returns NULL if not found.
2075 */
2076buf_T *buflist_findname_exp(char_u *fname)
2077{
2078 char_u *ffname;
2079 buf_T *buf = NULL;
2080
2081 // First make the name into a full path name
2082 ffname = (char_u *)FullName_save((char *)fname,
2083#ifdef UNIX
2084 // force expansion, get rid of symbolic links
2085 true
2086#else
2087 false
2088#endif
2089 );
2090 if (ffname != NULL) {
2091 buf = buflist_findname(ffname);
2092 xfree(ffname);
2093 }
2094 return buf;
2095}
2096
2097/*
2098 * Find file in buffer list by name (it has to be for the current window).
2099 * "ffname" must have a full path.
2100 * Skips dummy buffers.
2101 * Returns NULL if not found.
2102 */
2103buf_T *buflist_findname(char_u *ffname)
2104{
2105 FileID file_id;
2106 bool file_id_valid = os_fileid((char *)ffname, &file_id);
2107 return buflist_findname_file_id(ffname, &file_id, file_id_valid);
2108}
2109
2110/*
2111 * Same as buflist_findname(), but pass the FileID structure to avoid
2112 * getting it twice for the same file.
2113 * Returns NULL if not found.
2114 */
2115static buf_T *buflist_findname_file_id(char_u *ffname, FileID *file_id,
2116 bool file_id_valid)
2117{
2118 // Start at the last buffer, expect to find a match sooner.
2119 FOR_ALL_BUFFERS_BACKWARDS(buf) {
2120 if ((buf->b_flags & BF_DUMMY) == 0
2121 && !otherfile_buf(buf, ffname, file_id, file_id_valid)) {
2122 return buf;
2123 }
2124 }
2125 return NULL;
2126}
2127
2128/// Find file in buffer list by a regexp pattern.
2129/// Return fnum of the found buffer.
2130/// Return < 0 for error.
2131int buflist_findpat(
2132 const char_u *pattern,
2133 const char_u *pattern_end, // pointer to first char after pattern
2134 int unlisted, // find unlisted buffers
2135 int diffmode, // find diff-mode buffers only
2136 int curtab_only // find buffers in current tab only
2137)
2138{
2139 int match = -1;
2140 int find_listed;
2141 char_u *pat;
2142 char_u *patend;
2143 int attempt;
2144 char_u *p;
2145 int toggledollar;
2146
2147 if (pattern_end == pattern + 1 && (*pattern == '%' || *pattern == '#')) {
2148 if (*pattern == '%') {
2149 match = curbuf->b_fnum;
2150 } else {
2151 match = curwin->w_alt_fnum;
2152 }
2153 buf_T *found_buf = buflist_findnr(match);
2154 if (diffmode && !(found_buf && diff_mode_buf(found_buf))) {
2155 match = -1;
2156 }
2157 } else {
2158 //
2159 // Try four ways of matching a listed buffer:
2160 // attempt == 0: without '^' or '$' (at any position)
2161 // attempt == 1: with '^' at start (only at position 0)
2162 // attempt == 2: with '$' at end (only match at end)
2163 // attempt == 3: with '^' at start and '$' at end (only full match)
2164 // Repeat this for finding an unlisted buffer if there was no matching
2165 // listed buffer.
2166 //
2167
2168 pat = file_pat_to_reg_pat(pattern, pattern_end, NULL, false);
2169 if (pat == NULL) {
2170 return -1;
2171 }
2172 patend = pat + STRLEN(pat) - 1;
2173 toggledollar = (patend > pat && *patend == '$');
2174
2175 // First try finding a listed buffer. If not found and "unlisted"
2176 // is true, try finding an unlisted buffer.
2177 find_listed = true;
2178 for (;; ) {
2179 for (attempt = 0; attempt <= 3; attempt++) {
2180 // may add '^' and '$'
2181 if (toggledollar) {
2182 *patend = (attempt < 2) ? NUL : '$'; // add/remove '$'
2183 }
2184 p = pat;
2185 if (*p == '^' && !(attempt & 1)) { // add/remove '^'
2186 p++;
2187 }
2188
2189 regmatch_T regmatch;
2190 regmatch.regprog = vim_regcomp(p, p_magic ? RE_MAGIC : 0);
2191 if (regmatch.regprog == NULL) {
2192 xfree(pat);
2193 return -1;
2194 }
2195
2196 FOR_ALL_BUFFERS_BACKWARDS(buf) {
2197 if (buf->b_p_bl == find_listed
2198 && (!diffmode || diff_mode_buf(buf))
2199 && buflist_match(&regmatch, buf, false) != NULL) {
2200 if (curtab_only) {
2201 /* Ignore the match if the buffer is not open in
2202 * the current tab. */
2203 bool found_window = false;
2204 FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
2205 if (wp->w_buffer == buf) {
2206 found_window = true;
2207 break;
2208 }
2209 }
2210 if (!found_window) {
2211 continue;
2212 }
2213 }
2214 if (match >= 0) { // already found a match
2215 match = -2;
2216 break;
2217 }
2218 match = buf->b_fnum; // remember first match
2219 }
2220 }
2221
2222 vim_regfree(regmatch.regprog);
2223 if (match >= 0) { // found one match
2224 break;
2225 }
2226 }
2227
2228 /* Only search for unlisted buffers if there was no match with
2229 * a listed buffer. */
2230 if (!unlisted || !find_listed || match != -1) {
2231 break;
2232 }
2233 find_listed = false;
2234 }
2235
2236 xfree(pat);
2237 }
2238
2239 if (match == -2) {
2240 EMSG2(_("E93: More than one match for %s"), pattern);
2241 } else if (match < 0) {
2242 EMSG2(_("E94: No matching buffer for %s"), pattern);
2243 }
2244 return match;
2245}
2246
2247
2248/*
2249 * Find all buffer names that match.
2250 * For command line expansion of ":buf" and ":sbuf".
2251 * Return OK if matches found, FAIL otherwise.
2252 */
2253int ExpandBufnames(char_u *pat, int *num_file, char_u ***file, int options)
2254{
2255 int count = 0;
2256 int round;
2257 char_u *p;
2258 int attempt;
2259 char_u *patc;
2260
2261 *num_file = 0; // return values in case of FAIL
2262 *file = NULL;
2263
2264 // Make a copy of "pat" and change "^" to "\(^\|[\/]\)".
2265 if (*pat == '^') {
2266 patc = xmalloc(STRLEN(pat) + 11);
2267 STRCPY(patc, "\\(^\\|[\\/]\\)");
2268 STRCPY(patc + 11, pat + 1);
2269 } else
2270 patc = pat;
2271
2272 /*
2273 * attempt == 0: try match with '\<', match at start of word
2274 * attempt == 1: try match without '\<', match anywhere
2275 */
2276 for (attempt = 0; attempt <= 1; attempt++) {
2277 if (attempt > 0 && patc == pat) {
2278 break; // there was no anchor, no need to try again
2279 }
2280
2281 regmatch_T regmatch;
2282 regmatch.regprog = vim_regcomp(patc + attempt * 11, RE_MAGIC);
2283 if (regmatch.regprog == NULL) {
2284 if (patc != pat) {
2285 xfree(patc);
2286 }
2287 return FAIL;
2288 }
2289
2290 /*
2291 * round == 1: Count the matches.
2292 * round == 2: Build the array to keep the matches.
2293 */
2294 for (round = 1; round <= 2; round++) {
2295 count = 0;
2296 FOR_ALL_BUFFERS(buf) {
2297 if (!buf->b_p_bl) { // skip unlisted buffers
2298 continue;
2299 }
2300 p = buflist_match(&regmatch, buf, p_wic);
2301 if (p != NULL) {
2302 if (round == 1) {
2303 count++;
2304 } else {
2305 if (options & WILD_HOME_REPLACE) {
2306 p = home_replace_save(buf, p);
2307 } else {
2308 p = vim_strsave(p);
2309 }
2310 (*file)[count++] = p;
2311 }
2312 }
2313 }
2314 if (count == 0) { // no match found, break here
2315 break;
2316 }
2317 if (round == 1) {
2318 *file = xmalloc((size_t)count * sizeof(**file));
2319 }
2320 }
2321 vim_regfree(regmatch.regprog);
2322 if (count) { // match(es) found, break here
2323 break;
2324 }
2325 }
2326
2327 if (patc != pat) {
2328 xfree(patc);
2329 }
2330
2331 *num_file = count;
2332 return count == 0 ? FAIL : OK;
2333}
2334
2335
2336/// Check for a match on the file name for buffer "buf" with regprog "prog".
2337///
2338/// @param ignore_case When true, ignore case. Use 'fic' otherwise.
2339static char_u *buflist_match(regmatch_T *rmp, buf_T *buf, bool ignore_case)
2340{
2341 // First try the short file name, then the long file name.
2342 char_u *match = fname_match(rmp, buf->b_sfname, ignore_case);
2343 if (match == NULL) {
2344 match = fname_match(rmp, buf->b_ffname, ignore_case);
2345 }
2346 return match;
2347}
2348
2349/// Try matching the regexp in "prog" with file name "name".
2350///
2351/// @param ignore_case When true, ignore case. Use 'fileignorecase' otherwise.
2352/// @return "name" when there is a match, NULL when not.
2353static char_u *fname_match(regmatch_T *rmp, char_u *name, bool ignore_case)
2354{
2355 char_u *match = NULL;
2356 char_u *p;
2357
2358 if (name != NULL) {
2359 // Ignore case when 'fileignorecase' or the argument is set.
2360 rmp->rm_ic = p_fic || ignore_case;
2361 if (vim_regexec(rmp, name, (colnr_T)0)) {
2362 match = name;
2363 } else {
2364 // Replace $(HOME) with '~' and try matching again.
2365 p = home_replace_save(NULL, name);
2366 if (vim_regexec(rmp, p, (colnr_T)0)) {
2367 match = name;
2368 }
2369 xfree(p);
2370 }
2371 }
2372
2373 return match;
2374}
2375
2376/// Find a file in the buffer list by buffer number.
2377buf_T *buflist_findnr(int nr)
2378{
2379 if (nr == 0) {
2380 nr = curwin->w_alt_fnum;
2381 }
2382
2383 return handle_get_buffer((handle_T)nr);
2384}
2385
2386/*
2387 * Get name of file 'n' in the buffer list.
2388 * When the file has no name an empty string is returned.
2389 * home_replace() is used to shorten the file name (used for marks).
2390 * Returns a pointer to allocated memory, of NULL when failed.
2391 */
2392char_u *
2393buflist_nr2name(
2394 int n,
2395 int fullname,
2396 int helptail // for help buffers return tail only
2397)
2398{
2399 buf_T *buf;
2400
2401 buf = buflist_findnr(n);
2402 if (buf == NULL) {
2403 return NULL;
2404 }
2405 return home_replace_save(helptail ? buf : NULL,
2406 fullname ? buf->b_ffname : buf->b_fname);
2407}
2408
2409/// Set the line and column numbers for the given buffer and window
2410///
2411/// @param[in,out] buf Buffer for which line and column are set.
2412/// @param[in,out] win Window for which line and column are set.
2413/// @param[in] lnum Line number to be set. If it is zero then only
2414/// options are touched.
2415/// @param[in] col Column number to be set.
2416/// @param[in] copy_options If true save the local window option values.
2417void buflist_setfpos(buf_T *const buf, win_T *const win,
2418 linenr_T lnum, colnr_T col,
2419 bool copy_options)
2420 FUNC_ATTR_NONNULL_ALL
2421{
2422 wininfo_T *wip;
2423
2424 for (wip = buf->b_wininfo; wip != NULL; wip = wip->wi_next) {
2425 if (wip->wi_win == win) {
2426 break;
2427 }
2428 }
2429 if (wip == NULL) {
2430 // allocate a new entry
2431 wip = xcalloc(1, sizeof(wininfo_T));
2432 wip->wi_win = win;
2433 if (lnum == 0) { // set lnum even when it's 0
2434 lnum = 1;
2435 }
2436 } else {
2437 // remove the entry from the list
2438 if (wip->wi_prev) {
2439 wip->wi_prev->wi_next = wip->wi_next;
2440 } else {
2441 buf->b_wininfo = wip->wi_next;
2442 }
2443 if (wip->wi_next) {
2444 wip->wi_next->wi_prev = wip->wi_prev;
2445 }
2446 if (copy_options && wip->wi_optset) {
2447 clear_winopt(&wip->wi_opt);
2448 deleteFoldRecurse(&wip->wi_folds);
2449 }
2450 }
2451 if (lnum != 0) {
2452 wip->wi_fpos.lnum = lnum;
2453 wip->wi_fpos.col = col;
2454 }
2455 if (copy_options) {
2456 // Save the window-specific option values.
2457 copy_winopt(&win->w_onebuf_opt, &wip->wi_opt);
2458 wip->wi_fold_manual = win->w_fold_manual;
2459 cloneFoldGrowArray(&win->w_folds, &wip->wi_folds);
2460 wip->wi_optset = true;
2461 }
2462
2463 // insert the entry in front of the list
2464 wip->wi_next = buf->b_wininfo;
2465 buf->b_wininfo = wip;
2466 wip->wi_prev = NULL;
2467 if (wip->wi_next) {
2468 wip->wi_next->wi_prev = wip;
2469 }
2470
2471 return;
2472}
2473
2474
2475/// Check that "wip" has 'diff' set and the diff is only for another tab page.
2476/// That's because a diff is local to a tab page.
2477static bool wininfo_other_tab_diff(wininfo_T *wip)
2478 FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
2479{
2480 if (wip->wi_opt.wo_diff) {
2481 FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
2482 // return false when it's a window in the current tab page, thus
2483 // the buffer was in diff mode here
2484 if (wip->wi_win == wp) {
2485 return false;
2486 }
2487 }
2488 return true;
2489 }
2490 return false;
2491}
2492
2493/*
2494 * Find info for the current window in buffer "buf".
2495 * If not found, return the info for the most recently used window.
2496 * When "skip_diff_buffer" is true avoid windows with 'diff' set that is in
2497 * another tab page.
2498 * Returns NULL when there isn't any info.
2499 */
2500static wininfo_T *find_wininfo(buf_T *buf, int skip_diff_buffer)
2501{
2502 wininfo_T *wip;
2503
2504 for (wip = buf->b_wininfo; wip != NULL; wip = wip->wi_next)
2505 if (wip->wi_win == curwin
2506 && (!skip_diff_buffer || !wininfo_other_tab_diff(wip))
2507 )
2508 break;
2509
2510 /* If no wininfo for curwin, use the first in the list (that doesn't have
2511 * 'diff' set and is in another tab page). */
2512 if (wip == NULL) {
2513 if (skip_diff_buffer) {
2514 for (wip = buf->b_wininfo; wip != NULL; wip = wip->wi_next) {
2515 if (!wininfo_other_tab_diff(wip)) {
2516 break;
2517 }
2518 }
2519 } else {
2520 wip = buf->b_wininfo;
2521 }
2522 }
2523 return wip;
2524}
2525
2526/*
2527 * Reset the local window options to the values last used in this window.
2528 * If the buffer wasn't used in this window before, use the values from
2529 * the most recently used window. If the values were never set, use the
2530 * global values for the window.
2531 */
2532void get_winopts(buf_T *buf)
2533{
2534 wininfo_T *wip;
2535
2536 clear_winopt(&curwin->w_onebuf_opt);
2537 clearFolding(curwin);
2538
2539 wip = find_wininfo(buf, true);
2540 if (wip != NULL && wip->wi_win != curwin && wip->wi_win != NULL
2541 && wip->wi_win->w_buffer == buf) {
2542 win_T *wp = wip->wi_win;
2543 copy_winopt(&wp->w_onebuf_opt, &curwin->w_onebuf_opt);
2544 curwin->w_fold_manual = wp->w_fold_manual;
2545 curwin->w_foldinvalid = true;
2546 cloneFoldGrowArray(&wp->w_folds, &curwin->w_folds);
2547 } else if (wip != NULL && wip->wi_optset) {
2548 copy_winopt(&wip->wi_opt, &curwin->w_onebuf_opt);
2549 curwin->w_fold_manual = wip->wi_fold_manual;
2550 curwin->w_foldinvalid = true;
2551 cloneFoldGrowArray(&wip->wi_folds, &curwin->w_folds);
2552 } else
2553 copy_winopt(&curwin->w_allbuf_opt, &curwin->w_onebuf_opt);
2554
2555 if (curwin->w_float_config.style == kWinStyleMinimal) {
2556 didset_window_options(curwin);
2557 win_set_minimal_style(curwin);
2558 }
2559
2560 // Set 'foldlevel' to 'foldlevelstart' if it's not negative.
2561 if (p_fdls >= 0) {
2562 curwin->w_p_fdl = p_fdls;
2563 }
2564 didset_window_options(curwin);
2565}
2566
2567/*
2568 * Find the position (lnum and col) for the buffer 'buf' for the current
2569 * window.
2570 * Returns a pointer to no_position if no position is found.
2571 */
2572pos_T *buflist_findfpos(buf_T *buf)
2573{
2574 static pos_T no_position = { 1, 0, 0 };
2575
2576 wininfo_T *wip = find_wininfo(buf, false);
2577 return (wip == NULL) ? &no_position : &(wip->wi_fpos);
2578}
2579
2580/*
2581 * Find the lnum for the buffer 'buf' for the current window.
2582 */
2583linenr_T buflist_findlnum(buf_T *buf)
2584{
2585 return buflist_findfpos(buf)->lnum;
2586}
2587
2588// List all known file names (for :files and :buffers command).
2589void buflist_list(exarg_T *eap)
2590{
2591 buf_T *buf;
2592 int len;
2593 int i;
2594
2595 for (buf = firstbuf; buf != NULL && !got_int; buf = buf->b_next) {
2596 // skip unspecified buffers
2597 if ((!buf->b_p_bl && !eap->forceit && !strchr((char *)eap->arg, 'u'))
2598 || (strchr((char *)eap->arg, 'u') && buf->b_p_bl)
2599 || (strchr((char *)eap->arg, '+')
2600 && ((buf->b_flags & BF_READERR) || !bufIsChanged(buf)))
2601 || (strchr((char *)eap->arg, 'a')
2602 && (buf->b_ml.ml_mfp == NULL || buf->b_nwindows == 0))
2603 || (strchr((char *)eap->arg, 'h')
2604 && (buf->b_ml.ml_mfp == NULL || buf->b_nwindows != 0))
2605 || (strchr((char *)eap->arg, '-') && buf->b_p_ma)
2606 || (strchr((char *)eap->arg, '=') && !buf->b_p_ro)
2607 || (strchr((char *)eap->arg, 'x') && !(buf->b_flags & BF_READERR))
2608 || (strchr((char *)eap->arg, '%') && buf != curbuf)
2609 || (strchr((char *)eap->arg, '#')
2610 && (buf == curbuf || curwin->w_alt_fnum != buf->b_fnum))) {
2611 continue;
2612 }
2613 if (buf_spname(buf) != NULL) {
2614 STRLCPY(NameBuff, buf_spname(buf), MAXPATHL);
2615 } else {
2616 home_replace(buf, buf->b_fname, NameBuff, MAXPATHL, true);
2617 }
2618
2619 if (message_filtered(NameBuff)) {
2620 continue;
2621 }
2622
2623 const int changed_char = (buf->b_flags & BF_READERR)
2624 ? 'x'
2625 : (bufIsChanged(buf) ? '+' : ' ');
2626 int ro_char = !MODIFIABLE(buf) ? '-' : (buf->b_p_ro ? '=' : ' ');
2627 if (buf->terminal) {
2628 ro_char = channel_job_running((uint64_t)buf->b_p_channel) ? 'R' : 'F';
2629 }
2630
2631 msg_putchar('\n');
2632 len = vim_snprintf(
2633 (char *)IObuff, IOSIZE - 20, "%3d%c%c%c%c%c \"%s\"",
2634 buf->b_fnum,
2635 buf->b_p_bl ? ' ' : 'u',
2636 buf == curbuf ? '%' : (curwin->w_alt_fnum == buf->b_fnum ? '#' : ' '),
2637 buf->b_ml.ml_mfp == NULL ? ' ' : (buf->b_nwindows == 0 ? 'h' : 'a'),
2638 ro_char,
2639 changed_char,
2640 NameBuff);
2641
2642 if (len > IOSIZE - 20) {
2643 len = IOSIZE - 20;
2644 }
2645
2646 // put "line 999" in column 40 or after the file name
2647 i = 40 - vim_strsize(IObuff);
2648 do {
2649 IObuff[len++] = ' ';
2650 } while (--i > 0 && len < IOSIZE - 18);
2651 vim_snprintf((char *)IObuff + len, (size_t)(IOSIZE - len),
2652 _("line %" PRId64),
2653 buf == curbuf ? (int64_t)curwin->w_cursor.lnum
2654 : (int64_t)buflist_findlnum(buf));
2655 msg_outtrans(IObuff);
2656 line_breakcheck();
2657 }
2658}
2659
2660/*
2661 * Get file name and line number for file 'fnum'.
2662 * Used by DoOneCmd() for translating '%' and '#'.
2663 * Used by insert_reg() and cmdline_paste() for '#' register.
2664 * Return FAIL if not found, OK for success.
2665 */
2666int buflist_name_nr(int fnum, char_u **fname, linenr_T *lnum)
2667{
2668 buf_T *buf;
2669
2670 buf = buflist_findnr(fnum);
2671 if (buf == NULL || buf->b_fname == NULL) {
2672 return FAIL;
2673 }
2674
2675 *fname = buf->b_fname;
2676 *lnum = buflist_findlnum(buf);
2677
2678 return OK;
2679}
2680
2681/*
2682 * Set the file name for "buf"' to 'ffname', short file name to 'sfname'.
2683 * The file name with the full path is also remembered, for when :cd is used.
2684 * Returns FAIL for failure (file name already in use by other buffer)
2685 * OK otherwise.
2686 */
2687int
2688setfname(
2689 buf_T *buf,
2690 char_u *ffname,
2691 char_u *sfname,
2692 int message // give message when buffer already exists
2693)
2694{
2695 buf_T *obuf = NULL;
2696 FileID file_id;
2697 bool file_id_valid = false;
2698
2699 if (ffname == NULL || *ffname == NUL) {
2700 // Removing the name.
2701 XFREE_CLEAR(buf->b_ffname);
2702 XFREE_CLEAR(buf->b_sfname);
2703 } else {
2704 fname_expand(buf, &ffname, &sfname); // will allocate ffname
2705 if (ffname == NULL) { // out of memory
2706 return FAIL;
2707 }
2708
2709 /*
2710 * if the file name is already used in another buffer:
2711 * - if the buffer is loaded, fail
2712 * - if the buffer is not loaded, delete it from the list
2713 */
2714 file_id_valid = os_fileid((char *)ffname, &file_id);
2715 if (!(buf->b_flags & BF_DUMMY)) {
2716 obuf = buflist_findname_file_id(ffname, &file_id, file_id_valid);
2717 }
2718 if (obuf != NULL && obuf != buf) {
2719 if (obuf->b_ml.ml_mfp != NULL) { // it's loaded, fail
2720 if (message) {
2721 EMSG(_("E95: Buffer with this name already exists"));
2722 }
2723 xfree(ffname);
2724 return FAIL;
2725 }
2726 // delete from the list
2727 close_buffer(NULL, obuf, DOBUF_WIPE, false);
2728 }
2729 sfname = vim_strsave(sfname);
2730#ifdef USE_FNAME_CASE
2731 path_fix_case(sfname); // set correct case for short file name
2732#endif
2733 xfree(buf->b_ffname);
2734 xfree(buf->b_sfname);
2735 buf->b_ffname = ffname;
2736 buf->b_sfname = sfname;
2737 }
2738 buf->b_fname = buf->b_sfname;
2739 if (!file_id_valid) {
2740 buf->file_id_valid = false;
2741 } else {
2742 buf->file_id_valid = true;
2743 buf->file_id = file_id;
2744 }
2745
2746 buf_name_changed(buf);
2747 return OK;
2748}
2749
2750/*
2751 * Crude way of changing the name of a buffer. Use with care!
2752 * The name should be relative to the current directory.
2753 */
2754void buf_set_name(int fnum, char_u *name)
2755{
2756 buf_T *buf;
2757
2758 buf = buflist_findnr(fnum);
2759 if (buf != NULL) {
2760 xfree(buf->b_sfname);
2761 xfree(buf->b_ffname);
2762 buf->b_ffname = vim_strsave(name);
2763 buf->b_sfname = NULL;
2764 /* Allocate ffname and expand into full path. Also resolves .lnk
2765 * files on Win32. */
2766 fname_expand(buf, &buf->b_ffname, &buf->b_sfname);
2767 buf->b_fname = buf->b_sfname;
2768 }
2769}
2770
2771/*
2772 * Take care of what needs to be done when the name of buffer "buf" has
2773 * changed.
2774 */
2775void buf_name_changed(buf_T *buf)
2776{
2777 /*
2778 * If the file name changed, also change the name of the swapfile
2779 */
2780 if (buf->b_ml.ml_mfp != NULL) {
2781 ml_setname(buf);
2782 }
2783
2784 if (curwin->w_buffer == buf) {
2785 check_arg_idx(curwin); // check file name for arg list
2786 }
2787 maketitle(); // set window title
2788 status_redraw_all(); // status lines need to be redrawn
2789 fmarks_check_names(buf); // check named file marks
2790 ml_timestamp(buf); // reset timestamp
2791}
2792
2793/*
2794 * set alternate file name for current window
2795 *
2796 * Used by do_one_cmd(), do_write() and do_ecmd().
2797 * Return the buffer.
2798 */
2799buf_T *setaltfname(char_u *ffname, char_u *sfname, linenr_T lnum)
2800{
2801 buf_T *buf;
2802
2803 // Create a buffer. 'buflisted' is not set if it's a new buffer
2804 buf = buflist_new(ffname, sfname, lnum, 0);
2805 if (buf != NULL && !cmdmod.keepalt) {
2806 curwin->w_alt_fnum = buf->b_fnum;
2807 }
2808 return buf;
2809}
2810
2811/*
2812 * Get alternate file name for current window.
2813 * Return NULL if there isn't any, and give error message if requested.
2814 */
2815char_u * getaltfname(
2816 bool errmsg // give error message
2817)
2818{
2819 char_u *fname;
2820 linenr_T dummy;
2821
2822 if (buflist_name_nr(0, &fname, &dummy) == FAIL) {
2823 if (errmsg) {
2824 EMSG(_(e_noalt));
2825 }
2826 return NULL;
2827 }
2828 return fname;
2829}
2830
2831/*
2832 * Add a file name to the buflist and return its number.
2833 * Uses same flags as buflist_new(), except BLN_DUMMY.
2834 *
2835 * used by qf_init(), main() and doarglist()
2836 */
2837int buflist_add(char_u *fname, int flags)
2838{
2839 buf_T *buf;
2840
2841 buf = buflist_new(fname, NULL, (linenr_T)0, flags);
2842 if (buf != NULL) {
2843 return buf->b_fnum;
2844 }
2845 return 0;
2846}
2847
2848#if defined(BACKSLASH_IN_FILENAME)
2849/*
2850 * Adjust slashes in file names. Called after 'shellslash' was set.
2851 */
2852void buflist_slash_adjust(void)
2853{
2854 FOR_ALL_BUFFERS(bp) {
2855 if (bp->b_ffname != NULL) {
2856 slash_adjust(bp->b_ffname);
2857 }
2858 if (bp->b_sfname != NULL) {
2859 slash_adjust(bp->b_sfname);
2860 }
2861 }
2862}
2863
2864#endif
2865
2866/*
2867 * Set alternate cursor position for the current buffer and window "win".
2868 * Also save the local window option values.
2869 */
2870void buflist_altfpos(win_T *win)
2871{
2872 buflist_setfpos(curbuf, win, win->w_cursor.lnum, win->w_cursor.col, true);
2873}
2874
2875/// Check that "ffname" is not the same file as current file.
2876/// Fname must have a full path (expanded by path_to_absolute()).
2877///
2878/// @param ffname full path name to check
2879bool otherfile(char_u *ffname)
2880 FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
2881{
2882 return otherfile_buf(curbuf, ffname, NULL, false);
2883}
2884
2885/// Check that "ffname" is not the same file as the file loaded in "buf".
2886/// Fname must have a full path (expanded by path_to_absolute()).
2887///
2888/// @param buf buffer to check
2889/// @param ffname full path name to check
2890/// @param file_id_p information about the file at "ffname".
2891/// @param file_id_valid whether a valid "file_id_p" was passed in.
2892static bool otherfile_buf(buf_T *buf, char_u *ffname, FileID *file_id_p,
2893 bool file_id_valid)
2894 FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
2895{
2896 // no name is different
2897 if (ffname == NULL || *ffname == NUL || buf->b_ffname == NULL) {
2898 return true;
2899 }
2900 if (fnamecmp(ffname, buf->b_ffname) == 0) {
2901 return false;
2902 }
2903 {
2904 FileID file_id;
2905 // If no struct stat given, get it now
2906 if (file_id_p == NULL) {
2907 file_id_p = &file_id;
2908 file_id_valid = os_fileid((char *)ffname, file_id_p);
2909 }
2910 if (!file_id_valid) {
2911 // file_id not valid, assume files are different.
2912 return true;
2913 }
2914 // Use dev/ino to check if the files are the same, even when the names
2915 // are different (possible with links). Still need to compare the
2916 // name above, for when the file doesn't exist yet.
2917 // Problem: The dev/ino changes when a file is deleted (and created
2918 // again) and remains the same when renamed/moved. We don't want to
2919 // stat() each buffer each time, that would be too slow. Get the
2920 // dev/ino again when they appear to match, but not when they appear
2921 // to be different: Could skip a buffer when it's actually the same
2922 // file.
2923 if (buf_same_file_id(buf, file_id_p)) {
2924 buf_set_file_id(buf);
2925 if (buf_same_file_id(buf, file_id_p)) {
2926 return false;
2927 }
2928 }
2929 }
2930 return true;
2931}
2932
2933// Set file_id for a buffer.
2934// Must always be called when b_fname is changed!
2935void buf_set_file_id(buf_T *buf)
2936{
2937 FileID file_id;
2938 if (buf->b_fname != NULL
2939 && os_fileid((char *)buf->b_fname, &file_id)) {
2940 buf->file_id_valid = true;
2941 buf->file_id = file_id;
2942 } else {
2943 buf->file_id_valid = false;
2944 }
2945}
2946
2947/// Check that file_id in buffer "buf" matches with "file_id".
2948///
2949/// @param buf buffer
2950/// @param file_id file id
2951static bool buf_same_file_id(buf_T *buf, FileID *file_id)
2952 FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT FUNC_ATTR_NONNULL_ALL
2953{
2954 return buf->file_id_valid && os_fileid_equal(&(buf->file_id), file_id);
2955}
2956
2957/*
2958 * Print info about the current buffer.
2959 */
2960void
2961fileinfo(
2962 int fullname, // when non-zero print full path
2963 int shorthelp,
2964 int dont_truncate
2965)
2966{
2967 char_u *name;
2968 int n;
2969 char_u *p;
2970 char_u *buffer;
2971 size_t len;
2972
2973 buffer = xmalloc(IOSIZE);
2974
2975 if (fullname > 1) { // 2 CTRL-G: include buffer number
2976 vim_snprintf((char *)buffer, IOSIZE, "buf %d: ", curbuf->b_fnum);
2977 p = buffer + STRLEN(buffer);
2978 } else
2979 p = buffer;
2980
2981 *p++ = '"';
2982 if (buf_spname(curbuf) != NULL) {
2983 STRLCPY(p, buf_spname(curbuf), IOSIZE - (p - buffer));
2984 } else {
2985 if (!fullname && curbuf->b_fname != NULL) {
2986 name = curbuf->b_fname;
2987 } else {
2988 name = curbuf->b_ffname;
2989 }
2990 home_replace(shorthelp ? curbuf : NULL, name, p,
2991 (size_t)(IOSIZE - (p - buffer)), true);
2992 }
2993
2994 vim_snprintf_add((char *)buffer, IOSIZE, "\"%s%s%s%s%s%s",
2995 curbufIsChanged() ? (shortmess(SHM_MOD)
2996 ? " [+]" : _(" [Modified]")) : " ",
2997 (curbuf->b_flags & BF_NOTEDITED)
2998 && !bt_dontwrite(curbuf)
2999 ? _("[Not edited]") : "",
3000 (curbuf->b_flags & BF_NEW)
3001 && !bt_dontwrite(curbuf)
3002 ? _("[New file]") : "",
3003 (curbuf->b_flags & BF_READERR) ? _("[Read errors]") : "",
3004 curbuf->b_p_ro ? (shortmess(SHM_RO) ? _("[RO]")
3005 : _("[readonly]")) : "",
3006 (curbufIsChanged() || (curbuf->b_flags & BF_WRITE_MASK)
3007 || curbuf->b_p_ro) ?
3008 " " : "");
3009 /* With 32 bit longs and more than 21,474,836 lines multiplying by 100
3010 * causes an overflow, thus for large numbers divide instead. */
3011 if (curwin->w_cursor.lnum > 1000000L)
3012 n = (int)(((long)curwin->w_cursor.lnum) /
3013 ((long)curbuf->b_ml.ml_line_count / 100L));
3014 else
3015 n = (int)(((long)curwin->w_cursor.lnum * 100L) /
3016 (long)curbuf->b_ml.ml_line_count);
3017 if (curbuf->b_ml.ml_flags & ML_EMPTY) {
3018 vim_snprintf_add((char *)buffer, IOSIZE, "%s", _(no_lines_msg));
3019 } else if (p_ru) {
3020 // Current line and column are already on the screen -- webb
3021 if (curbuf->b_ml.ml_line_count == 1) {
3022 vim_snprintf_add((char *)buffer, IOSIZE, _("1 line --%d%%--"), n);
3023 } else {
3024 vim_snprintf_add((char *)buffer, IOSIZE, _("%" PRId64 " lines --%d%%--"),
3025 (int64_t)curbuf->b_ml.ml_line_count, n);
3026 }
3027 } else {
3028 vim_snprintf_add((char *)buffer, IOSIZE,
3029 _("line %" PRId64 " of %" PRId64 " --%d%%-- col "),
3030 (int64_t)curwin->w_cursor.lnum,
3031 (int64_t)curbuf->b_ml.ml_line_count,
3032 n);
3033 validate_virtcol();
3034 len = STRLEN(buffer);
3035 col_print(buffer + len, IOSIZE - len,
3036 (int)curwin->w_cursor.col + 1, (int)curwin->w_virtcol + 1);
3037 }
3038
3039 (void)append_arg_number(curwin, buffer, IOSIZE, !shortmess(SHM_FILE));
3040
3041 if (dont_truncate) {
3042 /* Temporarily set msg_scroll to avoid the message being truncated.
3043 * First call msg_start() to get the message in the right place. */
3044 msg_start();
3045 n = msg_scroll;
3046 msg_scroll = true;
3047 msg(buffer);
3048 msg_scroll = n;
3049 } else {
3050 p = msg_trunc_attr(buffer, false, 0);
3051 if (restart_edit != 0 || (msg_scrolled && !need_wait_return)) {
3052 // Need to repeat the message after redrawing when:
3053 // - When restart_edit is set (otherwise there will be a delay
3054 // before redrawing).
3055 // - When the screen was scrolled but there is no wait-return
3056 // prompt.
3057 set_keep_msg(p, 0);
3058 }
3059 }
3060
3061 xfree(buffer);
3062}
3063
3064void col_print(char_u *buf, size_t buflen, int col, int vcol)
3065{
3066 if (col == vcol) {
3067 vim_snprintf((char *)buf, buflen, "%d", col);
3068 } else {
3069 vim_snprintf((char *)buf, buflen, "%d-%d", col, vcol);
3070 }
3071}
3072
3073/*
3074 * put file name in title bar of window and in icon title
3075 */
3076
3077static char_u *lasttitle = NULL;
3078static char_u *lasticon = NULL;
3079
3080void maketitle(void)
3081{
3082 char_u *t_str = NULL;
3083 char_u *i_name;
3084 char_u *i_str = NULL;
3085 int maxlen = 0;
3086 int len;
3087 int mustset;
3088 char buf[IOSIZE];
3089
3090 if (!redrawing()) {
3091 // Postpone updating the title when 'lazyredraw' is set.
3092 need_maketitle = true;
3093 return;
3094 }
3095
3096 need_maketitle = false;
3097 if (!p_title && !p_icon && lasttitle == NULL && lasticon == NULL) {
3098 return;
3099 }
3100
3101 if (p_title) {
3102 if (p_titlelen > 0) {
3103 maxlen = (int)(p_titlelen * Columns / 100);
3104 if (maxlen < 10) {
3105 maxlen = 10;
3106 }
3107 }
3108
3109 if (*p_titlestring != NUL) {
3110 if (stl_syntax & STL_IN_TITLE) {
3111 int use_sandbox = false;
3112 int save_called_emsg = called_emsg;
3113
3114 use_sandbox = was_set_insecurely((char_u *)"titlestring", 0);
3115 called_emsg = false;
3116 build_stl_str_hl(curwin, (char_u *)buf, sizeof(buf),
3117 p_titlestring, use_sandbox,
3118 0, maxlen, NULL, NULL);
3119 t_str = (char_u *)buf;
3120 if (called_emsg) {
3121 set_string_option_direct((char_u *)"titlestring", -1, (char_u *)"",
3122 OPT_FREE, SID_ERROR);
3123 }
3124 called_emsg |= save_called_emsg;
3125 } else {
3126 t_str = p_titlestring;
3127 }
3128 } else {
3129 // Format: "fname + (path) (1 of 2) - VIM".
3130
3131#define SPACE_FOR_FNAME (sizeof(buf) - 100)
3132#define SPACE_FOR_DIR (sizeof(buf) - 20)
3133#define SPACE_FOR_ARGNR (sizeof(buf) - 10) // At least room for " - NVIM".
3134 char *buf_p = buf;
3135 if (curbuf->b_fname == NULL) {
3136 const size_t size = xstrlcpy(buf_p, _("[No Name]"),
3137 SPACE_FOR_FNAME + 1);
3138 buf_p += MIN(size, SPACE_FOR_FNAME);
3139 } else {
3140 buf_p += transstr_buf((const char *)path_tail(curbuf->b_fname),
3141 buf_p, SPACE_FOR_FNAME + 1);
3142 }
3143
3144 switch (bufIsChanged(curbuf)
3145 | (curbuf->b_p_ro << 1)
3146 | (!MODIFIABLE(curbuf) << 2)) {
3147 case 0: break;
3148 case 1: buf_p = strappend(buf_p, " +"); break;
3149 case 2: buf_p = strappend(buf_p, " ="); break;
3150 case 3: buf_p = strappend(buf_p, " =+"); break;
3151 case 4:
3152 case 6: buf_p = strappend(buf_p, " -"); break;
3153 case 5:
3154 case 7: buf_p = strappend(buf_p, " -+"); break;
3155 default: assert(false);
3156 }
3157
3158 if (curbuf->b_fname != NULL) {
3159 // Get path of file, replace home dir with ~.
3160 *buf_p++ = ' ';
3161 *buf_p++ = '(';
3162 home_replace(curbuf, curbuf->b_ffname, (char_u *)buf_p,
3163 (SPACE_FOR_DIR - (size_t)(buf_p - buf)), true);
3164#ifdef BACKSLASH_IN_FILENAME
3165 // Avoid "c:/name" to be reduced to "c".
3166 if (isalpha((uint8_t)buf_p) && *(buf_p + 1) == ':') {
3167 buf_p += 2;
3168 }
3169#endif
3170 // Remove the file name.
3171 char *p = (char *)path_tail_with_sep((char_u *)buf_p);
3172 if (p == buf_p) {
3173 // Must be a help buffer.
3174 xstrlcpy(buf_p, _("help"), SPACE_FOR_DIR - (size_t)(buf_p - buf));
3175 } else {
3176 *p = NUL;
3177 }
3178
3179 // Translate unprintable chars and concatenate. Keep some
3180 // room for the server name. When there is no room (very long
3181 // file name) use (...).
3182 if ((size_t)(buf_p - buf) < SPACE_FOR_DIR) {
3183 char *const tbuf = transstr(buf_p);
3184 const size_t free_space = SPACE_FOR_DIR - (size_t)(buf_p - buf) + 1;
3185 const size_t dir_len = xstrlcpy(buf_p, tbuf, free_space);
3186 buf_p += MIN(dir_len, free_space - 1);
3187 xfree(tbuf);
3188 } else {
3189 const size_t free_space = SPACE_FOR_ARGNR - (size_t)(buf_p - buf) + 1;
3190 const size_t dots_len = xstrlcpy(buf_p, "...", free_space);
3191 buf_p += MIN(dots_len, free_space - 1);
3192 }
3193 *buf_p++ = ')';
3194 *buf_p = NUL;
3195 } else {
3196 *buf_p = NUL;
3197 }
3198
3199 append_arg_number(curwin, (char_u *)buf_p,
3200 (int)(SPACE_FOR_ARGNR - (size_t)(buf_p - buf)), false);
3201
3202 xstrlcat(buf_p, " - NVIM", (sizeof(buf) - (size_t)(buf_p - buf)));
3203
3204 if (maxlen > 0) {
3205 // Make it shorter by removing a bit in the middle.
3206 if (vim_strsize((char_u *)buf) > maxlen) {
3207 trunc_string((char_u *)buf, (char_u *)buf, maxlen, sizeof(buf));
3208 }
3209 }
3210 t_str = (char_u *)buf;
3211#undef SPACE_FOR_FNAME
3212#undef SPACE_FOR_DIR
3213#undef SPACE_FOR_ARGNR
3214 }
3215 }
3216 mustset = ti_change(t_str, &lasttitle);
3217
3218 if (p_icon) {
3219 i_str = (char_u *)buf;
3220 if (*p_iconstring != NUL) {
3221 if (stl_syntax & STL_IN_ICON) {
3222 int use_sandbox = false;
3223 int save_called_emsg = called_emsg;
3224
3225 use_sandbox = was_set_insecurely((char_u *)"iconstring", 0);
3226 called_emsg = false;
3227 build_stl_str_hl(curwin, i_str, sizeof(buf),
3228 p_iconstring, use_sandbox,
3229 0, 0, NULL, NULL);
3230 if (called_emsg)
3231 set_string_option_direct((char_u *)"iconstring", -1,
3232 (char_u *)"", OPT_FREE, SID_ERROR);
3233 called_emsg |= save_called_emsg;
3234 } else
3235 i_str = p_iconstring;
3236 } else {
3237 if (buf_spname(curbuf) != NULL) {
3238 i_name = buf_spname(curbuf);
3239 } else { // use file name only in icon
3240 i_name = path_tail(curbuf->b_ffname);
3241 }
3242 *i_str = NUL;
3243 // Truncate name at 100 bytes.
3244 len = (int)STRLEN(i_name);
3245 if (len > 100) {
3246 len -= 100;
3247 if (has_mbyte) {
3248 len += (*mb_tail_off)(i_name, i_name + len) + 1;
3249 }
3250 i_name += len;
3251 }
3252 STRCPY(i_str, i_name);
3253 trans_characters(i_str, IOSIZE);
3254 }
3255 }
3256
3257 mustset |= ti_change(i_str, &lasticon);
3258
3259 if (mustset) {
3260 resettitle();
3261 }
3262}
3263
3264/// Used for title and icon: Check if "str" differs from "*last". Set "*last"
3265/// from "str" if it does by freeing the old value of "*last" and duplicating
3266/// "str".
3267///
3268/// @param str desired title string
3269/// @param[in,out] last current title string
3270//
3271/// @return true when "*last" changed.
3272static bool ti_change(char_u *str, char_u **last)
3273 FUNC_ATTR_WARN_UNUSED_RESULT
3274{
3275 if ((str == NULL) != (*last == NULL)
3276 || (str != NULL && *last != NULL && STRCMP(str, *last) != 0)) {
3277 xfree(*last);
3278 if (str == NULL) {
3279 *last = NULL;
3280 } else {
3281 *last = vim_strsave(str);
3282 }
3283 return true;
3284 }
3285 return false;
3286}
3287
3288
3289/// Set current window title
3290void resettitle(void)
3291{
3292 ui_call_set_icon(cstr_as_string((char *)lasticon));
3293 ui_call_set_title(cstr_as_string((char *)lasttitle));
3294 ui_flush();
3295}
3296
3297# if defined(EXITFREE)
3298void free_titles(void)
3299{
3300 xfree(lasttitle);
3301 xfree(lasticon);
3302}
3303
3304# endif
3305
3306/// Enumeration specifying the valid numeric bases that can
3307/// be used when printing numbers in the status line.
3308typedef enum {
3309 kNumBaseDecimal = 10,
3310 kNumBaseHexadecimal = 16
3311} NumberBase;
3312
3313
3314/// Build a string from the status line items in "fmt".
3315/// Return length of string in screen cells.
3316///
3317/// Normally works for window "wp", except when working for 'tabline' then it
3318/// is "curwin".
3319///
3320/// Items are drawn interspersed with the text that surrounds it
3321/// Specials: %-<wid>(xxx%) => group, %= => separation marker, %< => truncation
3322/// Item: %-<minwid>.<maxwid><itemch> All but <itemch> are optional
3323///
3324/// If maxwidth is not zero, the string will be filled at any middle marker
3325/// or truncated if too long, fillchar is used for all whitespace.
3326///
3327/// @param wp The window to build a statusline for
3328/// @param out The output buffer to write the statusline to
3329/// Note: This should not be NameBuff
3330/// @param outlen The length of the output buffer
3331/// @param fmt The statusline format string
3332/// @param use_sandbox Use a sandboxed environment when evaluating fmt
3333/// @param fillchar Character to use when filling empty space in the statusline
3334/// @param maxwidth The maximum width to make the statusline
3335/// @param hltab HL attributes (can be NULL)
3336/// @param tabtab Tab clicks definition (can be NULL).
3337///
3338/// @return The final width of the statusline
3339int build_stl_str_hl(
3340 win_T *wp,
3341 char_u *out,
3342 size_t outlen,
3343 char_u *fmt,
3344 int use_sandbox,
3345 char_u fillchar,
3346 int maxwidth,
3347 struct stl_hlrec *hltab,
3348 StlClickRecord *tabtab
3349)
3350{
3351 int groupitems[STL_MAX_ITEM];
3352 struct stl_item {
3353 // Where the item starts in the status line output buffer
3354 char_u *start;
3355 // Function to run for ClickFunc items.
3356 char *cmd;
3357 // The minimum width of the item
3358 int minwid;
3359 // The maximum width of the item
3360 int maxwid;
3361 enum {
3362 Normal,
3363 Empty,
3364 Group,
3365 Separate,
3366 Highlight,
3367 TabPage,
3368 ClickFunc,
3369 Trunc
3370 } type;
3371 } items[STL_MAX_ITEM];
3372#define TMPLEN 70
3373 char_u tmp[TMPLEN];
3374 char_u *usefmt = fmt;
3375 const int save_must_redraw = must_redraw;
3376 const int save_redr_type = curwin->w_redr_type;
3377
3378 // When the format starts with "%!" then evaluate it as an expression and
3379 // use the result as the actual format string.
3380 if (fmt[0] == '%' && fmt[1] == '!') {
3381 usefmt = eval_to_string_safe(fmt + 2, NULL, use_sandbox);
3382 if (usefmt == NULL) {
3383 usefmt = fmt;
3384 }
3385 }
3386
3387 if (fillchar == 0) {
3388 fillchar = ' ';
3389 } else if (mb_char2len(fillchar) > 1) {
3390 // Can't handle a multi-byte fill character yet.
3391 fillchar = '-';
3392 }
3393
3394 // Get line & check if empty (cursorpos will show "0-1").
3395 char_u *line_ptr = ml_get_buf(wp->w_buffer, wp->w_cursor.lnum, false);
3396 bool empty_line = (*line_ptr == NUL);
3397
3398 // Get the byte value now, in case we need it below. This is more
3399 // efficient than making a copy of the line.
3400 int byteval;
3401 if (wp->w_cursor.col > (colnr_T)STRLEN(line_ptr)) {
3402 byteval = 0;
3403 } else {
3404 byteval = utf_ptr2char(line_ptr + wp->w_cursor.col);
3405 }
3406
3407 int groupdepth = 0;
3408
3409 int curitem = 0;
3410 bool prevchar_isflag = true;
3411 bool prevchar_isitem = false;
3412
3413 // out_p is the current position in the output buffer
3414 char_u *out_p = out;
3415
3416 // out_end_p is the last valid character in the output buffer
3417 // Note: The null termination character must occur here or earlier,
3418 // so any user-visible characters must occur before here.
3419 char_u *out_end_p = (out + outlen) - 1;
3420
3421
3422 // Proceed character by character through the statusline format string
3423 // fmt_p is the current positon in the input buffer
3424 for (char_u *fmt_p = usefmt; *fmt_p; ) {
3425 if (curitem == STL_MAX_ITEM) {
3426 // There are too many items. Add the error code to the statusline
3427 // to give the user a hint about what went wrong.
3428 if (out_p + 5 < out_end_p) {
3429 memmove(out_p, " E541", (size_t)5);
3430 out_p += 5;
3431 }
3432 break;
3433 }
3434
3435 if (*fmt_p != NUL && *fmt_p != '%') {
3436 prevchar_isflag = prevchar_isitem = false;
3437 }
3438
3439 // Copy the formatting verbatim until we reach the end of the string
3440 // or find a formatting item (denoted by `%`)
3441 // or run out of room in our output buffer.
3442 while (*fmt_p != NUL && *fmt_p != '%' && out_p < out_end_p)
3443 *out_p++ = *fmt_p++;
3444
3445 // If we have processed the entire format string or run out of
3446 // room in our output buffer, exit the loop.
3447 if (*fmt_p == NUL || out_p >= out_end_p) {
3448 break;
3449 }
3450
3451 // The rest of this loop will handle a single `%` item.
3452 // Note: We increment here to skip over the `%` character we are currently
3453 // on so we can process the item's contents.
3454 fmt_p++;
3455
3456 // Ignore `%` at the end of the format string
3457 if (*fmt_p == NUL) {
3458 break;
3459 }
3460
3461 // Two `%` in a row is the escape sequence to print a
3462 // single `%` in the output buffer.
3463 if (*fmt_p == '%') {
3464 *out_p++ = *fmt_p++;
3465 prevchar_isflag = prevchar_isitem = false;
3466 continue;
3467 }
3468
3469 // STL_SEPARATE: Separation place between left and right aligned items.
3470 if (*fmt_p == STL_SEPARATE) {
3471 fmt_p++;
3472 // Ignored when we are inside of a grouping
3473 if (groupdepth > 0) {
3474 continue;
3475 }
3476 items[curitem].type = Separate;
3477 items[curitem++].start = out_p;
3478 continue;
3479 }
3480
3481 // STL_TRUNCMARK: Where to begin truncating if the statusline is too long.
3482 if (*fmt_p == STL_TRUNCMARK) {
3483 fmt_p++;
3484 items[curitem].type = Trunc;
3485 items[curitem++].start = out_p;
3486 continue;
3487 }
3488
3489 // The end of a grouping
3490 if (*fmt_p == ')') {
3491 fmt_p++;
3492 // Ignore if we are not actually inside a group currently
3493 if (groupdepth < 1) {
3494 continue;
3495 }
3496 groupdepth--;
3497
3498 // Determine how long the group is.
3499 // Note: We set the current output position to null
3500 // so `vim_strsize` will work.
3501 char_u *t = items[groupitems[groupdepth]].start;
3502 *out_p = NUL;
3503 long group_len = vim_strsize(t);
3504
3505 // If the group contained internal items
3506 // and the group did not have a minimum width,
3507 // and if there were no normal items in the group,
3508 // move the output pointer back to where the group started.
3509 // Note: This erases any non-item characters that were in the group.
3510 // Otherwise there would be no reason to do this step.
3511 if (curitem > groupitems[groupdepth] + 1
3512 && items[groupitems[groupdepth]].minwid == 0) {
3513 // remove group if all items are empty and highlight group
3514 // doesn't change
3515 int group_start_userhl = 0;
3516 int group_end_userhl = 0;
3517 int n;
3518 for (n = groupitems[groupdepth] - 1; n >= 0; n--) {
3519 if (items[n].type == Highlight) {
3520 group_start_userhl = group_end_userhl = items[n].minwid;
3521 break;
3522 }
3523 }
3524 for (n = groupitems[groupdepth] + 1; n < curitem; n++) {
3525 if (items[n].type == Normal) {
3526 break;
3527 }
3528 if (items[n].type == Highlight) {
3529 group_end_userhl = items[n].minwid;
3530 }
3531 }
3532 if (n == curitem && group_start_userhl == group_end_userhl) {
3533 out_p = t;
3534 group_len = 0;
3535 }
3536 }
3537
3538 // If the group is longer than it is allowed to be
3539 // truncate by removing bytes from the start of the group text.
3540 if (group_len > items[groupitems[groupdepth]].maxwid) {
3541 // { Determine the number of bytes to remove
3542 long n;
3543 if (has_mbyte) {
3544 // Find the first character that should be included.
3545 n = 0;
3546 while (group_len >= items[groupitems[groupdepth]].maxwid) {
3547 group_len -= ptr2cells(t + n);
3548 n += (*mb_ptr2len)(t + n);
3549 }
3550 } else {
3551 n = (long)(out_p - t) - items[groupitems[groupdepth]].maxwid + 1;
3552 }
3553 // }
3554
3555 // Prepend the `<` to indicate that the output was truncated.
3556 *t = '<';
3557
3558 // { Move the truncated output
3559 memmove(t + 1, t + n, (size_t)(out_p - (t + n)));
3560 out_p = out_p - n + 1;
3561 // Fill up space left over by half a double-wide char.
3562 while (++group_len < items[groupitems[groupdepth]].minwid) {
3563 *out_p++ = fillchar;
3564 }
3565 // }
3566
3567 // correct the start of the items for the truncation
3568 for (int idx = groupitems[groupdepth] + 1; idx < curitem; idx++) {
3569 // Shift everything back by the number of removed bytes
3570 items[idx].start -= n;
3571
3572 // If the item was partially or completely truncated, set its
3573 // start to the start of the group
3574 if (items[idx].start < t) {
3575 items[idx].start = t;
3576 }
3577 }
3578 // If the group is shorter than the minimum width, add padding characters.
3579 } else if (abs(items[groupitems[groupdepth]].minwid) > group_len) {
3580 long min_group_width = items[groupitems[groupdepth]].minwid;
3581 // If the group is left-aligned, add characters to the right.
3582 if (min_group_width < 0) {
3583 min_group_width = 0 - min_group_width;
3584 while (group_len++ < min_group_width && out_p < out_end_p)
3585 *out_p++ = fillchar;
3586 // If the group is right-aligned, shift everything to the right and
3587 // prepend with filler characters.
3588 } else {
3589 // { Move the group to the right
3590 memmove(t + min_group_width - group_len, t, (size_t)(out_p - t));
3591 group_len = min_group_width - group_len;
3592 if (out_p + group_len >= (out_end_p + 1)) {
3593 group_len = (long)(out_end_p - out_p);
3594 }
3595 out_p += group_len;
3596 // }
3597
3598 // Adjust item start positions
3599 for (int n = groupitems[groupdepth] + 1; n < curitem; n++) {
3600 items[n].start += group_len;
3601 }
3602
3603 // Prepend the fill characters
3604 for (; group_len > 0; group_len--) {
3605 *t++ = fillchar;
3606 }
3607 }
3608 }
3609 continue;
3610 }
3611 int minwid = 0;
3612 int maxwid = 9999;
3613 bool left_align = false;
3614
3615 // Denotes that numbers should be left-padded with zeros
3616 bool zeropad = (*fmt_p == '0');
3617 if (zeropad) {
3618 fmt_p++;
3619 }
3620
3621 // Denotes that the item should be left-aligned.
3622 // This is tracked by using a negative length.
3623 if (*fmt_p == '-') {
3624 fmt_p++;
3625 left_align = true;
3626 }
3627
3628 // The first digit group is the item's min width
3629 if (ascii_isdigit(*fmt_p)) {
3630 minwid = getdigits_int(&fmt_p, false, 0);
3631 }
3632
3633 // User highlight groups override the min width field
3634 // to denote the styling to use.
3635 if (*fmt_p == STL_USER_HL) {
3636 items[curitem].type = Highlight;
3637 items[curitem].start = out_p;
3638 items[curitem].minwid = minwid > 9 ? 1 : minwid;
3639 fmt_p++;
3640 curitem++;
3641 continue;
3642 }
3643
3644 // TABPAGE pairs are used to denote a region that when clicked will
3645 // either switch to or close a tab.
3646 //
3647 // Ex: tabline=%0Ttab\ zero%X
3648 // This tabline has a TABPAGENR item with minwid `0`,
3649 // which is then closed with a TABCLOSENR item.
3650 // Clicking on this region with mouse enabled will switch to tab 0.
3651 // Setting the minwid to a different value will switch
3652 // to that tab, if it exists
3653 //
3654 // Ex: tabline=%1Xtab\ one%X
3655 // This tabline has a TABCLOSENR item with minwid `1`,
3656 // which is then closed with a TABCLOSENR item.
3657 // Clicking on this region with mouse enabled will close tab 0.
3658 // This is determined by the following formula:
3659 // tab to close = (1 - minwid)
3660 // This is because for TABPAGENR we use `minwid` = `tab number`.
3661 // For TABCLOSENR we store the tab number as a negative value.
3662 // Because 0 is a valid TABPAGENR value, we have to
3663 // start our numbering at `-1`.
3664 // So, `-1` corresponds to us wanting to close tab `0`
3665 //
3666 // Note: These options are only valid when creating a tabline.
3667 if (*fmt_p == STL_TABPAGENR || *fmt_p == STL_TABCLOSENR) {
3668 if (*fmt_p == STL_TABCLOSENR) {
3669 if (minwid == 0) {
3670 // %X ends the close label, go back to the previous tab label nr.
3671 for (long n = curitem - 1; n >= 0; n--) {
3672 if (items[n].type == TabPage && items[n].minwid >= 0) {
3673 minwid = items[n].minwid;
3674 break;
3675 }
3676 }
3677 } else {
3678 // close nrs are stored as negative values
3679 minwid = -minwid;
3680 }
3681 }
3682 items[curitem].type = TabPage;
3683 items[curitem].start = out_p;
3684 items[curitem].minwid = minwid;
3685 fmt_p++;
3686 curitem++;
3687 continue;
3688 }
3689
3690 if (*fmt_p == STL_CLICK_FUNC) {
3691 fmt_p++;
3692 char *t = (char *) fmt_p;
3693 while (*fmt_p != STL_CLICK_FUNC && *fmt_p) {
3694 fmt_p++;
3695 }
3696 if (*fmt_p != STL_CLICK_FUNC) {
3697 break;
3698 }
3699 items[curitem].type = ClickFunc;
3700 items[curitem].start = out_p;
3701 items[curitem].cmd = xmemdupz(t, (size_t)(((char *)fmt_p - t)));
3702 items[curitem].minwid = minwid;
3703 fmt_p++;
3704 curitem++;
3705 continue;
3706 }
3707
3708 // Denotes the end of the minwid
3709 // the maxwid may follow immediately after
3710 if (*fmt_p == '.') {
3711 fmt_p++;
3712 if (ascii_isdigit(*fmt_p)) {
3713 maxwid = getdigits_int(&fmt_p, false, 50);
3714 }
3715 }
3716
3717 // Bound the minimum width at 50.
3718 // Make the number negative to denote left alignment of the item
3719 minwid = (minwid > 50 ? 50 : minwid) * (left_align ? -1 : 1);
3720
3721 // Denotes the start of a new group
3722 if (*fmt_p == '(') {
3723 groupitems[groupdepth++] = curitem;
3724 items[curitem].type = Group;
3725 items[curitem].start = out_p;
3726 items[curitem].minwid = minwid;
3727 items[curitem].maxwid = maxwid;
3728 fmt_p++;
3729 curitem++;
3730 continue;
3731 }
3732
3733 // An invalid item was specified.
3734 // Continue processing on the next character of the format string.
3735 if (vim_strchr(STL_ALL, *fmt_p) == NULL) {
3736 fmt_p++;
3737 continue;
3738 }
3739
3740 // The status line item type
3741 char_u opt = *fmt_p++;
3742
3743 // OK - now for the real work
3744 NumberBase base = kNumBaseDecimal;
3745 bool itemisflag = false;
3746 bool fillable = true;
3747 long num = -1;
3748 char_u *str = NULL;
3749 switch (opt) {
3750 case STL_FILEPATH:
3751 case STL_FULLPATH:
3752 case STL_FILENAME:
3753 {
3754 // Set fillable to false so that ' ' in the filename will not
3755 // get replaced with the fillchar
3756 fillable = false;
3757 if (buf_spname(wp->w_buffer) != NULL) {
3758 STRLCPY(NameBuff, buf_spname(wp->w_buffer), MAXPATHL);
3759 } else {
3760 char_u *t = (opt == STL_FULLPATH) ? wp->w_buffer->b_ffname
3761 : wp->w_buffer->b_fname;
3762 home_replace(wp->w_buffer, t, NameBuff, MAXPATHL, true);
3763 }
3764 trans_characters(NameBuff, MAXPATHL);
3765 if (opt != STL_FILENAME) {
3766 str = NameBuff;
3767 } else {
3768 str = path_tail(NameBuff);
3769 }
3770 break;
3771 }
3772 case STL_VIM_EXPR: // '{'
3773 {
3774 itemisflag = true;
3775
3776 // Attempt to copy the expression to evaluate into
3777 // the output buffer as a null-terminated string.
3778 char_u *t = out_p;
3779 while (*fmt_p != '}' && *fmt_p != NUL && out_p < out_end_p)
3780 *out_p++ = *fmt_p++;
3781 if (*fmt_p != '}') { // missing '}' or out of space
3782 break;
3783 }
3784 fmt_p++;
3785 *out_p = 0;
3786
3787 // Move our position in the output buffer
3788 // to the beginning of the expression
3789 out_p = t;
3790
3791 // { Evaluate the expression
3792
3793 // Store the current buffer number as a string variable
3794 vim_snprintf((char *)tmp, sizeof(tmp), "%d", curbuf->b_fnum);
3795 set_internal_string_var((char_u *)"g:actual_curbuf", tmp);
3796
3797 buf_T *const save_curbuf = curbuf;
3798 win_T *const save_curwin = curwin;
3799 curwin = wp;
3800 curbuf = wp->w_buffer;
3801
3802 // Note: The result stored in `t` is unused.
3803 str = eval_to_string_safe(out_p, &t, use_sandbox);
3804
3805 curwin = save_curwin;
3806 curbuf = save_curbuf;
3807
3808 // Remove the variable we just stored
3809 do_unlet(S_LEN("g:actual_curbuf"), true);
3810
3811 // }
3812
3813 // Check if the evaluated result is a number.
3814 // If so, convert the number to an int and free the string.
3815 if (str != NULL && *str != 0) {
3816 if (*skipdigits(str) == NUL) {
3817 num = atoi((char *)str);
3818 XFREE_CLEAR(str);
3819 itemisflag = false;
3820 }
3821 }
3822 break;
3823 }
3824
3825 case STL_LINE:
3826 num = (wp->w_buffer->b_ml.ml_flags & ML_EMPTY)
3827 ? 0L : (long)(wp->w_cursor.lnum);
3828 break;
3829
3830 case STL_NUMLINES:
3831 num = wp->w_buffer->b_ml.ml_line_count;
3832 break;
3833
3834 case STL_COLUMN:
3835 num = !(State & INSERT) && empty_line
3836 ? 0 : (int)wp->w_cursor.col + 1;
3837 break;
3838
3839 case STL_VIRTCOL:
3840 case STL_VIRTCOL_ALT:
3841 {
3842 // In list mode virtcol needs to be recomputed
3843 colnr_T virtcol = wp->w_virtcol;
3844 if (wp->w_p_list && wp->w_p_lcs_chars.tab1 == NUL) {
3845 wp->w_p_list = false;
3846 getvcol(wp, &wp->w_cursor, NULL, &virtcol, NULL);
3847 wp->w_p_list = true;
3848 }
3849 virtcol++;
3850 // Don't display %V if it's the same as %c.
3851 if (opt == STL_VIRTCOL_ALT
3852 && (virtcol == (colnr_T)(!(State & INSERT) && empty_line
3853 ? 0 : (int)wp->w_cursor.col + 1)))
3854 break;
3855 num = (long)virtcol;
3856 break;
3857 }
3858
3859 case STL_PERCENTAGE:
3860 num = (int)(((long)wp->w_cursor.lnum * 100L) /
3861 (long)wp->w_buffer->b_ml.ml_line_count);
3862 break;
3863
3864 case STL_ALTPERCENT:
3865 // Store the position percentage in our temporary buffer.
3866 // Note: We cannot store the value in `num` because
3867 // `get_rel_pos` can return a named position. Ex: "Top"
3868 get_rel_pos(wp, tmp, TMPLEN);
3869 str = tmp;
3870 break;
3871
3872 case STL_ARGLISTSTAT:
3873 fillable = false;
3874
3875 // Note: This is important because `append_arg_number` starts appending
3876 // at the end of the null-terminated string.
3877 // Setting the first byte to null means it will place the argument
3878 // number string at the beginning of the buffer.
3879 tmp[0] = 0;
3880
3881 // Note: The call will only return true if it actually
3882 // appended data to the `tmp` buffer.
3883 if (append_arg_number(wp, tmp, (int)sizeof(tmp), false)) {
3884 str = tmp;
3885 }
3886 break;
3887
3888 case STL_KEYMAP:
3889 fillable = false;
3890 if (get_keymap_str(wp, (char_u *)"<%s>", tmp, TMPLEN)) {
3891 str = tmp;
3892 }
3893 break;
3894 case STL_PAGENUM:
3895 num = printer_page_num;
3896 break;
3897
3898 case STL_BUFNO:
3899 num = wp->w_buffer->b_fnum;
3900 break;
3901
3902 case STL_OFFSET_X:
3903 base = kNumBaseHexadecimal;
3904 FALLTHROUGH;
3905 case STL_OFFSET:
3906 {
3907 long l = ml_find_line_or_offset(wp->w_buffer, wp->w_cursor.lnum, NULL,
3908 false);
3909 num = (wp->w_buffer->b_ml.ml_flags & ML_EMPTY) || l < 0 ?
3910 0L : l + 1 + (!(State & INSERT) && empty_line ?
3911 0 : (int)wp->w_cursor.col);
3912 break;
3913 }
3914 case STL_BYTEVAL_X:
3915 base = kNumBaseHexadecimal;
3916 FALLTHROUGH;
3917 case STL_BYTEVAL:
3918 num = byteval;
3919 if (num == NL) {
3920 num = 0;
3921 } else if (num == CAR && get_fileformat(wp->w_buffer) == EOL_MAC) {
3922 num = NL;
3923 }
3924 break;
3925
3926 case STL_ROFLAG:
3927 case STL_ROFLAG_ALT:
3928 itemisflag = true;
3929 if (wp->w_buffer->b_p_ro) {
3930 str = (char_u *)((opt == STL_ROFLAG_ALT) ? ",RO" : _("[RO]"));
3931 }
3932 break;
3933
3934 case STL_HELPFLAG:
3935 case STL_HELPFLAG_ALT:
3936 itemisflag = true;
3937 if (wp->w_buffer->b_help)
3938 str = (char_u *)((opt == STL_HELPFLAG_ALT) ? ",HLP"
3939 : _("[Help]"));
3940 break;
3941
3942 case STL_FILETYPE:
3943 // Copy the filetype if it is not null and the formatted string will fit
3944 // in the temporary buffer
3945 // (including the brackets and null terminating character)
3946 if (*wp->w_buffer->b_p_ft != NUL
3947 && STRLEN(wp->w_buffer->b_p_ft) < TMPLEN - 3) {
3948 vim_snprintf((char *)tmp, sizeof(tmp), "[%s]",
3949 wp->w_buffer->b_p_ft);
3950 str = tmp;
3951 }
3952 break;
3953
3954 case STL_FILETYPE_ALT:
3955 {
3956 itemisflag = true;
3957 // Copy the filetype if it is not null and the formatted string will fit
3958 // in the temporary buffer
3959 // (including the comma and null terminating character)
3960 if (*wp->w_buffer->b_p_ft != NUL
3961 && STRLEN(wp->w_buffer->b_p_ft) < TMPLEN - 2) {
3962 vim_snprintf((char *)tmp, sizeof(tmp), ",%s",
3963 wp->w_buffer->b_p_ft);
3964 // Uppercase the file extension
3965 for (char_u *t = tmp; *t != 0; t++) {
3966 *t = (char_u)TOUPPER_LOC(*t);
3967 }
3968 str = tmp;
3969 }
3970 break;
3971 }
3972 case STL_PREVIEWFLAG:
3973 case STL_PREVIEWFLAG_ALT:
3974 itemisflag = true;
3975 if (wp->w_p_pvw)
3976 str = (char_u *)((opt == STL_PREVIEWFLAG_ALT) ? ",PRV"
3977 : _("[Preview]"));
3978 break;
3979
3980 case STL_QUICKFIX:
3981 if (bt_quickfix(wp->w_buffer))
3982 str = (char_u *)(wp->w_llist_ref
3983 ? _(msg_loclist)
3984 : _(msg_qflist));
3985 break;
3986
3987 case STL_MODIFIED:
3988 case STL_MODIFIED_ALT:
3989 itemisflag = true;
3990 switch ((opt == STL_MODIFIED_ALT)
3991 + bufIsChanged(wp->w_buffer) * 2
3992 + (!MODIFIABLE(wp->w_buffer)) * 4) {
3993 case 2: str = (char_u *)"[+]"; break;
3994 case 3: str = (char_u *)",+"; break;
3995 case 4: str = (char_u *)"[-]"; break;
3996 case 5: str = (char_u *)",-"; break;
3997 case 6: str = (char_u *)"[+-]"; break;
3998 case 7: str = (char_u *)",+-"; break;
3999 }
4000 break;
4001
4002 case STL_HIGHLIGHT:
4003 {
4004 // { The name of the highlight is surrounded by `#`
4005 char_u *t = fmt_p;
4006 while (*fmt_p != '#' && *fmt_p != NUL) {
4007 fmt_p++;
4008 }
4009 // }
4010
4011 // Create a highlight item based on the name
4012 if (*fmt_p == '#') {
4013 items[curitem].type = Highlight;
4014 items[curitem].start = out_p;
4015 items[curitem].minwid = -syn_namen2id(t, (int)(fmt_p - t));
4016 curitem++;
4017 fmt_p++;
4018 }
4019 continue;
4020 }
4021 }
4022
4023 // If we made it this far, the item is normal and starts at
4024 // our current position in the output buffer.
4025 // Non-normal items would have `continued`.
4026 items[curitem].start = out_p;
4027 items[curitem].type = Normal;
4028
4029 // Copy the item string into the output buffer
4030 if (str != NULL && *str) {
4031 // { Skip the leading `,` or ` ` if the item is a flag
4032 // and the proper conditions are met
4033 char_u *t = str;
4034 if (itemisflag) {
4035 if ((t[0] && t[1])
4036 && ((!prevchar_isitem && *t == ',')
4037 || (prevchar_isflag && *t == ' ')))
4038 t++;
4039 prevchar_isflag = true;
4040 }
4041 // }
4042
4043 long l = vim_strsize(t);
4044
4045 // If this item is non-empty, record that the last thing
4046 // we put in the output buffer was an item
4047 if (l > 0) {
4048 prevchar_isitem = true;
4049 }
4050
4051 // If the item is too wide, truncate it from the beginning
4052 if (l > maxwid) {
4053 while (l >= maxwid)
4054 if (has_mbyte) {
4055 l -= ptr2cells(t);
4056 t += (*mb_ptr2len)(t);
4057 } else {
4058 l -= byte2cells(*t++);
4059 }
4060
4061 // Early out if there isn't enough room for the truncation marker
4062 if (out_p >= out_end_p) {
4063 break;
4064 }
4065
4066 // Add the truncation marker
4067 *out_p++ = '<';
4068 }
4069
4070 // If the item is right aligned and not wide enough,
4071 // pad with fill characters.
4072 if (minwid > 0) {
4073 for (; l < minwid && out_p < out_end_p; l++) {
4074 // Don't put a "-" in front of a digit.
4075 if (l + 1 == minwid && fillchar == '-' && ascii_isdigit(*t)) {
4076 *out_p++ = ' ';
4077 } else {
4078 *out_p++ = fillchar;
4079 }
4080 }
4081 minwid = 0;
4082 } else {
4083 // Note: The negative value denotes a left aligned item.
4084 // Here we switch the minimum width back to a positive value.
4085 minwid *= -1;
4086 }
4087
4088 // { Copy the string text into the output buffer
4089 while (*t && out_p < out_end_p) {
4090 *out_p++ = *t++;
4091 // Change a space by fillchar, unless fillchar is '-' and a
4092 // digit follows.
4093 if (fillable && out_p[-1] == ' '
4094 && (!ascii_isdigit(*t) || fillchar != '-'))
4095 out_p[-1] = fillchar;
4096 }
4097 // }
4098
4099 // For left-aligned items, fill any remaining space with the fillchar
4100 for (; l < minwid && out_p < out_end_p; l++) {
4101 *out_p++ = fillchar;
4102 }
4103
4104 // Otherwise if the item is a number, copy that to the output buffer.
4105 } else if (num >= 0) {
4106 if (out_p + 20 > out_end_p) {
4107 break; // not sufficient space
4108 }
4109 prevchar_isitem = true;
4110
4111 // { Build the formatting string
4112 char_u nstr[20];
4113 char_u *t = nstr;
4114 if (opt == STL_VIRTCOL_ALT) {
4115 *t++ = '-';
4116 minwid--;
4117 }
4118 *t++ = '%';
4119 if (zeropad) {
4120 *t++ = '0';
4121 }
4122
4123 // Note: The `*` means we take the width as one of the arguments
4124 *t++ = '*';
4125 *t++ = (char_u)(base == kNumBaseHexadecimal ? 'X' : 'd');
4126 *t = 0;
4127 // }
4128
4129 // { Determine how many characters the number will take up when printed
4130 // Note: We have to cast the base because the compiler uses
4131 // unsigned ints for the enum values.
4132 long num_chars = 1;
4133 for (long n = num; n >= (int) base; n /= (int) base) {
4134 num_chars++;
4135 }
4136
4137 // VIRTCOL_ALT takes up an extra character because
4138 // of the `-` we added above.
4139 if (opt == STL_VIRTCOL_ALT) {
4140 num_chars++;
4141 }
4142 // }
4143
4144 assert(out_end_p >= out_p);
4145 size_t remaining_buf_len = (size_t)(out_end_p - out_p) + 1;
4146
4147 // If the number is going to take up too much room
4148 // Figure out the approximate number in "scientific" type notation.
4149 // Ex: 14532 with maxwid of 4 -> '14>3'
4150 if (num_chars > maxwid) {
4151 // Add two to the width because the power piece will take
4152 // two extra characters
4153 num_chars += 2;
4154
4155 // How many extra characters there are
4156 long n = num_chars - maxwid;
4157
4158 // { Reduce the number by base^n
4159 while (num_chars-- > maxwid) {
4160 num /= (long)base;
4161 }
4162 // }
4163
4164 // { Add the format string for the exponent bit
4165 *t++ = '>';
4166 *t++ = '%';
4167 // Use the same base as the first number
4168 *t = t[-3];
4169 *++t = 0;
4170 // }
4171
4172 vim_snprintf((char *)out_p, remaining_buf_len, (char *)nstr,
4173 0, num, n);
4174 } else {
4175 vim_snprintf((char *)out_p, remaining_buf_len, (char *)nstr,
4176 minwid, num);
4177 }
4178
4179 // Advance the output buffer position to the end of the
4180 // number we just printed
4181 out_p += STRLEN(out_p);
4182
4183 // Otherwise, there was nothing to print so mark the item as empty
4184 } else {
4185 items[curitem].type = Empty;
4186 }
4187
4188 // Only free the string buffer if we allocated it.
4189 // Note: This is not needed if `str` is pointing at `tmp`
4190 if (opt == STL_VIM_EXPR) {
4191 xfree(str);
4192 }
4193
4194 if (num >= 0 || (!itemisflag && str && *str)) {
4195 prevchar_isflag = false; // Item not NULL, but not a flag
4196 }
4197
4198 // Item processed, move to the next
4199 curitem++;
4200 }
4201
4202 *out_p = NUL;
4203 int itemcnt = curitem;
4204
4205 // Free the format buffer if we allocated it internally
4206 if (usefmt != fmt) {
4207 xfree(usefmt);
4208 }
4209
4210 // We have now processed the entire statusline format string.
4211 // What follows is post-processing to handle alignment and highlighting.
4212
4213 int width = vim_strsize(out);
4214 if (maxwidth > 0 && width > maxwidth) {
4215 // Result is too long, must truncate somewhere.
4216 int item_idx = 0;
4217 char_u *trunc_p;
4218
4219 // If there are no items, truncate from beginning
4220 if (itemcnt == 0) {
4221 trunc_p = out;
4222
4223 // Otherwise, look for the truncation item
4224 } else {
4225 // Default to truncating at the first item
4226 trunc_p = items[0].start;
4227 item_idx = 0;
4228
4229 for (int i = 0; i < itemcnt; i++) {
4230 if (items[i].type == Trunc) {
4231 // Truncate at %< items.
4232 trunc_p = items[i].start;
4233 item_idx = i;
4234 break;
4235 }
4236 }
4237 }
4238
4239 // If the truncation point we found is beyond the maximum
4240 // length of the string, truncate the end of the string.
4241 if (width - vim_strsize(trunc_p) >= maxwidth) {
4242 // If we are using a multi-byte encoding, walk from the beginning of the
4243 // string to find the last character that will fit.
4244 if (has_mbyte) {
4245 trunc_p = out;
4246 width = 0;
4247 for (;; ) {
4248 width += ptr2cells(trunc_p);
4249 if (width >= maxwidth) {
4250 break;
4251 }
4252
4253 // Note: Only advance the pointer if the next
4254 // character will fit in the available output space
4255 trunc_p += (*mb_ptr2len)(trunc_p);
4256 }
4257
4258 // Otherwise put the truncation point at the end, leaving enough room
4259 // for a single-character truncation marker
4260 } else {
4261 trunc_p = out + maxwidth - 1;
4262 }
4263
4264 // Ignore any items in the statusline that occur after
4265 // the truncation point
4266 for (int i = 0; i < itemcnt; i++) {
4267 if (items[i].start > trunc_p) {
4268 itemcnt = i;
4269 break;
4270 }
4271 }
4272
4273 // Truncate the output
4274 *trunc_p++ = '>';
4275 *trunc_p = 0;
4276
4277 // Truncate at the truncation point we found
4278 } else {
4279 // { Determine how many bytes to remove
4280 long trunc_len;
4281 if (has_mbyte) {
4282 trunc_len = 0;
4283 while (width >= maxwidth) {
4284 width -= ptr2cells(trunc_p + trunc_len);
4285 trunc_len += (*mb_ptr2len)(trunc_p + trunc_len);
4286 }
4287 } else {
4288 // Truncate an extra character so we can insert our `<`.
4289 trunc_len = (width - maxwidth) + 1;
4290 }
4291 // }
4292
4293 // { Truncate the string
4294 char_u *trunc_end_p = trunc_p + trunc_len;
4295 STRMOVE(trunc_p + 1, trunc_end_p);
4296
4297 // Put a `<` to mark where we truncated at
4298 *trunc_p = '<';
4299
4300 if (width + 1 < maxwidth) {
4301 // Advance the pointer to the end of the string
4302 trunc_p = trunc_p + STRLEN(trunc_p);
4303 }
4304
4305 // Fill up for half a double-wide character.
4306 while (++width < maxwidth) {
4307 *trunc_p++ = fillchar;
4308 *trunc_p = NUL;
4309 }
4310 // }
4311
4312 // { Change the start point for items based on
4313 // their position relative to our truncation point
4314
4315 // Note: The offset is one less than the truncation length because
4316 // the truncation marker `<` is not counted.
4317 long item_offset = trunc_len - 1;
4318
4319 for (int i = item_idx; i < itemcnt; i++) {
4320 // Items starting at or after the end of the truncated section need
4321 // to be moved backwards.
4322 if (items[i].start >= trunc_end_p) {
4323 items[i].start -= item_offset;
4324 // Anything inside the truncated area is set to start
4325 // at the `<` truncation character.
4326 } else {
4327 items[i].start = trunc_p;
4328 }
4329 }
4330 // }
4331 }
4332 width = maxwidth;
4333
4334 // If there is room left in our statusline, and room left in our buffer,
4335 // add characters at the separate marker (if there is one) to
4336 // fill up the available space.
4337 } else if (width < maxwidth
4338 && STRLEN(out) + (size_t)(maxwidth - width) + 1 < outlen) {
4339 // Find how many separators there are, which we will use when
4340 // figuring out how many groups there are.
4341 int num_separators = 0;
4342 for (int i = 0; i < itemcnt; i++) {
4343 if (items[i].type == Separate) {
4344 num_separators++;
4345 }
4346 }
4347
4348 // If we have separated groups, then we deal with it now
4349 if (num_separators) {
4350 // Create an array of the start location for each
4351 // separator mark.
4352 int separator_locations[STL_MAX_ITEM];
4353 int index = 0;
4354 for (int i = 0; i < itemcnt; i++) {
4355 if (items[i].type == Separate) {
4356 separator_locations[index] = i;
4357 index++;
4358 }
4359 }
4360
4361 int standard_spaces = (maxwidth - width) / num_separators;
4362 int final_spaces = (maxwidth - width) -
4363 standard_spaces * (num_separators - 1);
4364
4365 for (int i = 0; i < num_separators; i++) {
4366 int dislocation = (i == (num_separators - 1))
4367 ? final_spaces : standard_spaces;
4368 char_u *seploc = items[separator_locations[i]].start + dislocation;
4369 STRMOVE(seploc, items[separator_locations[i]].start);
4370 for (char_u *s = items[separator_locations[i]].start; s < seploc; s++) {
4371 *s = fillchar;
4372 }
4373
4374 for (int item_idx = separator_locations[i] + 1;
4375 item_idx < itemcnt;
4376 item_idx++) {
4377 items[item_idx].start += dislocation;
4378 }
4379 }
4380
4381 width = maxwidth;
4382 }
4383 }
4384
4385 // Store the info about highlighting.
4386 if (hltab != NULL) {
4387 struct stl_hlrec *sp = hltab;
4388 for (long l = 0; l < itemcnt; l++) {
4389 if (items[l].type == Highlight) {
4390 sp->start = items[l].start;
4391 sp->userhl = items[l].minwid;
4392 sp++;
4393 }
4394 }
4395 sp->start = NULL;
4396 sp->userhl = 0;
4397 }
4398
4399 // Store the info about tab pages labels.
4400 if (tabtab != NULL) {
4401 StlClickRecord *cur_tab_rec = tabtab;
4402 for (long l = 0; l < itemcnt; l++) {
4403 if (items[l].type == TabPage) {
4404 cur_tab_rec->start = (char *)items[l].start;
4405 if (items[l].minwid == 0) {
4406 cur_tab_rec->def.type = kStlClickDisabled;
4407 cur_tab_rec->def.tabnr = 0;
4408 } else {
4409 int tabnr = items[l].minwid;
4410 if (items[l].minwid > 0) {
4411 cur_tab_rec->def.type = kStlClickTabSwitch;
4412 } else {
4413 cur_tab_rec->def.type = kStlClickTabClose;
4414 tabnr = -tabnr;
4415 }
4416 cur_tab_rec->def.tabnr = tabnr;
4417 }
4418 cur_tab_rec->def.func = NULL;
4419 cur_tab_rec++;
4420 } else if (items[l].type == ClickFunc) {
4421 cur_tab_rec->start = (char *)items[l].start;
4422 cur_tab_rec->def.type = kStlClickFuncRun;
4423 cur_tab_rec->def.tabnr = items[l].minwid;
4424 cur_tab_rec->def.func = items[l].cmd;
4425 cur_tab_rec++;
4426 }
4427 }
4428 cur_tab_rec->start = NULL;
4429 cur_tab_rec->def.type = kStlClickDisabled;
4430 cur_tab_rec->def.tabnr = 0;
4431 cur_tab_rec->def.func = NULL;
4432 }
4433
4434 // When inside update_screen we do not want redrawing a stausline, ruler,
4435 // title, etc. to trigger another redraw, it may cause an endless loop.
4436 if (updating_screen) {
4437 must_redraw = save_must_redraw;
4438 curwin->w_redr_type = save_redr_type;
4439 }
4440
4441 return width;
4442}
4443
4444/*
4445 * Get relative cursor position in window into "buf[buflen]", in the form 99%,
4446 * using "Top", "Bot" or "All" when appropriate.
4447 */
4448void get_rel_pos(win_T *wp, char_u *buf, int buflen)
4449{
4450 // Need at least 3 chars for writing.
4451 if (buflen < 3) {
4452 return;
4453 }
4454
4455 long above; // number of lines above window
4456 long below; // number of lines below window
4457
4458 above = wp->w_topline - 1;
4459 above += diff_check_fill(wp, wp->w_topline) - wp->w_topfill;
4460 if (wp->w_topline == 1 && wp->w_topfill >= 1) {
4461 // All buffer lines are displayed and there is an indication
4462 // of filler lines, that can be considered seeing all lines.
4463 above = 0;
4464 }
4465 below = wp->w_buffer->b_ml.ml_line_count - wp->w_botline + 1;
4466 if (below <= 0) {
4467 STRLCPY(buf, (above == 0 ? _("All") : _("Bot")), buflen);
4468 } else if (above <= 0) {
4469 STRLCPY(buf, _("Top"), buflen);
4470 } else {
4471 vim_snprintf((char *)buf, (size_t)buflen, "%2d%%", above > 1000000L
4472 ? (int)(above / ((above + below) / 100L))
4473 : (int)(above * 100L / (above + below)));
4474 }
4475}
4476
4477/// Append (file 2 of 8) to "buf[buflen]", if editing more than one file.
4478///
4479/// @param wp window whose buffers to check
4480/// @param[in,out] buf string buffer to add the text to
4481/// @param buflen length of the string buffer
4482/// @param add_file if true, add "file" before the arg number
4483///
4484/// @return true if it was appended.
4485static bool append_arg_number(win_T *wp, char_u *buf, int buflen, bool add_file)
4486 FUNC_ATTR_NONNULL_ALL
4487{
4488 // Nothing to do
4489 if (ARGCOUNT <= 1) {
4490 return false;
4491 }
4492
4493 char_u *p = buf + STRLEN(buf); // go to the end of the buffer
4494
4495 // Early out if the string is getting too long
4496 if (p - buf + 35 >= buflen) {
4497 return false;
4498 }
4499
4500 *p++ = ' ';
4501 *p++ = '(';
4502 if (add_file) {
4503 STRCPY(p, "file ");
4504 p += 5;
4505 }
4506 vim_snprintf((char *)p, (size_t)(buflen - (p - buf)),
4507 wp->w_arg_idx_invalid
4508 ? "(%d) of %d)"
4509 : "%d of %d)", wp->w_arg_idx + 1, ARGCOUNT);
4510 return true;
4511}
4512
4513/*
4514 * Make "ffname" a full file name, set "sfname" to "ffname" if not NULL.
4515 * "ffname" becomes a pointer to allocated memory (or NULL).
4516 */
4517void fname_expand(buf_T *buf, char_u **ffname, char_u **sfname)
4518{
4519 if (*ffname == NULL) { // if no file name given, nothing to do
4520 return;
4521 }
4522 if (*sfname == NULL) { // if no short file name given, use ffname
4523 *sfname = *ffname;
4524 }
4525 *ffname = (char_u *)fix_fname((char *)(*ffname)); // expand to full path
4526
4527#ifdef WIN32
4528 if (!buf->b_p_bin) {
4529 // If the file name is a shortcut file, use the file it links to.
4530 char *rfname = os_resolve_shortcut((const char *)(*ffname));
4531 if (rfname != NULL) {
4532 xfree(*ffname);
4533 *ffname = (char_u *)rfname;
4534 *sfname = (char_u *)rfname;
4535 }
4536 }
4537#endif
4538}
4539
4540/*
4541 * Get the file name for an argument list entry.
4542 */
4543char_u *alist_name(aentry_T *aep)
4544{
4545 buf_T *bp;
4546
4547 // Use the name from the associated buffer if it exists.
4548 bp = buflist_findnr(aep->ae_fnum);
4549 if (bp == NULL || bp->b_fname == NULL) {
4550 return aep->ae_fname;
4551 }
4552 return bp->b_fname;
4553}
4554
4555/*
4556 * do_arg_all(): Open up to 'count' windows, one for each argument.
4557 */
4558void
4559do_arg_all(
4560 int count,
4561 int forceit, // hide buffers in current windows
4562 int keep_tabs // keep current tabs, for ":tab drop file"
4563)
4564{
4565 int i;
4566 char_u *opened; // Array of weight for which args are open:
4567 // 0: not opened
4568 // 1: opened in other tab
4569 // 2: opened in curtab
4570 // 3: opened in curtab and curwin
4571
4572 int opened_len; // length of opened[]
4573 int use_firstwin = false; // use first window for arglist
4574 int split_ret = OK;
4575 bool p_ea_save;
4576 alist_T *alist; // argument list to be used
4577 buf_T *buf;
4578 tabpage_T *tpnext;
4579 int had_tab = cmdmod.tab;
4580 win_T *old_curwin, *last_curwin;
4581 tabpage_T *old_curtab, *last_curtab;
4582 win_T *new_curwin = NULL;
4583 tabpage_T *new_curtab = NULL;
4584
4585 assert(firstwin != NULL); // satisfy coverity
4586
4587 if (ARGCOUNT <= 0) {
4588 /* Don't give an error message. We don't want it when the ":all"
4589 * command is in the .vimrc. */
4590 return;
4591 }
4592 setpcmark();
4593
4594 opened_len = ARGCOUNT;
4595 opened = xcalloc((size_t)opened_len, 1);
4596
4597 /* Autocommands may do anything to the argument list. Make sure it's not
4598 * freed while we are working here by "locking" it. We still have to
4599 * watch out for its size to be changed. */
4600 alist = curwin->w_alist;
4601 alist->al_refcount++;
4602
4603 old_curwin = curwin;
4604 old_curtab = curtab;
4605
4606
4607 /*
4608 * Try closing all windows that are not in the argument list.
4609 * Also close windows that are not full width;
4610 * When 'hidden' or "forceit" set the buffer becomes hidden.
4611 * Windows that have a changed buffer and can't be hidden won't be closed.
4612 * When the ":tab" modifier was used do this for all tab pages.
4613 */
4614 if (had_tab > 0) {
4615 goto_tabpage_tp(first_tabpage, true, true);
4616 }
4617 for (;; ) {
4618 win_T *wpnext = NULL;
4619 tpnext = curtab->tp_next;
4620 for (win_T *wp = firstwin; wp != NULL; wp = wpnext) {
4621 wpnext = wp->w_next;
4622 buf = wp->w_buffer;
4623 if (buf->b_ffname == NULL
4624 || (!keep_tabs && (buf->b_nwindows > 1 || wp->w_width != Columns))) {
4625 i = opened_len;
4626 } else {
4627 // check if the buffer in this window is in the arglist
4628 for (i = 0; i < opened_len; i++) {
4629 if (i < alist->al_ga.ga_len
4630 && (AARGLIST(alist)[i].ae_fnum == buf->b_fnum
4631 || path_full_compare(alist_name(&AARGLIST(alist)[i]),
4632 buf->b_ffname, true) & kEqualFiles)) {
4633 int weight = 1;
4634
4635 if (old_curtab == curtab) {
4636 weight++;
4637 if (old_curwin == wp) {
4638 weight++;
4639 }
4640 }
4641
4642 if (weight > (int)opened[i]) {
4643 opened[i] = (char_u)weight;
4644 if (i == 0) {
4645 if (new_curwin != NULL) {
4646 new_curwin->w_arg_idx = opened_len;
4647 }
4648 new_curwin = wp;
4649 new_curtab = curtab;
4650 }
4651 } else if (keep_tabs) {
4652 i = opened_len;
4653 }
4654
4655 if (wp->w_alist != alist) {
4656 /* Use the current argument list for all windows
4657 * containing a file from it. */
4658 alist_unlink(wp->w_alist);
4659 wp->w_alist = alist;
4660 wp->w_alist->al_refcount++;
4661 }
4662 break;
4663 }
4664 }
4665 }
4666 wp->w_arg_idx = i;
4667
4668 if (i == opened_len && !keep_tabs) { // close this window
4669 if (buf_hide(buf) || forceit || buf->b_nwindows > 1
4670 || !bufIsChanged(buf)) {
4671 /* If the buffer was changed, and we would like to hide it,
4672 * try autowriting. */
4673 if (!buf_hide(buf) && buf->b_nwindows <= 1 && bufIsChanged(buf)) {
4674 bufref_T bufref;
4675 set_bufref(&bufref, buf);
4676 (void)autowrite(buf, false);
4677 // Check if autocommands removed the window.
4678 if (!win_valid(wp) || !bufref_valid(&bufref)) {
4679 wpnext = firstwin; // Start all over...
4680 continue;
4681 }
4682 }
4683 // don't close last window
4684 if (ONE_WINDOW
4685 && (first_tabpage->tp_next == NULL || !had_tab)) {
4686 use_firstwin = true;
4687 } else {
4688 win_close(wp, !buf_hide(buf) && !bufIsChanged(buf));
4689 // check if autocommands removed the next window
4690 if (!win_valid(wpnext)) {
4691 // start all over...
4692 wpnext = firstwin;
4693 }
4694 }
4695 }
4696 }
4697 }
4698
4699 // Without the ":tab" modifier only do the current tab page.
4700 if (had_tab == 0 || tpnext == NULL) {
4701 break;
4702 }
4703
4704 // check if autocommands removed the next tab page
4705 if (!valid_tabpage(tpnext)) {
4706 tpnext = first_tabpage; // start all over...
4707 }
4708 goto_tabpage_tp(tpnext, true, true);
4709 }
4710
4711 /*
4712 * Open a window for files in the argument list that don't have one.
4713 * ARGCOUNT may change while doing this, because of autocommands.
4714 */
4715 if (count > opened_len || count <= 0) {
4716 count = opened_len;
4717 }
4718
4719 // Don't execute Win/Buf Enter/Leave autocommands here.
4720 autocmd_no_enter++;
4721 autocmd_no_leave++;
4722 last_curwin = curwin;
4723 last_curtab = curtab;
4724 win_enter(lastwin, false);
4725 // ":drop all" should re-use an empty window to avoid "--remote-tab"
4726 // leaving an empty tab page when executed locally.
4727 if (keep_tabs && BUFEMPTY() && curbuf->b_nwindows == 1
4728 && curbuf->b_ffname == NULL && !curbuf->b_changed) {
4729 use_firstwin = true;
4730 }
4731
4732 for (i = 0; i < count && i < opened_len && !got_int; i++) {
4733 if (alist == &global_alist && i == global_alist.al_ga.ga_len - 1) {
4734 arg_had_last = true;
4735 }
4736 if (opened[i] > 0) {
4737 // Move the already present window to below the current window
4738 if (curwin->w_arg_idx != i) {
4739 FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
4740 if (wp->w_arg_idx == i) {
4741 if (keep_tabs) {
4742 new_curwin = wp;
4743 new_curtab = curtab;
4744 } else {
4745 win_move_after(wp, curwin);
4746 }
4747 break;
4748 }
4749 }
4750 }
4751 } else if (split_ret == OK) {
4752 if (!use_firstwin) { // split current window
4753 p_ea_save = p_ea;
4754 p_ea = true; // use space from all windows
4755 split_ret = win_split(0, WSP_ROOM | WSP_BELOW);
4756 p_ea = p_ea_save;
4757 if (split_ret == FAIL) {
4758 continue;
4759 }
4760 } else { // first window: do autocmd for leaving this buffer
4761 autocmd_no_leave--;
4762 }
4763
4764 /*
4765 * edit file "i"
4766 */
4767 curwin->w_arg_idx = i;
4768 if (i == 0) {
4769 new_curwin = curwin;
4770 new_curtab = curtab;
4771 }
4772 (void)do_ecmd(0, alist_name(&AARGLIST(alist)[i]), NULL, NULL, ECMD_ONE,
4773 ((buf_hide(curwin->w_buffer)
4774 || bufIsChanged(curwin->w_buffer))
4775 ? ECMD_HIDE : 0) + ECMD_OLDBUF,
4776 curwin);
4777 if (use_firstwin) {
4778 autocmd_no_leave++;
4779 }
4780 use_firstwin = false;
4781 }
4782 os_breakcheck();
4783
4784 // When ":tab" was used open a new tab for a new window repeatedly.
4785 if (had_tab > 0 && tabpage_index(NULL) <= p_tpm) {
4786 cmdmod.tab = 9999;
4787 }
4788 }
4789
4790 // Remove the "lock" on the argument list.
4791 alist_unlink(alist);
4792
4793 autocmd_no_enter--;
4794 // restore last referenced tabpage's curwin
4795 if (last_curtab != new_curtab) {
4796 if (valid_tabpage(last_curtab)) {
4797 goto_tabpage_tp(last_curtab, true, true);
4798 }
4799 if (win_valid(last_curwin)) {
4800 win_enter(last_curwin, false);
4801 }
4802 }
4803 // to window with first arg
4804 if (valid_tabpage(new_curtab)) {
4805 goto_tabpage_tp(new_curtab, true, true);
4806 }
4807 if (win_valid(new_curwin)) {
4808 win_enter(new_curwin, false);
4809 }
4810
4811 autocmd_no_leave--;
4812 xfree(opened);
4813}
4814
4815/*
4816 * Open a window for a number of buffers.
4817 */
4818void ex_buffer_all(exarg_T *eap)
4819{
4820 buf_T *buf;
4821 win_T *wp, *wpnext;
4822 int split_ret = OK;
4823 bool p_ea_save;
4824 int open_wins = 0;
4825 int r;
4826 long count; // Maximum number of windows to open.
4827 int all; // When true also load inactive buffers.
4828 int had_tab = cmdmod.tab;
4829 tabpage_T *tpnext;
4830
4831 if (eap->addr_count == 0) { // make as many windows as possible
4832 count = 9999;
4833 } else {
4834 count = eap->line2; // make as many windows as specified
4835 }
4836 if (eap->cmdidx == CMD_unhide || eap->cmdidx == CMD_sunhide) {
4837 all = false;
4838 } else {
4839 all = true;
4840 }
4841
4842 setpcmark();
4843
4844
4845 /*
4846 * Close superfluous windows (two windows for the same buffer).
4847 * Also close windows that are not full-width.
4848 */
4849 if (had_tab > 0) {
4850 goto_tabpage_tp(first_tabpage, true, true);
4851 }
4852 for (;; ) {
4853 tpnext = curtab->tp_next;
4854 for (wp = firstwin; wp != NULL; wp = wpnext) {
4855 wpnext = wp->w_next;
4856 if ((wp->w_buffer->b_nwindows > 1
4857 || ((cmdmod.split & WSP_VERT)
4858 ? wp->w_height + wp->w_status_height < Rows - p_ch
4859 - tabline_height()
4860 : wp->w_width != Columns)
4861 || (had_tab > 0 && wp != firstwin))
4862 && !ONE_WINDOW
4863 && !(wp->w_closing || wp->w_buffer->b_locked > 0)
4864 ) {
4865 win_close(wp, false);
4866 wpnext = firstwin; // just in case an autocommand does
4867 // something strange with windows
4868 tpnext = first_tabpage; // start all over...
4869 open_wins = 0;
4870 } else {
4871 open_wins++;
4872 }
4873 }
4874
4875 // Without the ":tab" modifier only do the current tab page.
4876 if (had_tab == 0 || tpnext == NULL) {
4877 break;
4878 }
4879 goto_tabpage_tp(tpnext, true, true);
4880 }
4881
4882 //
4883 // Go through the buffer list. When a buffer doesn't have a window yet,
4884 // open one. Otherwise move the window to the right position.
4885 // Watch out for autocommands that delete buffers or windows!
4886 //
4887 // Don't execute Win/Buf Enter/Leave autocommands here.
4888 autocmd_no_enter++;
4889 win_enter(lastwin, false);
4890 autocmd_no_leave++;
4891 for (buf = firstbuf; buf != NULL && open_wins < count; buf = buf->b_next) {
4892 // Check if this buffer needs a window
4893 if ((!all && buf->b_ml.ml_mfp == NULL) || !buf->b_p_bl) {
4894 continue;
4895 }
4896
4897 if (had_tab != 0) {
4898 // With the ":tab" modifier don't move the window.
4899 if (buf->b_nwindows > 0) {
4900 wp = lastwin; // buffer has a window, skip it
4901 } else {
4902 wp = NULL;
4903 }
4904 } else {
4905 // Check if this buffer already has a window
4906 for (wp = firstwin; wp != NULL; wp = wp->w_next) {
4907 if (wp->w_buffer == buf) {
4908 break;
4909 }
4910 }
4911 // If the buffer already has a window, move it
4912 if (wp != NULL) {
4913 win_move_after(wp, curwin);
4914 }
4915 }
4916
4917 if (wp == NULL && split_ret == OK) {
4918 bufref_T bufref;
4919 set_bufref(&bufref, buf);
4920 // Split the window and put the buffer in it.
4921 p_ea_save = p_ea;
4922 p_ea = true; // use space from all windows
4923 split_ret = win_split(0, WSP_ROOM | WSP_BELOW);
4924 open_wins++;
4925 p_ea = p_ea_save;
4926 if (split_ret == FAIL) {
4927 continue;
4928 }
4929
4930 // Open the buffer in this window.
4931 swap_exists_action = SEA_DIALOG;
4932 set_curbuf(buf, DOBUF_GOTO);
4933 if (!bufref_valid(&bufref)) {
4934 // Autocommands deleted the buffer.
4935 swap_exists_action = SEA_NONE;
4936 break;
4937 }
4938 if (swap_exists_action == SEA_QUIT) {
4939 cleanup_T cs;
4940
4941 // Reset the error/interrupt/exception state here so that
4942 // aborting() returns false when closing a window.
4943 enter_cleanup(&cs);
4944
4945 // User selected Quit at ATTENTION prompt; close this window.
4946 win_close(curwin, true);
4947 open_wins--;
4948 swap_exists_action = SEA_NONE;
4949 swap_exists_did_quit = true;
4950
4951 /* Restore the error/interrupt/exception state if not
4952 * discarded by a new aborting error, interrupt, or uncaught
4953 * exception. */
4954 leave_cleanup(&cs);
4955 } else
4956 handle_swap_exists(NULL);
4957 }
4958
4959 os_breakcheck();
4960 if (got_int) {
4961 (void)vgetc(); // only break the file loading, not the rest
4962 break;
4963 }
4964 // Autocommands deleted the buffer or aborted script processing!!!
4965 if (aborting()) {
4966 break;
4967 }
4968 // When ":tab" was used open a new tab for a new window repeatedly.
4969 if (had_tab > 0 && tabpage_index(NULL) <= p_tpm) {
4970 cmdmod.tab = 9999;
4971 }
4972 }
4973 autocmd_no_enter--;
4974 win_enter(firstwin, false); // back to first window
4975 autocmd_no_leave--;
4976
4977 /*
4978 * Close superfluous windows.
4979 */
4980 for (wp = lastwin; open_wins > count; ) {
4981 r = (buf_hide(wp->w_buffer) || !bufIsChanged(wp->w_buffer)
4982 || autowrite(wp->w_buffer, false) == OK);
4983 if (!win_valid(wp)) {
4984 // BufWrite Autocommands made the window invalid, start over
4985 wp = lastwin;
4986 } else if (r) {
4987 win_close(wp, !buf_hide(wp->w_buffer));
4988 open_wins--;
4989 wp = lastwin;
4990 } else {
4991 wp = wp->w_prev;
4992 if (wp == NULL) {
4993 break;
4994 }
4995 }
4996 }
4997}
4998
4999
5000
5001/*
5002 * do_modelines() - process mode lines for the current file
5003 *
5004 * "flags" can be:
5005 * OPT_WINONLY only set options local to window
5006 * OPT_NOWIN don't set options local to window
5007 *
5008 * Returns immediately if the "ml" option isn't set.
5009 */
5010void do_modelines(int flags)
5011{
5012 linenr_T lnum;
5013 int nmlines;
5014 static int entered = 0;
5015
5016 if (!curbuf->b_p_ml || (nmlines = (int)p_mls) == 0) {
5017 return;
5018 }
5019
5020 /* Disallow recursive entry here. Can happen when executing a modeline
5021 * triggers an autocommand, which reloads modelines with a ":do". */
5022 if (entered) {
5023 return;
5024 }
5025
5026 entered++;
5027 for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count && lnum <= nmlines;
5028 lnum++) {
5029 if (chk_modeline(lnum, flags) == FAIL) {
5030 nmlines = 0;
5031 }
5032 }
5033
5034 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0 && lnum > nmlines
5035 && lnum > curbuf->b_ml.ml_line_count - nmlines; lnum--) {
5036 if (chk_modeline(lnum, flags) == FAIL) {
5037 nmlines = 0;
5038 }
5039 }
5040 entered--;
5041}
5042
5043/*
5044 * chk_modeline() - check a single line for a mode string
5045 * Return FAIL if an error encountered.
5046 */
5047static int
5048chk_modeline(
5049 linenr_T lnum,
5050 int flags // Same as for do_modelines().
5051)
5052{
5053 char_u *s;
5054 char_u *e;
5055 char_u *linecopy; // local copy of any modeline found
5056 int prev;
5057 intmax_t vers;
5058 int end;
5059 int retval = OK;
5060 char_u *save_sourcing_name;
5061 linenr_T save_sourcing_lnum;
5062
5063 prev = -1;
5064 for (s = ml_get(lnum); *s != NUL; s++) {
5065 if (prev == -1 || ascii_isspace(prev)) {
5066 if ((prev != -1 && STRNCMP(s, "ex:", (size_t)3) == 0)
5067 || STRNCMP(s, "vi:", (size_t)3) == 0)
5068 break;
5069 // Accept both "vim" and "Vim".
5070 if ((s[0] == 'v' || s[0] == 'V') && s[1] == 'i' && s[2] == 'm') {
5071 if (s[3] == '<' || s[3] == '=' || s[3] == '>') {
5072 e = s + 4;
5073 } else {
5074 e = s + 3;
5075 }
5076 if (!try_getdigits(&e, &vers)) {
5077 continue;
5078 }
5079
5080 if (*e == ':'
5081 && (s[0] != 'V'
5082 || STRNCMP(skipwhite(e + 1), "set", 3) == 0)
5083 && (s[3] == ':'
5084 || (VIM_VERSION_100 >= vers && isdigit(s[3]))
5085 || (VIM_VERSION_100 < vers && s[3] == '<')
5086 || (VIM_VERSION_100 > vers && s[3] == '>')
5087 || (VIM_VERSION_100 == vers && s[3] == '='))) {
5088 break;
5089 }
5090 }
5091 }
5092 prev = *s;
5093 }
5094
5095 if (!*s) {
5096 return retval;
5097 }
5098
5099 do { // skip over "ex:", "vi:" or "vim:"
5100 s++;
5101 } while (s[-1] != ':');
5102
5103 s = linecopy = vim_strsave(s); // copy the line, it will change
5104
5105 save_sourcing_lnum = sourcing_lnum;
5106 save_sourcing_name = sourcing_name;
5107 sourcing_lnum = lnum; // prepare for emsg()
5108 sourcing_name = (char_u *)"modelines";
5109
5110 end = false;
5111 while (end == false) {
5112 s = skipwhite(s);
5113 if (*s == NUL) {
5114 break;
5115 }
5116
5117 /*
5118 * Find end of set command: ':' or end of line.
5119 * Skip over "\:", replacing it with ":".
5120 */
5121 for (e = s; *e != ':' && *e != NUL; e++) {
5122 if (e[0] == '\\' && e[1] == ':') {
5123 STRMOVE(e, e + 1);
5124 }
5125 }
5126 if (*e == NUL) {
5127 end = true;
5128 }
5129
5130 /*
5131 * If there is a "set" command, require a terminating ':' and
5132 * ignore the stuff after the ':'.
5133 * "vi:set opt opt opt: foo" -- foo not interpreted
5134 * "vi:opt opt opt: foo" -- foo interpreted
5135 * Accept "se" for compatibility with Elvis.
5136 */
5137 if (STRNCMP(s, "set ", (size_t)4) == 0
5138 || STRNCMP(s, "se ", (size_t)3) == 0) {
5139 if (*e != ':') { // no terminating ':'?
5140 break;
5141 }
5142 end = true;
5143 s = vim_strchr(s, ' ') + 1;
5144 }
5145 *e = NUL; // truncate the set command
5146
5147 if (*s != NUL) { // skip over an empty "::"
5148 const int secure_save = secure;
5149 const sctx_T save_current_sctx = current_sctx;
5150 current_sctx.sc_sid = SID_MODELINE;
5151 current_sctx.sc_seq = 0;
5152 current_sctx.sc_lnum = 0;
5153 // Make sure no risky things are executed as a side effect.
5154 secure = 1;
5155
5156 retval = do_set(s, OPT_MODELINE | OPT_LOCAL | flags);
5157
5158 secure = secure_save;
5159 current_sctx = save_current_sctx;
5160 if (retval == FAIL) { // stop if error found
5161 break;
5162 }
5163 }
5164 s = e + 1; // advance to next part
5165 }
5166
5167 sourcing_lnum = save_sourcing_lnum;
5168 sourcing_name = save_sourcing_name;
5169
5170 xfree(linecopy);
5171
5172 return retval;
5173}
5174
5175// Return true if "buf" is a help buffer.
5176bool bt_help(const buf_T *const buf)
5177 FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
5178{
5179 return buf != NULL && buf->b_help;
5180}
5181
5182// Return true if "buf" is the quickfix buffer.
5183bool bt_quickfix(const buf_T *const buf)
5184 FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
5185{
5186 return buf != NULL && buf->b_p_bt[0] == 'q';
5187}
5188
5189// Return true if "buf" is a terminal buffer.
5190bool bt_terminal(const buf_T *const buf)
5191 FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
5192{
5193 return buf != NULL && buf->b_p_bt[0] == 't';
5194}
5195
5196// Return true if "buf" is a "nofile", "acwrite" or "terminal" buffer.
5197// This means the buffer name is not a file name.
5198bool bt_nofile(const buf_T *const buf)
5199 FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
5200{
5201 return buf != NULL && ((buf->b_p_bt[0] == 'n' && buf->b_p_bt[2] == 'f')
5202 || buf->b_p_bt[0] == 'a' || buf->terminal);
5203}
5204
5205// Return true if "buf" is a "nowrite", "nofile" or "terminal" buffer.
5206bool bt_dontwrite(const buf_T *const buf)
5207 FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
5208{
5209 return buf != NULL && (buf->b_p_bt[0] == 'n' || buf->terminal);
5210}
5211
5212bool bt_dontwrite_msg(const buf_T *const buf)
5213 FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
5214{
5215 if (bt_dontwrite(buf)) {
5216 EMSG(_("E382: Cannot write, 'buftype' option is set"));
5217 return true;
5218 }
5219 return false;
5220}
5221
5222// Return true if the buffer should be hidden, according to 'hidden', ":hide"
5223// and 'bufhidden'.
5224bool buf_hide(const buf_T *const buf)
5225{
5226 // 'bufhidden' overrules 'hidden' and ":hide", check it first
5227 switch (buf->b_p_bh[0]) {
5228 case 'u': // "unload"
5229 case 'w': // "wipe"
5230 case 'd': return false; // "delete"
5231 case 'h': return true; // "hide"
5232 }
5233 return p_hid || cmdmod.hide;
5234}
5235
5236/*
5237 * Return special buffer name.
5238 * Returns NULL when the buffer has a normal file name.
5239 */
5240char_u *buf_spname(buf_T *buf)
5241{
5242 if (bt_quickfix(buf)) {
5243 win_T *win;
5244 tabpage_T *tp;
5245
5246 /*
5247 * For location list window, w_llist_ref points to the location list.
5248 * For quickfix window, w_llist_ref is NULL.
5249 */
5250 if (find_win_for_buf(buf, &win, &tp) && win->w_llist_ref != NULL) {
5251 return (char_u *)_(msg_loclist);
5252 } else {
5253 return (char_u *)_(msg_qflist);
5254 }
5255 }
5256 // There is no _file_ when 'buftype' is "nofile", b_sfname
5257 // contains the name as specified by the user.
5258 if (bt_nofile(buf)) {
5259 if (buf->b_fname != NULL) {
5260 return buf->b_fname;
5261 }
5262 return (char_u *)_("[Scratch]");
5263 }
5264 if (buf->b_fname == NULL) {
5265 return (char_u *)_("[No Name]");
5266 }
5267 return NULL;
5268}
5269
5270/// Find a window for buffer "buf".
5271/// If found true is returned and "wp" and "tp" are set to
5272/// the window and tabpage.
5273/// If not found, false is returned.
5274///
5275/// @param buf buffer to find a window for
5276/// @param[out] wp stores the found window
5277/// @param[out] tp stores the found tabpage
5278///
5279/// @return true if a window was found for the buffer.
5280bool find_win_for_buf(buf_T *buf, win_T **wp, tabpage_T **tp)
5281{
5282 *wp = NULL;
5283 *tp = NULL;
5284 FOR_ALL_TAB_WINDOWS(tp2, wp2) {
5285 if (wp2->w_buffer == buf) {
5286 *tp = tp2;
5287 *wp = wp2;
5288 return true;
5289 }
5290 }
5291 return false;
5292}
5293
5294int buf_signcols(buf_T *buf)
5295{
5296 if (buf->b_signcols_max == -1) {
5297 signlist_T *sign; // a sign in the signlist
5298 buf->b_signcols_max = 0;
5299 int linesum = 0;
5300 linenr_T curline = 0;
5301
5302 FOR_ALL_SIGNS_IN_BUF(buf, sign) {
5303 if (sign->lnum > curline) {
5304 if (linesum > buf->b_signcols_max) {
5305 buf->b_signcols_max = linesum;
5306 }
5307 curline = sign->lnum;
5308 linesum = 0;
5309 }
5310 linesum++;
5311 }
5312 if (linesum > buf->b_signcols_max) {
5313 buf->b_signcols_max = linesum;
5314 }
5315
5316 // Check if we need to redraw
5317 if (buf->b_signcols_max != buf->b_signcols) {
5318 buf->b_signcols = buf->b_signcols_max;
5319 redraw_buf_later(buf, NOT_VALID);
5320 }
5321 }
5322
5323 return buf->b_signcols;
5324}
5325
5326// bufhl: plugin highlights associated with a buffer
5327
5328/// Get reference to line in kbtree_t
5329///
5330/// @param b the three
5331/// @param line the linenumber to lookup
5332/// @param put if true, put a new line when not found
5333/// if false, return NULL when not found
5334BufhlLine *bufhl_tree_ref(BufhlInfo *b, linenr_T line, bool put)
5335{
5336 BufhlLine t = BUFHLLINE_INIT(line);
5337
5338 // kp_put() only works if key is absent, try get first
5339 BufhlLine **pp = kb_get(bufhl, b, &t);
5340 if (pp) {
5341 return *pp;
5342 } else if (!put) {
5343 return NULL;
5344 }
5345
5346 BufhlLine *p = xmalloc(sizeof(*p));
5347 *p = (BufhlLine)BUFHLLINE_INIT(line);
5348 kb_put(bufhl, b, p);
5349 return p;
5350}
5351
5352/// Adds a highlight to buffer.
5353///
5354/// Unlike matchaddpos() highlights follow changes to line numbering (as lines
5355/// are inserted/removed above the highlighted line), like signs and marks do.
5356///
5357/// When called with "src_id" set to 0, a unique source id is generated and
5358/// returned. Succesive calls can pass it in as "src_id" to add new highlights
5359/// to the same source group. All highlights in the same group can be cleared
5360/// at once. If the highlight never will be manually deleted pass in -1 for
5361/// "src_id"
5362///
5363/// if "hl_id" or "lnum" is invalid no highlight is added, but a new src_id
5364/// is still returned.
5365///
5366/// @param buf The buffer to add highlights to
5367/// @param src_id src_id to use or 0 to use a new src_id group,
5368/// or -1 for ungrouped highlight.
5369/// @param hl_id Id of the highlight group to use
5370/// @param lnum The line to highlight
5371/// @param col_start First column to highlight
5372/// @param col_end The last column to highlight,
5373/// or -1 to highlight to end of line
5374/// @return The src_id that was used
5375int bufhl_add_hl(buf_T *buf,
5376 int src_id,
5377 int hl_id,
5378 linenr_T lnum,
5379 colnr_T col_start,
5380 colnr_T col_end)
5381{
5382 if (src_id == 0) {
5383 src_id = (int)nvim_create_namespace((String)STRING_INIT);
5384 }
5385 if (hl_id <= 0) {
5386 // no highlight group or invalid line, just return src_id
5387 return src_id;
5388 }
5389
5390 BufhlLine *lineinfo = bufhl_tree_ref(&buf->b_bufhl_info, lnum, true);
5391
5392 BufhlItem *hlentry = kv_pushp(lineinfo->items);
5393 hlentry->src_id = src_id;
5394 hlentry->hl_id = hl_id;
5395 hlentry->start = col_start;
5396 hlentry->stop = col_end;
5397
5398 if (0 < lnum && lnum <= buf->b_ml.ml_line_count) {
5399 redraw_buf_line_later(buf, lnum);
5400 }
5401 return src_id;
5402}
5403
5404/// Add highlighting to a buffer, bounded by two cursor positions,
5405/// with an offset.
5406///
5407/// @param buf Buffer to add highlights to
5408/// @param src_id src_id to use or 0 to use a new src_id group,
5409/// or -1 for ungrouped highlight.
5410/// @param hl_id Highlight group id
5411/// @param pos_start Cursor position to start the hightlighting at
5412/// @param pos_end Cursor position to end the highlighting at
5413/// @param offset Move the whole highlighting this many columns to the right
5414void bufhl_add_hl_pos_offset(buf_T *buf,
5415 int src_id,
5416 int hl_id,
5417 lpos_T pos_start,
5418 lpos_T pos_end,
5419 colnr_T offset)
5420{
5421 colnr_T hl_start = 0;
5422 colnr_T hl_end = 0;
5423
5424 for (linenr_T lnum = pos_start.lnum; lnum <= pos_end.lnum; lnum ++) {
5425 if (pos_start.lnum < lnum && lnum < pos_end.lnum) {
5426 hl_start = offset;
5427 hl_end = MAXCOL;
5428 } else if (lnum == pos_start.lnum && lnum < pos_end.lnum) {
5429 hl_start = pos_start.col + offset + 1;
5430 hl_end = MAXCOL;
5431 } else if (pos_start.lnum < lnum && lnum == pos_end.lnum) {
5432 hl_start = offset;
5433 hl_end = pos_end.col + offset;
5434 } else if (pos_start.lnum == lnum && pos_end.lnum == lnum) {
5435 hl_start = pos_start.col + offset + 1;
5436 hl_end = pos_end.col + offset;
5437 }
5438 (void)bufhl_add_hl(buf, src_id, hl_id, lnum, hl_start, hl_end);
5439 }
5440}
5441
5442int bufhl_add_virt_text(buf_T *buf,
5443 int src_id,
5444 linenr_T lnum,
5445 VirtText virt_text)
5446{
5447 if (src_id == 0) {
5448 src_id = (int)nvim_create_namespace((String)STRING_INIT);
5449 }
5450
5451 BufhlLine *lineinfo = bufhl_tree_ref(&buf->b_bufhl_info, lnum, true);
5452
5453 bufhl_clear_virttext(&lineinfo->virt_text);
5454 if (kv_size(virt_text) > 0) {
5455 lineinfo->virt_text_src = src_id;
5456 lineinfo->virt_text = virt_text;
5457 } else {
5458 lineinfo->virt_text_src = 0;
5459 // currently not needed, but allow a future caller with
5460 // 0 size and non-zero capacity
5461 kv_destroy(virt_text);
5462 }
5463
5464 if (0 < lnum && lnum <= buf->b_ml.ml_line_count) {
5465 redraw_buf_line_later(buf, lnum);
5466 }
5467 return src_id;
5468}
5469
5470static void bufhl_clear_virttext(VirtText *text)
5471{
5472 for (size_t i = 0; i < kv_size(*text); i++) {
5473 xfree(kv_A(*text, i).text);
5474 }
5475 kv_destroy(*text);
5476 *text = (VirtText)KV_INITIAL_VALUE;
5477}
5478
5479/// Clear bufhl highlights from a given source group and range of lines.
5480///
5481/// @param buf The buffer to remove highlights from
5482/// @param src_id highlight source group to clear, or -1 to clear all groups.
5483/// @param line_start first line to clear
5484/// @param line_end last line to clear or MAXLNUM to clear to end of file.
5485void bufhl_clear_line_range(buf_T *buf,
5486 int src_id,
5487 linenr_T line_start,
5488 linenr_T line_end)
5489{
5490 kbitr_t(bufhl) itr;
5491 BufhlLine *l, t = BUFHLLINE_INIT(line_start);
5492 if (!kb_itr_get(bufhl, &buf->b_bufhl_info, &t, &itr)) {
5493 kb_itr_next(bufhl, &buf->b_bufhl_info, &itr);
5494 }
5495 for (; kb_itr_valid(&itr); kb_itr_next(bufhl, &buf->b_bufhl_info, &itr)) {
5496 l = kb_itr_key(&itr);
5497 linenr_T line = l->line;
5498 if (line > line_end) {
5499 break;
5500 }
5501 if (line_start <= line) {
5502 BufhlLineStatus status = bufhl_clear_line(l, src_id, line);
5503 if (status != kBLSUnchanged) {
5504 redraw_buf_line_later(buf, line);
5505 }
5506 if (status == kBLSDeleted) {
5507 kb_del_itr(bufhl, &buf->b_bufhl_info, &itr);
5508 xfree(l);
5509 }
5510 }
5511 }
5512}
5513
5514/// Clear bufhl highlights from a given source group and given line
5515///
5516/// @param bufhl_info The highlight info for the buffer
5517/// @param src_id Highlight source group to clear, or -1 to clear all groups.
5518/// @param lnum Linenr where the highlight should be cleared
5519static BufhlLineStatus bufhl_clear_line(BufhlLine *lineinfo, int src_id,
5520 linenr_T lnum)
5521{
5522 BufhlLineStatus changed = kBLSUnchanged;
5523 size_t oldsize = kv_size(lineinfo->items);
5524 if (src_id < 0) {
5525 kv_size(lineinfo->items) = 0;
5526 } else {
5527 size_t newidx = 0;
5528 for (size_t i = 0; i < kv_size(lineinfo->items); i++) {
5529 if (kv_A(lineinfo->items, i).src_id != src_id) {
5530 if (i != newidx) {
5531 kv_A(lineinfo->items, newidx) = kv_A(lineinfo->items, i);
5532 }
5533 newidx++;
5534 }
5535 }
5536 kv_size(lineinfo->items) = newidx;
5537 }
5538 if (kv_size(lineinfo->items) != oldsize) {
5539 changed = kBLSChanged;
5540 }
5541
5542 if (kv_size(lineinfo->virt_text) != 0
5543 && (src_id < 0 || src_id == lineinfo->virt_text_src)) {
5544 bufhl_clear_virttext(&lineinfo->virt_text);
5545 lineinfo->virt_text_src = 0;
5546 changed = kBLSChanged;
5547 }
5548
5549 if (kv_size(lineinfo->items) == 0 && kv_size(lineinfo->virt_text) == 0) {
5550 kv_destroy(lineinfo->items);
5551 return kBLSDeleted;
5552 }
5553 return changed;
5554}
5555
5556
5557/// Remove all highlights and free the highlight data
5558void bufhl_clear_all(buf_T *buf)
5559{
5560 bufhl_clear_line_range(buf, -1, 1, MAXLNUM);
5561 kb_destroy(bufhl, (&buf->b_bufhl_info));
5562 kb_init(&buf->b_bufhl_info);
5563 kv_destroy(buf->b_bufhl_move_space);
5564 kv_init(buf->b_bufhl_move_space);
5565}
5566
5567/// Adjust a placed highlight for inserted/deleted lines.
5568void bufhl_mark_adjust(buf_T* buf,
5569 linenr_T line1,
5570 linenr_T line2,
5571 long amount,
5572 long amount_after,
5573 bool end_temp)
5574{
5575 kbitr_t(bufhl) itr;
5576 BufhlLine *l, t = BUFHLLINE_INIT(line1);
5577 if (end_temp && amount < 0) {
5578 // Move all items from b_bufhl_move_space to the btree.
5579 for (size_t i = 0; i < kv_size(buf->b_bufhl_move_space); i++) {
5580 l = kv_A(buf->b_bufhl_move_space, i);
5581 l->line += amount;
5582 kb_put(bufhl, &buf->b_bufhl_info, l);
5583 }
5584 kv_size(buf->b_bufhl_move_space) = 0;
5585 return;
5586 }
5587
5588 if (!kb_itr_get(bufhl, &buf->b_bufhl_info, &t, &itr)) {
5589 kb_itr_next(bufhl, &buf->b_bufhl_info, &itr);
5590 }
5591 for (; kb_itr_valid(&itr); kb_itr_next(bufhl, &buf->b_bufhl_info, &itr)) {
5592 l = kb_itr_key(&itr);
5593 if (l->line >= line1 && l->line <= line2) {
5594 if (end_temp && amount > 0) {
5595 kb_del_itr(bufhl, &buf->b_bufhl_info, &itr);
5596 kv_push(buf->b_bufhl_move_space, l);
5597 }
5598 if (amount == MAXLNUM) {
5599 if (bufhl_clear_line(l, -1, l->line) == kBLSDeleted) {
5600 kb_del_itr(bufhl, &buf->b_bufhl_info, &itr);
5601 xfree(l);
5602 } else {
5603 assert(false);
5604 }
5605 } else {
5606 l->line += amount;
5607 }
5608 } else if (l->line > line2) {
5609 if (amount_after == 0) {
5610 break;
5611 }
5612 l->line += amount_after;
5613 }
5614 }
5615}
5616
5617
5618/// Get highlights to display at a specific line
5619///
5620/// @param buf The buffer handle
5621/// @param lnum The line number
5622/// @param[out] info The highligts for the line
5623/// @return true if there was highlights to display
5624bool bufhl_start_line(buf_T *buf, linenr_T lnum, BufhlLineInfo *info)
5625{
5626 BufhlLine *lineinfo = bufhl_tree_ref(&buf->b_bufhl_info, lnum, false);
5627 if (!lineinfo) {
5628 return false;
5629 }
5630 info->valid_to = -1;
5631 info->line = lineinfo;
5632 return true;
5633}
5634
5635/// get highlighting at column col
5636///
5637/// It is is assumed this will be called with
5638/// non-decreasing column nrs, so that it is
5639/// possible to only recalculate highlights
5640/// at endpoints.
5641///
5642/// @param info The info returned by bufhl_start_line
5643/// @param col The column to get the attr for
5644/// @return The highilight attr to display at the column
5645int bufhl_get_attr(BufhlLineInfo *info, colnr_T col)
5646{
5647 if (col <= info->valid_to) {
5648 return info->current;
5649 }
5650 int attr = 0;
5651 info->valid_to = MAXCOL;
5652 for (size_t i = 0; i < kv_size(info->line->items); i++) {
5653 BufhlItem entry = kv_A(info->line->items, i);
5654 if (entry.start <= col && col <= entry.stop) {
5655 int entry_attr = syn_id2attr(entry.hl_id);
5656 attr = hl_combine_attr(attr, entry_attr);
5657 if (entry.stop < info->valid_to) {
5658 info->valid_to = entry.stop;
5659 }
5660 } else if (col < entry.start && entry.start-1 < info->valid_to) {
5661 info->valid_to = entry.start-1;
5662 }
5663 }
5664 info->current = attr;
5665 return attr;
5666}
5667
5668
5669/*
5670 * Set 'buflisted' for curbuf to "on" and trigger autocommands if it changed.
5671 */
5672void set_buflisted(int on)
5673{
5674 if (on != curbuf->b_p_bl) {
5675 curbuf->b_p_bl = on;
5676 if (on) {
5677 apply_autocmds(EVENT_BUFADD, NULL, NULL, false, curbuf);
5678 } else {
5679 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, false, curbuf);
5680 }
5681 }
5682}
5683
5684/// Read the file for "buf" again and check if the contents changed.
5685/// Return true if it changed or this could not be checked.
5686///
5687/// @param buf buffer to check
5688///
5689/// @return true if the buffer's contents have changed
5690bool buf_contents_changed(buf_T *buf)
5691 FUNC_ATTR_NONNULL_ALL
5692{
5693 bool differ = true;
5694
5695 // Allocate a buffer without putting it in the buffer list.
5696 buf_T *newbuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
5697 if (newbuf == NULL) {
5698 return true;
5699 }
5700
5701 // Force the 'fileencoding' and 'fileformat' to be equal.
5702 exarg_T ea;
5703 prep_exarg(&ea, buf);
5704
5705 // set curwin/curbuf to buf and save a few things
5706 aco_save_T aco;
5707 aucmd_prepbuf(&aco, newbuf);
5708
5709 if (ml_open(curbuf) == OK
5710 && readfile(buf->b_ffname, buf->b_fname,
5711 (linenr_T)0, (linenr_T)0, (linenr_T)MAXLNUM,
5712 &ea, READ_NEW | READ_DUMMY) == OK) {
5713 // compare the two files line by line
5714 if (buf->b_ml.ml_line_count == curbuf->b_ml.ml_line_count) {
5715 differ = false;
5716 for (linenr_T lnum = 1; lnum <= curbuf->b_ml.ml_line_count; lnum++) {
5717 if (STRCMP(ml_get_buf(buf, lnum, false), ml_get(lnum)) != 0) {
5718 differ = true;
5719 break;
5720 }
5721 }
5722 }
5723 }
5724 xfree(ea.cmd);
5725
5726 // restore curwin/curbuf and a few other things
5727 aucmd_restbuf(&aco);
5728
5729 if (curbuf != newbuf) { // safety check
5730 wipe_buffer(newbuf, false);
5731 }
5732
5733 return differ;
5734}
5735
5736/*
5737 * Wipe out a buffer and decrement the last buffer number if it was used for
5738 * this buffer. Call this to wipe out a temp buffer that does not contain any
5739 * marks.
5740 */
5741void
5742wipe_buffer(
5743 buf_T *buf,
5744 int aucmd // When true trigger autocommands.
5745)
5746{
5747 if (!aucmd) {
5748 // Don't trigger BufDelete autocommands here.
5749 block_autocmds();
5750 }
5751 close_buffer(NULL, buf, DOBUF_WIPE, false);
5752 if (!aucmd) {
5753 unblock_autocmds();
5754 }
5755}
5756
5757/// Creates or switches to a scratch buffer. :h special-buffers
5758/// Scratch buffer is:
5759/// - buftype=nofile bufhidden=hide noswapfile
5760/// - Always considered 'nomodified'
5761///
5762/// @param bufnr Buffer to switch to, or 0 to create a new buffer.
5763///
5764/// @see curbufIsChanged()
5765void buf_open_scratch(handle_T bufnr, char *bufname)
5766{
5767 (void)do_ecmd((int)bufnr, NULL, NULL, NULL, ECMD_ONE, ECMD_HIDE, NULL);
5768 (void)setfname(curbuf, (char_u *)bufname, NULL, true);
5769 set_option_value("bh", 0L, "hide", OPT_LOCAL);
5770 set_option_value("bt", 0L, "nofile", OPT_LOCAL);
5771 set_option_value("swf", 0L, NULL, OPT_LOCAL);
5772 RESET_BINDING(curwin);
5773}
5774