Sync with newest CVS repository.
[MacVim/jjgod.git] / src / buffer.c
blob7d625f2e597f604b83a53db840a179967df0b747
1 /* vi:set ts=8 sts=4 sw=4:
3 * VIM - Vi IMproved by Bram Moolenaar
5 * Do ":help uganda" in Vim to read copying and usage conditions.
6 * Do ":help credits" in Vim to see a list of people who contributed.
7 * See README.txt for an overview of the Vim source code.
8 */
11 * buffer.c: functions for dealing with the buffer structure
15 * The buffer list is a double linked list of all buffers.
16 * Each buffer can be in one of these states:
17 * never loaded: BF_NEVERLOADED is set, only the file name is valid
18 * not loaded: b_ml.ml_mfp == NULL, no memfile allocated
19 * hidden: b_nwindows == 0, loaded but not displayed in a window
20 * normal: loaded and displayed in a window
22 * Instead of storing file names all over the place, each file name is
23 * stored in the buffer list. It can be referenced by a number.
25 * The current implementation remembers all file names ever used.
28 #include "vim.h"
30 #if defined(FEAT_CMDL_COMPL) || defined(FEAT_LISTCMDS) || defined(FEAT_EVAL) || defined(FEAT_PERL)
31 static char_u *buflist_match __ARGS((regprog_T *prog, buf_T *buf));
32 # define HAVE_BUFLIST_MATCH
33 static char_u *fname_match __ARGS((regprog_T *prog, char_u *name));
34 #endif
35 static void buflist_setfpos __ARGS((buf_T *buf, win_T *win, linenr_T lnum, colnr_T col, int copy_options));
36 static wininfo_T *find_wininfo __ARGS((buf_T *buf));
37 #ifdef UNIX
38 static buf_T *buflist_findname_stat __ARGS((char_u *ffname, struct stat *st));
39 static int otherfile_buf __ARGS((buf_T *buf, char_u *ffname, struct stat *stp));
40 static int buf_same_ino __ARGS((buf_T *buf, struct stat *stp));
41 #else
42 static int otherfile_buf __ARGS((buf_T *buf, char_u *ffname));
43 #endif
44 #ifdef FEAT_TITLE
45 static int ti_change __ARGS((char_u *str, char_u **last));
46 #endif
47 static void free_buffer __ARGS((buf_T *));
48 static void free_buffer_stuff __ARGS((buf_T *buf, int free_options));
49 static void clear_wininfo __ARGS((buf_T *buf));
51 #ifdef UNIX
52 # define dev_T dev_t
53 #else
54 # define dev_T unsigned
55 #endif
57 #if defined(FEAT_SIGNS)
58 static void insert_sign __ARGS((buf_T *buf, signlist_T *prev, signlist_T *next, int id, linenr_T lnum, int typenr));
59 static void buf_delete_signs __ARGS((buf_T *buf));
60 #endif
63 * Open current buffer, that is: open the memfile and read the file into memory
64 * return FAIL for failure, OK otherwise
66 int
67 open_buffer(read_stdin, eap)
68 int read_stdin; /* read file from stdin */
69 exarg_T *eap; /* for forced 'ff' and 'fenc' or NULL */
71 int retval = OK;
72 #ifdef FEAT_AUTOCMD
73 buf_T *old_curbuf;
74 #endif
77 * The 'readonly' flag is only set when BF_NEVERLOADED is being reset.
78 * When re-entering the same buffer, it should not change, because the
79 * user may have reset the flag by hand.
81 if (readonlymode && curbuf->b_ffname != NULL
82 && (curbuf->b_flags & BF_NEVERLOADED))
83 curbuf->b_p_ro = TRUE;
85 if (ml_open(curbuf) == FAIL)
88 * There MUST be a memfile, otherwise we can't do anything
89 * If we can't create one for the current buffer, take another buffer
91 close_buffer(NULL, curbuf, 0);
92 for (curbuf = firstbuf; curbuf != NULL; curbuf = curbuf->b_next)
93 if (curbuf->b_ml.ml_mfp != NULL)
94 break;
96 * if there is no memfile at all, exit
97 * This is OK, since there are no changes to loose.
99 if (curbuf == NULL)
101 EMSG(_("E82: Cannot allocate any buffer, exiting..."));
102 getout(2);
104 EMSG(_("E83: Cannot allocate buffer, using other one..."));
105 enter_buffer(curbuf);
106 return FAIL;
109 #ifdef FEAT_AUTOCMD
110 /* The autocommands in readfile() may change the buffer, but only AFTER
111 * reading the file. */
112 old_curbuf = curbuf;
113 modified_was_set = FALSE;
114 #endif
116 /* mark cursor position as being invalid */
117 changed_line_abv_curs();
119 if (curbuf->b_ffname != NULL
120 #ifdef FEAT_NETBEANS_INTG
121 && netbeansReadFile
122 #endif
125 #ifdef FEAT_NETBEANS_INTG
126 int oldFire = netbeansFireChanges;
128 netbeansFireChanges = 0;
129 #endif
130 retval = readfile(curbuf->b_ffname, curbuf->b_fname,
131 (linenr_T)0, (linenr_T)0, (linenr_T)MAXLNUM, eap, READ_NEW);
132 #ifdef FEAT_NETBEANS_INTG
133 netbeansFireChanges = oldFire;
134 #endif
135 /* Help buffer is filtered. */
136 if (curbuf->b_help)
137 fix_help_buffer();
139 else if (read_stdin)
141 int save_bin = curbuf->b_p_bin;
142 linenr_T line_count;
145 * First read the text in binary mode into the buffer.
146 * Then read from that same buffer and append at the end. This makes
147 * it possible to retry when 'fileformat' or 'fileencoding' was
148 * guessed wrong.
150 curbuf->b_p_bin = TRUE;
151 retval = readfile(NULL, NULL, (linenr_T)0,
152 (linenr_T)0, (linenr_T)MAXLNUM, NULL, READ_NEW + READ_STDIN);
153 curbuf->b_p_bin = save_bin;
154 if (retval == OK)
156 line_count = curbuf->b_ml.ml_line_count;
157 retval = readfile(NULL, NULL, (linenr_T)line_count,
158 (linenr_T)0, (linenr_T)MAXLNUM, eap, READ_BUFFER);
159 if (retval == OK)
161 /* Delete the binary lines. */
162 while (--line_count >= 0)
163 ml_delete((linenr_T)1, FALSE);
165 else
167 /* Delete the converted lines. */
168 while (curbuf->b_ml.ml_line_count > line_count)
169 ml_delete(line_count, FALSE);
171 /* Put the cursor on the first line. */
172 curwin->w_cursor.lnum = 1;
173 curwin->w_cursor.col = 0;
174 #ifdef FEAT_AUTOCMD
175 # ifdef FEAT_EVAL
176 apply_autocmds_retval(EVENT_STDINREADPOST, NULL, NULL, FALSE,
177 curbuf, &retval);
178 # else
179 apply_autocmds(EVENT_STDINREADPOST, NULL, NULL, FALSE, curbuf);
180 # endif
181 #endif
185 /* if first time loading this buffer, init b_chartab[] */
186 if (curbuf->b_flags & BF_NEVERLOADED)
187 (void)buf_init_chartab(curbuf, FALSE);
190 * Set/reset the Changed flag first, autocmds may change the buffer.
191 * Apply the automatic commands, before processing the modelines.
192 * So the modelines have priority over auto commands.
194 /* When reading stdin, the buffer contents always needs writing, so set
195 * the changed flag. Unless in readonly mode: "ls | gview -".
196 * When interrupted and 'cpoptions' contains 'i' set changed flag. */
197 if ((read_stdin && !readonlymode && !bufempty())
198 #ifdef FEAT_AUTOCMD
199 || modified_was_set /* ":set modified" used in autocmd */
200 # ifdef FEAT_EVAL
201 || (aborting() && vim_strchr(p_cpo, CPO_INTMOD) != NULL)
202 # endif
203 #endif
204 || (got_int && vim_strchr(p_cpo, CPO_INTMOD) != NULL))
205 changed();
206 else if (retval != FAIL)
207 unchanged(curbuf, FALSE);
208 save_file_ff(curbuf); /* keep this fileformat */
210 /* require "!" to overwrite the file, because it wasn't read completely */
211 #ifdef FEAT_EVAL
212 if (aborting())
213 #else
214 if (got_int)
215 #endif
216 curbuf->b_flags |= BF_READERR;
218 #ifdef FEAT_FOLDING
219 /* Need to update automatic folding. Do this before the autocommands,
220 * they may use the fold info. */
221 foldUpdateAll(curwin);
222 #endif
224 #ifdef FEAT_AUTOCMD
225 /* need to set w_topline, unless some autocommand already did that. */
226 if (!(curwin->w_valid & VALID_TOPLINE))
228 curwin->w_topline = 1;
229 # ifdef FEAT_DIFF
230 curwin->w_topfill = 0;
231 # endif
233 # ifdef FEAT_EVAL
234 apply_autocmds_retval(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf, &retval);
235 # else
236 apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf);
237 # endif
238 #endif
240 if (retval != FAIL)
242 #ifdef FEAT_AUTOCMD
244 * The autocommands may have changed the current buffer. Apply the
245 * modelines to the correct buffer, if it still exists and is loaded.
247 if (buf_valid(old_curbuf) && old_curbuf->b_ml.ml_mfp != NULL)
249 aco_save_T aco;
251 /* Go to the buffer that was opened. */
252 aucmd_prepbuf(&aco, old_curbuf);
253 #endif
254 do_modelines(0);
255 curbuf->b_flags &= ~(BF_CHECK_RO | BF_NEVERLOADED);
257 #ifdef FEAT_AUTOCMD
258 # ifdef FEAT_EVAL
259 apply_autocmds_retval(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf,
260 &retval);
261 # else
262 apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
263 # endif
265 /* restore curwin/curbuf and a few other things */
266 aucmd_restbuf(&aco);
268 #endif
271 return retval;
275 * Return TRUE if "buf" points to a valid buffer (in the buffer list).
278 buf_valid(buf)
279 buf_T *buf;
281 buf_T *bp;
283 for (bp = firstbuf; bp != NULL; bp = bp->b_next)
284 if (bp == buf)
285 return TRUE;
286 return FALSE;
290 * Close the link to a buffer.
291 * "action" is used when there is no longer a window for the buffer.
292 * It can be:
293 * 0 buffer becomes hidden
294 * DOBUF_UNLOAD buffer is unloaded
295 * DOBUF_DELETE buffer is unloaded and removed from buffer list
296 * DOBUF_WIPE buffer is unloaded and really deleted
297 * When doing all but the first one on the current buffer, the caller should
298 * get a new buffer very soon!
300 * The 'bufhidden' option can force freeing and deleting.
302 void
303 close_buffer(win, buf, action)
304 win_T *win; /* if not NULL, set b_last_cursor */
305 buf_T *buf;
306 int action;
308 #ifdef FEAT_AUTOCMD
309 int is_curbuf;
310 int nwindows = buf->b_nwindows;
311 #endif
312 int unload_buf = (action != 0);
313 int del_buf = (action == DOBUF_DEL || action == DOBUF_WIPE);
314 int wipe_buf = (action == DOBUF_WIPE);
316 #ifdef FEAT_QUICKFIX
318 * Force unloading or deleting when 'bufhidden' says so.
319 * The caller must take care of NOT deleting/freeing when 'bufhidden' is
320 * "hide" (otherwise we could never free or delete a buffer).
322 if (buf->b_p_bh[0] == 'd') /* 'bufhidden' == "delete" */
324 del_buf = TRUE;
325 unload_buf = TRUE;
327 else if (buf->b_p_bh[0] == 'w') /* 'bufhidden' == "wipe" */
329 del_buf = TRUE;
330 unload_buf = TRUE;
331 wipe_buf = TRUE;
333 else if (buf->b_p_bh[0] == 'u') /* 'bufhidden' == "unload" */
334 unload_buf = TRUE;
335 #endif
337 if (win != NULL)
339 /* Set b_last_cursor when closing the last window for the buffer.
340 * Remember the last cursor position and window options of the buffer.
341 * This used to be only for the current window, but then options like
342 * 'foldmethod' may be lost with a ":only" command. */
343 if (buf->b_nwindows == 1)
344 set_last_cursor(win);
345 buflist_setfpos(buf, win,
346 win->w_cursor.lnum == 1 ? 0 : win->w_cursor.lnum,
347 win->w_cursor.col, TRUE);
350 #ifdef FEAT_AUTOCMD
351 /* When the buffer is no longer in a window, trigger BufWinLeave */
352 if (buf->b_nwindows == 1)
354 apply_autocmds(EVENT_BUFWINLEAVE, buf->b_fname, buf->b_fname,
355 FALSE, buf);
356 if (!buf_valid(buf)) /* autocommands may delete the buffer */
357 return;
359 /* When the buffer becomes hidden, but is not unloaded, trigger
360 * BufHidden */
361 if (!unload_buf)
363 apply_autocmds(EVENT_BUFHIDDEN, buf->b_fname, buf->b_fname,
364 FALSE, buf);
365 if (!buf_valid(buf)) /* autocmds may delete the buffer */
366 return;
368 # ifdef FEAT_EVAL
369 if (aborting()) /* autocmds may abort script processing */
370 return;
371 # endif
373 nwindows = buf->b_nwindows;
374 #endif
376 /* decrease the link count from windows (unless not in any window) */
377 if (buf->b_nwindows > 0)
378 --buf->b_nwindows;
380 /* Return when a window is displaying the buffer or when it's not
381 * unloaded. */
382 if (buf->b_nwindows > 0 || !unload_buf)
384 #if 0 /* why was this here? */
385 if (buf == curbuf)
386 u_sync(); /* sync undo before going to another buffer */
387 #endif
388 return;
391 /* Always remove the buffer when there is no file name. */
392 if (buf->b_ffname == NULL)
393 del_buf = TRUE;
396 * Free all things allocated for this buffer.
397 * Also calls the "BufDelete" autocommands when del_buf is TRUE.
399 #ifdef FEAT_AUTOCMD
400 /* Remember if we are closing the current buffer. Restore the number of
401 * windows, so that autocommands in buf_freeall() don't get confused. */
402 is_curbuf = (buf == curbuf);
403 buf->b_nwindows = nwindows;
404 #endif
406 buf_freeall(buf, del_buf, wipe_buf);
408 #ifdef FEAT_AUTOCMD
409 /* Autocommands may have deleted the buffer. */
410 if (!buf_valid(buf))
411 return;
412 # ifdef FEAT_EVAL
413 if (aborting()) /* autocmds may abort script processing */
414 return;
415 # endif
417 /* Autocommands may have opened or closed windows for this buffer.
418 * Decrement the count for the close we do here. */
419 if (buf->b_nwindows > 0)
420 --buf->b_nwindows;
423 * It's possible that autocommands change curbuf to the one being deleted.
424 * This might cause the previous curbuf to be deleted unexpectedly. But
425 * in some cases it's OK to delete the curbuf, because a new one is
426 * obtained anyway. Therefore only return if curbuf changed to the
427 * deleted buffer.
429 if (buf == curbuf && !is_curbuf)
430 return;
431 #endif
433 #ifdef FEAT_NETBEANS_INTG
434 if (usingNetbeans)
435 netbeans_file_closed(buf);
436 #endif
437 #ifdef FEAT_AUTOCHDIR
438 /* Change directories when the acd option is set on. */
439 if (p_acd && curbuf->b_ffname != NULL
440 && vim_chdirfile(curbuf->b_ffname) == OK)
441 shorten_fnames(TRUE);
442 #endif
445 * Remove the buffer from the list.
447 if (wipe_buf)
449 #ifdef FEAT_SUN_WORKSHOP
450 if (usingSunWorkShop)
451 workshop_file_closed_lineno((char *)buf->b_ffname,
452 (int)buf->b_last_cursor.lnum);
453 #endif
454 vim_free(buf->b_ffname);
455 vim_free(buf->b_sfname);
456 if (buf->b_prev == NULL)
457 firstbuf = buf->b_next;
458 else
459 buf->b_prev->b_next = buf->b_next;
460 if (buf->b_next == NULL)
461 lastbuf = buf->b_prev;
462 else
463 buf->b_next->b_prev = buf->b_prev;
464 free_buffer(buf);
466 else
468 if (del_buf)
470 /* Free all internal variables and reset option values, to make
471 * ":bdel" compatible with Vim 5.7. */
472 free_buffer_stuff(buf, TRUE);
474 /* Make it look like a new buffer. */
475 buf->b_flags = BF_CHECK_RO | BF_NEVERLOADED;
477 /* Init the options when loaded again. */
478 buf->b_p_initialized = FALSE;
480 buf_clear_file(buf);
481 if (del_buf)
482 buf->b_p_bl = FALSE;
487 * Make buffer not contain a file.
489 void
490 buf_clear_file(buf)
491 buf_T *buf;
493 buf->b_ml.ml_line_count = 1;
494 unchanged(buf, TRUE);
495 #ifndef SHORT_FNAME
496 buf->b_shortname = FALSE;
497 #endif
498 buf->b_p_eol = TRUE;
499 buf->b_start_eol = TRUE;
500 #ifdef FEAT_MBYTE
501 buf->b_p_bomb = FALSE;
502 #endif
503 buf->b_ml.ml_mfp = NULL;
504 buf->b_ml.ml_flags = ML_EMPTY; /* empty buffer */
505 #ifdef FEAT_NETBEANS_INTG
506 netbeans_deleted_all_lines(buf);
507 #endif
511 * buf_freeall() - free all things allocated for a buffer that are related to
512 * the file.
514 /*ARGSUSED*/
515 void
516 buf_freeall(buf, del_buf, wipe_buf)
517 buf_T *buf;
518 int del_buf; /* buffer is going to be deleted */
519 int wipe_buf; /* buffer is going to be wiped out */
521 #ifdef FEAT_AUTOCMD
522 int is_curbuf = (buf == curbuf);
524 apply_autocmds(EVENT_BUFUNLOAD, buf->b_fname, buf->b_fname, FALSE, buf);
525 if (!buf_valid(buf)) /* autocommands may delete the buffer */
526 return;
527 if (del_buf && buf->b_p_bl)
529 apply_autocmds(EVENT_BUFDELETE, buf->b_fname, buf->b_fname, FALSE, buf);
530 if (!buf_valid(buf)) /* autocommands may delete the buffer */
531 return;
533 if (wipe_buf)
535 apply_autocmds(EVENT_BUFWIPEOUT, buf->b_fname, buf->b_fname,
536 FALSE, buf);
537 if (!buf_valid(buf)) /* autocommands may delete the buffer */
538 return;
540 # ifdef FEAT_EVAL
541 if (aborting()) /* autocmds may abort script processing */
542 return;
543 # endif
546 * It's possible that autocommands change curbuf to the one being deleted.
547 * This might cause curbuf to be deleted unexpectedly. But in some cases
548 * it's OK to delete the curbuf, because a new one is obtained anyway.
549 * Therefore only return if curbuf changed to the deleted buffer.
551 if (buf == curbuf && !is_curbuf)
552 return;
553 #endif
554 #ifdef FEAT_DIFF
555 diff_buf_delete(buf); /* Can't use 'diff' for unloaded buffer. */
556 #endif
557 #ifdef FEAT_TCL
558 tcl_buffer_free(buf);
559 #endif
560 u_blockfree(buf); /* free the memory allocated for undo */
561 ml_close(buf, TRUE); /* close and delete the memline/memfile */
562 buf->b_ml.ml_line_count = 0; /* no lines in buffer */
563 u_clearall(buf); /* reset all undo information */
564 #ifdef FEAT_SYN_HL
565 syntax_clear(buf); /* reset syntax info */
566 #endif
567 buf->b_flags &= ~BF_READERR; /* a read error is no longer relevant */
571 * Free a buffer structure and the things it contains related to the buffer
572 * itself (not the file, that must have been done already).
574 static void
575 free_buffer(buf)
576 buf_T *buf;
578 free_buffer_stuff(buf, TRUE);
579 #ifdef FEAT_MZSCHEME
580 mzscheme_buffer_free(buf);
581 #endif
582 #ifdef FEAT_PERL
583 perl_buf_free(buf);
584 #endif
585 #ifdef FEAT_PYTHON
586 python_buffer_free(buf);
587 #endif
588 #ifdef FEAT_RUBY
589 ruby_buffer_free(buf);
590 #endif
591 #ifdef FEAT_AUTOCMD
592 aubuflocal_remove(buf);
593 #endif
594 vim_free(buf);
598 * Free stuff in the buffer for ":bdel" and when wiping out the buffer.
600 static void
601 free_buffer_stuff(buf, free_options)
602 buf_T *buf;
603 int free_options; /* free options as well */
605 if (free_options)
607 clear_wininfo(buf); /* including window-local options */
608 free_buf_options(buf, TRUE);
610 #ifdef FEAT_EVAL
611 vars_clear(&buf->b_vars.dv_hashtab); /* free all internal variables */
612 hash_init(&buf->b_vars.dv_hashtab);
613 #endif
614 #ifdef FEAT_USR_CMDS
615 uc_clear(&buf->b_ucmds); /* clear local user commands */
616 #endif
617 #ifdef FEAT_SIGNS
618 buf_delete_signs(buf); /* delete any signs */
619 #endif
620 #ifdef FEAT_LOCALMAP
621 map_clear_int(buf, MAP_ALL_MODES, TRUE, FALSE); /* clear local mappings */
622 map_clear_int(buf, MAP_ALL_MODES, TRUE, TRUE); /* clear local abbrevs */
623 #endif
624 #ifdef FEAT_MBYTE
625 vim_free(buf->b_start_fenc);
626 buf->b_start_fenc = NULL;
627 #endif
631 * Free the b_wininfo list for buffer "buf".
633 static void
634 clear_wininfo(buf)
635 buf_T *buf;
637 wininfo_T *wip;
639 while (buf->b_wininfo != NULL)
641 wip = buf->b_wininfo;
642 buf->b_wininfo = wip->wi_next;
643 if (wip->wi_optset)
645 clear_winopt(&wip->wi_opt);
646 #ifdef FEAT_FOLDING
647 deleteFoldRecurse(&wip->wi_folds);
648 #endif
650 vim_free(wip);
654 #if defined(FEAT_LISTCMDS) || defined(PROTO)
656 * Go to another buffer. Handles the result of the ATTENTION dialog.
658 void
659 goto_buffer(eap, start, dir, count)
660 exarg_T *eap;
661 int start;
662 int dir;
663 int count;
665 # if defined(FEAT_WINDOWS) && defined(HAS_SWAP_EXISTS_ACTION)
666 buf_T *old_curbuf = curbuf;
668 swap_exists_action = SEA_DIALOG;
669 # endif
670 (void)do_buffer(*eap->cmd == 's' ? DOBUF_SPLIT : DOBUF_GOTO,
671 start, dir, count, eap->forceit);
672 # if defined(FEAT_WINDOWS) && defined(HAS_SWAP_EXISTS_ACTION)
673 if (swap_exists_action == SEA_QUIT && *eap->cmd == 's')
675 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
676 cleanup_T cs;
678 /* Reset the error/interrupt/exception state here so that
679 * aborting() returns FALSE when closing a window. */
680 enter_cleanup(&cs);
681 # endif
683 /* Quitting means closing the split window, nothing else. */
684 win_close(curwin, TRUE);
685 swap_exists_action = SEA_NONE;
686 swap_exists_did_quit = TRUE;
688 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
689 /* Restore the error/interrupt/exception state if not discarded by a
690 * new aborting error, interrupt, or uncaught exception. */
691 leave_cleanup(&cs);
692 # endif
694 else
695 handle_swap_exists(old_curbuf);
696 # endif
698 #endif
700 #if defined(HAS_SWAP_EXISTS_ACTION) || defined(PROTO)
702 * Handle the situation of swap_exists_action being set.
703 * It is allowed for "old_curbuf" to be NULL or invalid.
705 void
706 handle_swap_exists(old_curbuf)
707 buf_T *old_curbuf;
709 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
710 cleanup_T cs;
711 # endif
713 if (swap_exists_action == SEA_QUIT)
715 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
716 /* Reset the error/interrupt/exception state here so that
717 * aborting() returns FALSE when closing a buffer. */
718 enter_cleanup(&cs);
719 # endif
721 /* User selected Quit at ATTENTION prompt. Go back to previous
722 * buffer. If that buffer is gone or the same as the current one,
723 * open a new, empty buffer. */
724 swap_exists_action = SEA_NONE; /* don't want it again */
725 swap_exists_did_quit = TRUE;
726 close_buffer(curwin, curbuf, DOBUF_UNLOAD);
727 if (!buf_valid(old_curbuf) || old_curbuf == curbuf)
728 old_curbuf = buflist_new(NULL, NULL, 1L, BLN_CURBUF | BLN_LISTED);
729 if (old_curbuf != NULL)
730 enter_buffer(old_curbuf);
731 /* If "old_curbuf" is NULL we are in big trouble here... */
733 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
734 /* Restore the error/interrupt/exception state if not discarded by a
735 * new aborting error, interrupt, or uncaught exception. */
736 leave_cleanup(&cs);
737 # endif
739 else if (swap_exists_action == SEA_RECOVER)
741 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
742 /* Reset the error/interrupt/exception state here so that
743 * aborting() returns FALSE when closing a buffer. */
744 enter_cleanup(&cs);
745 # endif
747 /* User selected Recover at ATTENTION prompt. */
748 msg_scroll = TRUE;
749 ml_recover();
750 MSG_PUTS("\n"); /* don't overwrite the last message */
751 cmdline_row = msg_row;
752 do_modelines(0);
754 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
755 /* Restore the error/interrupt/exception state if not discarded by a
756 * new aborting error, interrupt, or uncaught exception. */
757 leave_cleanup(&cs);
758 # endif
760 swap_exists_action = SEA_NONE;
762 #endif
764 #if defined(FEAT_LISTCMDS) || defined(PROTO)
766 * do_bufdel() - delete or unload buffer(s)
768 * addr_count == 0: ":bdel" - delete current buffer
769 * addr_count == 1: ":N bdel" or ":bdel N [N ..]" - first delete
770 * buffer "end_bnr", then any other arguments.
771 * addr_count == 2: ":N,N bdel" - delete buffers in range
773 * command can be DOBUF_UNLOAD (":bunload"), DOBUF_WIPE (":bwipeout") or
774 * DOBUF_DEL (":bdel")
776 * Returns error message or NULL
778 char_u *
779 do_bufdel(command, arg, addr_count, start_bnr, end_bnr, forceit)
780 int command;
781 char_u *arg; /* pointer to extra arguments */
782 int addr_count;
783 int start_bnr; /* first buffer number in a range */
784 int end_bnr; /* buffer nr or last buffer nr in a range */
785 int forceit;
787 int do_current = 0; /* delete current buffer? */
788 int deleted = 0; /* number of buffers deleted */
789 char_u *errormsg = NULL; /* return value */
790 int bnr; /* buffer number */
791 char_u *p;
793 #ifdef FEAT_NETBEANS_INTG
794 netbeansCloseFile = 1;
795 #endif
796 if (addr_count == 0)
798 (void)do_buffer(command, DOBUF_CURRENT, FORWARD, 0, forceit);
800 else
802 if (addr_count == 2)
804 if (*arg) /* both range and argument is not allowed */
805 return (char_u *)_(e_trailing);
806 bnr = start_bnr;
808 else /* addr_count == 1 */
809 bnr = end_bnr;
811 for ( ;!got_int; ui_breakcheck())
814 * delete the current buffer last, otherwise when the
815 * current buffer is deleted, the next buffer becomes
816 * the current one and will be loaded, which may then
817 * also be deleted, etc.
819 if (bnr == curbuf->b_fnum)
820 do_current = bnr;
821 else if (do_buffer(command, DOBUF_FIRST, FORWARD, (int)bnr,
822 forceit) == OK)
823 ++deleted;
826 * find next buffer number to delete/unload
828 if (addr_count == 2)
830 if (++bnr > end_bnr)
831 break;
833 else /* addr_count == 1 */
835 arg = skipwhite(arg);
836 if (*arg == NUL)
837 break;
838 if (!VIM_ISDIGIT(*arg))
840 p = skiptowhite_esc(arg);
841 bnr = buflist_findpat(arg, p, command == DOBUF_WIPE, FALSE);
842 if (bnr < 0) /* failed */
843 break;
844 arg = p;
846 else
847 bnr = getdigits(&arg);
850 if (!got_int && do_current && do_buffer(command, DOBUF_FIRST,
851 FORWARD, do_current, forceit) == OK)
852 ++deleted;
854 if (deleted == 0)
856 if (command == DOBUF_UNLOAD)
857 STRCPY(IObuff, _("E515: No buffers were unloaded"));
858 else if (command == DOBUF_DEL)
859 STRCPY(IObuff, _("E516: No buffers were deleted"));
860 else
861 STRCPY(IObuff, _("E517: No buffers were wiped out"));
862 errormsg = IObuff;
864 else if (deleted >= p_report)
866 if (command == DOBUF_UNLOAD)
868 if (deleted == 1)
869 MSG(_("1 buffer unloaded"));
870 else
871 smsg((char_u *)_("%d buffers unloaded"), deleted);
873 else if (command == DOBUF_DEL)
875 if (deleted == 1)
876 MSG(_("1 buffer deleted"));
877 else
878 smsg((char_u *)_("%d buffers deleted"), deleted);
880 else
882 if (deleted == 1)
883 MSG(_("1 buffer wiped out"));
884 else
885 smsg((char_u *)_("%d buffers wiped out"), deleted);
890 #ifdef FEAT_NETBEANS_INTG
891 netbeansCloseFile = 0;
892 #endif
894 return errormsg;
898 * Implementation of the commands for the buffer list.
900 * action == DOBUF_GOTO go to specified buffer
901 * action == DOBUF_SPLIT split window and go to specified buffer
902 * action == DOBUF_UNLOAD unload specified buffer(s)
903 * action == DOBUF_DEL delete specified buffer(s) from buffer list
904 * action == DOBUF_WIPE delete specified buffer(s) really
906 * start == DOBUF_CURRENT go to "count" buffer from current buffer
907 * start == DOBUF_FIRST go to "count" buffer from first buffer
908 * start == DOBUF_LAST go to "count" buffer from last buffer
909 * start == DOBUF_MOD go to "count" modified buffer from current buffer
911 * Return FAIL or OK.
914 do_buffer(action, start, dir, count, forceit)
915 int action;
916 int start;
917 int dir; /* FORWARD or BACKWARD */
918 int count; /* buffer number or number of buffers */
919 int forceit; /* TRUE for :...! */
921 buf_T *buf;
922 buf_T *bp;
923 int unload = (action == DOBUF_UNLOAD || action == DOBUF_DEL
924 || action == DOBUF_WIPE);
926 switch (start)
928 case DOBUF_FIRST: buf = firstbuf; break;
929 case DOBUF_LAST: buf = lastbuf; break;
930 default: buf = curbuf; break;
932 if (start == DOBUF_MOD) /* find next modified buffer */
934 while (count-- > 0)
938 buf = buf->b_next;
939 if (buf == NULL)
940 buf = firstbuf;
942 while (buf != curbuf && !bufIsChanged(buf));
944 if (!bufIsChanged(buf))
946 EMSG(_("E84: No modified buffer found"));
947 return FAIL;
950 else if (start == DOBUF_FIRST && count) /* find specified buffer number */
952 while (buf != NULL && buf->b_fnum != count)
953 buf = buf->b_next;
955 else
957 bp = NULL;
958 while (count > 0 || (!unload && !buf->b_p_bl && bp != buf))
960 /* remember the buffer where we start, we come back there when all
961 * buffers are unlisted. */
962 if (bp == NULL)
963 bp = buf;
964 if (dir == FORWARD)
966 buf = buf->b_next;
967 if (buf == NULL)
968 buf = firstbuf;
970 else
972 buf = buf->b_prev;
973 if (buf == NULL)
974 buf = lastbuf;
976 /* don't count unlisted buffers */
977 if (unload || buf->b_p_bl)
979 --count;
980 bp = NULL; /* use this buffer as new starting point */
982 if (bp == buf)
984 /* back where we started, didn't find anything. */
985 EMSG(_("E85: There is no listed buffer"));
986 return FAIL;
991 if (buf == NULL) /* could not find it */
993 if (start == DOBUF_FIRST)
995 /* don't warn when deleting */
996 if (!unload)
997 EMSGN(_("E86: Buffer %ld does not exist"), count);
999 else if (dir == FORWARD)
1000 EMSG(_("E87: Cannot go beyond last buffer"));
1001 else
1002 EMSG(_("E88: Cannot go before first buffer"));
1003 return FAIL;
1006 #ifdef FEAT_GUI
1007 need_mouse_correct = TRUE;
1008 #endif
1010 #ifdef FEAT_LISTCMDS
1012 * delete buffer buf from memory and/or the list
1014 if (unload)
1016 int forward;
1017 int retval;
1019 /* When unloading or deleting a buffer that's already unloaded and
1020 * unlisted: fail silently. */
1021 if (action != DOBUF_WIPE && buf->b_ml.ml_mfp == NULL && !buf->b_p_bl)
1022 return FAIL;
1024 if (!forceit && bufIsChanged(buf))
1026 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1027 if ((p_confirm || cmdmod.confirm) && p_write)
1029 dialog_changed(buf, FALSE);
1030 # ifdef FEAT_AUTOCMD
1031 if (!buf_valid(buf))
1032 /* Autocommand deleted buffer, oops! It's not changed
1033 * now. */
1034 return FAIL;
1035 # endif
1036 /* If it's still changed fail silently, the dialog already
1037 * mentioned why it fails. */
1038 if (bufIsChanged(buf))
1039 return FAIL;
1041 else
1042 #endif
1044 EMSGN(_("E89: No write since last change for buffer %ld (add ! to override)"),
1045 buf->b_fnum);
1046 return FAIL;
1051 * If deleting the last (listed) buffer, make it empty.
1052 * The last (listed) buffer cannot be unloaded.
1054 for (bp = firstbuf; bp != NULL; bp = bp->b_next)
1055 if (bp->b_p_bl && bp != buf)
1056 break;
1057 if (bp == NULL && buf == curbuf)
1059 if (action == DOBUF_UNLOAD)
1061 EMSG(_("E90: Cannot unload last buffer"));
1062 return FAIL;
1065 /* Close any other windows on this buffer, then make it empty. */
1066 #ifdef FEAT_WINDOWS
1067 close_windows(buf, TRUE);
1068 #endif
1069 setpcmark();
1070 retval = do_ecmd(0, NULL, NULL, NULL, ECMD_ONE,
1071 forceit ? ECMD_FORCEIT : 0);
1074 * do_ecmd() may create a new buffer, then we have to delete
1075 * the old one. But do_ecmd() may have done that already, check
1076 * if the buffer still exists.
1078 if (buf != curbuf && buf_valid(buf) && buf->b_nwindows == 0)
1079 close_buffer(NULL, buf, action);
1080 return retval;
1083 #ifdef FEAT_WINDOWS
1085 * If the deleted buffer is the current one, close the current window
1086 * (unless it's the only window). Repeat this so long as we end up in
1087 * a window with this buffer.
1089 while (buf == curbuf
1090 && (firstwin != lastwin || first_tabpage->tp_next != NULL))
1091 win_close(curwin, FALSE);
1092 #endif
1095 * If the buffer to be deleted is not the current one, delete it here.
1097 if (buf != curbuf)
1099 #ifdef FEAT_WINDOWS
1100 close_windows(buf, FALSE);
1101 #endif
1102 if (buf != curbuf && buf_valid(buf) && buf->b_nwindows <= 0)
1103 close_buffer(NULL, buf, action);
1104 return OK;
1108 * Deleting the current buffer: Need to find another buffer to go to.
1109 * There must be another, otherwise it would have been handled above.
1110 * First use au_new_curbuf, if it is valid.
1111 * Then prefer the buffer we most recently visited.
1112 * Else try to find one that is loaded, after the current buffer,
1113 * then before the current buffer.
1114 * Finally use any buffer.
1116 buf = NULL; /* selected buffer */
1117 bp = NULL; /* used when no loaded buffer found */
1118 #ifdef FEAT_AUTOCMD
1119 if (au_new_curbuf != NULL && buf_valid(au_new_curbuf))
1120 buf = au_new_curbuf;
1121 # ifdef FEAT_JUMPLIST
1122 else
1123 # endif
1124 #endif
1125 #ifdef FEAT_JUMPLIST
1126 if (curwin->w_jumplistlen > 0)
1128 int jumpidx;
1130 jumpidx = curwin->w_jumplistidx - 1;
1131 if (jumpidx < 0)
1132 jumpidx = curwin->w_jumplistlen - 1;
1134 forward = jumpidx;
1135 while (jumpidx != curwin->w_jumplistidx)
1137 buf = buflist_findnr(curwin->w_jumplist[jumpidx].fmark.fnum);
1138 if (buf != NULL)
1140 if (buf == curbuf || !buf->b_p_bl)
1141 buf = NULL; /* skip current and unlisted bufs */
1142 else if (buf->b_ml.ml_mfp == NULL)
1144 /* skip unloaded buf, but may keep it for later */
1145 if (bp == NULL)
1146 bp = buf;
1147 buf = NULL;
1150 if (buf != NULL) /* found a valid buffer: stop searching */
1151 break;
1152 /* advance to older entry in jump list */
1153 if (!jumpidx && curwin->w_jumplistidx == curwin->w_jumplistlen)
1154 break;
1155 if (--jumpidx < 0)
1156 jumpidx = curwin->w_jumplistlen - 1;
1157 if (jumpidx == forward) /* List exhausted for sure */
1158 break;
1161 #endif
1163 if (buf == NULL) /* No previous buffer, Try 2'nd approach */
1165 forward = TRUE;
1166 buf = curbuf->b_next;
1167 for (;;)
1169 if (buf == NULL)
1171 if (!forward) /* tried both directions */
1172 break;
1173 buf = curbuf->b_prev;
1174 forward = FALSE;
1175 continue;
1177 /* in non-help buffer, try to skip help buffers, and vv */
1178 if (buf->b_help == curbuf->b_help && buf->b_p_bl)
1180 if (buf->b_ml.ml_mfp != NULL) /* found loaded buffer */
1181 break;
1182 if (bp == NULL) /* remember unloaded buf for later */
1183 bp = buf;
1185 if (forward)
1186 buf = buf->b_next;
1187 else
1188 buf = buf->b_prev;
1191 if (buf == NULL) /* No loaded buffer, use unloaded one */
1192 buf = bp;
1193 if (buf == NULL) /* No loaded buffer, find listed one */
1195 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1196 if (buf->b_p_bl && buf != curbuf)
1197 break;
1199 if (buf == NULL) /* Still no buffer, just take one */
1201 if (curbuf->b_next != NULL)
1202 buf = curbuf->b_next;
1203 else
1204 buf = curbuf->b_prev;
1209 * make buf current buffer
1211 if (action == DOBUF_SPLIT) /* split window first */
1213 # ifdef FEAT_WINDOWS
1214 /* jump to first window containing buf if one exists ("useopen") */
1215 if (vim_strchr(p_swb, 'o') && buf_jump_open_win(buf))
1216 return OK;
1217 /* jump to first window in any tab page containing buf if one exists
1218 * ("usetab") */
1219 if (vim_strchr(p_swb, 'a') && buf_jump_open_tab(buf))
1220 return OK;
1221 if (win_split(0, 0) == FAIL)
1222 # endif
1223 return FAIL;
1225 #endif
1227 /* go to current buffer - nothing to do */
1228 if (buf == curbuf)
1229 return OK;
1232 * Check if the current buffer may be abandoned.
1234 if (action == DOBUF_GOTO && !can_abandon(curbuf, forceit))
1236 #if defined(FEAT_GUI_DIALOG) || defined(FEAT_CON_DIALOG)
1237 if ((p_confirm || cmdmod.confirm) && p_write)
1239 dialog_changed(curbuf, FALSE);
1240 # ifdef FEAT_AUTOCMD
1241 if (!buf_valid(buf))
1242 /* Autocommand deleted buffer, oops! */
1243 return FAIL;
1244 # endif
1246 if (bufIsChanged(curbuf))
1247 #endif
1249 EMSG(_(e_nowrtmsg));
1250 return FAIL;
1254 /* Go to the other buffer. */
1255 set_curbuf(buf, action);
1257 #if defined(FEAT_LISTCMDS) && defined(FEAT_SCROLLBIND)
1258 if (action == DOBUF_SPLIT)
1259 curwin->w_p_scb = FALSE; /* reset 'scrollbind' */
1260 #endif
1262 #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
1263 if (aborting()) /* autocmds may abort script processing */
1264 return FAIL;
1265 #endif
1267 return OK;
1270 #endif /* FEAT_LISTCMDS */
1273 * Set current buffer to "buf". Executes autocommands and closes current
1274 * buffer. "action" tells how to close the current buffer:
1275 * DOBUF_GOTO free or hide it
1276 * DOBUF_SPLIT nothing
1277 * DOBUF_UNLOAD unload it
1278 * DOBUF_DEL delete it
1279 * DOBUF_WIPE wipe it out
1281 void
1282 set_curbuf(buf, action)
1283 buf_T *buf;
1284 int action;
1286 buf_T *prevbuf;
1287 int unload = (action == DOBUF_UNLOAD || action == DOBUF_DEL
1288 || action == DOBUF_WIPE);
1290 setpcmark();
1291 if (!cmdmod.keepalt)
1292 curwin->w_alt_fnum = curbuf->b_fnum; /* remember alternate file */
1293 buflist_altfpos(); /* remember curpos */
1295 #ifdef FEAT_VISUAL
1296 /* Don't restart Select mode after switching to another buffer. */
1297 VIsual_reselect = FALSE;
1298 #endif
1300 /* close_windows() or apply_autocmds() may change curbuf */
1301 prevbuf = curbuf;
1303 #ifdef FEAT_AUTOCMD
1304 apply_autocmds(EVENT_BUFLEAVE, NULL, NULL, FALSE, curbuf);
1305 # ifdef FEAT_EVAL
1306 if (buf_valid(prevbuf) && !aborting())
1307 # else
1308 if (buf_valid(prevbuf))
1309 # endif
1310 #endif
1312 #ifdef FEAT_WINDOWS
1313 if (unload)
1314 close_windows(prevbuf, FALSE);
1315 #endif
1316 #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
1317 if (buf_valid(prevbuf) && !aborting())
1318 #else
1319 if (buf_valid(prevbuf))
1320 #endif
1322 if (prevbuf == curbuf)
1323 u_sync(FALSE);
1324 close_buffer(prevbuf == curwin->w_buffer ? curwin : NULL, prevbuf,
1325 unload ? action : (action == DOBUF_GOTO
1326 && !P_HID(prevbuf)
1327 && !bufIsChanged(prevbuf)) ? DOBUF_UNLOAD : 0);
1330 #ifdef FEAT_AUTOCMD
1331 # ifdef FEAT_EVAL
1332 /* An autocommand may have deleted buf or aborted the script processing! */
1333 if (buf_valid(buf) && !aborting())
1334 # else
1335 if (buf_valid(buf)) /* an autocommand may have deleted buf! */
1336 # endif
1337 #endif
1338 enter_buffer(buf);
1342 * Enter a new current buffer.
1343 * Old curbuf must have been abandoned already!
1345 void
1346 enter_buffer(buf)
1347 buf_T *buf;
1349 /* Copy buffer and window local option values. Not for a help buffer. */
1350 buf_copy_options(buf, BCO_ENTER | BCO_NOHELP);
1351 if (!buf->b_help)
1352 get_winopts(buf);
1353 #ifdef FEAT_FOLDING
1354 else
1355 /* Remove all folds in the window. */
1356 clearFolding(curwin);
1357 foldUpdateAll(curwin); /* update folds (later). */
1358 #endif
1360 /* Get the buffer in the current window. */
1361 curwin->w_buffer = buf;
1362 curbuf = buf;
1363 ++curbuf->b_nwindows;
1365 #ifdef FEAT_DIFF
1366 if (curwin->w_p_diff)
1367 diff_buf_add(curbuf);
1368 #endif
1370 /* Cursor on first line by default. */
1371 curwin->w_cursor.lnum = 1;
1372 curwin->w_cursor.col = 0;
1373 #ifdef FEAT_VIRTUALEDIT
1374 curwin->w_cursor.coladd = 0;
1375 #endif
1376 curwin->w_set_curswant = TRUE;
1378 /* Make sure the buffer is loaded. */
1379 if (curbuf->b_ml.ml_mfp == NULL) /* need to load the file */
1381 #ifdef FEAT_AUTOCMD
1382 /* If there is no filetype, allow for detecting one. Esp. useful for
1383 * ":ball" used in a autocommand. If there already is a filetype we
1384 * might prefer to keep it. */
1385 if (*curbuf->b_p_ft == NUL)
1386 did_filetype = FALSE;
1387 #endif
1389 open_buffer(FALSE, NULL);
1391 else
1393 need_fileinfo = TRUE; /* display file info after redraw */
1394 (void)buf_check_timestamp(curbuf, FALSE); /* check if file changed */
1395 #ifdef FEAT_AUTOCMD
1396 curwin->w_topline = 1;
1397 # ifdef FEAT_DIFF
1398 curwin->w_topfill = 0;
1399 # endif
1400 apply_autocmds(EVENT_BUFENTER, NULL, NULL, FALSE, curbuf);
1401 apply_autocmds(EVENT_BUFWINENTER, NULL, NULL, FALSE, curbuf);
1402 #endif
1405 /* If autocommands did not change the cursor position, restore cursor lnum
1406 * and possibly cursor col. */
1407 if (curwin->w_cursor.lnum == 1 && inindent(0))
1408 buflist_getfpos();
1410 check_arg_idx(curwin); /* check for valid arg_idx */
1411 #ifdef FEAT_TITLE
1412 maketitle();
1413 #endif
1414 #ifdef FEAT_AUTOCMD
1415 if (curwin->w_topline == 1) /* when autocmds didn't change it */
1416 #endif
1417 scroll_cursor_halfway(FALSE); /* redisplay at correct position */
1419 #ifdef FEAT_NETBEANS_INTG
1420 /* Send fileOpened event because we've changed buffers. */
1421 if (usingNetbeans && isNetbeansBuffer(curbuf))
1422 netbeans_file_activated(curbuf);
1423 #endif
1425 #ifdef FEAT_AUTOCHDIR
1426 /* Change directories when the acd option is set on. */
1427 if (p_acd && curbuf->b_ffname != NULL
1428 && vim_chdirfile(curbuf->b_ffname) == OK)
1429 shorten_fnames(TRUE);
1430 #endif
1432 #ifdef FEAT_KEYMAP
1433 if (curbuf->b_kmap_state & KEYMAP_INIT)
1434 keymap_init();
1435 #endif
1436 redraw_later(NOT_VALID);
1440 * functions for dealing with the buffer list
1444 * Add a file name to the buffer list. Return a pointer to the buffer.
1445 * If the same file name already exists return a pointer to that buffer.
1446 * If it does not exist, or if fname == NULL, a new entry is created.
1447 * If (flags & BLN_CURBUF) is TRUE, may use current buffer.
1448 * If (flags & BLN_LISTED) is TRUE, add new buffer to buffer list.
1449 * If (flags & BLN_DUMMY) is TRUE, don't count it as a real buffer.
1450 * This is the ONLY way to create a new buffer.
1452 static int top_file_num = 1; /* highest file number */
1454 buf_T *
1455 buflist_new(ffname, sfname, lnum, flags)
1456 char_u *ffname; /* full path of fname or relative */
1457 char_u *sfname; /* short fname or NULL */
1458 linenr_T lnum; /* preferred cursor line */
1459 int flags; /* BLN_ defines */
1461 buf_T *buf;
1462 #ifdef UNIX
1463 struct stat st;
1464 #endif
1466 fname_expand(curbuf, &ffname, &sfname); /* will allocate ffname */
1469 * If file name already exists in the list, update the entry.
1471 #ifdef UNIX
1472 /* On Unix we can use inode numbers when the file exists. Works better
1473 * for hard links. */
1474 if (sfname == NULL || mch_stat((char *)sfname, &st) < 0)
1475 st.st_dev = (dev_T)-1;
1476 #endif
1477 if (ffname != NULL && !(flags & BLN_DUMMY) && (buf =
1478 #ifdef UNIX
1479 buflist_findname_stat(ffname, &st)
1480 #else
1481 buflist_findname(ffname)
1482 #endif
1483 ) != NULL)
1485 vim_free(ffname);
1486 if (lnum != 0)
1487 buflist_setfpos(buf, curwin, lnum, (colnr_T)0, FALSE);
1488 /* copy the options now, if 'cpo' doesn't have 's' and not done
1489 * already */
1490 buf_copy_options(buf, 0);
1491 if ((flags & BLN_LISTED) && !buf->b_p_bl)
1493 buf->b_p_bl = TRUE;
1494 #ifdef FEAT_AUTOCMD
1495 if (!(flags & BLN_DUMMY))
1496 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, buf);
1497 #endif
1499 return buf;
1503 * If the current buffer has no name and no contents, use the current
1504 * buffer. Otherwise: Need to allocate a new buffer structure.
1506 * This is the ONLY place where a new buffer structure is allocated!
1507 * (A spell file buffer is allocated in spell.c, but that's not a normal
1508 * buffer.)
1510 buf = NULL;
1511 if ((flags & BLN_CURBUF)
1512 && curbuf != NULL
1513 && curbuf->b_ffname == NULL
1514 && curbuf->b_nwindows <= 1
1515 && (curbuf->b_ml.ml_mfp == NULL || bufempty()))
1517 buf = curbuf;
1518 #ifdef FEAT_AUTOCMD
1519 /* It's like this buffer is deleted. Watch out for autocommands that
1520 * change curbuf! If that happens, allocate a new buffer anyway. */
1521 if (curbuf->b_p_bl)
1522 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
1523 if (buf == curbuf)
1524 apply_autocmds(EVENT_BUFWIPEOUT, NULL, NULL, FALSE, curbuf);
1525 # ifdef FEAT_EVAL
1526 if (aborting()) /* autocmds may abort script processing */
1527 return NULL;
1528 # endif
1529 #endif
1530 #ifdef FEAT_QUICKFIX
1531 # ifdef FEAT_AUTOCMD
1532 if (buf == curbuf)
1533 # endif
1535 /* Make sure 'bufhidden' and 'buftype' are empty */
1536 clear_string_option(&buf->b_p_bh);
1537 clear_string_option(&buf->b_p_bt);
1539 #endif
1541 if (buf != curbuf || curbuf == NULL)
1543 buf = (buf_T *)alloc_clear((unsigned)sizeof(buf_T));
1544 if (buf == NULL)
1546 vim_free(ffname);
1547 return NULL;
1551 if (ffname != NULL)
1553 buf->b_ffname = ffname;
1554 buf->b_sfname = vim_strsave(sfname);
1557 clear_wininfo(buf);
1558 buf->b_wininfo = (wininfo_T *)alloc_clear((unsigned)sizeof(wininfo_T));
1560 if ((ffname != NULL && (buf->b_ffname == NULL || buf->b_sfname == NULL))
1561 || buf->b_wininfo == NULL)
1563 vim_free(buf->b_ffname);
1564 buf->b_ffname = NULL;
1565 vim_free(buf->b_sfname);
1566 buf->b_sfname = NULL;
1567 if (buf != curbuf)
1568 free_buffer(buf);
1569 return NULL;
1572 if (buf == curbuf)
1574 /* free all things allocated for this buffer */
1575 buf_freeall(buf, FALSE, FALSE);
1576 if (buf != curbuf) /* autocommands deleted the buffer! */
1577 return NULL;
1578 #if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
1579 if (aborting()) /* autocmds may abort script processing */
1580 return NULL;
1581 #endif
1582 /* buf->b_nwindows = 0; why was this here? */
1583 free_buffer_stuff(buf, FALSE); /* delete local variables et al. */
1584 #ifdef FEAT_KEYMAP
1585 /* need to reload lmaps and set b:keymap_name */
1586 curbuf->b_kmap_state |= KEYMAP_INIT;
1587 #endif
1589 else
1592 * put new buffer at the end of the buffer list
1594 buf->b_next = NULL;
1595 if (firstbuf == NULL) /* buffer list is empty */
1597 buf->b_prev = NULL;
1598 firstbuf = buf;
1600 else /* append new buffer at end of list */
1602 lastbuf->b_next = buf;
1603 buf->b_prev = lastbuf;
1605 lastbuf = buf;
1607 buf->b_fnum = top_file_num++;
1608 if (top_file_num < 0) /* wrap around (may cause duplicates) */
1610 EMSG(_("W14: Warning: List of file names overflow"));
1611 if (emsg_silent == 0)
1613 out_flush();
1614 ui_delay(3000L, TRUE); /* make sure it is noticed */
1616 top_file_num = 1;
1620 * Always copy the options from the current buffer.
1622 buf_copy_options(buf, BCO_ALWAYS);
1625 buf->b_wininfo->wi_fpos.lnum = lnum;
1626 buf->b_wininfo->wi_win = curwin;
1628 #ifdef FEAT_EVAL
1629 init_var_dict(&buf->b_vars, &buf->b_bufvar); /* init b: variables */
1630 #endif
1631 #ifdef FEAT_SYN_HL
1632 hash_init(&buf->b_keywtab);
1633 hash_init(&buf->b_keywtab_ic);
1634 #endif
1636 buf->b_fname = buf->b_sfname;
1637 #ifdef UNIX
1638 if (st.st_dev == (dev_T)-1)
1639 buf->b_dev = -1;
1640 else
1642 buf->b_dev = st.st_dev;
1643 buf->b_ino = st.st_ino;
1645 #endif
1646 buf->b_u_synced = TRUE;
1647 buf->b_flags = BF_CHECK_RO | BF_NEVERLOADED;
1648 if (flags & BLN_DUMMY)
1649 buf->b_flags |= BF_DUMMY;
1650 buf_clear_file(buf);
1651 clrallmarks(buf); /* clear marks */
1652 fmarks_check_names(buf); /* check file marks for this file */
1653 buf->b_p_bl = (flags & BLN_LISTED) ? TRUE : FALSE; /* init 'buflisted' */
1654 #ifdef FEAT_AUTOCMD
1655 if (!(flags & BLN_DUMMY))
1657 apply_autocmds(EVENT_BUFNEW, NULL, NULL, FALSE, buf);
1658 if (flags & BLN_LISTED)
1659 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, buf);
1660 # ifdef FEAT_EVAL
1661 if (aborting()) /* autocmds may abort script processing */
1662 return NULL;
1663 # endif
1665 #endif
1667 return buf;
1671 * Free the memory for the options of a buffer.
1672 * If "free_p_ff" is TRUE also free 'fileformat', 'buftype' and
1673 * 'fileencoding'.
1675 void
1676 free_buf_options(buf, free_p_ff)
1677 buf_T *buf;
1678 int free_p_ff;
1680 if (free_p_ff)
1682 #ifdef FEAT_MBYTE
1683 clear_string_option(&buf->b_p_fenc);
1684 #endif
1685 clear_string_option(&buf->b_p_ff);
1686 #ifdef FEAT_QUICKFIX
1687 clear_string_option(&buf->b_p_bh);
1688 clear_string_option(&buf->b_p_bt);
1689 #endif
1691 #ifdef FEAT_FIND_ID
1692 clear_string_option(&buf->b_p_def);
1693 clear_string_option(&buf->b_p_inc);
1694 # ifdef FEAT_EVAL
1695 clear_string_option(&buf->b_p_inex);
1696 # endif
1697 #endif
1698 #if defined(FEAT_CINDENT) && defined(FEAT_EVAL)
1699 clear_string_option(&buf->b_p_inde);
1700 clear_string_option(&buf->b_p_indk);
1701 #endif
1702 #if defined(FEAT_BEVAL) && defined(FEAT_EVAL)
1703 clear_string_option(&buf->b_p_bexpr);
1704 #endif
1705 #if defined(FEAT_EVAL)
1706 clear_string_option(&buf->b_p_fex);
1707 #endif
1708 #ifdef FEAT_CRYPT
1709 clear_string_option(&buf->b_p_key);
1710 #endif
1711 clear_string_option(&buf->b_p_kp);
1712 clear_string_option(&buf->b_p_mps);
1713 clear_string_option(&buf->b_p_fo);
1714 clear_string_option(&buf->b_p_flp);
1715 clear_string_option(&buf->b_p_isk);
1716 #ifdef FEAT_KEYMAP
1717 clear_string_option(&buf->b_p_keymap);
1718 ga_clear(&buf->b_kmap_ga);
1719 #endif
1720 #ifdef FEAT_COMMENTS
1721 clear_string_option(&buf->b_p_com);
1722 #endif
1723 #ifdef FEAT_FOLDING
1724 clear_string_option(&buf->b_p_cms);
1725 #endif
1726 clear_string_option(&buf->b_p_nf);
1727 #ifdef FEAT_SYN_HL
1728 clear_string_option(&buf->b_p_syn);
1729 #endif
1730 #ifdef FEAT_SPELL
1731 clear_string_option(&buf->b_p_spc);
1732 clear_string_option(&buf->b_p_spf);
1733 vim_free(buf->b_cap_prog);
1734 buf->b_cap_prog = NULL;
1735 clear_string_option(&buf->b_p_spl);
1736 #endif
1737 #ifdef FEAT_SEARCHPATH
1738 clear_string_option(&buf->b_p_sua);
1739 #endif
1740 #ifdef FEAT_AUTOCMD
1741 clear_string_option(&buf->b_p_ft);
1742 #endif
1743 #ifdef FEAT_OSFILETYPE
1744 clear_string_option(&buf->b_p_oft);
1745 #endif
1746 #ifdef FEAT_CINDENT
1747 clear_string_option(&buf->b_p_cink);
1748 clear_string_option(&buf->b_p_cino);
1749 #endif
1750 #if defined(FEAT_CINDENT) || defined(FEAT_SMARTINDENT)
1751 clear_string_option(&buf->b_p_cinw);
1752 #endif
1753 #ifdef FEAT_INS_EXPAND
1754 clear_string_option(&buf->b_p_cpt);
1755 #endif
1756 #ifdef FEAT_COMPL_FUNC
1757 clear_string_option(&buf->b_p_cfu);
1758 clear_string_option(&buf->b_p_ofu);
1759 #endif
1760 #ifdef FEAT_QUICKFIX
1761 clear_string_option(&buf->b_p_gp);
1762 clear_string_option(&buf->b_p_mp);
1763 clear_string_option(&buf->b_p_efm);
1764 #endif
1765 clear_string_option(&buf->b_p_ep);
1766 clear_string_option(&buf->b_p_path);
1767 clear_string_option(&buf->b_p_tags);
1768 #ifdef FEAT_INS_EXPAND
1769 clear_string_option(&buf->b_p_dict);
1770 clear_string_option(&buf->b_p_tsr);
1771 #endif
1772 #ifdef FEAT_TEXTOBJ
1773 clear_string_option(&buf->b_p_qe);
1774 #endif
1775 buf->b_p_ar = -1;
1779 * get alternate file n
1780 * set linenr to lnum or altfpos.lnum if lnum == 0
1781 * also set cursor column to altfpos.col if 'startofline' is not set.
1782 * if (options & GETF_SETMARK) call setpcmark()
1783 * if (options & GETF_ALT) we are jumping to an alternate file.
1784 * if (options & GETF_SWITCH) respect 'switchbuf' settings when jumping
1786 * return FAIL for failure, OK for success
1789 buflist_getfile(n, lnum, options, forceit)
1790 int n;
1791 linenr_T lnum;
1792 int options;
1793 int forceit;
1795 buf_T *buf;
1796 #ifdef FEAT_WINDOWS
1797 win_T *wp = NULL;
1798 #endif
1799 pos_T *fpos;
1800 colnr_T col;
1802 buf = buflist_findnr(n);
1803 if (buf == NULL)
1805 if ((options & GETF_ALT) && n == 0)
1806 EMSG(_(e_noalt));
1807 else
1808 EMSGN(_("E92: Buffer %ld not found"), n);
1809 return FAIL;
1812 /* if alternate file is the current buffer, nothing to do */
1813 if (buf == curbuf)
1814 return OK;
1816 if (text_locked())
1818 text_locked_msg();
1819 return FAIL;
1821 #ifdef FEAT_AUTOCMD
1822 if (curbuf_locked())
1823 return FAIL;
1824 #endif
1826 /* altfpos may be changed by getfile(), get it now */
1827 if (lnum == 0)
1829 fpos = buflist_findfpos(buf);
1830 lnum = fpos->lnum;
1831 col = fpos->col;
1833 else
1834 col = 0;
1836 #ifdef FEAT_WINDOWS
1837 if (options & GETF_SWITCH)
1839 /* use existing open window for buffer if wanted */
1840 if (vim_strchr(p_swb, 'o')) /* useopen */
1841 wp = buf_jump_open_win(buf);
1842 /* use existing open window in any tab page for buffer if wanted */
1843 if (vim_strchr(p_swb, 'a')) /* usetab */
1844 wp = buf_jump_open_tab(buf);
1845 /* split window if wanted ("split") */
1846 if (wp == NULL && vim_strchr(p_swb, 't') && !bufempty())
1848 if (win_split(0, 0) == FAIL)
1849 return FAIL;
1850 # ifdef FEAT_SCROLLBIND
1851 curwin->w_p_scb = FALSE;
1852 # endif
1855 #endif
1857 ++RedrawingDisabled;
1858 if (getfile(buf->b_fnum, NULL, NULL, (options & GETF_SETMARK),
1859 lnum, forceit) <= 0)
1861 --RedrawingDisabled;
1863 /* cursor is at to BOL and w_cursor.lnum is checked due to getfile() */
1864 if (!p_sol && col != 0)
1866 curwin->w_cursor.col = col;
1867 check_cursor_col();
1868 #ifdef FEAT_VIRTUALEDIT
1869 curwin->w_cursor.coladd = 0;
1870 #endif
1871 curwin->w_set_curswant = TRUE;
1873 return OK;
1875 --RedrawingDisabled;
1876 return FAIL;
1880 * go to the last know line number for the current buffer
1882 void
1883 buflist_getfpos()
1885 pos_T *fpos;
1887 fpos = buflist_findfpos(curbuf);
1889 curwin->w_cursor.lnum = fpos->lnum;
1890 check_cursor_lnum();
1892 if (p_sol)
1893 curwin->w_cursor.col = 0;
1894 else
1896 curwin->w_cursor.col = fpos->col;
1897 check_cursor_col();
1898 #ifdef FEAT_VIRTUALEDIT
1899 curwin->w_cursor.coladd = 0;
1900 #endif
1901 curwin->w_set_curswant = TRUE;
1905 #if defined(FEAT_QUICKFIX) || defined(FEAT_EVAL) || defined(PROTO)
1907 * Find file in buffer list by name (it has to be for the current window).
1908 * Returns NULL if not found.
1910 buf_T *
1911 buflist_findname_exp(fname)
1912 char_u *fname;
1914 char_u *ffname;
1915 buf_T *buf = NULL;
1917 /* First make the name into a full path name */
1918 ffname = FullName_save(fname,
1919 #ifdef UNIX
1920 TRUE /* force expansion, get rid of symbolic links */
1921 #else
1922 FALSE
1923 #endif
1925 if (ffname != NULL)
1927 buf = buflist_findname(ffname);
1928 vim_free(ffname);
1930 return buf;
1932 #endif
1935 * Find file in buffer list by name (it has to be for the current window).
1936 * "ffname" must have a full path.
1937 * Skips dummy buffers.
1938 * Returns NULL if not found.
1940 buf_T *
1941 buflist_findname(ffname)
1942 char_u *ffname;
1944 #ifdef UNIX
1945 struct stat st;
1947 if (mch_stat((char *)ffname, &st) < 0)
1948 st.st_dev = (dev_T)-1;
1949 return buflist_findname_stat(ffname, &st);
1953 * Same as buflist_findname(), but pass the stat structure to avoid getting it
1954 * twice for the same file.
1955 * Returns NULL if not found.
1957 static buf_T *
1958 buflist_findname_stat(ffname, stp)
1959 char_u *ffname;
1960 struct stat *stp;
1962 #endif
1963 buf_T *buf;
1965 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
1966 if ((buf->b_flags & BF_DUMMY) == 0 && !otherfile_buf(buf, ffname
1967 #ifdef UNIX
1968 , stp
1969 #endif
1971 return buf;
1972 return NULL;
1975 #if defined(FEAT_LISTCMDS) || defined(FEAT_EVAL) || defined(FEAT_PERL) || defined(PROTO)
1977 * Find file in buffer list by a regexp pattern.
1978 * Return fnum of the found buffer.
1979 * Return < 0 for error.
1981 /*ARGSUSED*/
1983 buflist_findpat(pattern, pattern_end, unlisted, diffmode)
1984 char_u *pattern;
1985 char_u *pattern_end; /* pointer to first char after pattern */
1986 int unlisted; /* find unlisted buffers */
1987 int diffmode; /* find diff-mode buffers only */
1989 buf_T *buf;
1990 regprog_T *prog;
1991 int match = -1;
1992 int find_listed;
1993 char_u *pat;
1994 char_u *patend;
1995 int attempt;
1996 char_u *p;
1997 int toggledollar;
1999 if (pattern_end == pattern + 1 && (*pattern == '%' || *pattern == '#'))
2001 if (*pattern == '%')
2002 match = curbuf->b_fnum;
2003 else
2004 match = curwin->w_alt_fnum;
2005 #ifdef FEAT_DIFF
2006 if (diffmode && !diff_mode_buf(buflist_findnr(match)))
2007 match = -1;
2008 #endif
2012 * Try four ways of matching a listed buffer:
2013 * attempt == 0: without '^' or '$' (at any position)
2014 * attempt == 1: with '^' at start (only at postion 0)
2015 * attempt == 2: with '$' at end (only match at end)
2016 * attempt == 3: with '^' at start and '$' at end (only full match)
2017 * Repeat this for finding an unlisted buffer if there was no matching
2018 * listed buffer.
2020 else
2022 pat = file_pat_to_reg_pat(pattern, pattern_end, NULL, FALSE);
2023 if (pat == NULL)
2024 return -1;
2025 patend = pat + STRLEN(pat) - 1;
2026 toggledollar = (patend > pat && *patend == '$');
2028 /* First try finding a listed buffer. If not found and "unlisted"
2029 * is TRUE, try finding an unlisted buffer. */
2030 find_listed = TRUE;
2031 for (;;)
2033 for (attempt = 0; attempt <= 3; ++attempt)
2035 /* may add '^' and '$' */
2036 if (toggledollar)
2037 *patend = (attempt < 2) ? NUL : '$'; /* add/remove '$' */
2038 p = pat;
2039 if (*p == '^' && !(attempt & 1)) /* add/remove '^' */
2040 ++p;
2041 prog = vim_regcomp(p, p_magic ? RE_MAGIC : 0);
2042 if (prog == NULL)
2044 vim_free(pat);
2045 return -1;
2048 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2049 if (buf->b_p_bl == find_listed
2050 #ifdef FEAT_DIFF
2051 && (!diffmode || diff_mode_buf(buf))
2052 #endif
2053 && buflist_match(prog, buf) != NULL)
2055 if (match >= 0) /* already found a match */
2057 match = -2;
2058 break;
2060 match = buf->b_fnum; /* remember first match */
2063 vim_free(prog);
2064 if (match >= 0) /* found one match */
2065 break;
2068 /* Only search for unlisted buffers if there was no match with
2069 * a listed buffer. */
2070 if (!unlisted || !find_listed || match != -1)
2071 break;
2072 find_listed = FALSE;
2075 vim_free(pat);
2078 if (match == -2)
2079 EMSG2(_("E93: More than one match for %s"), pattern);
2080 else if (match < 0)
2081 EMSG2(_("E94: No matching buffer for %s"), pattern);
2082 return match;
2084 #endif
2086 #if defined(FEAT_CMDL_COMPL) || defined(PROTO)
2089 * Find all buffer names that match.
2090 * For command line expansion of ":buf" and ":sbuf".
2091 * Return OK if matches found, FAIL otherwise.
2094 ExpandBufnames(pat, num_file, file, options)
2095 char_u *pat;
2096 int *num_file;
2097 char_u ***file;
2098 int options;
2100 int count = 0;
2101 buf_T *buf;
2102 int round;
2103 char_u *p;
2104 int attempt;
2105 regprog_T *prog;
2106 char_u *patc;
2108 *num_file = 0; /* return values in case of FAIL */
2109 *file = NULL;
2111 /* Make a copy of "pat" and change "^" to "\(^\|[\/]\)". */
2112 if (*pat == '^')
2114 patc = alloc((unsigned)STRLEN(pat) + 11);
2115 if (patc == NULL)
2116 return FAIL;
2117 STRCPY(patc, "\\(^\\|[\\/]\\)");
2118 STRCPY(patc + 11, pat + 1);
2120 else
2121 patc = pat;
2124 * attempt == 0: try match with '\<', match at start of word
2125 * attempt == 1: try match without '\<', match anywhere
2127 for (attempt = 0; attempt <= 1; ++attempt)
2129 if (attempt > 0 && patc == pat)
2130 break; /* there was no anchor, no need to try again */
2131 prog = vim_regcomp(patc + attempt * 11, RE_MAGIC);
2132 if (prog == NULL)
2134 if (patc != pat)
2135 vim_free(patc);
2136 return FAIL;
2140 * round == 1: Count the matches.
2141 * round == 2: Build the array to keep the matches.
2143 for (round = 1; round <= 2; ++round)
2145 count = 0;
2146 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2148 if (!buf->b_p_bl) /* skip unlisted buffers */
2149 continue;
2150 p = buflist_match(prog, buf);
2151 if (p != NULL)
2153 if (round == 1)
2154 ++count;
2155 else
2157 if (options & WILD_HOME_REPLACE)
2158 p = home_replace_save(buf, p);
2159 else
2160 p = vim_strsave(p);
2161 (*file)[count++] = p;
2165 if (count == 0) /* no match found, break here */
2166 break;
2167 if (round == 1)
2169 *file = (char_u **)alloc((unsigned)(count * sizeof(char_u *)));
2170 if (*file == NULL)
2172 vim_free(prog);
2173 if (patc != pat)
2174 vim_free(patc);
2175 return FAIL;
2179 vim_free(prog);
2180 if (count) /* match(es) found, break here */
2181 break;
2184 if (patc != pat)
2185 vim_free(patc);
2187 *num_file = count;
2188 return (count == 0 ? FAIL : OK);
2191 #endif /* FEAT_CMDL_COMPL */
2193 #ifdef HAVE_BUFLIST_MATCH
2195 * Check for a match on the file name for buffer "buf" with regprog "prog".
2197 static char_u *
2198 buflist_match(prog, buf)
2199 regprog_T *prog;
2200 buf_T *buf;
2202 char_u *match;
2204 /* First try the short file name, then the long file name. */
2205 match = fname_match(prog, buf->b_sfname);
2206 if (match == NULL)
2207 match = fname_match(prog, buf->b_ffname);
2209 return match;
2213 * Try matching the regexp in "prog" with file name "name".
2214 * Return "name" when there is a match, NULL when not.
2216 static char_u *
2217 fname_match(prog, name)
2218 regprog_T *prog;
2219 char_u *name;
2221 char_u *match = NULL;
2222 char_u *p;
2223 regmatch_T regmatch;
2225 if (name != NULL)
2227 regmatch.regprog = prog;
2228 #ifdef CASE_INSENSITIVE_FILENAME
2229 regmatch.rm_ic = TRUE; /* Always ignore case */
2230 #else
2231 regmatch.rm_ic = FALSE; /* Never ignore case */
2232 #endif
2234 if (vim_regexec(&regmatch, name, (colnr_T)0))
2235 match = name;
2236 else
2238 /* Replace $(HOME) with '~' and try matching again. */
2239 p = home_replace_save(NULL, name);
2240 if (p != NULL && vim_regexec(&regmatch, p, (colnr_T)0))
2241 match = name;
2242 vim_free(p);
2246 return match;
2248 #endif
2251 * find file in buffer list by number
2253 buf_T *
2254 buflist_findnr(nr)
2255 int nr;
2257 buf_T *buf;
2259 if (nr == 0)
2260 nr = curwin->w_alt_fnum;
2261 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
2262 if (buf->b_fnum == nr)
2263 return (buf);
2264 return NULL;
2268 * Get name of file 'n' in the buffer list.
2269 * When the file has no name an empty string is returned.
2270 * home_replace() is used to shorten the file name (used for marks).
2271 * Returns a pointer to allocated memory, of NULL when failed.
2273 char_u *
2274 buflist_nr2name(n, fullname, helptail)
2275 int n;
2276 int fullname;
2277 int helptail; /* for help buffers return tail only */
2279 buf_T *buf;
2281 buf = buflist_findnr(n);
2282 if (buf == NULL)
2283 return NULL;
2284 return home_replace_save(helptail ? buf : NULL,
2285 fullname ? buf->b_ffname : buf->b_fname);
2289 * Set the "lnum" and "col" for the buffer "buf" and the current window.
2290 * When "copy_options" is TRUE save the local window option values.
2291 * When "lnum" is 0 only do the options.
2293 static void
2294 buflist_setfpos(buf, win, lnum, col, copy_options)
2295 buf_T *buf;
2296 win_T *win;
2297 linenr_T lnum;
2298 colnr_T col;
2299 int copy_options;
2301 wininfo_T *wip;
2303 for (wip = buf->b_wininfo; wip != NULL; wip = wip->wi_next)
2304 if (wip->wi_win == win)
2305 break;
2306 if (wip == NULL)
2308 /* allocate a new entry */
2309 wip = (wininfo_T *)alloc_clear((unsigned)sizeof(wininfo_T));
2310 if (wip == NULL)
2311 return;
2312 wip->wi_win = win;
2313 if (lnum == 0) /* set lnum even when it's 0 */
2314 lnum = 1;
2316 else
2318 /* remove the entry from the list */
2319 if (wip->wi_prev)
2320 wip->wi_prev->wi_next = wip->wi_next;
2321 else
2322 buf->b_wininfo = wip->wi_next;
2323 if (wip->wi_next)
2324 wip->wi_next->wi_prev = wip->wi_prev;
2325 if (copy_options && wip->wi_optset)
2327 clear_winopt(&wip->wi_opt);
2328 #ifdef FEAT_FOLDING
2329 deleteFoldRecurse(&wip->wi_folds);
2330 #endif
2333 if (lnum != 0)
2335 wip->wi_fpos.lnum = lnum;
2336 wip->wi_fpos.col = col;
2338 if (copy_options)
2340 /* Save the window-specific option values. */
2341 copy_winopt(&win->w_onebuf_opt, &wip->wi_opt);
2342 #ifdef FEAT_FOLDING
2343 wip->wi_fold_manual = win->w_fold_manual;
2344 cloneFoldGrowArray(&win->w_folds, &wip->wi_folds);
2345 #endif
2346 wip->wi_optset = TRUE;
2349 /* insert the entry in front of the list */
2350 wip->wi_next = buf->b_wininfo;
2351 buf->b_wininfo = wip;
2352 wip->wi_prev = NULL;
2353 if (wip->wi_next)
2354 wip->wi_next->wi_prev = wip;
2356 return;
2360 * Find info for the current window in buffer "buf".
2361 * If not found, return the info for the most recently used window.
2362 * Returns NULL when there isn't any info.
2364 static wininfo_T *
2365 find_wininfo(buf)
2366 buf_T *buf;
2368 wininfo_T *wip;
2370 for (wip = buf->b_wininfo; wip != NULL; wip = wip->wi_next)
2371 if (wip->wi_win == curwin)
2372 break;
2373 if (wip == NULL) /* if no fpos for curwin, use the first in the list */
2374 wip = buf->b_wininfo;
2375 return wip;
2379 * Reset the local window options to the values last used in this window.
2380 * If the buffer wasn't used in this window before, use the values from
2381 * the most recently used window. If the values were never set, use the
2382 * global values for the window.
2384 void
2385 get_winopts(buf)
2386 buf_T *buf;
2388 wininfo_T *wip;
2390 clear_winopt(&curwin->w_onebuf_opt);
2391 #ifdef FEAT_FOLDING
2392 clearFolding(curwin);
2393 #endif
2395 wip = find_wininfo(buf);
2396 if (wip != NULL && wip->wi_optset)
2398 copy_winopt(&wip->wi_opt, &curwin->w_onebuf_opt);
2399 #ifdef FEAT_FOLDING
2400 curwin->w_fold_manual = wip->wi_fold_manual;
2401 curwin->w_foldinvalid = TRUE;
2402 cloneFoldGrowArray(&wip->wi_folds, &curwin->w_folds);
2403 #endif
2405 else
2406 copy_winopt(&curwin->w_allbuf_opt, &curwin->w_onebuf_opt);
2408 #ifdef FEAT_FOLDING
2409 /* Set 'foldlevel' to 'foldlevelstart' if it's not negative. */
2410 if (p_fdls >= 0)
2411 curwin->w_p_fdl = p_fdls;
2412 #endif
2414 #ifdef FEAT_SPELL
2415 if (curwin->w_p_spell && *buf->b_p_spl != NUL)
2416 did_set_spelllang(buf);
2417 #endif
2421 * Find the position (lnum and col) for the buffer 'buf' for the current
2422 * window.
2423 * Returns a pointer to no_position if no position is found.
2425 pos_T *
2426 buflist_findfpos(buf)
2427 buf_T *buf;
2429 wininfo_T *wip;
2430 static pos_T no_position = {1, 0};
2432 wip = find_wininfo(buf);
2433 if (wip != NULL)
2434 return &(wip->wi_fpos);
2435 else
2436 return &no_position;
2440 * Find the lnum for the buffer 'buf' for the current window.
2442 linenr_T
2443 buflist_findlnum(buf)
2444 buf_T *buf;
2446 return buflist_findfpos(buf)->lnum;
2449 #if defined(FEAT_LISTCMDS) || defined(PROTO)
2451 * List all know file names (for :files and :buffers command).
2453 /*ARGSUSED*/
2454 void
2455 buflist_list(eap)
2456 exarg_T *eap;
2458 buf_T *buf;
2459 int len;
2460 int i;
2462 for (buf = firstbuf; buf != NULL && !got_int; buf = buf->b_next)
2464 /* skip unlisted buffers, unless ! was used */
2465 if (!buf->b_p_bl && !eap->forceit)
2466 continue;
2467 msg_putchar('\n');
2468 if (buf_spname(buf) != NULL)
2469 STRCPY(NameBuff, buf_spname(buf));
2470 else
2471 home_replace(buf, buf->b_fname, NameBuff, MAXPATHL, TRUE);
2473 len = vim_snprintf((char *)IObuff, IOSIZE - 20, "%3d%c%c%c%c%c \"%s\"",
2474 buf->b_fnum,
2475 buf->b_p_bl ? ' ' : 'u',
2476 buf == curbuf ? '%' :
2477 (curwin->w_alt_fnum == buf->b_fnum ? '#' : ' '),
2478 buf->b_ml.ml_mfp == NULL ? ' ' :
2479 (buf->b_nwindows == 0 ? 'h' : 'a'),
2480 !buf->b_p_ma ? '-' : (buf->b_p_ro ? '=' : ' '),
2481 (buf->b_flags & BF_READERR) ? 'x'
2482 : (bufIsChanged(buf) ? '+' : ' '),
2483 NameBuff);
2485 /* put "line 999" in column 40 or after the file name */
2486 i = 40 - vim_strsize(IObuff);
2489 IObuff[len++] = ' ';
2490 } while (--i > 0 && len < IOSIZE - 18);
2491 vim_snprintf((char *)IObuff + len, IOSIZE - len, _("line %ld"),
2492 buf == curbuf ? curwin->w_cursor.lnum
2493 : (long)buflist_findlnum(buf));
2494 msg_outtrans(IObuff);
2495 out_flush(); /* output one line at a time */
2496 ui_breakcheck();
2499 #endif
2502 * Get file name and line number for file 'fnum'.
2503 * Used by DoOneCmd() for translating '%' and '#'.
2504 * Used by insert_reg() and cmdline_paste() for '#' register.
2505 * Return FAIL if not found, OK for success.
2508 buflist_name_nr(fnum, fname, lnum)
2509 int fnum;
2510 char_u **fname;
2511 linenr_T *lnum;
2513 buf_T *buf;
2515 buf = buflist_findnr(fnum);
2516 if (buf == NULL || buf->b_fname == NULL)
2517 return FAIL;
2519 *fname = buf->b_fname;
2520 *lnum = buflist_findlnum(buf);
2522 return OK;
2526 * Set the file name for "buf"' to 'ffname', short file name to 'sfname'.
2527 * The file name with the full path is also remembered, for when :cd is used.
2528 * Returns FAIL for failure (file name already in use by other buffer)
2529 * OK otherwise.
2532 setfname(buf, ffname, sfname, message)
2533 buf_T *buf;
2534 char_u *ffname, *sfname;
2535 int message; /* give message when buffer already exists */
2537 buf_T *obuf = NULL;
2538 #ifdef UNIX
2539 struct stat st;
2540 #endif
2542 if (ffname == NULL || *ffname == NUL)
2544 /* Removing the name. */
2545 vim_free(buf->b_ffname);
2546 vim_free(buf->b_sfname);
2547 buf->b_ffname = NULL;
2548 buf->b_sfname = NULL;
2549 #ifdef UNIX
2550 st.st_dev = (dev_T)-1;
2551 #endif
2553 else
2555 fname_expand(buf, &ffname, &sfname); /* will allocate ffname */
2556 if (ffname == NULL) /* out of memory */
2557 return FAIL;
2560 * if the file name is already used in another buffer:
2561 * - if the buffer is loaded, fail
2562 * - if the buffer is not loaded, delete it from the list
2564 #ifdef UNIX
2565 if (mch_stat((char *)ffname, &st) < 0)
2566 st.st_dev = (dev_T)-1;
2567 #endif
2568 if (!(buf->b_flags & BF_DUMMY))
2569 #ifdef UNIX
2570 obuf = buflist_findname_stat(ffname, &st);
2571 #else
2572 obuf = buflist_findname(ffname);
2573 #endif
2574 if (obuf != NULL && obuf != buf)
2576 if (obuf->b_ml.ml_mfp != NULL) /* it's loaded, fail */
2578 if (message)
2579 EMSG(_("E95: Buffer with this name already exists"));
2580 vim_free(ffname);
2581 return FAIL;
2583 close_buffer(NULL, obuf, DOBUF_WIPE); /* delete from the list */
2585 sfname = vim_strsave(sfname);
2586 if (ffname == NULL || sfname == NULL)
2588 vim_free(sfname);
2589 vim_free(ffname);
2590 return FAIL;
2592 #ifdef USE_FNAME_CASE
2593 # ifdef USE_LONG_FNAME
2594 if (USE_LONG_FNAME)
2595 # endif
2596 fname_case(sfname, 0); /* set correct case for short file name */
2597 #endif
2598 vim_free(buf->b_ffname);
2599 vim_free(buf->b_sfname);
2600 buf->b_ffname = ffname;
2601 buf->b_sfname = sfname;
2603 buf->b_fname = buf->b_sfname;
2604 #ifdef UNIX
2605 if (st.st_dev == (dev_T)-1)
2606 buf->b_dev = -1;
2607 else
2609 buf->b_dev = st.st_dev;
2610 buf->b_ino = st.st_ino;
2612 #endif
2614 #ifndef SHORT_FNAME
2615 buf->b_shortname = FALSE;
2616 #endif
2618 buf_name_changed(buf);
2619 return OK;
2623 * Crude way of changing the name of a buffer. Use with care!
2624 * The name should be relative to the current directory.
2626 void
2627 buf_set_name(fnum, name)
2628 int fnum;
2629 char_u *name;
2631 buf_T *buf;
2633 buf = buflist_findnr(fnum);
2634 if (buf != NULL)
2636 vim_free(buf->b_sfname);
2637 vim_free(buf->b_ffname);
2638 buf->b_sfname = vim_strsave(name);
2639 buf->b_ffname = FullName_save(buf->b_sfname, FALSE);
2640 buf->b_fname = buf->b_sfname;
2645 * Take care of what needs to be done when the name of buffer "buf" has
2646 * changed.
2648 void
2649 buf_name_changed(buf)
2650 buf_T *buf;
2653 * If the file name changed, also change the name of the swapfile
2655 if (buf->b_ml.ml_mfp != NULL)
2656 ml_setname(buf);
2658 if (curwin->w_buffer == buf)
2659 check_arg_idx(curwin); /* check file name for arg list */
2660 #ifdef FEAT_TITLE
2661 maketitle(); /* set window title */
2662 #endif
2663 #ifdef FEAT_WINDOWS
2664 status_redraw_all(); /* status lines need to be redrawn */
2665 #endif
2666 fmarks_check_names(buf); /* check named file marks */
2667 ml_timestamp(buf); /* reset timestamp */
2671 * set alternate file name for current window
2673 * Used by do_one_cmd(), do_write() and do_ecmd().
2674 * Return the buffer.
2676 buf_T *
2677 setaltfname(ffname, sfname, lnum)
2678 char_u *ffname;
2679 char_u *sfname;
2680 linenr_T lnum;
2682 buf_T *buf;
2684 /* Create a buffer. 'buflisted' is not set if it's a new buffer */
2685 buf = buflist_new(ffname, sfname, lnum, 0);
2686 if (buf != NULL && !cmdmod.keepalt)
2687 curwin->w_alt_fnum = buf->b_fnum;
2688 return buf;
2692 * Get alternate file name for current window.
2693 * Return NULL if there isn't any, and give error message if requested.
2695 char_u *
2696 getaltfname(errmsg)
2697 int errmsg; /* give error message */
2699 char_u *fname;
2700 linenr_T dummy;
2702 if (buflist_name_nr(0, &fname, &dummy) == FAIL)
2704 if (errmsg)
2705 EMSG(_(e_noalt));
2706 return NULL;
2708 return fname;
2712 * Add a file name to the buflist and return its number.
2713 * Uses same flags as buflist_new(), except BLN_DUMMY.
2715 * used by qf_init(), main() and doarglist()
2718 buflist_add(fname, flags)
2719 char_u *fname;
2720 int flags;
2722 buf_T *buf;
2724 buf = buflist_new(fname, NULL, (linenr_T)0, flags);
2725 if (buf != NULL)
2726 return buf->b_fnum;
2727 return 0;
2730 #if defined(BACKSLASH_IN_FILENAME) || defined(PROTO)
2732 * Adjust slashes in file names. Called after 'shellslash' was set.
2734 void
2735 buflist_slash_adjust()
2737 buf_T *bp;
2739 for (bp = firstbuf; bp != NULL; bp = bp->b_next)
2741 if (bp->b_ffname != NULL)
2742 slash_adjust(bp->b_ffname);
2743 if (bp->b_sfname != NULL)
2744 slash_adjust(bp->b_sfname);
2747 #endif
2750 * Set alternate cursor position for current window.
2751 * Also save the local window option values.
2753 void
2754 buflist_altfpos()
2756 buflist_setfpos(curbuf, curwin, curwin->w_cursor.lnum,
2757 curwin->w_cursor.col, TRUE);
2761 * Return TRUE if 'ffname' is not the same file as current file.
2762 * Fname must have a full path (expanded by mch_FullName()).
2765 otherfile(ffname)
2766 char_u *ffname;
2768 return otherfile_buf(curbuf, ffname
2769 #ifdef UNIX
2770 , NULL
2771 #endif
2775 static int
2776 otherfile_buf(buf, ffname
2777 #ifdef UNIX
2778 , stp
2779 #endif
2781 buf_T *buf;
2782 char_u *ffname;
2783 #ifdef UNIX
2784 struct stat *stp;
2785 #endif
2787 /* no name is different */
2788 if (ffname == NULL || *ffname == NUL || buf->b_ffname == NULL)
2789 return TRUE;
2790 if (fnamecmp(ffname, buf->b_ffname) == 0)
2791 return FALSE;
2792 #ifdef UNIX
2794 struct stat st;
2796 /* If no struct stat given, get it now */
2797 if (stp == NULL)
2799 if (buf->b_dev < 0 || mch_stat((char *)ffname, &st) < 0)
2800 st.st_dev = (dev_T)-1;
2801 stp = &st;
2803 /* Use dev/ino to check if the files are the same, even when the names
2804 * are different (possible with links). Still need to compare the
2805 * name above, for when the file doesn't exist yet.
2806 * Problem: The dev/ino changes when a file is deleted (and created
2807 * again) and remains the same when renamed/moved. We don't want to
2808 * mch_stat() each buffer each time, that would be too slow. Get the
2809 * dev/ino again when they appear to match, but not when they appear
2810 * to be different: Could skip a buffer when it's actually the same
2811 * file. */
2812 if (buf_same_ino(buf, stp))
2814 buf_setino(buf);
2815 if (buf_same_ino(buf, stp))
2816 return FALSE;
2819 #endif
2820 return TRUE;
2823 #if defined(UNIX) || defined(PROTO)
2825 * Set inode and device number for a buffer.
2826 * Must always be called when b_fname is changed!.
2828 void
2829 buf_setino(buf)
2830 buf_T *buf;
2832 struct stat st;
2834 if (buf->b_fname != NULL && mch_stat((char *)buf->b_fname, &st) >= 0)
2836 buf->b_dev = st.st_dev;
2837 buf->b_ino = st.st_ino;
2839 else
2840 buf->b_dev = -1;
2844 * Return TRUE if dev/ino in buffer "buf" matches with "stp".
2846 static int
2847 buf_same_ino(buf, stp)
2848 buf_T *buf;
2849 struct stat *stp;
2851 return (buf->b_dev >= 0
2852 && stp->st_dev == buf->b_dev
2853 && stp->st_ino == buf->b_ino);
2855 #endif
2858 * Print info about the current buffer.
2860 void
2861 fileinfo(fullname, shorthelp, dont_truncate)
2862 int fullname; /* when non-zero print full path */
2863 int shorthelp;
2864 int dont_truncate;
2866 char_u *name;
2867 int n;
2868 char_u *p;
2869 char_u *buffer;
2870 size_t len;
2872 buffer = alloc(IOSIZE);
2873 if (buffer == NULL)
2874 return;
2876 if (fullname > 1) /* 2 CTRL-G: include buffer number */
2878 sprintf((char *)buffer, "buf %d: ", curbuf->b_fnum);
2879 p = buffer + STRLEN(buffer);
2881 else
2882 p = buffer;
2884 *p++ = '"';
2885 if (buf_spname(curbuf) != NULL)
2886 STRCPY(p, buf_spname(curbuf));
2887 else
2889 if (!fullname && curbuf->b_fname != NULL)
2890 name = curbuf->b_fname;
2891 else
2892 name = curbuf->b_ffname;
2893 home_replace(shorthelp ? curbuf : NULL, name, p,
2894 (int)(IOSIZE - (p - buffer)), TRUE);
2897 len = STRLEN(buffer);
2898 vim_snprintf((char *)buffer + len, IOSIZE - len,
2899 "\"%s%s%s%s%s%s",
2900 curbufIsChanged() ? (shortmess(SHM_MOD)
2901 ? " [+]" : _(" [Modified]")) : " ",
2902 (curbuf->b_flags & BF_NOTEDITED)
2903 #ifdef FEAT_QUICKFIX
2904 && !bt_dontwrite(curbuf)
2905 #endif
2906 ? _("[Not edited]") : "",
2907 (curbuf->b_flags & BF_NEW)
2908 #ifdef FEAT_QUICKFIX
2909 && !bt_dontwrite(curbuf)
2910 #endif
2911 ? _("[New file]") : "",
2912 (curbuf->b_flags & BF_READERR) ? _("[Read errors]") : "",
2913 curbuf->b_p_ro ? (shortmess(SHM_RO) ? "[RO]"
2914 : _("[readonly]")) : "",
2915 (curbufIsChanged() || (curbuf->b_flags & BF_WRITE_MASK)
2916 || curbuf->b_p_ro) ?
2917 " " : "");
2918 /* With 32 bit longs and more than 21,474,836 lines multiplying by 100
2919 * causes an overflow, thus for large numbers divide instead. */
2920 if (curwin->w_cursor.lnum > 1000000L)
2921 n = (int)(((long)curwin->w_cursor.lnum) /
2922 ((long)curbuf->b_ml.ml_line_count / 100L));
2923 else
2924 n = (int)(((long)curwin->w_cursor.lnum * 100L) /
2925 (long)curbuf->b_ml.ml_line_count);
2926 len = STRLEN(buffer);
2927 if (curbuf->b_ml.ml_flags & ML_EMPTY)
2929 vim_snprintf((char *)buffer + len, IOSIZE - len, "%s", _(no_lines_msg));
2931 #ifdef FEAT_CMDL_INFO
2932 else if (p_ru)
2934 /* Current line and column are already on the screen -- webb */
2935 if (curbuf->b_ml.ml_line_count == 1)
2936 vim_snprintf((char *)buffer + len, IOSIZE - len,
2937 _("1 line --%d%%--"), n);
2938 else
2939 vim_snprintf((char *)buffer + len, IOSIZE - len,
2940 _("%ld lines --%d%%--"),
2941 (long)curbuf->b_ml.ml_line_count, n);
2943 #endif
2944 else
2946 vim_snprintf((char *)buffer + len, IOSIZE - len,
2947 _("line %ld of %ld --%d%%-- col "),
2948 (long)curwin->w_cursor.lnum,
2949 (long)curbuf->b_ml.ml_line_count,
2951 validate_virtcol();
2952 col_print(buffer + STRLEN(buffer),
2953 (int)curwin->w_cursor.col + 1, (int)curwin->w_virtcol + 1);
2956 (void)append_arg_number(curwin, buffer, !shortmess(SHM_FILE), IOSIZE);
2958 if (dont_truncate)
2960 /* Temporarily set msg_scroll to avoid the message being truncated.
2961 * First call msg_start() to get the message in the right place. */
2962 msg_start();
2963 n = msg_scroll;
2964 msg_scroll = TRUE;
2965 msg(buffer);
2966 msg_scroll = n;
2968 else
2970 p = msg_trunc_attr(buffer, FALSE, 0);
2971 if (restart_edit != 0 || (msg_scrolled && !need_wait_return))
2972 /* Need to repeat the message after redrawing when:
2973 * - When restart_edit is set (otherwise there will be a delay
2974 * before redrawing).
2975 * - When the screen was scrolled but there is no wait-return
2976 * prompt. */
2977 set_keep_msg(p, 0);
2980 vim_free(buffer);
2983 void
2984 col_print(buf, col, vcol)
2985 char_u *buf;
2986 int col;
2987 int vcol;
2989 if (col == vcol)
2990 sprintf((char *)buf, "%d", col);
2991 else
2992 sprintf((char *)buf, "%d-%d", col, vcol);
2995 #if defined(FEAT_TITLE) || defined(PROTO)
2997 * put file name in title bar of window and in icon title
3000 static char_u *lasttitle = NULL;
3001 static char_u *lasticon = NULL;
3003 void
3004 maketitle()
3006 char_u *p;
3007 char_u *t_str = NULL;
3008 char_u *i_name;
3009 char_u *i_str = NULL;
3010 int maxlen = 0;
3011 int len;
3012 int mustset;
3013 char_u buf[IOSIZE];
3014 int off;
3016 if (!redrawing())
3018 /* Postpone updating the title when 'lazyredraw' is set. */
3019 need_maketitle = TRUE;
3020 return;
3023 need_maketitle = FALSE;
3024 if (!p_title && !p_icon)
3025 return;
3027 if (p_title)
3029 if (p_titlelen > 0)
3031 maxlen = p_titlelen * Columns / 100;
3032 if (maxlen < 10)
3033 maxlen = 10;
3036 t_str = buf;
3037 if (*p_titlestring != NUL)
3039 #ifdef FEAT_STL_OPT
3040 if (stl_syntax & STL_IN_TITLE)
3042 int use_sandbox = FALSE;
3043 int save_called_emsg = called_emsg;
3045 # ifdef FEAT_EVAL
3046 use_sandbox = was_set_insecurely((char_u *)"titlestring", 0);
3047 # endif
3048 called_emsg = FALSE;
3049 build_stl_str_hl(curwin, t_str, sizeof(buf),
3050 p_titlestring, use_sandbox,
3051 0, maxlen, NULL, NULL);
3052 if (called_emsg)
3053 set_string_option_direct((char_u *)"titlestring", -1,
3054 (char_u *)"", OPT_FREE, SID_ERROR);
3055 called_emsg |= save_called_emsg;
3057 else
3058 #endif
3059 t_str = p_titlestring;
3061 else
3063 /* format: "fname + (path) (1 of 2) - VIM" */
3065 if (curbuf->b_fname == NULL)
3066 STRCPY(buf, _("[No Name]"));
3067 else
3069 p = transstr(gettail(curbuf->b_fname));
3070 vim_strncpy(buf, p, IOSIZE - 100);
3071 vim_free(p);
3074 switch (bufIsChanged(curbuf)
3075 + (curbuf->b_p_ro * 2)
3076 + (!curbuf->b_p_ma * 4))
3078 case 1: STRCAT(buf, " +"); break;
3079 case 2: STRCAT(buf, " ="); break;
3080 case 3: STRCAT(buf, " =+"); break;
3081 case 4:
3082 case 6: STRCAT(buf, " -"); break;
3083 case 5:
3084 case 7: STRCAT(buf, " -+"); break;
3087 if (curbuf->b_fname != NULL)
3089 /* Get path of file, replace home dir with ~ */
3090 off = (int)STRLEN(buf);
3091 buf[off++] = ' ';
3092 buf[off++] = '(';
3093 home_replace(curbuf, curbuf->b_ffname,
3094 buf + off, IOSIZE - off, TRUE);
3095 #ifdef BACKSLASH_IN_FILENAME
3096 /* avoid "c:/name" to be reduced to "c" */
3097 if (isalpha(buf[off]) && buf[off + 1] == ':')
3098 off += 2;
3099 #endif
3100 /* remove the file name */
3101 p = gettail_sep(buf + off);
3102 if (p == buf + off)
3103 /* must be a help buffer */
3104 vim_strncpy(buf + off, (char_u *)_("help"),
3105 IOSIZE - off - 1);
3106 else
3107 *p = NUL;
3109 /* translate unprintable chars */
3110 p = transstr(buf + off);
3111 vim_strncpy(buf + off, p, IOSIZE - off - 1);
3112 vim_free(p);
3113 STRCAT(buf, ")");
3116 append_arg_number(curwin, buf, FALSE, IOSIZE);
3118 #if defined(FEAT_CLIENTSERVER)
3119 if (serverName != NULL)
3121 STRCAT(buf, " - ");
3122 STRCAT(buf, serverName);
3124 else
3125 #endif
3126 STRCAT(buf, " - VIM");
3128 if (maxlen > 0)
3130 /* make it shorter by removing a bit in the middle */
3131 len = vim_strsize(buf);
3132 if (len > maxlen)
3133 trunc_string(buf, buf, maxlen);
3137 mustset = ti_change(t_str, &lasttitle);
3139 if (p_icon)
3141 i_str = buf;
3142 if (*p_iconstring != NUL)
3144 #ifdef FEAT_STL_OPT
3145 if (stl_syntax & STL_IN_ICON)
3147 int use_sandbox = FALSE;
3148 int save_called_emsg = called_emsg;
3150 # ifdef FEAT_EVAL
3151 use_sandbox = was_set_insecurely((char_u *)"iconstring", 0);
3152 # endif
3153 called_emsg = FALSE;
3154 build_stl_str_hl(curwin, i_str, sizeof(buf),
3155 p_iconstring, use_sandbox,
3156 0, 0, NULL, NULL);
3157 if (called_emsg)
3158 set_string_option_direct((char_u *)"iconstring", -1,
3159 (char_u *)"", OPT_FREE, SID_ERROR);
3160 called_emsg |= save_called_emsg;
3162 else
3163 #endif
3164 i_str = p_iconstring;
3166 else
3168 if (buf_spname(curbuf) != NULL)
3169 i_name = (char_u *)buf_spname(curbuf);
3170 else /* use file name only in icon */
3171 i_name = gettail(curbuf->b_ffname);
3172 *i_str = NUL;
3173 /* Truncate name at 100 bytes. */
3174 len = (int)STRLEN(i_name);
3175 if (len > 100)
3177 len -= 100;
3178 #ifdef FEAT_MBYTE
3179 if (has_mbyte)
3180 len += (*mb_tail_off)(i_name, i_name + len) + 1;
3181 #endif
3182 i_name += len;
3184 STRCPY(i_str, i_name);
3185 trans_characters(i_str, IOSIZE);
3189 mustset |= ti_change(i_str, &lasticon);
3191 if (mustset)
3192 resettitle();
3196 * Used for title and icon: Check if "str" differs from "*last". Set "*last"
3197 * from "str" if it does.
3198 * Return TRUE when "*last" changed.
3200 static int
3201 ti_change(str, last)
3202 char_u *str;
3203 char_u **last;
3205 if ((str == NULL) != (*last == NULL)
3206 || (str != NULL && *last != NULL && STRCMP(str, *last) != 0))
3208 vim_free(*last);
3209 if (str == NULL)
3210 *last = NULL;
3211 else
3212 *last = vim_strsave(str);
3213 return TRUE;
3215 return FALSE;
3219 * Put current window title back (used after calling a shell)
3221 void
3222 resettitle()
3224 mch_settitle(lasttitle, lasticon);
3227 # if defined(EXITFREE) || defined(PROTO)
3228 void
3229 free_titles()
3231 vim_free(lasttitle);
3232 vim_free(lasticon);
3234 # endif
3236 #endif /* FEAT_TITLE */
3238 #if defined(FEAT_STL_OPT) || defined(FEAT_GUI_TABLINE) || defined(PROTO)
3240 * Build a string from the status line items in "fmt".
3241 * Return length of string in screen cells.
3243 * Normally works for window "wp", except when working for 'tabline' then it
3244 * is "curwin".
3246 * Items are drawn interspersed with the text that surrounds it
3247 * Specials: %-<wid>(xxx%) => group, %= => middle marker, %< => truncation
3248 * Item: %-<minwid>.<maxwid><itemch> All but <itemch> are optional
3250 * If maxwidth is not zero, the string will be filled at any middle marker
3251 * or truncated if too long, fillchar is used for all whitespace.
3253 /*ARGSUSED*/
3255 build_stl_str_hl(wp, out, outlen, fmt, use_sandbox, fillchar, maxwidth, hltab, tabtab)
3256 win_T *wp;
3257 char_u *out; /* buffer to write into != NameBuff */
3258 size_t outlen; /* length of out[] */
3259 char_u *fmt;
3260 int use_sandbox; /* "fmt" was set insecurely, use sandbox */
3261 int fillchar;
3262 int maxwidth;
3263 struct stl_hlrec *hltab; /* return: HL attributes (can be NULL) */
3264 struct stl_hlrec *tabtab; /* return: tab page nrs (can be NULL) */
3266 char_u *p;
3267 char_u *s;
3268 char_u *t;
3269 char_u *linecont;
3270 #ifdef FEAT_EVAL
3271 win_T *o_curwin;
3272 buf_T *o_curbuf;
3273 #endif
3274 int empty_line;
3275 colnr_T virtcol;
3276 long l;
3277 long n;
3278 int prevchar_isflag;
3279 int prevchar_isitem;
3280 int itemisflag;
3281 int fillable;
3282 char_u *str;
3283 long num;
3284 int width;
3285 int itemcnt;
3286 int curitem;
3287 int groupitem[STL_MAX_ITEM];
3288 int groupdepth;
3289 struct stl_item
3291 char_u *start;
3292 int minwid;
3293 int maxwid;
3294 enum
3296 Normal,
3297 Empty,
3298 Group,
3299 Middle,
3300 Highlight,
3301 TabPage,
3302 Trunc
3303 } type;
3304 } item[STL_MAX_ITEM];
3305 int minwid;
3306 int maxwid;
3307 int zeropad;
3308 char_u base;
3309 char_u opt;
3310 #define TMPLEN 70
3311 char_u tmp[TMPLEN];
3312 char_u *usefmt = fmt;
3313 struct stl_hlrec *sp;
3315 #ifdef FEAT_EVAL
3317 * When the format starts with "%!" then evaluate it as an expression and
3318 * use the result as the actual format string.
3320 if (fmt[0] == '%' && fmt[1] == '!')
3322 usefmt = eval_to_string_safe(fmt + 2, NULL, use_sandbox);
3323 if (usefmt == NULL)
3324 usefmt = (char_u *)"";
3326 #endif
3328 if (fillchar == 0)
3329 fillchar = ' ';
3330 #ifdef FEAT_MBYTE
3331 /* Can't handle a multi-byte fill character yet. */
3332 else if (mb_char2len(fillchar) > 1)
3333 fillchar = '-';
3334 #endif
3337 * Get line & check if empty (cursorpos will show "0-1").
3338 * If inversion is possible we use it. Else '=' characters are used.
3340 linecont = ml_get_buf(wp->w_buffer, wp->w_cursor.lnum, FALSE);
3341 empty_line = (*linecont == NUL);
3343 groupdepth = 0;
3344 p = out;
3345 curitem = 0;
3346 prevchar_isflag = TRUE;
3347 prevchar_isitem = FALSE;
3348 for (s = usefmt; *s; )
3350 if (*s != NUL && *s != '%')
3351 prevchar_isflag = prevchar_isitem = FALSE;
3354 * Handle up to the next '%' or the end.
3356 while (*s != NUL && *s != '%' && p + 1 < out + outlen)
3357 *p++ = *s++;
3358 if (*s == NUL || p + 1 >= out + outlen)
3359 break;
3362 * Handle one '%' item.
3364 s++;
3365 if (*s == '%')
3367 if (p + 1 >= out + outlen)
3368 break;
3369 *p++ = *s++;
3370 prevchar_isflag = prevchar_isitem = FALSE;
3371 continue;
3373 if (*s == STL_MIDDLEMARK)
3375 s++;
3376 if (groupdepth > 0)
3377 continue;
3378 item[curitem].type = Middle;
3379 item[curitem++].start = p;
3380 continue;
3382 if (*s == STL_TRUNCMARK)
3384 s++;
3385 item[curitem].type = Trunc;
3386 item[curitem++].start = p;
3387 continue;
3389 if (*s == ')')
3391 s++;
3392 if (groupdepth < 1)
3393 continue;
3394 groupdepth--;
3396 t = item[groupitem[groupdepth]].start;
3397 *p = NUL;
3398 l = vim_strsize(t);
3399 if (curitem > groupitem[groupdepth] + 1
3400 && item[groupitem[groupdepth]].minwid == 0)
3402 /* remove group if all items are empty */
3403 for (n = groupitem[groupdepth] + 1; n < curitem; n++)
3404 if (item[n].type == Normal)
3405 break;
3406 if (n == curitem)
3408 p = t;
3409 l = 0;
3412 if (l > item[groupitem[groupdepth]].maxwid)
3414 /* truncate, remove n bytes of text at the start */
3415 #ifdef FEAT_MBYTE
3416 if (has_mbyte)
3418 /* Find the first character that should be included. */
3419 n = 0;
3420 while (l >= item[groupitem[groupdepth]].maxwid)
3422 l -= ptr2cells(t + n);
3423 n += (*mb_ptr2len)(t + n);
3426 else
3427 #endif
3428 n = (long)(p - t) - item[groupitem[groupdepth]].maxwid + 1;
3430 *t = '<';
3431 mch_memmove(t + 1, t + n, p - (t + n));
3432 p = p - n + 1;
3433 #ifdef FEAT_MBYTE
3434 /* Fill up space left over by half a double-wide char. */
3435 while (++l < item[groupitem[groupdepth]].minwid)
3436 *p++ = fillchar;
3437 #endif
3439 /* correct the start of the items for the truncation */
3440 for (l = groupitem[groupdepth] + 1; l < curitem; l++)
3442 item[l].start -= n;
3443 if (item[l].start < t)
3444 item[l].start = t;
3447 else if (abs(item[groupitem[groupdepth]].minwid) > l)
3449 /* fill */
3450 n = item[groupitem[groupdepth]].minwid;
3451 if (n < 0)
3453 /* fill by appending characters */
3454 n = 0 - n;
3455 while (l++ < n && p + 1 < out + outlen)
3456 *p++ = fillchar;
3458 else
3460 /* fill by inserting characters */
3461 mch_memmove(t + n - l, t, p - t);
3462 l = n - l;
3463 if (p + l >= out + outlen)
3464 l = (long)((out + outlen) - p - 1);
3465 p += l;
3466 for (n = groupitem[groupdepth] + 1; n < curitem; n++)
3467 item[n].start += l;
3468 for ( ; l > 0; l--)
3469 *t++ = fillchar;
3472 continue;
3474 minwid = 0;
3475 maxwid = 9999;
3476 zeropad = FALSE;
3477 l = 1;
3478 if (*s == '0')
3480 s++;
3481 zeropad = TRUE;
3483 if (*s == '-')
3485 s++;
3486 l = -1;
3488 if (VIM_ISDIGIT(*s))
3490 minwid = (int)getdigits(&s);
3491 if (minwid < 0) /* overflow */
3492 minwid = 0;
3494 if (*s == STL_USER_HL)
3496 item[curitem].type = Highlight;
3497 item[curitem].start = p;
3498 item[curitem].minwid = minwid > 9 ? 1 : minwid;
3499 s++;
3500 curitem++;
3501 continue;
3503 if (*s == STL_TABPAGENR || *s == STL_TABCLOSENR)
3505 if (*s == STL_TABCLOSENR)
3507 if (minwid == 0)
3509 /* %X ends the close label, go back to the previously
3510 * define tab label nr. */
3511 for (n = curitem - 1; n >= 0; --n)
3512 if (item[n].type == TabPage && item[n].minwid >= 0)
3514 minwid = item[n].minwid;
3515 break;
3518 else
3519 /* close nrs are stored as negative values */
3520 minwid = - minwid;
3522 item[curitem].type = TabPage;
3523 item[curitem].start = p;
3524 item[curitem].minwid = minwid;
3525 s++;
3526 curitem++;
3527 continue;
3529 if (*s == '.')
3531 s++;
3532 if (VIM_ISDIGIT(*s))
3534 maxwid = (int)getdigits(&s);
3535 if (maxwid <= 0) /* overflow */
3536 maxwid = 50;
3539 minwid = (minwid > 50 ? 50 : minwid) * l;
3540 if (*s == '(')
3542 groupitem[groupdepth++] = curitem;
3543 item[curitem].type = Group;
3544 item[curitem].start = p;
3545 item[curitem].minwid = minwid;
3546 item[curitem].maxwid = maxwid;
3547 s++;
3548 curitem++;
3549 continue;
3551 if (vim_strchr(STL_ALL, *s) == NULL)
3553 s++;
3554 continue;
3556 opt = *s++;
3558 /* OK - now for the real work */
3559 base = 'D';
3560 itemisflag = FALSE;
3561 fillable = TRUE;
3562 num = -1;
3563 str = NULL;
3564 switch (opt)
3566 case STL_FILEPATH:
3567 case STL_FULLPATH:
3568 case STL_FILENAME:
3569 fillable = FALSE; /* don't change ' ' to fillchar */
3570 if (buf_spname(wp->w_buffer) != NULL)
3571 STRCPY(NameBuff, buf_spname(wp->w_buffer));
3572 else
3574 t = (opt == STL_FULLPATH) ? wp->w_buffer->b_ffname
3575 : wp->w_buffer->b_fname;
3576 home_replace(wp->w_buffer, t, NameBuff, MAXPATHL, TRUE);
3578 trans_characters(NameBuff, MAXPATHL);
3579 if (opt != STL_FILENAME)
3580 str = NameBuff;
3581 else
3582 str = gettail(NameBuff);
3583 break;
3585 case STL_VIM_EXPR: /* '{' */
3586 itemisflag = TRUE;
3587 t = p;
3588 while (*s != '}' && *s != NUL && p + 1 < out + outlen)
3589 *p++ = *s++;
3590 if (*s != '}') /* missing '}' or out of space */
3591 break;
3592 s++;
3593 *p = 0;
3594 p = t;
3596 #ifdef FEAT_EVAL
3597 sprintf((char *)tmp, "%d", curbuf->b_fnum);
3598 set_internal_string_var((char_u *)"actual_curbuf", tmp);
3600 o_curbuf = curbuf;
3601 o_curwin = curwin;
3602 curwin = wp;
3603 curbuf = wp->w_buffer;
3605 str = eval_to_string_safe(p, &t, use_sandbox);
3607 curwin = o_curwin;
3608 curbuf = o_curbuf;
3609 do_unlet((char_u *)"g:actual_curbuf", TRUE);
3611 if (str != NULL && *str != 0)
3613 if (*skipdigits(str) == NUL)
3615 num = atoi((char *)str);
3616 vim_free(str);
3617 str = NULL;
3618 itemisflag = FALSE;
3621 #endif
3622 break;
3624 case STL_LINE:
3625 num = (wp->w_buffer->b_ml.ml_flags & ML_EMPTY)
3626 ? 0L : (long)(wp->w_cursor.lnum);
3627 break;
3629 case STL_NUMLINES:
3630 num = wp->w_buffer->b_ml.ml_line_count;
3631 break;
3633 case STL_COLUMN:
3634 num = !(State & INSERT) && empty_line
3635 ? 0 : (int)wp->w_cursor.col + 1;
3636 break;
3638 case STL_VIRTCOL:
3639 case STL_VIRTCOL_ALT:
3640 /* In list mode virtcol needs to be recomputed */
3641 virtcol = wp->w_virtcol;
3642 if (wp->w_p_list && lcs_tab1 == NUL)
3644 wp->w_p_list = FALSE;
3645 getvcol(wp, &wp->w_cursor, NULL, &virtcol, NULL);
3646 wp->w_p_list = TRUE;
3648 ++virtcol;
3649 /* Don't display %V if it's the same as %c. */
3650 if (opt == STL_VIRTCOL_ALT
3651 && (virtcol == (colnr_T)(!(State & INSERT) && empty_line
3652 ? 0 : (int)wp->w_cursor.col + 1)))
3653 break;
3654 num = (long)virtcol;
3655 break;
3657 case STL_PERCENTAGE:
3658 num = (int)(((long)wp->w_cursor.lnum * 100L) /
3659 (long)wp->w_buffer->b_ml.ml_line_count);
3660 break;
3662 case STL_ALTPERCENT:
3663 str = tmp;
3664 get_rel_pos(wp, str);
3665 break;
3667 case STL_ARGLISTSTAT:
3668 fillable = FALSE;
3669 tmp[0] = 0;
3670 if (append_arg_number(wp, tmp, FALSE, (int)sizeof(tmp)))
3671 str = tmp;
3672 break;
3674 case STL_KEYMAP:
3675 fillable = FALSE;
3676 if (get_keymap_str(wp, tmp, TMPLEN))
3677 str = tmp;
3678 break;
3679 case STL_PAGENUM:
3680 #if defined(FEAT_PRINTER) || defined(FEAT_GUI_TABLINE)
3681 num = printer_page_num;
3682 #else
3683 num = 0;
3684 #endif
3685 break;
3687 case STL_BUFNO:
3688 num = wp->w_buffer->b_fnum;
3689 break;
3691 case STL_OFFSET_X:
3692 base = 'X';
3693 case STL_OFFSET:
3694 #ifdef FEAT_BYTEOFF
3695 l = ml_find_line_or_offset(wp->w_buffer, wp->w_cursor.lnum, NULL);
3696 num = (wp->w_buffer->b_ml.ml_flags & ML_EMPTY) || l < 0 ?
3697 0L : l + 1 + (!(State & INSERT) && empty_line ?
3698 0 : (int)wp->w_cursor.col);
3699 #endif
3700 break;
3702 case STL_BYTEVAL_X:
3703 base = 'X';
3704 case STL_BYTEVAL:
3705 if (((State & INSERT) && wp == curwin) || empty_line)
3706 num = 0;
3707 else
3709 #ifdef FEAT_MBYTE
3710 num = (*mb_ptr2char)(linecont + wp->w_cursor.col);
3711 #else
3712 num = linecont[wp->w_cursor.col];
3713 #endif
3715 if (num == NL)
3716 num = 0;
3717 else if (num == CAR && get_fileformat(wp->w_buffer) == EOL_MAC)
3718 num = NL;
3719 break;
3721 case STL_ROFLAG:
3722 case STL_ROFLAG_ALT:
3723 itemisflag = TRUE;
3724 if (wp->w_buffer->b_p_ro)
3725 str = (char_u *)((opt == STL_ROFLAG_ALT) ? ",RO" : "[RO]");
3726 break;
3728 case STL_HELPFLAG:
3729 case STL_HELPFLAG_ALT:
3730 itemisflag = TRUE;
3731 if (wp->w_buffer->b_help)
3732 str = (char_u *)((opt == STL_HELPFLAG_ALT) ? ",HLP"
3733 : _("[Help]"));
3734 break;
3736 #ifdef FEAT_AUTOCMD
3737 case STL_FILETYPE:
3738 if (*wp->w_buffer->b_p_ft != NUL
3739 && STRLEN(wp->w_buffer->b_p_ft) < TMPLEN - 3)
3741 vim_snprintf((char *)tmp, sizeof(tmp), "[%s]",
3742 wp->w_buffer->b_p_ft);
3743 str = tmp;
3745 break;
3747 case STL_FILETYPE_ALT:
3748 itemisflag = TRUE;
3749 if (*wp->w_buffer->b_p_ft != NUL
3750 && STRLEN(wp->w_buffer->b_p_ft) < TMPLEN - 2)
3752 vim_snprintf((char *)tmp, sizeof(tmp), ",%s",
3753 wp->w_buffer->b_p_ft);
3754 for (t = tmp; *t != 0; t++)
3755 *t = TOUPPER_LOC(*t);
3756 str = tmp;
3758 break;
3759 #endif
3761 #if defined(FEAT_WINDOWS) && defined(FEAT_QUICKFIX)
3762 case STL_PREVIEWFLAG:
3763 case STL_PREVIEWFLAG_ALT:
3764 itemisflag = TRUE;
3765 if (wp->w_p_pvw)
3766 str = (char_u *)((opt == STL_PREVIEWFLAG_ALT) ? ",PRV"
3767 : _("[Preview]"));
3768 break;
3769 #endif
3771 case STL_MODIFIED:
3772 case STL_MODIFIED_ALT:
3773 itemisflag = TRUE;
3774 switch ((opt == STL_MODIFIED_ALT)
3775 + bufIsChanged(wp->w_buffer) * 2
3776 + (!wp->w_buffer->b_p_ma) * 4)
3778 case 2: str = (char_u *)"[+]"; break;
3779 case 3: str = (char_u *)",+"; break;
3780 case 4: str = (char_u *)"[-]"; break;
3781 case 5: str = (char_u *)",-"; break;
3782 case 6: str = (char_u *)"[+-]"; break;
3783 case 7: str = (char_u *)",+-"; break;
3785 break;
3787 case STL_HIGHLIGHT:
3788 t = s;
3789 while (*s != '#' && *s != NUL)
3790 ++s;
3791 if (*s == '#')
3793 item[curitem].type = Highlight;
3794 item[curitem].start = p;
3795 item[curitem].minwid = -syn_namen2id(t, (int)(s - t));
3796 curitem++;
3798 ++s;
3799 continue;
3802 item[curitem].start = p;
3803 item[curitem].type = Normal;
3804 if (str != NULL && *str)
3806 t = str;
3807 if (itemisflag)
3809 if ((t[0] && t[1])
3810 && ((!prevchar_isitem && *t == ',')
3811 || (prevchar_isflag && *t == ' ')))
3812 t++;
3813 prevchar_isflag = TRUE;
3815 l = vim_strsize(t);
3816 if (l > 0)
3817 prevchar_isitem = TRUE;
3818 if (l > maxwid)
3820 while (l >= maxwid)
3821 #ifdef FEAT_MBYTE
3822 if (has_mbyte)
3824 l -= ptr2cells(t);
3825 t += (*mb_ptr2len)(t);
3827 else
3828 #endif
3829 l -= byte2cells(*t++);
3830 if (p + 1 >= out + outlen)
3831 break;
3832 *p++ = '<';
3834 if (minwid > 0)
3836 for (; l < minwid && p + 1 < out + outlen; l++)
3838 /* Don't put a "-" in front of a digit. */
3839 if (l + 1 == minwid && fillchar == '-' && VIM_ISDIGIT(*t))
3840 *p++ = ' ';
3841 else
3842 *p++ = fillchar;
3844 minwid = 0;
3846 else
3847 minwid *= -1;
3848 while (*t && p + 1 < out + outlen)
3850 *p++ = *t++;
3851 /* Change a space by fillchar, unless fillchar is '-' and a
3852 * digit follows. */
3853 if (fillable && p[-1] == ' '
3854 && (!VIM_ISDIGIT(*t) || fillchar != '-'))
3855 p[-1] = fillchar;
3857 for (; l < minwid && p + 1 < out + outlen; l++)
3858 *p++ = fillchar;
3860 else if (num >= 0)
3862 int nbase = (base == 'D' ? 10 : (base == 'O' ? 8 : 16));
3863 char_u nstr[20];
3865 if (p + 20 >= out + outlen)
3866 break; /* not sufficient space */
3867 prevchar_isitem = TRUE;
3868 t = nstr;
3869 if (opt == STL_VIRTCOL_ALT)
3871 *t++ = '-';
3872 minwid--;
3874 *t++ = '%';
3875 if (zeropad)
3876 *t++ = '0';
3877 *t++ = '*';
3878 *t++ = nbase == 16 ? base : (nbase == 8 ? 'o' : 'd');
3879 *t = 0;
3881 for (n = num, l = 1; n >= nbase; n /= nbase)
3882 l++;
3883 if (opt == STL_VIRTCOL_ALT)
3884 l++;
3885 if (l > maxwid)
3887 l += 2;
3888 n = l - maxwid;
3889 while (l-- > maxwid)
3890 num /= nbase;
3891 *t++ = '>';
3892 *t++ = '%';
3893 *t = t[-3];
3894 *++t = 0;
3895 vim_snprintf((char *)p, outlen - (p - out), (char *)nstr,
3896 0, num, n);
3898 else
3899 vim_snprintf((char *)p, outlen - (p - out), (char *)nstr,
3900 minwid, num);
3901 p += STRLEN(p);
3903 else
3904 item[curitem].type = Empty;
3906 if (opt == STL_VIM_EXPR)
3907 vim_free(str);
3909 if (num >= 0 || (!itemisflag && str && *str))
3910 prevchar_isflag = FALSE; /* Item not NULL, but not a flag */
3911 curitem++;
3913 *p = NUL;
3914 itemcnt = curitem;
3916 #ifdef FEAT_EVAL
3917 if (usefmt != fmt)
3918 vim_free(usefmt);
3919 #endif
3921 width = vim_strsize(out);
3922 if (maxwidth > 0 && width > maxwidth)
3924 /* Result is too long, must trunctate somewhere. */
3925 l = 0;
3926 if (itemcnt == 0)
3927 s = out;
3928 else
3930 for ( ; l < itemcnt; l++)
3931 if (item[l].type == Trunc)
3933 /* Truncate at %< item. */
3934 s = item[l].start;
3935 break;
3937 if (l == itemcnt)
3939 /* No %< item, truncate first item. */
3940 s = item[0].start;
3941 l = 0;
3945 if (width - vim_strsize(s) >= maxwidth)
3947 /* Truncation mark is beyond max length */
3948 #ifdef FEAT_MBYTE
3949 if (has_mbyte)
3951 s = out;
3952 width = 0;
3953 for (;;)
3955 width += ptr2cells(s);
3956 if (width >= maxwidth)
3957 break;
3958 s += (*mb_ptr2len)(s);
3960 /* Fill up for half a double-wide character. */
3961 while (++width < maxwidth)
3962 *s++ = fillchar;
3964 else
3965 #endif
3966 s = out + maxwidth - 1;
3967 for (l = 0; l < itemcnt; l++)
3968 if (item[l].start > s)
3969 break;
3970 itemcnt = l;
3971 *s++ = '>';
3972 *s = 0;
3974 else
3976 #ifdef FEAT_MBYTE
3977 if (has_mbyte)
3979 n = 0;
3980 while (width >= maxwidth)
3982 width -= ptr2cells(s + n);
3983 n += (*mb_ptr2len)(s + n);
3986 else
3987 #endif
3988 n = width - maxwidth + 1;
3989 p = s + n;
3990 mch_memmove(s + 1, p, STRLEN(p) + 1);
3991 *s = '<';
3993 /* Fill up for half a double-wide character. */
3994 while (++width < maxwidth)
3996 s = s + STRLEN(s);
3997 *s++ = fillchar;
3998 *s = NUL;
4001 --n; /* count the '<' */
4002 for (; l < itemcnt; l++)
4004 if (item[l].start - n >= s)
4005 item[l].start -= n;
4006 else
4007 item[l].start = s;
4010 width = maxwidth;
4012 else if (width < maxwidth && STRLEN(out) + maxwidth - width + 1 < outlen)
4014 /* Apply STL_MIDDLE if any */
4015 for (l = 0; l < itemcnt; l++)
4016 if (item[l].type == Middle)
4017 break;
4018 if (l < itemcnt)
4020 p = item[l].start + maxwidth - width;
4021 mch_memmove(p, item[l].start, STRLEN(item[l].start) + 1);
4022 for (s = item[l].start; s < p; s++)
4023 *s = fillchar;
4024 for (l++; l < itemcnt; l++)
4025 item[l].start += maxwidth - width;
4026 width = maxwidth;
4030 /* Store the info about highlighting. */
4031 if (hltab != NULL)
4033 sp = hltab;
4034 for (l = 0; l < itemcnt; l++)
4036 if (item[l].type == Highlight)
4038 sp->start = item[l].start;
4039 sp->userhl = item[l].minwid;
4040 sp++;
4043 sp->start = NULL;
4044 sp->userhl = 0;
4047 /* Store the info about tab pages labels. */
4048 if (tabtab != NULL)
4050 sp = tabtab;
4051 for (l = 0; l < itemcnt; l++)
4053 if (item[l].type == TabPage)
4055 sp->start = item[l].start;
4056 sp->userhl = item[l].minwid;
4057 sp++;
4060 sp->start = NULL;
4061 sp->userhl = 0;
4064 return width;
4066 #endif /* FEAT_STL_OPT */
4068 #if defined(FEAT_STL_OPT) || defined(FEAT_CMDL_INFO) \
4069 || defined(FEAT_GUI_TABLINE) || defined(PROTO)
4071 * Get relative cursor position in window into "str[]", in the form 99%, using
4072 * "Top", "Bot" or "All" when appropriate.
4074 void
4075 get_rel_pos(wp, str)
4076 win_T *wp;
4077 char_u *str;
4079 long above; /* number of lines above window */
4080 long below; /* number of lines below window */
4082 above = wp->w_topline - 1;
4083 #ifdef FEAT_DIFF
4084 above += diff_check_fill(wp, wp->w_topline) - wp->w_topfill;
4085 #endif
4086 below = wp->w_buffer->b_ml.ml_line_count - wp->w_botline + 1;
4087 if (below <= 0)
4088 STRCPY(str, above == 0 ? _("All") : _("Bot"));
4089 else if (above <= 0)
4090 STRCPY(str, _("Top"));
4091 else
4092 sprintf((char *)str, "%2d%%", above > 1000000L
4093 ? (int)(above / ((above + below) / 100L))
4094 : (int)(above * 100L / (above + below)));
4096 #endif
4099 * Append (file 2 of 8) to 'buf', if editing more than one file.
4100 * Return TRUE if it was appended.
4103 append_arg_number(wp, buf, add_file, maxlen)
4104 win_T *wp;
4105 char_u *buf;
4106 int add_file; /* Add "file" before the arg number */
4107 int maxlen; /* maximum nr of chars in buf or zero*/
4109 char_u *p;
4111 if (ARGCOUNT <= 1) /* nothing to do */
4112 return FALSE;
4114 p = buf + STRLEN(buf); /* go to the end of the buffer */
4115 if (maxlen && p - buf + 35 >= maxlen) /* getting too long */
4116 return FALSE;
4117 *p++ = ' ';
4118 *p++ = '(';
4119 if (add_file)
4121 STRCPY(p, "file ");
4122 p += 5;
4124 sprintf((char *)p, wp->w_arg_idx_invalid ? "(%d) of %d)"
4125 : "%d of %d)", wp->w_arg_idx + 1, ARGCOUNT);
4126 return TRUE;
4130 * If fname is not a full path, make it a full path.
4131 * Returns pointer to allocated memory (NULL for failure).
4133 char_u *
4134 fix_fname(fname)
4135 char_u *fname;
4138 * Force expanding the path always for Unix, because symbolic links may
4139 * mess up the full path name, even though it starts with a '/'.
4140 * Also expand when there is ".." in the file name, try to remove it,
4141 * because "c:/src/../README" is equal to "c:/README".
4142 * For MS-Windows also expand names like "longna~1" to "longname".
4144 #ifdef UNIX
4145 return FullName_save(fname, TRUE);
4146 #else
4147 if (!vim_isAbsName(fname) || strstr((char *)fname, "..") != NULL
4148 #if defined(MSWIN) || defined(DJGPP)
4149 || vim_strchr(fname, '~') != NULL
4150 #endif
4152 return FullName_save(fname, FALSE);
4154 fname = vim_strsave(fname);
4156 #ifdef USE_FNAME_CASE
4157 # ifdef USE_LONG_FNAME
4158 if (USE_LONG_FNAME)
4159 # endif
4161 if (fname != NULL)
4162 fname_case(fname, 0); /* set correct case for file name */
4164 #endif
4166 return fname;
4167 #endif
4171 * Make "ffname" a full file name, set "sfname" to "ffname" if not NULL.
4172 * "ffname" becomes a pointer to allocated memory (or NULL).
4174 /*ARGSUSED*/
4175 void
4176 fname_expand(buf, ffname, sfname)
4177 buf_T *buf;
4178 char_u **ffname;
4179 char_u **sfname;
4181 if (*ffname == NULL) /* if no file name given, nothing to do */
4182 return;
4183 if (*sfname == NULL) /* if no short file name given, use ffname */
4184 *sfname = *ffname;
4185 *ffname = fix_fname(*ffname); /* expand to full path */
4187 #ifdef FEAT_SHORTCUT
4188 if (!buf->b_p_bin)
4190 char_u *rfname = NULL;
4192 /* If the file name is a shortcut file, use the file it links to. */
4193 rfname = mch_resolve_shortcut(*ffname);
4194 if (rfname)
4196 vim_free(*ffname);
4197 *ffname = rfname;
4198 *sfname = rfname;
4201 #endif
4205 * Get the file name for an argument list entry.
4207 char_u *
4208 alist_name(aep)
4209 aentry_T *aep;
4211 buf_T *bp;
4213 /* Use the name from the associated buffer if it exists. */
4214 bp = buflist_findnr(aep->ae_fnum);
4215 if (bp == NULL)
4216 return aep->ae_fname;
4217 return bp->b_fname;
4220 #if defined(FEAT_WINDOWS) || defined(PROTO)
4222 * do_arg_all(): Open up to 'count' windows, one for each argument.
4224 void
4225 do_arg_all(count, forceit, keep_tabs)
4226 int count;
4227 int forceit; /* hide buffers in current windows */
4228 int keep_tabs; /* keep curren tabs, for ":tab drop file" */
4230 int i;
4231 win_T *wp, *wpnext;
4232 char_u *opened; /* array of flags for which args are open */
4233 int opened_len; /* lenght of opened[] */
4234 int use_firstwin = FALSE; /* use first window for arglist */
4235 int split_ret = OK;
4236 int p_ea_save;
4237 alist_T *alist; /* argument list to be used */
4238 buf_T *buf;
4239 tabpage_T *tpnext;
4240 int had_tab = cmdmod.tab;
4241 win_T *new_curwin = NULL;
4242 tabpage_T *new_curtab = NULL;
4244 if (ARGCOUNT <= 0)
4246 /* Don't give an error message. We don't want it when the ":all"
4247 * command is in the .vimrc. */
4248 return;
4250 setpcmark();
4252 opened_len = ARGCOUNT;
4253 opened = alloc_clear((unsigned)opened_len);
4254 if (opened == NULL)
4255 return;
4257 #ifdef FEAT_GUI
4258 need_mouse_correct = TRUE;
4259 #endif
4262 * Try closing all windows that are not in the argument list.
4263 * Also close windows that are not full width;
4264 * When 'hidden' or "forceit" set the buffer becomes hidden.
4265 * Windows that have a changed buffer and can't be hidden won't be closed.
4266 * When the ":tab" modifier was used do this for all tab pages.
4268 if (had_tab > 0)
4269 goto_tabpage_tp(first_tabpage);
4270 for (;;)
4272 tpnext = curtab->tp_next;
4273 for (wp = firstwin; wp != NULL; wp = wpnext)
4275 wpnext = wp->w_next;
4276 buf = wp->w_buffer;
4277 if (buf->b_ffname == NULL
4278 || buf->b_nwindows > 1
4279 #ifdef FEAT_VERTSPLIT
4280 || wp->w_width != Columns
4281 #endif
4283 i = ARGCOUNT;
4284 else
4286 /* check if the buffer in this window is in the arglist */
4287 for (i = 0; i < ARGCOUNT; ++i)
4289 if (ARGLIST[i].ae_fnum == buf->b_fnum
4290 || fullpathcmp(alist_name(&ARGLIST[i]),
4291 buf->b_ffname, TRUE) & FPC_SAME)
4293 if (i < opened_len)
4295 opened[i] = TRUE;
4296 if (i == 0)
4298 new_curwin = wp;
4299 new_curtab = curtab;
4302 if (wp->w_alist != curwin->w_alist)
4304 /* Use the current argument list for all windows
4305 * containing a file from it. */
4306 alist_unlink(wp->w_alist);
4307 wp->w_alist = curwin->w_alist;
4308 ++wp->w_alist->al_refcount;
4310 break;
4314 wp->w_arg_idx = i;
4316 if (i == ARGCOUNT && !keep_tabs) /* close this window */
4318 if (P_HID(buf) || forceit || buf->b_nwindows > 1
4319 || !bufIsChanged(buf))
4321 /* If the buffer was changed, and we would like to hide it,
4322 * try autowriting. */
4323 if (!P_HID(buf) && buf->b_nwindows <= 1
4324 && bufIsChanged(buf))
4326 (void)autowrite(buf, FALSE);
4327 #ifdef FEAT_AUTOCMD
4328 /* check if autocommands removed the window */
4329 if (!win_valid(wp) || !buf_valid(buf))
4331 wpnext = firstwin; /* start all over... */
4332 continue;
4334 #endif
4336 #ifdef FEAT_WINDOWS
4337 /* don't close last window */
4338 if (firstwin == lastwin && first_tabpage->tp_next == NULL)
4339 #endif
4340 use_firstwin = TRUE;
4341 #ifdef FEAT_WINDOWS
4342 else
4344 win_close(wp, !P_HID(buf) && !bufIsChanged(buf));
4345 # ifdef FEAT_AUTOCMD
4346 /* check if autocommands removed the next window */
4347 if (!win_valid(wpnext))
4348 wpnext = firstwin; /* start all over... */
4349 # endif
4351 #endif
4356 /* Without the ":tab" modifier only do the current tab page. */
4357 if (had_tab == 0 || tpnext == NULL)
4358 break;
4360 # ifdef FEAT_AUTOCMD
4361 /* check if autocommands removed the next tab page */
4362 if (!valid_tabpage(tpnext))
4363 tpnext = first_tabpage; /* start all over...*/
4364 # endif
4365 goto_tabpage_tp(tpnext);
4369 * Open a window for files in the argument list that don't have one.
4370 * ARGCOUNT may change while doing this, because of autocommands.
4372 if (count > ARGCOUNT || count <= 0)
4373 count = ARGCOUNT;
4375 /* Autocommands may do anything to the argument list. Make sure it's not
4376 * freed while we are working here by "locking" it. We still have to
4377 * watch out for its size to be changed. */
4378 alist = curwin->w_alist;
4379 ++alist->al_refcount;
4381 #ifdef FEAT_AUTOCMD
4382 /* Don't execute Win/Buf Enter/Leave autocommands here. */
4383 ++autocmd_no_enter;
4384 ++autocmd_no_leave;
4385 #endif
4386 win_enter(lastwin, FALSE);
4387 #ifdef FEAT_WINDOWS
4388 /* ":drop all" should re-use an empty window to avoid "--remote-tab"
4389 * leaving an empty tab page when executed locally. */
4390 if (keep_tabs && bufempty() && curbuf->b_nwindows == 1
4391 && curbuf->b_ffname == NULL && !curbuf->b_changed)
4392 use_firstwin = TRUE;
4393 #endif
4395 for (i = 0; i < count && i < alist->al_ga.ga_len && !got_int; ++i)
4397 if (alist == &global_alist && i == global_alist.al_ga.ga_len - 1)
4398 arg_had_last = TRUE;
4399 if (i < opened_len && opened[i])
4401 /* Move the already present window to below the current window */
4402 if (curwin->w_arg_idx != i)
4404 for (wpnext = firstwin; wpnext != NULL; wpnext = wpnext->w_next)
4406 if (wpnext->w_arg_idx == i)
4408 win_move_after(wpnext, curwin);
4409 break;
4414 else if (split_ret == OK)
4416 if (!use_firstwin) /* split current window */
4418 p_ea_save = p_ea;
4419 p_ea = TRUE; /* use space from all windows */
4420 split_ret = win_split(0, WSP_ROOM | WSP_BELOW);
4421 p_ea = p_ea_save;
4422 if (split_ret == FAIL)
4423 continue;
4425 #ifdef FEAT_AUTOCMD
4426 else /* first window: do autocmd for leaving this buffer */
4427 --autocmd_no_leave;
4428 #endif
4431 * edit file "i"
4433 curwin->w_arg_idx = i;
4434 if (i == 0)
4436 new_curwin = curwin;
4437 new_curtab = curtab;
4439 (void)do_ecmd(0, alist_name(&AARGLIST(alist)[i]), NULL, NULL,
4440 ECMD_ONE,
4441 ((P_HID(curwin->w_buffer)
4442 || bufIsChanged(curwin->w_buffer)) ? ECMD_HIDE : 0)
4443 + ECMD_OLDBUF);
4444 #ifdef FEAT_AUTOCMD
4445 if (use_firstwin)
4446 ++autocmd_no_leave;
4447 #endif
4448 use_firstwin = FALSE;
4450 ui_breakcheck();
4452 /* When ":tab" was used open a new tab for a new window repeatedly. */
4453 if (had_tab > 0 && tabpage_index(NULL) <= p_tpm)
4454 cmdmod.tab = 9999;
4457 /* Remove the "lock" on the argument list. */
4458 alist_unlink(alist);
4460 #ifdef FEAT_AUTOCMD
4461 --autocmd_no_enter;
4462 #endif
4463 /* to window with first arg */
4464 if (valid_tabpage(new_curtab))
4465 goto_tabpage_tp(new_curtab);
4466 if (win_valid(new_curwin))
4467 win_enter(new_curwin, FALSE);
4469 #ifdef FEAT_AUTOCMD
4470 --autocmd_no_leave;
4471 #endif
4472 vim_free(opened);
4475 # if defined(FEAT_LISTCMDS) || defined(PROTO)
4477 * Open a window for a number of buffers.
4479 void
4480 ex_buffer_all(eap)
4481 exarg_T *eap;
4483 buf_T *buf;
4484 win_T *wp, *wpnext;
4485 int split_ret = OK;
4486 int p_ea_save;
4487 int open_wins = 0;
4488 int r;
4489 int count; /* Maximum number of windows to open. */
4490 int all; /* When TRUE also load inactive buffers. */
4491 #ifdef FEAT_WINDOWS
4492 int had_tab = cmdmod.tab;
4493 tabpage_T *tpnext;
4494 #endif
4496 if (eap->addr_count == 0) /* make as many windows as possible */
4497 count = 9999;
4498 else
4499 count = eap->line2; /* make as many windows as specified */
4500 if (eap->cmdidx == CMD_unhide || eap->cmdidx == CMD_sunhide)
4501 all = FALSE;
4502 else
4503 all = TRUE;
4505 setpcmark();
4507 #ifdef FEAT_GUI
4508 need_mouse_correct = TRUE;
4509 #endif
4512 * Close superfluous windows (two windows for the same buffer).
4513 * Also close windows that are not full-width.
4515 #ifdef FEAT_WINDOWS
4516 if (had_tab > 0)
4517 goto_tabpage_tp(first_tabpage);
4518 for (;;)
4520 #endif
4521 tpnext = curtab->tp_next;
4522 for (wp = firstwin; wp != NULL; wp = wpnext)
4524 wpnext = wp->w_next;
4525 if ((wp->w_buffer->b_nwindows > 1
4526 #ifdef FEAT_VERTSPLIT
4527 || ((cmdmod.split & WSP_VERT)
4528 ? wp->w_height + wp->w_status_height < Rows - p_ch
4529 - tabline_height()
4530 : wp->w_width != Columns)
4531 #endif
4532 #ifdef FEAT_WINDOWS
4533 || (had_tab > 0 && wp != firstwin)
4534 #endif
4535 ) && firstwin != lastwin)
4537 win_close(wp, FALSE);
4538 #ifdef FEAT_AUTOCMD
4539 wpnext = firstwin; /* just in case an autocommand does
4540 something strange with windows */
4541 tpnext = first_tabpage; /* start all over...*/
4542 open_wins = 0;
4543 #endif
4545 else
4546 ++open_wins;
4549 #ifdef FEAT_WINDOWS
4550 /* Without the ":tab" modifier only do the current tab page. */
4551 if (had_tab == 0 || tpnext == NULL)
4552 break;
4553 goto_tabpage_tp(tpnext);
4555 #endif
4558 * Go through the buffer list. When a buffer doesn't have a window yet,
4559 * open one. Otherwise move the window to the right position.
4560 * Watch out for autocommands that delete buffers or windows!
4562 #ifdef FEAT_AUTOCMD
4563 /* Don't execute Win/Buf Enter/Leave autocommands here. */
4564 ++autocmd_no_enter;
4565 #endif
4566 win_enter(lastwin, FALSE);
4567 #ifdef FEAT_AUTOCMD
4568 ++autocmd_no_leave;
4569 #endif
4570 for (buf = firstbuf; buf != NULL && open_wins < count; buf = buf->b_next)
4572 /* Check if this buffer needs a window */
4573 if ((!all && buf->b_ml.ml_mfp == NULL) || !buf->b_p_bl)
4574 continue;
4576 #ifdef FEAT_WINDOWS
4577 if (had_tab != 0)
4579 /* With the ":tab" modifier don't move the window. */
4580 if (buf->b_nwindows > 0)
4581 wp = lastwin; /* buffer has a window, skip it */
4582 else
4583 wp = NULL;
4585 else
4586 #endif
4588 /* Check if this buffer already has a window */
4589 for (wp = firstwin; wp != NULL; wp = wp->w_next)
4590 if (wp->w_buffer == buf)
4591 break;
4592 /* If the buffer already has a window, move it */
4593 if (wp != NULL)
4594 win_move_after(wp, curwin);
4597 if (wp == NULL && split_ret == OK)
4599 /* Split the window and put the buffer in it */
4600 p_ea_save = p_ea;
4601 p_ea = TRUE; /* use space from all windows */
4602 split_ret = win_split(0, WSP_ROOM | WSP_BELOW);
4603 ++open_wins;
4604 p_ea = p_ea_save;
4605 if (split_ret == FAIL)
4606 continue;
4608 /* Open the buffer in this window. */
4609 #if defined(HAS_SWAP_EXISTS_ACTION)
4610 swap_exists_action = SEA_DIALOG;
4611 #endif
4612 set_curbuf(buf, DOBUF_GOTO);
4613 #ifdef FEAT_AUTOCMD
4614 if (!buf_valid(buf)) /* autocommands deleted the buffer!!! */
4616 #if defined(HAS_SWAP_EXISTS_ACTION)
4617 swap_exists_action = SEA_NONE;
4618 # endif
4619 break;
4621 #endif
4622 #if defined(HAS_SWAP_EXISTS_ACTION)
4623 if (swap_exists_action == SEA_QUIT)
4625 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
4626 cleanup_T cs;
4628 /* Reset the error/interrupt/exception state here so that
4629 * aborting() returns FALSE when closing a window. */
4630 enter_cleanup(&cs);
4631 # endif
4633 /* User selected Quit at ATTENTION prompt; close this window. */
4634 win_close(curwin, TRUE);
4635 --open_wins;
4636 swap_exists_action = SEA_NONE;
4637 swap_exists_did_quit = TRUE;
4639 # if defined(FEAT_AUTOCMD) && defined(FEAT_EVAL)
4640 /* Restore the error/interrupt/exception state if not
4641 * discarded by a new aborting error, interrupt, or uncaught
4642 * exception. */
4643 leave_cleanup(&cs);
4644 # endif
4646 else
4647 handle_swap_exists(NULL);
4648 #endif
4651 ui_breakcheck();
4652 if (got_int)
4654 (void)vgetc(); /* only break the file loading, not the rest */
4655 break;
4657 #ifdef FEAT_EVAL
4658 /* Autocommands deleted the buffer or aborted script processing!!! */
4659 if (aborting())
4660 break;
4661 #endif
4662 #ifdef FEAT_WINDOWS
4663 /* When ":tab" was used open a new tab for a new window repeatedly. */
4664 if (had_tab > 0 && tabpage_index(NULL) <= p_tpm)
4665 cmdmod.tab = 9999;
4666 #endif
4668 #ifdef FEAT_AUTOCMD
4669 --autocmd_no_enter;
4670 #endif
4671 win_enter(firstwin, FALSE); /* back to first window */
4672 #ifdef FEAT_AUTOCMD
4673 --autocmd_no_leave;
4674 #endif
4677 * Close superfluous windows.
4679 for (wp = lastwin; open_wins > count; )
4681 r = (P_HID(wp->w_buffer) || !bufIsChanged(wp->w_buffer)
4682 || autowrite(wp->w_buffer, FALSE) == OK);
4683 #ifdef FEAT_AUTOCMD
4684 if (!win_valid(wp))
4686 /* BufWrite Autocommands made the window invalid, start over */
4687 wp = lastwin;
4689 else
4690 #endif
4691 if (r)
4693 win_close(wp, !P_HID(wp->w_buffer));
4694 --open_wins;
4695 wp = lastwin;
4697 else
4699 wp = wp->w_prev;
4700 if (wp == NULL)
4701 break;
4705 # endif /* FEAT_LISTCMDS */
4707 #endif /* FEAT_WINDOWS */
4709 static int chk_modeline __ARGS((linenr_T, int));
4712 * do_modelines() - process mode lines for the current file
4714 * "flags" can be:
4715 * OPT_WINONLY only set options local to window
4716 * OPT_NOWIN don't set options local to window
4718 * Returns immediately if the "ml" option isn't set.
4720 void
4721 do_modelines(flags)
4722 int flags;
4724 linenr_T lnum;
4725 int nmlines;
4726 static int entered = 0;
4728 if (!curbuf->b_p_ml || (nmlines = (int)p_mls) == 0)
4729 return;
4731 /* Disallow recursive entry here. Can happen when executing a modeline
4732 * triggers an autocommand, which reloads modelines with a ":do". */
4733 if (entered)
4734 return;
4736 ++entered;
4737 for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count && lnum <= nmlines;
4738 ++lnum)
4739 if (chk_modeline(lnum, flags) == FAIL)
4740 nmlines = 0;
4742 for (lnum = curbuf->b_ml.ml_line_count; lnum > 0 && lnum > nmlines
4743 && lnum > curbuf->b_ml.ml_line_count - nmlines; --lnum)
4744 if (chk_modeline(lnum, flags) == FAIL)
4745 nmlines = 0;
4746 --entered;
4749 #include "version.h" /* for version number */
4752 * chk_modeline() - check a single line for a mode string
4753 * Return FAIL if an error encountered.
4755 static int
4756 chk_modeline(lnum, flags)
4757 linenr_T lnum;
4758 int flags; /* Same as for do_modelines(). */
4760 char_u *s;
4761 char_u *e;
4762 char_u *linecopy; /* local copy of any modeline found */
4763 int prev;
4764 int vers;
4765 int end;
4766 int retval = OK;
4767 char_u *save_sourcing_name;
4768 linenr_T save_sourcing_lnum;
4769 #ifdef FEAT_EVAL
4770 scid_T save_SID;
4771 #endif
4773 prev = -1;
4774 for (s = ml_get(lnum); *s != NUL; ++s)
4776 if (prev == -1 || vim_isspace(prev))
4778 if ((prev != -1 && STRNCMP(s, "ex:", (size_t)3) == 0)
4779 || STRNCMP(s, "vi:", (size_t)3) == 0)
4780 break;
4781 if (STRNCMP(s, "vim", 3) == 0)
4783 if (s[3] == '<' || s[3] == '=' || s[3] == '>')
4784 e = s + 4;
4785 else
4786 e = s + 3;
4787 vers = getdigits(&e);
4788 if (*e == ':'
4789 && (s[3] == ':'
4790 || (VIM_VERSION_100 >= vers && isdigit(s[3]))
4791 || (VIM_VERSION_100 < vers && s[3] == '<')
4792 || (VIM_VERSION_100 > vers && s[3] == '>')
4793 || (VIM_VERSION_100 == vers && s[3] == '=')))
4794 break;
4797 prev = *s;
4800 if (*s)
4802 do /* skip over "ex:", "vi:" or "vim:" */
4803 ++s;
4804 while (s[-1] != ':');
4806 s = linecopy = vim_strsave(s); /* copy the line, it will change */
4807 if (linecopy == NULL)
4808 return FAIL;
4810 save_sourcing_lnum = sourcing_lnum;
4811 save_sourcing_name = sourcing_name;
4812 sourcing_lnum = lnum; /* prepare for emsg() */
4813 sourcing_name = (char_u *)"modelines";
4815 end = FALSE;
4816 while (end == FALSE)
4818 s = skipwhite(s);
4819 if (*s == NUL)
4820 break;
4823 * Find end of set command: ':' or end of line.
4824 * Skip over "\:", replacing it with ":".
4826 for (e = s; *e != ':' && *e != NUL; ++e)
4827 if (e[0] == '\\' && e[1] == ':')
4828 STRCPY(e, e + 1);
4829 if (*e == NUL)
4830 end = TRUE;
4833 * If there is a "set" command, require a terminating ':' and
4834 * ignore the stuff after the ':'.
4835 * "vi:set opt opt opt: foo" -- foo not interpreted
4836 * "vi:opt opt opt: foo" -- foo interpreted
4837 * Accept "se" for compatibility with Elvis.
4839 if (STRNCMP(s, "set ", (size_t)4) == 0
4840 || STRNCMP(s, "se ", (size_t)3) == 0)
4842 if (*e != ':') /* no terminating ':'? */
4843 break;
4844 end = TRUE;
4845 s = vim_strchr(s, ' ') + 1;
4847 *e = NUL; /* truncate the set command */
4849 if (*s != NUL) /* skip over an empty "::" */
4851 #ifdef FEAT_EVAL
4852 save_SID = current_SID;
4853 current_SID = SID_MODELINE;
4854 #endif
4855 retval = do_set(s, OPT_MODELINE | OPT_LOCAL | flags);
4856 #ifdef FEAT_EVAL
4857 current_SID = save_SID;
4858 #endif
4859 if (retval == FAIL) /* stop if error found */
4860 break;
4862 s = e + 1; /* advance to next part */
4865 sourcing_lnum = save_sourcing_lnum;
4866 sourcing_name = save_sourcing_name;
4868 vim_free(linecopy);
4870 return retval;
4873 #ifdef FEAT_VIMINFO
4875 read_viminfo_bufferlist(virp, writing)
4876 vir_T *virp;
4877 int writing;
4879 char_u *tab;
4880 linenr_T lnum;
4881 colnr_T col;
4882 buf_T *buf;
4883 char_u *sfname;
4884 char_u *xline;
4886 /* Handle long line and escaped characters. */
4887 xline = viminfo_readstring(virp, 1, FALSE);
4889 /* don't read in if there are files on the command-line or if writing: */
4890 if (xline != NULL && !writing && ARGCOUNT == 0
4891 && find_viminfo_parameter('%') != NULL)
4893 /* Format is: <fname> Tab <lnum> Tab <col>.
4894 * Watch out for a Tab in the file name, work from the end. */
4895 lnum = 0;
4896 col = 0;
4897 tab = vim_strrchr(xline, '\t');
4898 if (tab != NULL)
4900 *tab++ = '\0';
4901 col = atoi((char *)tab);
4902 tab = vim_strrchr(xline, '\t');
4903 if (tab != NULL)
4905 *tab++ = '\0';
4906 lnum = atol((char *)tab);
4910 /* Expand "~/" in the file name at "line + 1" to a full path.
4911 * Then try shortening it by comparing with the current directory */
4912 expand_env(xline, NameBuff, MAXPATHL);
4913 mch_dirname(IObuff, IOSIZE);
4914 sfname = shorten_fname(NameBuff, IObuff);
4915 if (sfname == NULL)
4916 sfname = NameBuff;
4918 buf = buflist_new(NameBuff, sfname, (linenr_T)0, BLN_LISTED);
4919 if (buf != NULL) /* just in case... */
4921 buf->b_last_cursor.lnum = lnum;
4922 buf->b_last_cursor.col = col;
4923 buflist_setfpos(buf, curwin, lnum, col, FALSE);
4926 vim_free(xline);
4928 return viminfo_readline(virp);
4931 void
4932 write_viminfo_bufferlist(fp)
4933 FILE *fp;
4935 buf_T *buf;
4936 #ifdef FEAT_WINDOWS
4937 win_T *win;
4938 tabpage_T *tp;
4939 #endif
4940 char_u *line;
4941 int max_buffers;
4943 if (find_viminfo_parameter('%') == NULL)
4944 return;
4946 /* Without a number -1 is returned: do all buffers. */
4947 max_buffers = get_viminfo_parameter('%');
4949 /* Allocate room for the file name, lnum and col. */
4950 line = alloc(MAXPATHL + 40);
4951 if (line == NULL)
4952 return;
4954 #ifdef FEAT_WINDOWS
4955 FOR_ALL_TAB_WINDOWS(tp, win)
4956 set_last_cursor(win);
4957 #else
4958 set_last_cursor(curwin);
4959 #endif
4961 fprintf(fp, _("\n# Buffer list:\n"));
4962 for (buf = firstbuf; buf != NULL ; buf = buf->b_next)
4964 if (buf->b_fname == NULL
4965 || !buf->b_p_bl
4966 #ifdef FEAT_QUICKFIX
4967 || bt_quickfix(buf)
4968 #endif
4969 || removable(buf->b_ffname))
4970 continue;
4972 if (max_buffers-- == 0)
4973 break;
4974 putc('%', fp);
4975 home_replace(NULL, buf->b_ffname, line, MAXPATHL, TRUE);
4976 sprintf((char *)line + STRLEN(line), "\t%ld\t%d",
4977 (long)buf->b_last_cursor.lnum,
4978 buf->b_last_cursor.col);
4979 viminfo_writestring(fp, line);
4981 vim_free(line);
4983 #endif
4987 * Return special buffer name.
4988 * Returns NULL when the buffer has a normal file name.
4990 char *
4991 buf_spname(buf)
4992 buf_T *buf;
4994 #if defined(FEAT_QUICKFIX) && defined(FEAT_WINDOWS)
4995 if (bt_quickfix(buf))
4997 win_T *win;
5000 * For location list window, w_llist_ref points to the location list.
5001 * For quickfix window, w_llist_ref is NULL.
5003 FOR_ALL_WINDOWS(win)
5004 if (win->w_buffer == buf)
5005 break;
5006 if (win != NULL && win->w_llist_ref != NULL)
5007 return _("[Location List]");
5008 else
5009 return _("[Quickfix List]");
5011 #endif
5012 #ifdef FEAT_QUICKFIX
5013 /* There is no _file_ when 'buftype' is "nofile", b_sfname
5014 * contains the name as specified by the user */
5015 if (bt_nofile(buf))
5017 if (buf->b_sfname != NULL)
5018 return (char *)buf->b_sfname;
5019 return "[Scratch]";
5021 #endif
5022 if (buf->b_fname == NULL)
5023 return _("[No Name]");
5024 return NULL;
5028 #if defined(FEAT_SIGNS) || defined(PROTO)
5030 * Insert the sign into the signlist.
5032 static void
5033 insert_sign(buf, prev, next, id, lnum, typenr)
5034 buf_T *buf; /* buffer to store sign in */
5035 signlist_T *prev; /* previous sign entry */
5036 signlist_T *next; /* next sign entry */
5037 int id; /* sign ID */
5038 linenr_T lnum; /* line number which gets the mark */
5039 int typenr; /* typenr of sign we are adding */
5041 signlist_T *newsign;
5043 newsign = (signlist_T *)lalloc((long_u)sizeof(signlist_T), FALSE);
5044 if (newsign != NULL)
5046 newsign->id = id;
5047 newsign->lnum = lnum;
5048 newsign->typenr = typenr;
5049 newsign->next = next;
5050 #ifdef FEAT_NETBEANS_INTG
5051 newsign->prev = prev;
5052 if (next != NULL)
5053 next->prev = newsign;
5054 #endif
5056 if (prev == NULL)
5058 /* When adding first sign need to redraw the windows to create the
5059 * column for signs. */
5060 if (buf->b_signlist == NULL)
5062 redraw_buf_later(buf, NOT_VALID);
5063 changed_cline_bef_curs();
5066 /* first sign in signlist */
5067 buf->b_signlist = newsign;
5069 else
5070 prev->next = newsign;
5075 * Add the sign into the signlist. Find the right spot to do it though.
5077 void
5078 buf_addsign(buf, id, lnum, typenr)
5079 buf_T *buf; /* buffer to store sign in */
5080 int id; /* sign ID */
5081 linenr_T lnum; /* line number which gets the mark */
5082 int typenr; /* typenr of sign we are adding */
5084 signlist_T *sign; /* a sign in the signlist */
5085 signlist_T *prev; /* the previous sign */
5087 prev = NULL;
5088 for (sign = buf->b_signlist; sign != NULL; sign = sign->next)
5090 if (lnum == sign->lnum && id == sign->id)
5092 sign->typenr = typenr;
5093 return;
5095 else if (
5096 #ifndef FEAT_NETBEANS_INTG /* keep signs sorted by lnum */
5097 id < 0 &&
5098 #endif
5099 lnum < sign->lnum)
5101 #ifdef FEAT_NETBEANS_INTG /* insert new sign at head of list for this lnum */
5102 /* XXX - GRP: Is this because of sign slide problem? Or is it
5103 * really needed? Or is it because we allow multiple signs per
5104 * line? If so, should I add that feature to FEAT_SIGNS?
5106 while (prev != NULL && prev->lnum == lnum)
5107 prev = prev->prev;
5108 if (prev == NULL)
5109 sign = buf->b_signlist;
5110 else
5111 sign = prev->next;
5112 #endif
5113 insert_sign(buf, prev, sign, id, lnum, typenr);
5114 return;
5116 prev = sign;
5118 #ifdef FEAT_NETBEANS_INTG /* insert new sign at head of list for this lnum */
5119 /* XXX - GRP: See previous comment */
5120 while (prev != NULL && prev->lnum == lnum)
5121 prev = prev->prev;
5122 if (prev == NULL)
5123 sign = buf->b_signlist;
5124 else
5125 sign = prev->next;
5126 #endif
5127 insert_sign(buf, prev, sign, id, lnum, typenr);
5129 return;
5133 buf_change_sign_type(buf, markId, typenr)
5134 buf_T *buf; /* buffer to store sign in */
5135 int markId; /* sign ID */
5136 int typenr; /* typenr of sign we are adding */
5138 signlist_T *sign; /* a sign in the signlist */
5140 for (sign = buf->b_signlist; sign != NULL; sign = sign->next)
5142 if (sign->id == markId)
5144 sign->typenr = typenr;
5145 return sign->lnum;
5149 return 0;
5152 int_u
5153 buf_getsigntype(buf, lnum, type)
5154 buf_T *buf;
5155 linenr_T lnum;
5156 int type; /* SIGN_ICON, SIGN_TEXT, SIGN_ANY, SIGN_LINEHL */
5158 signlist_T *sign; /* a sign in a b_signlist */
5160 for (sign = buf->b_signlist; sign != NULL; sign = sign->next)
5161 if (sign->lnum == lnum
5162 && (type == SIGN_ANY
5163 # ifdef FEAT_SIGN_ICONS
5164 || (type == SIGN_ICON
5165 && sign_get_image(sign->typenr) != NULL)
5166 # endif
5167 || (type == SIGN_TEXT
5168 && sign_get_text(sign->typenr) != NULL)
5169 || (type == SIGN_LINEHL
5170 && sign_get_attr(sign->typenr, TRUE) != 0)))
5171 return sign->typenr;
5172 return 0;
5176 linenr_T
5177 buf_delsign(buf, id)
5178 buf_T *buf; /* buffer sign is stored in */
5179 int id; /* sign id */
5181 signlist_T **lastp; /* pointer to pointer to current sign */
5182 signlist_T *sign; /* a sign in a b_signlist */
5183 signlist_T *next; /* the next sign in a b_signlist */
5184 linenr_T lnum; /* line number whose sign was deleted */
5186 lastp = &buf->b_signlist;
5187 lnum = 0;
5188 for (sign = buf->b_signlist; sign != NULL; sign = next)
5190 next = sign->next;
5191 if (sign->id == id)
5193 *lastp = next;
5194 #ifdef FEAT_NETBEANS_INTG
5195 if (next != NULL)
5196 next->prev = sign->prev;
5197 #endif
5198 lnum = sign->lnum;
5199 vim_free(sign);
5200 break;
5202 else
5203 lastp = &sign->next;
5206 /* When deleted the last sign need to redraw the windows to remove the
5207 * sign column. */
5208 if (buf->b_signlist == NULL)
5210 redraw_buf_later(buf, NOT_VALID);
5211 changed_cline_bef_curs();
5214 return lnum;
5219 * Find the line number of the sign with the requested id. If the sign does
5220 * not exist, return 0 as the line number. This will still let the correct file
5221 * get loaded.
5224 buf_findsign(buf, id)
5225 buf_T *buf; /* buffer to store sign in */
5226 int id; /* sign ID */
5228 signlist_T *sign; /* a sign in the signlist */
5230 for (sign = buf->b_signlist; sign != NULL; sign = sign->next)
5231 if (sign->id == id)
5232 return sign->lnum;
5234 return 0;
5238 buf_findsign_id(buf, lnum)
5239 buf_T *buf; /* buffer whose sign we are searching for */
5240 linenr_T lnum; /* line number of sign */
5242 signlist_T *sign; /* a sign in the signlist */
5244 for (sign = buf->b_signlist; sign != NULL; sign = sign->next)
5245 if (sign->lnum == lnum)
5246 return sign->id;
5248 return 0;
5252 # if defined(FEAT_NETBEANS_INTG) || defined(PROTO)
5253 /* see if a given type of sign exists on a specific line */
5255 buf_findsigntype_id(buf, lnum, typenr)
5256 buf_T *buf; /* buffer whose sign we are searching for */
5257 linenr_T lnum; /* line number of sign */
5258 int typenr; /* sign type number */
5260 signlist_T *sign; /* a sign in the signlist */
5262 for (sign = buf->b_signlist; sign != NULL; sign = sign->next)
5263 if (sign->lnum == lnum && sign->typenr == typenr)
5264 return sign->id;
5266 return 0;
5270 # if defined(FEAT_SIGN_ICONS) || defined(PROTO)
5271 /* return the number of icons on the given line */
5273 buf_signcount(buf, lnum)
5274 buf_T *buf;
5275 linenr_T lnum;
5277 signlist_T *sign; /* a sign in the signlist */
5278 int count = 0;
5280 for (sign = buf->b_signlist; sign != NULL; sign = sign->next)
5281 if (sign->lnum == lnum)
5282 if (sign_get_image(sign->typenr) != NULL)
5283 count++;
5285 return count;
5287 # endif /* FEAT_SIGN_ICONS */
5288 # endif /* FEAT_NETBEANS_INTG */
5292 * Delete signs in buffer "buf".
5294 static void
5295 buf_delete_signs(buf)
5296 buf_T *buf;
5298 signlist_T *next;
5300 while (buf->b_signlist != NULL)
5302 next = buf->b_signlist->next;
5303 vim_free(buf->b_signlist);
5304 buf->b_signlist = next;
5309 * Delete all signs in all buffers.
5311 void
5312 buf_delete_all_signs()
5314 buf_T *buf; /* buffer we are checking for signs */
5316 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
5317 if (buf->b_signlist != NULL)
5319 /* Need to redraw the windows to remove the sign column. */
5320 redraw_buf_later(buf, NOT_VALID);
5321 buf_delete_signs(buf);
5326 * List placed signs for "rbuf". If "rbuf" is NULL do it for all buffers.
5328 void
5329 sign_list_placed(rbuf)
5330 buf_T *rbuf;
5332 buf_T *buf;
5333 signlist_T *p;
5334 char lbuf[BUFSIZ];
5336 MSG_PUTS_TITLE(_("\n--- Signs ---"));
5337 msg_putchar('\n');
5338 if (rbuf == NULL)
5339 buf = firstbuf;
5340 else
5341 buf = rbuf;
5342 while (buf != NULL)
5344 if (buf->b_signlist != NULL)
5346 vim_snprintf(lbuf, BUFSIZ, _("Signs for %s:"), buf->b_fname);
5347 MSG_PUTS_ATTR(lbuf, hl_attr(HLF_D));
5348 msg_putchar('\n');
5350 for (p = buf->b_signlist; p != NULL; p = p->next)
5352 vim_snprintf(lbuf, BUFSIZ, _(" line=%ld id=%d name=%s"),
5353 (long)p->lnum, p->id, sign_typenr2name(p->typenr));
5354 MSG_PUTS(lbuf);
5355 msg_putchar('\n');
5357 if (rbuf != NULL)
5358 break;
5359 buf = buf->b_next;
5364 * Adjust a placed sign for inserted/deleted lines.
5366 void
5367 sign_mark_adjust(line1, line2, amount, amount_after)
5368 linenr_T line1;
5369 linenr_T line2;
5370 long amount;
5371 long amount_after;
5373 signlist_T *sign; /* a sign in a b_signlist */
5375 for (sign = curbuf->b_signlist; sign != NULL; sign = sign->next)
5377 if (sign->lnum >= line1 && sign->lnum <= line2)
5379 if (amount == MAXLNUM)
5380 sign->lnum = line1;
5381 else
5382 sign->lnum += amount;
5384 else if (sign->lnum > line2)
5385 sign->lnum += amount_after;
5388 #endif /* FEAT_SIGNS */
5391 * Set 'buflisted' for curbuf to "on" and trigger autocommands if it changed.
5393 void
5394 set_buflisted(on)
5395 int on;
5397 if (on != curbuf->b_p_bl)
5399 curbuf->b_p_bl = on;
5400 #ifdef FEAT_AUTOCMD
5401 if (on)
5402 apply_autocmds(EVENT_BUFADD, NULL, NULL, FALSE, curbuf);
5403 else
5404 apply_autocmds(EVENT_BUFDELETE, NULL, NULL, FALSE, curbuf);
5405 #endif
5410 * Read the file for "buf" again and check if the contents changed.
5411 * Return TRUE if it changed or this could not be checked.
5414 buf_contents_changed(buf)
5415 buf_T *buf;
5417 buf_T *newbuf;
5418 int differ = TRUE;
5419 linenr_T lnum;
5420 #ifdef FEAT_AUTOCMD
5421 aco_save_T aco;
5422 #else
5423 buf_T *old_curbuf = curbuf;
5424 #endif
5425 exarg_T ea;
5427 /* Allocate a buffer without putting it in the buffer list. */
5428 newbuf = buflist_new(NULL, NULL, (linenr_T)1, BLN_DUMMY);
5429 if (newbuf == NULL)
5430 return TRUE;
5432 /* Force the 'fileencoding' and 'fileformat' to be equal. */
5433 if (prep_exarg(&ea, buf) == FAIL)
5435 wipe_buffer(newbuf, FALSE);
5436 return TRUE;
5439 #ifdef FEAT_AUTOCMD
5440 /* set curwin/curbuf to buf and save a few things */
5441 aucmd_prepbuf(&aco, newbuf);
5442 #else
5443 curbuf = newbuf;
5444 curwin->w_buffer = newbuf;
5445 #endif
5447 if (ml_open(curbuf) == OK
5448 && readfile(buf->b_ffname, buf->b_fname,
5449 (linenr_T)0, (linenr_T)0, (linenr_T)MAXLNUM,
5450 &ea, READ_NEW | READ_DUMMY) == OK)
5452 /* compare the two files line by line */
5453 if (buf->b_ml.ml_line_count == curbuf->b_ml.ml_line_count)
5455 differ = FALSE;
5456 for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum)
5457 if (STRCMP(ml_get_buf(buf, lnum, FALSE), ml_get(lnum)) != 0)
5459 differ = TRUE;
5460 break;
5464 vim_free(ea.cmd);
5466 #ifdef FEAT_AUTOCMD
5467 /* restore curwin/curbuf and a few other things */
5468 aucmd_restbuf(&aco);
5469 #else
5470 curbuf = old_curbuf;
5471 curwin->w_buffer = old_curbuf;
5472 #endif
5474 if (curbuf != newbuf) /* safety check */
5475 wipe_buffer(newbuf, FALSE);
5477 return differ;
5481 * Wipe out a buffer and decrement the last buffer number if it was used for
5482 * this buffer. Call this to wipe out a temp buffer that does not contain any
5483 * marks.
5485 /*ARGSUSED*/
5486 void
5487 wipe_buffer(buf, aucmd)
5488 buf_T *buf;
5489 int aucmd; /* When TRUE trigger autocommands. */
5491 if (buf->b_fnum == top_file_num - 1)
5492 --top_file_num;
5494 #ifdef FEAT_AUTOCMD
5495 if (!aucmd) /* Don't trigger BufDelete autocommands here. */
5496 ++autocmd_block;
5497 #endif
5498 close_buffer(NULL, buf, DOBUF_WIPE);
5499 #ifdef FEAT_AUTOCMD
5500 if (!aucmd)
5501 --autocmd_block;
5502 #endif