blob: b43ba357456001ce331467654d3bffc5251b863c [file] [log] [blame]
Bram Moolenaar3f86ca02019-05-11 18:30:00 +02001/* vi:set ts=8 sts=4 sw=4 noet:
2 *
3 * VIM - Vi IMproved by Bram Moolenaar
4 *
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 */
9
10/*
11 * change.c: functions related to changing text
12 */
13
14#include "vim.h"
15
16/*
17 * If the file is readonly, give a warning message with the first change.
18 * Don't do this for autocommands.
19 * Doesn't use emsg(), because it flushes the macro buffer.
20 * If we have undone all changes b_changed will be FALSE, but "b_did_warn"
21 * will be TRUE.
22 * "col" is the column for the message; non-zero when in insert mode and
23 * 'showmode' is on.
24 * Careful: may trigger autocommands that reload the buffer.
25 */
26 void
27change_warning(int col)
28{
29 static char *w_readonly = N_("W10: Warning: Changing a readonly file");
30
31 if (curbuf->b_did_warn == FALSE
32 && curbufIsChanged() == 0
33 && !autocmd_busy
34 && curbuf->b_p_ro)
35 {
36 ++curbuf_lock;
37 apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, FALSE, curbuf);
38 --curbuf_lock;
39 if (!curbuf->b_p_ro)
40 return;
41
42 // Do what msg() does, but with a column offset if the warning should
43 // be after the mode message.
44 msg_start();
45 if (msg_row == Rows - 1)
46 msg_col = col;
47 msg_source(HL_ATTR(HLF_W));
48 msg_puts_attr(_(w_readonly), HL_ATTR(HLF_W) | MSG_HIST);
49#ifdef FEAT_EVAL
50 set_vim_var_string(VV_WARNINGMSG, (char_u *)_(w_readonly), -1);
51#endif
52 msg_clr_eos();
53 (void)msg_end();
54 if (msg_silent == 0 && !silent_mode
55#ifdef FEAT_EVAL
56 && time_for_testing != 1
57#endif
58 )
59 {
60 out_flush();
61 ui_delay(1000L, TRUE); // give the user time to think about it
62 }
63 curbuf->b_did_warn = TRUE;
64 redraw_cmdline = FALSE; // don't redraw and erase the message
65 if (msg_row < Rows - 1)
66 showmode();
67 }
68}
69
70/*
71 * Call this function when something in the current buffer is changed.
72 *
73 * Most often called through changed_bytes() and changed_lines(), which also
74 * mark the area of the display to be redrawn.
75 *
76 * Careful: may trigger autocommands that reload the buffer.
77 */
78 void
79changed(void)
80{
81#if defined(FEAT_XIM) && defined(FEAT_GUI_GTK)
82 if (p_imst == IM_ON_THE_SPOT)
83 {
84 // The text of the preediting area is inserted, but this doesn't
85 // mean a change of the buffer yet. That is delayed until the
86 // text is committed. (this means preedit becomes empty)
87 if (im_is_preediting() && !xim_changed_while_preediting)
88 return;
89 xim_changed_while_preediting = FALSE;
90 }
91#endif
92
93 if (!curbuf->b_changed)
94 {
95 int save_msg_scroll = msg_scroll;
96
97 // Give a warning about changing a read-only file. This may also
98 // check-out the file, thus change "curbuf"!
99 change_warning(0);
100
101 // Create a swap file if that is wanted.
102 // Don't do this for "nofile" and "nowrite" buffer types.
103 if (curbuf->b_may_swap
104#ifdef FEAT_QUICKFIX
105 && !bt_dontwrite(curbuf)
106#endif
107 )
108 {
109 int save_need_wait_return = need_wait_return;
110
111 need_wait_return = FALSE;
112 ml_open_file(curbuf);
113
114 // The ml_open_file() can cause an ATTENTION message.
115 // Wait two seconds, to make sure the user reads this unexpected
116 // message. Since we could be anywhere, call wait_return() now,
117 // and don't let the emsg() set msg_scroll.
118 if (need_wait_return && emsg_silent == 0)
119 {
120 out_flush();
121 ui_delay(2000L, TRUE);
122 wait_return(TRUE);
123 msg_scroll = save_msg_scroll;
124 }
125 else
126 need_wait_return = save_need_wait_return;
127 }
128 changed_internal();
129 }
130 ++CHANGEDTICK(curbuf);
131
132#ifdef FEAT_SEARCH_EXTRA
133 // If a pattern is highlighted, the position may now be invalid.
134 highlight_match = FALSE;
135#endif
136}
137
138/*
139 * Internal part of changed(), no user interaction.
140 * Also used for recovery.
141 */
142 void
143changed_internal(void)
144{
145 curbuf->b_changed = TRUE;
146 ml_setflags(curbuf);
147 check_status(curbuf);
148 redraw_tabline = TRUE;
149#ifdef FEAT_TITLE
150 need_maketitle = TRUE; // set window title later
151#endif
152}
153
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200154#ifdef FEAT_EVAL
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200155static long next_listener_id = 0;
156
157/*
Bram Moolenaardda41442019-05-16 22:11:47 +0200158 * Check if the change at "lnum" / "col" is above or overlaps with an existing
159 * changed. If above then flush changes and invoke listeners.
160 * If "merge" is TRUE do the merge.
161 * Returns TRUE if the change was merged.
162 */
163 static int
164check_recorded_changes(
165 buf_T *buf,
166 linenr_T lnum,
167 colnr_T col,
168 linenr_T lnume,
169 long xtra,
170 int merge)
171{
172 if (buf->b_recorded_changes != NULL && xtra != 0)
173 {
174 listitem_T *li;
175 linenr_T nr;
176
177 for (li = buf->b_recorded_changes->lv_first; li != NULL;
178 li = li->li_next)
179 {
180 nr = (linenr_T)dict_get_number(
181 li->li_tv.vval.v_dict, (char_u *)"lnum");
182 if (nr >= lnum || nr > lnume)
183 {
184 if (li->li_next == NULL && lnum == nr
185 && col + 1 == (colnr_T)dict_get_number(
186 li->li_tv.vval.v_dict, (char_u *)"col"))
187 {
188 if (merge)
189 {
190 dictitem_T *di;
191
192 // Same start point and nothing is following, entries
193 // can be merged.
194 di = dict_find(li->li_tv.vval.v_dict,
195 (char_u *)"end", -1);
Bram Moolenaar0d3cb732019-05-18 13:05:18 +0200196 if (di != NULL)
197 {
198 nr = tv_get_number(&di->di_tv);
199 if (lnume > nr)
200 di->di_tv.vval.v_number = lnume;
201 }
Bram Moolenaardda41442019-05-16 22:11:47 +0200202 di = dict_find(li->li_tv.vval.v_dict,
203 (char_u *)"added", -1);
Bram Moolenaar0d3cb732019-05-18 13:05:18 +0200204 if (di != NULL)
205 di->di_tv.vval.v_number += xtra;
Bram Moolenaardda41442019-05-16 22:11:47 +0200206 return TRUE;
207 }
208 }
209 else
210 {
211 // the current change is going to make the line number in
212 // the older change invalid, flush now
213 invoke_listeners(curbuf);
214 break;
215 }
216 }
217 }
218 }
219 return FALSE;
220}
221
222/*
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200223 * Record a change for listeners added with listener_add().
Bram Moolenaardda41442019-05-16 22:11:47 +0200224 * Always for the current buffer.
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200225 */
226 static void
227may_record_change(
228 linenr_T lnum,
229 colnr_T col,
230 linenr_T lnume,
231 long xtra)
232{
233 dict_T *dict;
234
235 if (curbuf->b_listener == NULL)
236 return;
Bram Moolenaarfe1ade02019-05-14 21:20:36 +0200237
238 // If the new change is going to change the line numbers in already listed
239 // changes, then flush.
Bram Moolenaardda41442019-05-16 22:11:47 +0200240 if (check_recorded_changes(curbuf, lnum, col, lnume, xtra, TRUE))
241 return;
242
243 if (curbuf->b_recorded_changes == NULL)
Bram Moolenaarfe1ade02019-05-14 21:20:36 +0200244 {
Bram Moolenaardda41442019-05-16 22:11:47 +0200245 curbuf->b_recorded_changes = list_alloc();
246 if (curbuf->b_recorded_changes == NULL) // out of memory
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200247 return;
Bram Moolenaardda41442019-05-16 22:11:47 +0200248 ++curbuf->b_recorded_changes->lv_refcount;
249 curbuf->b_recorded_changes->lv_lock = VAR_FIXED;
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200250 }
251
252 dict = dict_alloc();
253 if (dict == NULL)
254 return;
255 dict_add_number(dict, "lnum", (varnumber_T)lnum);
256 dict_add_number(dict, "end", (varnumber_T)lnume);
257 dict_add_number(dict, "added", (varnumber_T)xtra);
Bram Moolenaara3347722019-05-11 21:14:24 +0200258 dict_add_number(dict, "col", (varnumber_T)col + 1);
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200259
Bram Moolenaardda41442019-05-16 22:11:47 +0200260 list_append_dict(curbuf->b_recorded_changes, dict);
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200261}
262
263/*
264 * listener_add() function
265 */
266 void
267f_listener_add(typval_T *argvars, typval_T *rettv)
268{
269 char_u *callback;
270 partial_T *partial;
271 listener_T *lnr;
Bram Moolenaara3347722019-05-11 21:14:24 +0200272 buf_T *buf = curbuf;
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200273
274 callback = get_callback(&argvars[0], &partial);
275 if (callback == NULL)
276 return;
277
Bram Moolenaara3347722019-05-11 21:14:24 +0200278 if (argvars[1].v_type != VAR_UNKNOWN)
279 {
280 buf = get_buf_arg(&argvars[1]);
281 if (buf == NULL)
282 return;
283 }
284
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200285 lnr = (listener_T *)alloc_clear((sizeof(listener_T)));
286 if (lnr == NULL)
287 {
288 free_callback(callback, partial);
289 return;
290 }
Bram Moolenaara3347722019-05-11 21:14:24 +0200291 lnr->lr_next = buf->b_listener;
292 buf->b_listener = lnr;
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200293
294 if (partial == NULL)
295 lnr->lr_callback = vim_strsave(callback);
296 else
297 lnr->lr_callback = callback; // pointer into the partial
298 lnr->lr_partial = partial;
299
300 lnr->lr_id = ++next_listener_id;
301 rettv->vval.v_number = lnr->lr_id;
302}
303
304/*
Bram Moolenaarfe1ade02019-05-14 21:20:36 +0200305 * listener_flush() function
306 */
307 void
308f_listener_flush(typval_T *argvars, typval_T *rettv UNUSED)
309{
310 buf_T *buf = curbuf;
311
312 if (argvars[0].v_type != VAR_UNKNOWN)
313 {
314 buf = get_buf_arg(&argvars[0]);
315 if (buf == NULL)
316 return;
317 }
318 invoke_listeners(buf);
319}
320
321/*
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200322 * listener_remove() function
323 */
324 void
325f_listener_remove(typval_T *argvars, typval_T *rettv UNUSED)
326{
327 listener_T *lnr;
328 listener_T *next;
329 listener_T *prev = NULL;
330 int id = tv_get_number(argvars);
Bram Moolenaara3347722019-05-11 21:14:24 +0200331 buf_T *buf;
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200332
Bram Moolenaara3347722019-05-11 21:14:24 +0200333 for (buf = firstbuf; buf != NULL; buf = buf->b_next)
334 for (lnr = buf->b_listener; lnr != NULL; lnr = next)
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200335 {
Bram Moolenaara3347722019-05-11 21:14:24 +0200336 next = lnr->lr_next;
337 if (lnr->lr_id == id)
338 {
339 if (prev != NULL)
340 prev->lr_next = lnr->lr_next;
341 else
342 buf->b_listener = lnr->lr_next;
343 free_callback(lnr->lr_callback, lnr->lr_partial);
344 vim_free(lnr);
345 }
346 prev = lnr;
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200347 }
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200348}
349
350/*
Bram Moolenaardda41442019-05-16 22:11:47 +0200351 * Called before inserting a line above "lnum"/"lnum3" or deleting line "lnum"
352 * to "lnume".
353 */
354 void
355may_invoke_listeners(buf_T *buf, linenr_T lnum, linenr_T lnume, int added)
356{
357 check_recorded_changes(buf, lnum, 0, lnume, added, FALSE);
358}
359
360/*
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200361 * Called when a sequence of changes is done: invoke listeners added with
362 * listener_add().
363 */
364 void
Bram Moolenaarfe1ade02019-05-14 21:20:36 +0200365invoke_listeners(buf_T *buf)
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200366{
367 listener_T *lnr;
368 typval_T rettv;
369 int dummy;
Bram Moolenaarfe1ade02019-05-14 21:20:36 +0200370 typval_T argv[6];
371 listitem_T *li;
372 linenr_T start = MAXLNUM;
373 linenr_T end = 0;
374 linenr_T added = 0;
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200375
Bram Moolenaardda41442019-05-16 22:11:47 +0200376 if (buf->b_recorded_changes == NULL // nothing changed
Bram Moolenaarfe1ade02019-05-14 21:20:36 +0200377 || buf->b_listener == NULL) // no listeners
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200378 return;
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200379
Bram Moolenaarfe1ade02019-05-14 21:20:36 +0200380 argv[0].v_type = VAR_NUMBER;
381 argv[0].vval.v_number = buf->b_fnum; // a:bufnr
382
383
Bram Moolenaardda41442019-05-16 22:11:47 +0200384 for (li = buf->b_recorded_changes->lv_first; li != NULL; li = li->li_next)
Bram Moolenaarfe1ade02019-05-14 21:20:36 +0200385 {
386 varnumber_T lnum;
387
388 lnum = dict_get_number(li->li_tv.vval.v_dict, (char_u *)"lnum");
389 if (start > lnum)
390 start = lnum;
391 lnum = dict_get_number(li->li_tv.vval.v_dict, (char_u *)"end");
392 if (lnum > end)
393 end = lnum;
394 added = dict_get_number(li->li_tv.vval.v_dict, (char_u *)"added");
395 }
396 argv[1].v_type = VAR_NUMBER;
397 argv[1].vval.v_number = start;
398 argv[2].v_type = VAR_NUMBER;
399 argv[2].vval.v_number = end;
400 argv[3].v_type = VAR_NUMBER;
401 argv[3].vval.v_number = added;
402
403 argv[4].v_type = VAR_LIST;
Bram Moolenaardda41442019-05-16 22:11:47 +0200404 argv[4].vval.v_list = buf->b_recorded_changes;
Bram Moolenaarfe1ade02019-05-14 21:20:36 +0200405 ++textlock;
406
407 for (lnr = buf->b_listener; lnr != NULL; lnr = lnr->lr_next)
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200408 {
409 call_func(lnr->lr_callback, -1, &rettv,
Bram Moolenaarfe1ade02019-05-14 21:20:36 +0200410 5, argv, NULL, 0L, 0L, &dummy, TRUE, lnr->lr_partial, NULL);
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200411 clear_tv(&rettv);
412 }
413
Bram Moolenaarfe1ade02019-05-14 21:20:36 +0200414 --textlock;
Bram Moolenaardda41442019-05-16 22:11:47 +0200415 list_unref(buf->b_recorded_changes);
416 buf->b_recorded_changes = NULL;
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200417}
418#endif
419
Bram Moolenaar3f86ca02019-05-11 18:30:00 +0200420/*
421 * Common code for when a change was made.
422 * See changed_lines() for the arguments.
423 * Careful: may trigger autocommands that reload the buffer.
424 */
425 static void
426changed_common(
427 linenr_T lnum,
428 colnr_T col,
429 linenr_T lnume,
430 long xtra)
431{
432 win_T *wp;
433 tabpage_T *tp;
434 int i;
435#ifdef FEAT_JUMPLIST
436 int cols;
437 pos_T *p;
438 int add;
439#endif
440
441 // mark the buffer as modified
442 changed();
443
Bram Moolenaar6d2399b2019-05-11 19:14:16 +0200444#ifdef FEAT_EVAL
445 may_record_change(lnum, col, lnume, xtra);
446#endif
Bram Moolenaar3f86ca02019-05-11 18:30:00 +0200447#ifdef FEAT_DIFF
448 if (curwin->w_p_diff && diff_internal())
449 curtab->tp_diff_update = TRUE;
450#endif
451
452 // set the '. mark
453 if (!cmdmod.keepjumps)
454 {
455 curbuf->b_last_change.lnum = lnum;
456 curbuf->b_last_change.col = col;
457
458#ifdef FEAT_JUMPLIST
459 // Create a new entry if a new undo-able change was started or we
460 // don't have an entry yet.
461 if (curbuf->b_new_change || curbuf->b_changelistlen == 0)
462 {
463 if (curbuf->b_changelistlen == 0)
464 add = TRUE;
465 else
466 {
467 // Don't create a new entry when the line number is the same
468 // as the last one and the column is not too far away. Avoids
469 // creating many entries for typing "xxxxx".
470 p = &curbuf->b_changelist[curbuf->b_changelistlen - 1];
471 if (p->lnum != lnum)
472 add = TRUE;
473 else
474 {
475 cols = comp_textwidth(FALSE);
476 if (cols == 0)
477 cols = 79;
478 add = (p->col + cols < col || col + cols < p->col);
479 }
480 }
481 if (add)
482 {
483 // This is the first of a new sequence of undo-able changes
484 // and it's at some distance of the last change. Use a new
485 // position in the changelist.
486 curbuf->b_new_change = FALSE;
487
488 if (curbuf->b_changelistlen == JUMPLISTSIZE)
489 {
490 // changelist is full: remove oldest entry
491 curbuf->b_changelistlen = JUMPLISTSIZE - 1;
492 mch_memmove(curbuf->b_changelist, curbuf->b_changelist + 1,
493 sizeof(pos_T) * (JUMPLISTSIZE - 1));
494 FOR_ALL_TAB_WINDOWS(tp, wp)
495 {
496 // Correct position in changelist for other windows on
497 // this buffer.
498 if (wp->w_buffer == curbuf && wp->w_changelistidx > 0)
499 --wp->w_changelistidx;
500 }
501 }
502 FOR_ALL_TAB_WINDOWS(tp, wp)
503 {
504 // For other windows, if the position in the changelist is
505 // at the end it stays at the end.
506 if (wp->w_buffer == curbuf
507 && wp->w_changelistidx == curbuf->b_changelistlen)
508 ++wp->w_changelistidx;
509 }
510 ++curbuf->b_changelistlen;
511 }
512 }
513 curbuf->b_changelist[curbuf->b_changelistlen - 1] =
514 curbuf->b_last_change;
515 // The current window is always after the last change, so that "g,"
516 // takes you back to it.
517 curwin->w_changelistidx = curbuf->b_changelistlen;
518#endif
519 }
520
521 FOR_ALL_TAB_WINDOWS(tp, wp)
522 {
523 if (wp->w_buffer == curbuf)
524 {
525 // Mark this window to be redrawn later.
526 if (wp->w_redr_type < VALID)
527 wp->w_redr_type = VALID;
528
529 // Check if a change in the buffer has invalidated the cached
530 // values for the cursor.
531#ifdef FEAT_FOLDING
532 // Update the folds for this window. Can't postpone this, because
533 // a following operator might work on the whole fold: ">>dd".
534 foldUpdate(wp, lnum, lnume + xtra - 1);
535
536 // The change may cause lines above or below the change to become
537 // included in a fold. Set lnum/lnume to the first/last line that
538 // might be displayed differently.
539 // Set w_cline_folded here as an efficient way to update it when
540 // inserting lines just above a closed fold.
541 i = hasFoldingWin(wp, lnum, &lnum, NULL, FALSE, NULL);
542 if (wp->w_cursor.lnum == lnum)
543 wp->w_cline_folded = i;
544 i = hasFoldingWin(wp, lnume, NULL, &lnume, FALSE, NULL);
545 if (wp->w_cursor.lnum == lnume)
546 wp->w_cline_folded = i;
547
548 // If the changed line is in a range of previously folded lines,
549 // compare with the first line in that range.
550 if (wp->w_cursor.lnum <= lnum)
551 {
552 i = find_wl_entry(wp, lnum);
553 if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum)
554 changed_line_abv_curs_win(wp);
555 }
556#endif
557
558 if (wp->w_cursor.lnum > lnum)
559 changed_line_abv_curs_win(wp);
560 else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col)
561 changed_cline_bef_curs_win(wp);
562 if (wp->w_botline >= lnum)
563 {
564 // Assume that botline doesn't change (inserted lines make
565 // other lines scroll down below botline).
566 approximate_botline_win(wp);
567 }
568
569 // Check if any w_lines[] entries have become invalid.
570 // For entries below the change: Correct the lnums for
571 // inserted/deleted lines. Makes it possible to stop displaying
572 // after the change.
573 for (i = 0; i < wp->w_lines_valid; ++i)
574 if (wp->w_lines[i].wl_valid)
575 {
576 if (wp->w_lines[i].wl_lnum >= lnum)
577 {
578 if (wp->w_lines[i].wl_lnum < lnume)
579 {
580 // line included in change
581 wp->w_lines[i].wl_valid = FALSE;
582 }
583 else if (xtra != 0)
584 {
585 // line below change
586 wp->w_lines[i].wl_lnum += xtra;
587#ifdef FEAT_FOLDING
588 wp->w_lines[i].wl_lastlnum += xtra;
589#endif
590 }
591 }
592#ifdef FEAT_FOLDING
593 else if (wp->w_lines[i].wl_lastlnum >= lnum)
594 {
595 // change somewhere inside this range of folded lines,
596 // may need to be redrawn
597 wp->w_lines[i].wl_valid = FALSE;
598 }
599#endif
600 }
601
602#ifdef FEAT_FOLDING
603 // Take care of side effects for setting w_topline when folds have
604 // changed. Esp. when the buffer was changed in another window.
605 if (hasAnyFolding(wp))
606 set_topline(wp, wp->w_topline);
607#endif
608 // relative numbering may require updating more
609 if (wp->w_p_rnu)
610 redraw_win_later(wp, SOME_VALID);
611 }
612 }
613
614 // Call update_screen() later, which checks out what needs to be redrawn,
615 // since it notices b_mod_set and then uses b_mod_*.
616 if (must_redraw < VALID)
617 must_redraw = VALID;
618
619 // when the cursor line is changed always trigger CursorMoved
620 if (lnum <= curwin->w_cursor.lnum
621 && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum)
622 last_cursormoved.lnum = 0;
623}
624
625 static void
626changedOneline(buf_T *buf, linenr_T lnum)
627{
628 if (buf->b_mod_set)
629 {
630 // find the maximum area that must be redisplayed
631 if (lnum < buf->b_mod_top)
632 buf->b_mod_top = lnum;
633 else if (lnum >= buf->b_mod_bot)
634 buf->b_mod_bot = lnum + 1;
635 }
636 else
637 {
638 // set the area that must be redisplayed to one line
639 buf->b_mod_set = TRUE;
640 buf->b_mod_top = lnum;
641 buf->b_mod_bot = lnum + 1;
642 buf->b_mod_xlines = 0;
643 }
644}
645
646/*
647 * Changed bytes within a single line for the current buffer.
648 * - marks the windows on this buffer to be redisplayed
649 * - marks the buffer changed by calling changed()
650 * - invalidates cached values
651 * Careful: may trigger autocommands that reload the buffer.
652 */
653 void
654changed_bytes(linenr_T lnum, colnr_T col)
655{
656 changedOneline(curbuf, lnum);
657 changed_common(lnum, col, lnum + 1, 0L);
658
659#ifdef FEAT_DIFF
660 // Diff highlighting in other diff windows may need to be updated too.
661 if (curwin->w_p_diff)
662 {
663 win_T *wp;
664 linenr_T wlnum;
665
666 FOR_ALL_WINDOWS(wp)
667 if (wp->w_p_diff && wp != curwin)
668 {
669 redraw_win_later(wp, VALID);
670 wlnum = diff_lnum_win(lnum, wp);
671 if (wlnum > 0)
672 changedOneline(wp->w_buffer, wlnum);
673 }
674 }
675#endif
676}
677
678/*
679 * Like changed_bytes() but also adjust text properties for "added" bytes.
680 * When "added" is negative text was deleted.
681 */
682 void
683inserted_bytes(linenr_T lnum, colnr_T col, int added UNUSED)
684{
Bram Moolenaar3f86ca02019-05-11 18:30:00 +0200685#ifdef FEAT_TEXT_PROP
686 if (curbuf->b_has_textprop && added != 0)
Bram Moolenaarf3333b02019-05-19 22:53:40 +0200687 adjust_prop_columns(lnum, col, added, 0);
Bram Moolenaar3f86ca02019-05-11 18:30:00 +0200688#endif
Bram Moolenaar45dd07f2019-05-15 22:45:37 +0200689
690 changed_bytes(lnum, col);
Bram Moolenaar3f86ca02019-05-11 18:30:00 +0200691}
692
693/*
694 * Appended "count" lines below line "lnum" in the current buffer.
695 * Must be called AFTER the change and after mark_adjust().
696 * Takes care of marking the buffer to be redrawn and sets the changed flag.
697 */
698 void
699appended_lines(linenr_T lnum, long count)
700{
701 changed_lines(lnum + 1, 0, lnum + 1, count);
702}
703
704/*
705 * Like appended_lines(), but adjust marks first.
706 */
707 void
708appended_lines_mark(linenr_T lnum, long count)
709{
710 // Skip mark_adjust when adding a line after the last one, there can't
711 // be marks there. But it's still needed in diff mode.
712 if (lnum + count < curbuf->b_ml.ml_line_count
713#ifdef FEAT_DIFF
714 || curwin->w_p_diff
715#endif
716 )
717 mark_adjust(lnum + 1, (linenr_T)MAXLNUM, count, 0L);
718 changed_lines(lnum + 1, 0, lnum + 1, count);
719}
720
721/*
722 * Deleted "count" lines at line "lnum" in the current buffer.
723 * Must be called AFTER the change and after mark_adjust().
724 * Takes care of marking the buffer to be redrawn and sets the changed flag.
725 */
726 void
727deleted_lines(linenr_T lnum, long count)
728{
729 changed_lines(lnum, 0, lnum + count, -count);
730}
731
732/*
733 * Like deleted_lines(), but adjust marks first.
734 * Make sure the cursor is on a valid line before calling, a GUI callback may
735 * be triggered to display the cursor.
736 */
737 void
738deleted_lines_mark(linenr_T lnum, long count)
739{
740 mark_adjust(lnum, (linenr_T)(lnum + count - 1), (long)MAXLNUM, -count);
741 changed_lines(lnum, 0, lnum + count, -count);
742}
743
744/*
745 * Marks the area to be redrawn after a change.
746 */
747 static void
748changed_lines_buf(
749 buf_T *buf,
750 linenr_T lnum, // first line with change
751 linenr_T lnume, // line below last changed line
752 long xtra) // number of extra lines (negative when deleting)
753{
754 if (buf->b_mod_set)
755 {
756 // find the maximum area that must be redisplayed
757 if (lnum < buf->b_mod_top)
758 buf->b_mod_top = lnum;
759 if (lnum < buf->b_mod_bot)
760 {
761 // adjust old bot position for xtra lines
762 buf->b_mod_bot += xtra;
763 if (buf->b_mod_bot < lnum)
764 buf->b_mod_bot = lnum;
765 }
766 if (lnume + xtra > buf->b_mod_bot)
767 buf->b_mod_bot = lnume + xtra;
768 buf->b_mod_xlines += xtra;
769 }
770 else
771 {
772 // set the area that must be redisplayed
773 buf->b_mod_set = TRUE;
774 buf->b_mod_top = lnum;
775 buf->b_mod_bot = lnume + xtra;
776 buf->b_mod_xlines = xtra;
777 }
778}
779
780/*
781 * Changed lines for the current buffer.
782 * Must be called AFTER the change and after mark_adjust().
783 * - mark the buffer changed by calling changed()
784 * - mark the windows on this buffer to be redisplayed
785 * - invalidate cached values
786 * "lnum" is the first line that needs displaying, "lnume" the first line
787 * below the changed lines (BEFORE the change).
788 * When only inserting lines, "lnum" and "lnume" are equal.
789 * Takes care of calling changed() and updating b_mod_*.
790 * Careful: may trigger autocommands that reload the buffer.
791 */
792 void
793changed_lines(
794 linenr_T lnum, // first line with change
795 colnr_T col, // column in first line with change
796 linenr_T lnume, // line below last changed line
797 long xtra) // number of extra lines (negative when deleting)
798{
799 changed_lines_buf(curbuf, lnum, lnume, xtra);
800
801#ifdef FEAT_DIFF
802 if (xtra == 0 && curwin->w_p_diff && !diff_internal())
803 {
804 // When the number of lines doesn't change then mark_adjust() isn't
805 // called and other diff buffers still need to be marked for
806 // displaying.
807 win_T *wp;
808 linenr_T wlnum;
809
810 FOR_ALL_WINDOWS(wp)
811 if (wp->w_p_diff && wp != curwin)
812 {
813 redraw_win_later(wp, VALID);
814 wlnum = diff_lnum_win(lnum, wp);
815 if (wlnum > 0)
816 changed_lines_buf(wp->w_buffer, wlnum,
817 lnume - lnum + wlnum, 0L);
818 }
819 }
820#endif
821
822 changed_common(lnum, col, lnume, xtra);
823}
824
825/*
826 * Called when the changed flag must be reset for buffer "buf".
827 * When "ff" is TRUE also reset 'fileformat'.
828 */
829 void
830unchanged(buf_T *buf, int ff)
831{
832 if (buf->b_changed || (ff && file_ff_differs(buf, FALSE)))
833 {
834 buf->b_changed = 0;
835 ml_setflags(buf);
836 if (ff)
837 save_file_ff(buf);
838 check_status(buf);
839 redraw_tabline = TRUE;
840#ifdef FEAT_TITLE
841 need_maketitle = TRUE; // set window title later
842#endif
843 }
844 ++CHANGEDTICK(buf);
845#ifdef FEAT_NETBEANS_INTG
846 netbeans_unmodified(buf);
847#endif
848}
849
850/*
851 * Insert string "p" at the cursor position. Stops at a NUL byte.
852 * Handles Replace mode and multi-byte characters.
853 */
854 void
855ins_bytes(char_u *p)
856{
857 ins_bytes_len(p, (int)STRLEN(p));
858}
859
860/*
861 * Insert string "p" with length "len" at the cursor position.
862 * Handles Replace mode and multi-byte characters.
863 */
864 void
865ins_bytes_len(char_u *p, int len)
866{
867 int i;
868 int n;
869
870 if (has_mbyte)
871 for (i = 0; i < len; i += n)
872 {
873 if (enc_utf8)
874 // avoid reading past p[len]
875 n = utfc_ptr2len_len(p + i, len - i);
876 else
877 n = (*mb_ptr2len)(p + i);
878 ins_char_bytes(p + i, n);
879 }
880 else
881 for (i = 0; i < len; ++i)
882 ins_char(p[i]);
883}
884
885/*
886 * Insert or replace a single character at the cursor position.
887 * When in REPLACE or VREPLACE mode, replace any existing character.
888 * Caller must have prepared for undo.
889 * For multi-byte characters we get the whole character, the caller must
890 * convert bytes to a character.
891 */
892 void
893ins_char(int c)
894{
895 char_u buf[MB_MAXBYTES + 1];
896 int n = (*mb_char2bytes)(c, buf);
897
898 // When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
899 // Happens for CTRL-Vu9900.
900 if (buf[0] == 0)
901 buf[0] = '\n';
902
903 ins_char_bytes(buf, n);
904}
905
906 void
907ins_char_bytes(char_u *buf, int charlen)
908{
909 int c = buf[0];
910 int newlen; // nr of bytes inserted
911 int oldlen; // nr of bytes deleted (0 when not replacing)
912 char_u *p;
913 char_u *newp;
914 char_u *oldp;
915 int linelen; // length of old line including NUL
916 colnr_T col;
917 linenr_T lnum = curwin->w_cursor.lnum;
918 int i;
919
920 // Break tabs if needed.
921 if (virtual_active() && curwin->w_cursor.coladd > 0)
922 coladvance_force(getviscol());
923
924 col = curwin->w_cursor.col;
925 oldp = ml_get(lnum);
926 linelen = (int)STRLEN(oldp) + 1;
927
928 // The lengths default to the values for when not replacing.
929 oldlen = 0;
930 newlen = charlen;
931
932 if (State & REPLACE_FLAG)
933 {
934 if (State & VREPLACE_FLAG)
935 {
936 colnr_T new_vcol = 0; // init for GCC
937 colnr_T vcol;
938 int old_list;
939
940 // Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
941 // Returns the old value of list, so when finished,
942 // curwin->w_p_list should be set back to this.
943 old_list = curwin->w_p_list;
944 if (old_list && vim_strchr(p_cpo, CPO_LISTWM) == NULL)
945 curwin->w_p_list = FALSE;
946
947 // In virtual replace mode each character may replace one or more
948 // characters (zero if it's a TAB). Count the number of bytes to
949 // be deleted to make room for the new character, counting screen
950 // cells. May result in adding spaces to fill a gap.
951 getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL);
952 new_vcol = vcol + chartabsize(buf, vcol);
953 while (oldp[col + oldlen] != NUL && vcol < new_vcol)
954 {
955 vcol += chartabsize(oldp + col + oldlen, vcol);
956 // Don't need to remove a TAB that takes us to the right
957 // position.
958 if (vcol > new_vcol && oldp[col + oldlen] == TAB)
959 break;
960 oldlen += (*mb_ptr2len)(oldp + col + oldlen);
961 // Deleted a bit too much, insert spaces.
962 if (vcol > new_vcol)
963 newlen += vcol - new_vcol;
964 }
965 curwin->w_p_list = old_list;
966 }
967 else if (oldp[col] != NUL)
968 {
969 // normal replace
970 oldlen = (*mb_ptr2len)(oldp + col);
971 }
972
973
974 // Push the replaced bytes onto the replace stack, so that they can be
975 // put back when BS is used. The bytes of a multi-byte character are
976 // done the other way around, so that the first byte is popped off
977 // first (it tells the byte length of the character).
978 replace_push(NUL);
979 for (i = 0; i < oldlen; ++i)
980 {
981 if (has_mbyte)
982 i += replace_push_mb(oldp + col + i) - 1;
983 else
984 replace_push(oldp[col + i]);
985 }
986 }
987
988 newp = alloc_check((unsigned)(linelen + newlen - oldlen));
989 if (newp == NULL)
990 return;
991
992 // Copy bytes before the cursor.
993 if (col > 0)
994 mch_memmove(newp, oldp, (size_t)col);
995
996 // Copy bytes after the changed character(s).
997 p = newp + col;
998 if (linelen > col + oldlen)
999 mch_memmove(p + newlen, oldp + col + oldlen,
1000 (size_t)(linelen - col - oldlen));
1001
1002 // Insert or overwrite the new character.
1003 mch_memmove(p, buf, charlen);
1004 i = charlen;
1005
1006 // Fill with spaces when necessary.
1007 while (i < newlen)
1008 p[i++] = ' ';
1009
1010 // Replace the line in the buffer.
1011 ml_replace(lnum, newp, FALSE);
1012
1013 // mark the buffer as changed and prepare for displaying
1014 inserted_bytes(lnum, col, newlen - oldlen);
1015
1016 // If we're in Insert or Replace mode and 'showmatch' is set, then briefly
1017 // show the match for right parens and braces.
1018 if (p_sm && (State & INSERT)
1019 && msg_silent == 0
1020#ifdef FEAT_INS_EXPAND
1021 && !ins_compl_active()
1022#endif
1023 )
1024 {
1025 if (has_mbyte)
1026 showmatch(mb_ptr2char(buf));
1027 else
1028 showmatch(c);
1029 }
1030
1031#ifdef FEAT_RIGHTLEFT
1032 if (!p_ri || (State & REPLACE_FLAG))
1033#endif
1034 {
1035 // Normal insert: move cursor right
1036 curwin->w_cursor.col += charlen;
1037 }
1038
1039 // TODO: should try to update w_row here, to avoid recomputing it later.
1040}
1041
1042/*
1043 * Insert a string at the cursor position.
1044 * Note: Does NOT handle Replace mode.
1045 * Caller must have prepared for undo.
1046 */
1047 void
1048ins_str(char_u *s)
1049{
1050 char_u *oldp, *newp;
1051 int newlen = (int)STRLEN(s);
1052 int oldlen;
1053 colnr_T col;
1054 linenr_T lnum = curwin->w_cursor.lnum;
1055
1056 if (virtual_active() && curwin->w_cursor.coladd > 0)
1057 coladvance_force(getviscol());
1058
1059 col = curwin->w_cursor.col;
1060 oldp = ml_get(lnum);
1061 oldlen = (int)STRLEN(oldp);
1062
1063 newp = alloc_check((unsigned)(oldlen + newlen + 1));
1064 if (newp == NULL)
1065 return;
1066 if (col > 0)
1067 mch_memmove(newp, oldp, (size_t)col);
1068 mch_memmove(newp + col, s, (size_t)newlen);
1069 mch_memmove(newp + col + newlen, oldp + col, (size_t)(oldlen - col + 1));
1070 ml_replace(lnum, newp, FALSE);
1071 inserted_bytes(lnum, col, newlen);
1072 curwin->w_cursor.col += newlen;
1073}
1074
1075/*
1076 * Delete one character under the cursor.
1077 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
1078 * Caller must have prepared for undo.
1079 *
1080 * return FAIL for failure, OK otherwise
1081 */
1082 int
1083del_char(int fixpos)
1084{
1085 if (has_mbyte)
1086 {
1087 // Make sure the cursor is at the start of a character.
1088 mb_adjust_cursor();
1089 if (*ml_get_cursor() == NUL)
1090 return FAIL;
1091 return del_chars(1L, fixpos);
1092 }
1093 return del_bytes(1L, fixpos, TRUE);
1094}
1095
1096/*
1097 * Like del_bytes(), but delete characters instead of bytes.
1098 */
1099 int
1100del_chars(long count, int fixpos)
1101{
1102 long bytes = 0;
1103 long i;
1104 char_u *p;
1105 int l;
1106
1107 p = ml_get_cursor();
1108 for (i = 0; i < count && *p != NUL; ++i)
1109 {
1110 l = (*mb_ptr2len)(p);
1111 bytes += l;
1112 p += l;
1113 }
1114 return del_bytes(bytes, fixpos, TRUE);
1115}
1116
1117/*
1118 * Delete "count" bytes under the cursor.
1119 * If "fixpos" is TRUE, don't leave the cursor on the NUL after the line.
1120 * Caller must have prepared for undo.
1121 *
1122 * Return FAIL for failure, OK otherwise.
1123 */
1124 int
1125del_bytes(
1126 long count,
1127 int fixpos_arg,
1128 int use_delcombine UNUSED) // 'delcombine' option applies
1129{
1130 char_u *oldp, *newp;
1131 colnr_T oldlen;
1132 colnr_T newlen;
1133 linenr_T lnum = curwin->w_cursor.lnum;
1134 colnr_T col = curwin->w_cursor.col;
1135 int alloc_newp;
1136 long movelen;
1137 int fixpos = fixpos_arg;
1138
1139 oldp = ml_get(lnum);
1140 oldlen = (int)STRLEN(oldp);
1141
1142 // Can't do anything when the cursor is on the NUL after the line.
1143 if (col >= oldlen)
1144 return FAIL;
1145
1146 // If "count" is zero there is nothing to do.
1147 if (count == 0)
1148 return OK;
1149
1150 // If "count" is negative the caller must be doing something wrong.
1151 if (count < 1)
1152 {
1153 siemsg("E950: Invalid count for del_bytes(): %ld", count);
1154 return FAIL;
1155 }
1156
1157 // If 'delcombine' is set and deleting (less than) one character, only
1158 // delete the last combining character.
1159 if (p_deco && use_delcombine && enc_utf8
1160 && utfc_ptr2len(oldp + col) >= count)
1161 {
1162 int cc[MAX_MCO];
1163 int n;
1164
1165 (void)utfc_ptr2char(oldp + col, cc);
1166 if (cc[0] != NUL)
1167 {
1168 // Find the last composing char, there can be several.
1169 n = col;
1170 do
1171 {
1172 col = n;
1173 count = utf_ptr2len(oldp + n);
1174 n += count;
1175 } while (UTF_COMPOSINGLIKE(oldp + col, oldp + n));
1176 fixpos = 0;
1177 }
1178 }
1179
1180 // When count is too big, reduce it.
1181 movelen = (long)oldlen - (long)col - count + 1; // includes trailing NUL
1182 if (movelen <= 1)
1183 {
1184 // If we just took off the last character of a non-blank line, and
1185 // fixpos is TRUE, we don't want to end up positioned at the NUL,
1186 // unless "restart_edit" is set or 'virtualedit' contains "onemore".
1187 if (col > 0 && fixpos && restart_edit == 0
1188 && (ve_flags & VE_ONEMORE) == 0)
1189 {
1190 --curwin->w_cursor.col;
1191 curwin->w_cursor.coladd = 0;
1192 if (has_mbyte)
1193 curwin->w_cursor.col -=
1194 (*mb_head_off)(oldp, oldp + curwin->w_cursor.col);
1195 }
1196 count = oldlen - col;
1197 movelen = 1;
1198 }
1199 newlen = oldlen - count;
1200
1201 // If the old line has been allocated the deletion can be done in the
1202 // existing line. Otherwise a new line has to be allocated
1203 // Can't do this when using Netbeans, because we would need to invoke
1204 // netbeans_removed(), which deallocates the line. Let ml_replace() take
1205 // care of notifying Netbeans.
1206#ifdef FEAT_NETBEANS_INTG
1207 if (netbeans_active())
1208 alloc_newp = TRUE;
1209 else
1210#endif
1211 alloc_newp = !ml_line_alloced(); // check if oldp was allocated
1212 if (!alloc_newp)
1213 newp = oldp; // use same allocated memory
1214 else
1215 { // need to allocate a new line
1216 newp = alloc((unsigned)(newlen + 1));
1217 if (newp == NULL)
1218 return FAIL;
1219 mch_memmove(newp, oldp, (size_t)col);
1220 }
1221 mch_memmove(newp + col, oldp + col + count, (size_t)movelen);
1222 if (alloc_newp)
1223 ml_replace(lnum, newp, FALSE);
1224#ifdef FEAT_TEXT_PROP
1225 else
1226 {
1227 // Also move any following text properties.
1228 if (oldlen + 1 < curbuf->b_ml.ml_line_len)
1229 mch_memmove(newp + newlen + 1, oldp + oldlen + 1,
1230 (size_t)curbuf->b_ml.ml_line_len - oldlen - 1);
1231 curbuf->b_ml.ml_line_len -= count;
1232 }
1233#endif
1234
1235 // mark the buffer as changed and prepare for displaying
1236 inserted_bytes(lnum, curwin->w_cursor.col, -count);
1237
1238 return OK;
1239}
1240
1241/*
1242 * Copy the indent from ptr to the current line (and fill to size)
1243 * Leaves the cursor on the first non-blank in the line.
1244 * Returns TRUE if the line was changed.
1245 */
1246 static int
1247copy_indent(int size, char_u *src)
1248{
1249 char_u *p = NULL;
1250 char_u *line = NULL;
1251 char_u *s;
1252 int todo;
1253 int ind_len;
1254 int line_len = 0;
1255 int tab_pad;
1256 int ind_done;
1257 int round;
1258#ifdef FEAT_VARTABS
1259 int ind_col;
1260#endif
1261
1262 // Round 1: compute the number of characters needed for the indent
1263 // Round 2: copy the characters.
1264 for (round = 1; round <= 2; ++round)
1265 {
1266 todo = size;
1267 ind_len = 0;
1268 ind_done = 0;
1269#ifdef FEAT_VARTABS
1270 ind_col = 0;
1271#endif
1272 s = src;
1273
1274 // Count/copy the usable portion of the source line
1275 while (todo > 0 && VIM_ISWHITE(*s))
1276 {
1277 if (*s == TAB)
1278 {
1279#ifdef FEAT_VARTABS
1280 tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,
1281 curbuf->b_p_vts_array);
1282#else
1283 tab_pad = (int)curbuf->b_p_ts
1284 - (ind_done % (int)curbuf->b_p_ts);
1285#endif
1286 // Stop if this tab will overshoot the target
1287 if (todo < tab_pad)
1288 break;
1289 todo -= tab_pad;
1290 ind_done += tab_pad;
1291#ifdef FEAT_VARTABS
1292 ind_col += tab_pad;
1293#endif
1294 }
1295 else
1296 {
1297 --todo;
1298 ++ind_done;
1299#ifdef FEAT_VARTABS
1300 ++ind_col;
1301#endif
1302 }
1303 ++ind_len;
1304 if (p != NULL)
1305 *p++ = *s;
1306 ++s;
1307 }
1308
1309 // Fill to next tabstop with a tab, if possible
1310#ifdef FEAT_VARTABS
1311 tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,
1312 curbuf->b_p_vts_array);
1313#else
1314 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
1315#endif
1316 if (todo >= tab_pad && !curbuf->b_p_et)
1317 {
1318 todo -= tab_pad;
1319 ++ind_len;
1320#ifdef FEAT_VARTABS
1321 ind_col += tab_pad;
1322#endif
1323 if (p != NULL)
1324 *p++ = TAB;
1325 }
1326
1327 // Add tabs required for indent
1328 if (!curbuf->b_p_et)
1329 {
1330#ifdef FEAT_VARTABS
1331 for (;;)
1332 {
1333 tab_pad = tabstop_padding(ind_col, curbuf->b_p_ts,
1334 curbuf->b_p_vts_array);
1335 if (todo < tab_pad)
1336 break;
1337 todo -= tab_pad;
1338 ++ind_len;
1339 ind_col += tab_pad;
1340 if (p != NULL)
1341 *p++ = TAB;
1342 }
1343#else
1344 while (todo >= (int)curbuf->b_p_ts)
1345 {
1346 todo -= (int)curbuf->b_p_ts;
1347 ++ind_len;
1348 if (p != NULL)
1349 *p++ = TAB;
1350 }
1351#endif
1352 }
1353
1354 // Count/add spaces required for indent
1355 while (todo > 0)
1356 {
1357 --todo;
1358 ++ind_len;
1359 if (p != NULL)
1360 *p++ = ' ';
1361 }
1362
1363 if (p == NULL)
1364 {
1365 // Allocate memory for the result: the copied indent, new indent
1366 // and the rest of the line.
1367 line_len = (int)STRLEN(ml_get_curline()) + 1;
1368 line = alloc(ind_len + line_len);
1369 if (line == NULL)
1370 return FALSE;
1371 p = line;
1372 }
1373 }
1374
1375 // Append the original line
1376 mch_memmove(p, ml_get_curline(), (size_t)line_len);
1377
1378 // Replace the line
1379 ml_replace(curwin->w_cursor.lnum, line, FALSE);
1380
1381 // Put the cursor after the indent.
1382 curwin->w_cursor.col = ind_len;
1383 return TRUE;
1384}
1385
1386/*
1387 * open_line: Add a new line below or above the current line.
1388 *
1389 * For VREPLACE mode, we only add a new line when we get to the end of the
1390 * file, otherwise we just start replacing the next line.
1391 *
1392 * Caller must take care of undo. Since VREPLACE may affect any number of
1393 * lines however, it may call u_save_cursor() again when starting to change a
1394 * new line.
1395 * "flags": OPENLINE_DELSPACES delete spaces after cursor
1396 * OPENLINE_DO_COM format comments
1397 * OPENLINE_KEEPTRAIL keep trailing spaces
1398 * OPENLINE_MARKFIX adjust mark positions after the line break
1399 * OPENLINE_COM_LIST format comments with list or 2nd line indent
1400 *
1401 * "second_line_indent": indent for after ^^D in Insert mode or if flag
1402 * OPENLINE_COM_LIST
1403 *
1404 * Return OK for success, FAIL for failure
1405 */
1406 int
1407open_line(
1408 int dir, // FORWARD or BACKWARD
1409 int flags,
1410 int second_line_indent)
1411{
1412 char_u *saved_line; // copy of the original line
1413 char_u *next_line = NULL; // copy of the next line
1414 char_u *p_extra = NULL; // what goes to next line
1415 int less_cols = 0; // less columns for mark in new line
1416 int less_cols_off = 0; // columns to skip for mark adjust
1417 pos_T old_cursor; // old cursor position
1418 int newcol = 0; // new cursor column
1419 int newindent = 0; // auto-indent of the new line
1420 int n;
1421 int trunc_line = FALSE; // truncate current line afterwards
1422 int retval = FAIL; // return value
1423#ifdef FEAT_COMMENTS
1424 int extra_len = 0; // length of p_extra string
1425 int lead_len; // length of comment leader
1426 char_u *lead_flags; // position in 'comments' for comment leader
1427 char_u *leader = NULL; // copy of comment leader
1428#endif
1429 char_u *allocated = NULL; // allocated memory
1430 char_u *p;
1431 int saved_char = NUL; // init for GCC
1432#if defined(FEAT_SMARTINDENT) || defined(FEAT_COMMENTS)
1433 pos_T *pos;
1434#endif
1435#ifdef FEAT_SMARTINDENT
1436 int do_si = (!p_paste && curbuf->b_p_si
1437# ifdef FEAT_CINDENT
1438 && !curbuf->b_p_cin
1439# endif
1440# ifdef FEAT_EVAL
1441 && *curbuf->b_p_inde == NUL
1442# endif
1443 );
1444 int no_si = FALSE; // reset did_si afterwards
1445 int first_char = NUL; // init for GCC
1446#endif
1447#if defined(FEAT_LISP) || defined(FEAT_CINDENT)
1448 int vreplace_mode;
1449#endif
1450 int did_append; // appended a new line
1451 int saved_pi = curbuf->b_p_pi; // copy of preserveindent setting
1452
1453 // make a copy of the current line so we can mess with it
1454 saved_line = vim_strsave(ml_get_curline());
1455 if (saved_line == NULL) /* out of memory! */
1456 return FALSE;
1457
1458 if (State & VREPLACE_FLAG)
1459 {
1460 // With VREPLACE we make a copy of the next line, which we will be
1461 // starting to replace. First make the new line empty and let vim play
1462 // with the indenting and comment leader to its heart's content. Then
1463 // we grab what it ended up putting on the new line, put back the
1464 // original line, and call ins_char() to put each new character onto
1465 // the line, replacing what was there before and pushing the right
1466 // stuff onto the replace stack. -- webb.
1467 if (curwin->w_cursor.lnum < orig_line_count)
1468 next_line = vim_strsave(ml_get(curwin->w_cursor.lnum + 1));
1469 else
1470 next_line = vim_strsave((char_u *)"");
1471 if (next_line == NULL) // out of memory!
1472 goto theend;
1473
1474 // In VREPLACE mode, a NL replaces the rest of the line, and starts
1475 // replacing the next line, so push all of the characters left on the
1476 // line onto the replace stack. We'll push any other characters that
1477 // might be replaced at the start of the next line (due to autoindent
1478 // etc) a bit later.
1479 replace_push(NUL); // Call twice because BS over NL expects it
1480 replace_push(NUL);
1481 p = saved_line + curwin->w_cursor.col;
1482 while (*p != NUL)
1483 {
1484 if (has_mbyte)
1485 p += replace_push_mb(p);
1486 else
1487 replace_push(*p++);
1488 }
1489 saved_line[curwin->w_cursor.col] = NUL;
1490 }
1491
1492 if ((State & INSERT) && !(State & VREPLACE_FLAG))
1493 {
1494 p_extra = saved_line + curwin->w_cursor.col;
1495#ifdef FEAT_SMARTINDENT
1496 if (do_si) // need first char after new line break
1497 {
1498 p = skipwhite(p_extra);
1499 first_char = *p;
1500 }
1501#endif
1502#ifdef FEAT_COMMENTS
1503 extra_len = (int)STRLEN(p_extra);
1504#endif
1505 saved_char = *p_extra;
1506 *p_extra = NUL;
1507 }
1508
1509 u_clearline(); // cannot do "U" command when adding lines
1510#ifdef FEAT_SMARTINDENT
1511 did_si = FALSE;
1512#endif
1513 ai_col = 0;
1514
1515 // If we just did an auto-indent, then we didn't type anything on
1516 // the prior line, and it should be truncated. Do this even if 'ai' is not
1517 // set because automatically inserting a comment leader also sets did_ai.
1518 if (dir == FORWARD && did_ai)
1519 trunc_line = TRUE;
1520
1521 // If 'autoindent' and/or 'smartindent' is set, try to figure out what
1522 // indent to use for the new line.
1523 if (curbuf->b_p_ai
1524#ifdef FEAT_SMARTINDENT
1525 || do_si
1526#endif
1527 )
1528 {
1529 // count white space on current line
1530#ifdef FEAT_VARTABS
1531 newindent = get_indent_str_vtab(saved_line, curbuf->b_p_ts,
1532 curbuf->b_p_vts_array, FALSE);
1533#else
1534 newindent = get_indent_str(saved_line, (int)curbuf->b_p_ts, FALSE);
1535#endif
1536 if (newindent == 0 && !(flags & OPENLINE_COM_LIST))
1537 newindent = second_line_indent; // for ^^D command in insert mode
1538
1539#ifdef FEAT_SMARTINDENT
1540 // Do smart indenting.
1541 // In insert/replace mode (only when dir == FORWARD)
1542 // we may move some text to the next line. If it starts with '{'
1543 // don't add an indent. Fixes inserting a NL before '{' in line
1544 // "if (condition) {"
1545 if (!trunc_line && do_si && *saved_line != NUL
1546 && (p_extra == NULL || first_char != '{'))
1547 {
1548 char_u *ptr;
1549 char_u last_char;
1550
1551 old_cursor = curwin->w_cursor;
1552 ptr = saved_line;
1553# ifdef FEAT_COMMENTS
1554 if (flags & OPENLINE_DO_COM)
1555 lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
1556 else
1557 lead_len = 0;
1558# endif
1559 if (dir == FORWARD)
1560 {
1561 // Skip preprocessor directives, unless they are
1562 // recognised as comments.
1563 if (
1564# ifdef FEAT_COMMENTS
1565 lead_len == 0 &&
1566# endif
1567 ptr[0] == '#')
1568 {
1569 while (ptr[0] == '#' && curwin->w_cursor.lnum > 1)
1570 ptr = ml_get(--curwin->w_cursor.lnum);
1571 newindent = get_indent();
1572 }
1573# ifdef FEAT_COMMENTS
1574 if (flags & OPENLINE_DO_COM)
1575 lead_len = get_leader_len(ptr, NULL, FALSE, TRUE);
1576 else
1577 lead_len = 0;
1578 if (lead_len > 0)
1579 {
1580 // This case gets the following right:
1581 // /*
1582 // * A comment (read '\' as '/').
1583 // */
1584 // #define IN_THE_WAY
1585 // This should line up here;
1586 p = skipwhite(ptr);
1587 if (p[0] == '/' && p[1] == '*')
1588 p++;
1589 if (p[0] == '*')
1590 {
1591 for (p++; *p; p++)
1592 {
1593 if (p[0] == '/' && p[-1] == '*')
1594 {
1595 // End of C comment, indent should line up
1596 // with the line containing the start of
1597 // the comment
1598 curwin->w_cursor.col = (colnr_T)(p - ptr);
1599 if ((pos = findmatch(NULL, NUL)) != NULL)
1600 {
1601 curwin->w_cursor.lnum = pos->lnum;
1602 newindent = get_indent();
1603 }
1604 }
1605 }
1606 }
1607 }
1608 else // Not a comment line
1609# endif
1610 {
1611 // Find last non-blank in line
1612 p = ptr + STRLEN(ptr) - 1;
1613 while (p > ptr && VIM_ISWHITE(*p))
1614 --p;
1615 last_char = *p;
1616
1617 // find the character just before the '{' or ';'
1618 if (last_char == '{' || last_char == ';')
1619 {
1620 if (p > ptr)
1621 --p;
1622 while (p > ptr && VIM_ISWHITE(*p))
1623 --p;
1624 }
1625 // Try to catch lines that are split over multiple
1626 // lines. eg:
1627 // if (condition &&
1628 // condition) {
1629 // Should line up here!
1630 // }
1631 if (*p == ')')
1632 {
1633 curwin->w_cursor.col = (colnr_T)(p - ptr);
1634 if ((pos = findmatch(NULL, '(')) != NULL)
1635 {
1636 curwin->w_cursor.lnum = pos->lnum;
1637 newindent = get_indent();
1638 ptr = ml_get_curline();
1639 }
1640 }
1641 // If last character is '{' do indent, without
1642 // checking for "if" and the like.
1643 if (last_char == '{')
1644 {
1645 did_si = TRUE; // do indent
1646 no_si = TRUE; // don't delete it when '{' typed
1647 }
1648 // Look for "if" and the like, use 'cinwords'.
1649 // Don't do this if the previous line ended in ';' or
1650 // '}'.
1651 else if (last_char != ';' && last_char != '}'
1652 && cin_is_cinword(ptr))
1653 did_si = TRUE;
1654 }
1655 }
1656 else // dir == BACKWARD
1657 {
1658 // Skip preprocessor directives, unless they are
1659 // recognised as comments.
1660 if (
1661# ifdef FEAT_COMMENTS
1662 lead_len == 0 &&
1663# endif
1664 ptr[0] == '#')
1665 {
1666 int was_backslashed = FALSE;
1667
1668 while ((ptr[0] == '#' || was_backslashed) &&
1669 curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count)
1670 {
1671 if (*ptr && ptr[STRLEN(ptr) - 1] == '\\')
1672 was_backslashed = TRUE;
1673 else
1674 was_backslashed = FALSE;
1675 ptr = ml_get(++curwin->w_cursor.lnum);
1676 }
1677 if (was_backslashed)
1678 newindent = 0; // Got to end of file
1679 else
1680 newindent = get_indent();
1681 }
1682 p = skipwhite(ptr);
1683 if (*p == '}') // if line starts with '}': do indent
1684 did_si = TRUE;
1685 else // can delete indent when '{' typed
1686 can_si_back = TRUE;
1687 }
1688 curwin->w_cursor = old_cursor;
1689 }
1690 if (do_si)
1691 can_si = TRUE;
1692#endif // FEAT_SMARTINDENT
1693
1694 did_ai = TRUE;
1695 }
1696
1697#ifdef FEAT_COMMENTS
1698 // Find out if the current line starts with a comment leader.
1699 // This may then be inserted in front of the new line.
1700 end_comment_pending = NUL;
1701 if (flags & OPENLINE_DO_COM)
1702 lead_len = get_leader_len(saved_line, &lead_flags,
1703 dir == BACKWARD, TRUE);
1704 else
1705 lead_len = 0;
1706 if (lead_len > 0)
1707 {
1708 char_u *lead_repl = NULL; // replaces comment leader
1709 int lead_repl_len = 0; // length of *lead_repl
1710 char_u lead_middle[COM_MAX_LEN]; // middle-comment string
1711 char_u lead_end[COM_MAX_LEN]; // end-comment string
1712 char_u *comment_end = NULL; // where lead_end has been found
1713 int extra_space = FALSE; // append extra space
1714 int current_flag;
1715 int require_blank = FALSE; // requires blank after middle
1716 char_u *p2;
1717
1718 // If the comment leader has the start, middle or end flag, it may not
1719 // be used or may be replaced with the middle leader.
1720 for (p = lead_flags; *p && *p != ':'; ++p)
1721 {
1722 if (*p == COM_BLANK)
1723 {
1724 require_blank = TRUE;
1725 continue;
1726 }
1727 if (*p == COM_START || *p == COM_MIDDLE)
1728 {
1729 current_flag = *p;
1730 if (*p == COM_START)
1731 {
1732 // Doing "O" on a start of comment does not insert leader.
1733 if (dir == BACKWARD)
1734 {
1735 lead_len = 0;
1736 break;
1737 }
1738
1739 // find start of middle part
1740 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
1741 require_blank = FALSE;
1742 }
1743
1744 // Isolate the strings of the middle and end leader.
1745 while (*p && p[-1] != ':') /* find end of middle flags */
1746 {
1747 if (*p == COM_BLANK)
1748 require_blank = TRUE;
1749 ++p;
1750 }
1751 (void)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
1752
1753 while (*p && p[-1] != ':') // find end of end flags
1754 {
1755 // Check whether we allow automatic ending of comments
1756 if (*p == COM_AUTO_END)
1757 end_comment_pending = -1; // means we want to set it
1758 ++p;
1759 }
1760 n = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
1761
1762 if (end_comment_pending == -1) // we can set it now
1763 end_comment_pending = lead_end[n - 1];
1764
1765 // If the end of the comment is in the same line, don't use
1766 // the comment leader.
1767 if (dir == FORWARD)
1768 {
1769 for (p = saved_line + lead_len; *p; ++p)
1770 if (STRNCMP(p, lead_end, n) == 0)
1771 {
1772 comment_end = p;
1773 lead_len = 0;
1774 break;
1775 }
1776 }
1777
1778 // Doing "o" on a start of comment inserts the middle leader.
1779 if (lead_len > 0)
1780 {
1781 if (current_flag == COM_START)
1782 {
1783 lead_repl = lead_middle;
1784 lead_repl_len = (int)STRLEN(lead_middle);
1785 }
1786
1787 // If we have hit RETURN immediately after the start
1788 // comment leader, then put a space after the middle
1789 // comment leader on the next line.
1790 if (!VIM_ISWHITE(saved_line[lead_len - 1])
1791 && ((p_extra != NULL
1792 && (int)curwin->w_cursor.col == lead_len)
1793 || (p_extra == NULL
1794 && saved_line[lead_len] == NUL)
1795 || require_blank))
1796 extra_space = TRUE;
1797 }
1798 break;
1799 }
1800 if (*p == COM_END)
1801 {
1802 // Doing "o" on the end of a comment does not insert leader.
1803 // Remember where the end is, might want to use it to find the
1804 // start (for C-comments).
1805 if (dir == FORWARD)
1806 {
1807 comment_end = skipwhite(saved_line);
1808 lead_len = 0;
1809 break;
1810 }
1811
1812 // Doing "O" on the end of a comment inserts the middle leader.
1813 // Find the string for the middle leader, searching backwards.
1814 while (p > curbuf->b_p_com && *p != ',')
1815 --p;
1816 for (lead_repl = p; lead_repl > curbuf->b_p_com
1817 && lead_repl[-1] != ':'; --lead_repl)
1818 ;
1819 lead_repl_len = (int)(p - lead_repl);
1820
1821 // We can probably always add an extra space when doing "O" on
1822 // the comment-end
1823 extra_space = TRUE;
1824
1825 // Check whether we allow automatic ending of comments
1826 for (p2 = p; *p2 && *p2 != ':'; p2++)
1827 {
1828 if (*p2 == COM_AUTO_END)
1829 end_comment_pending = -1; // means we want to set it
1830 }
1831 if (end_comment_pending == -1)
1832 {
1833 // Find last character in end-comment string
1834 while (*p2 && *p2 != ',')
1835 p2++;
1836 end_comment_pending = p2[-1];
1837 }
1838 break;
1839 }
1840 if (*p == COM_FIRST)
1841 {
1842 // Comment leader for first line only: Don't repeat leader
1843 // when using "O", blank out leader when using "o".
1844 if (dir == BACKWARD)
1845 lead_len = 0;
1846 else
1847 {
1848 lead_repl = (char_u *)"";
1849 lead_repl_len = 0;
1850 }
1851 break;
1852 }
1853 }
1854 if (lead_len)
1855 {
1856 // allocate buffer (may concatenate p_extra later)
1857 leader = alloc(lead_len + lead_repl_len + extra_space + extra_len
1858 + (second_line_indent > 0 ? second_line_indent : 0) + 1);
1859 allocated = leader; // remember to free it later
1860
1861 if (leader == NULL)
1862 lead_len = 0;
1863 else
1864 {
1865 vim_strncpy(leader, saved_line, lead_len);
1866
1867 // Replace leader with lead_repl, right or left adjusted
1868 if (lead_repl != NULL)
1869 {
1870 int c = 0;
1871 int off = 0;
1872
1873 for (p = lead_flags; *p != NUL && *p != ':'; )
1874 {
1875 if (*p == COM_RIGHT || *p == COM_LEFT)
1876 c = *p++;
1877 else if (VIM_ISDIGIT(*p) || *p == '-')
1878 off = getdigits(&p);
1879 else
1880 ++p;
1881 }
1882 if (c == COM_RIGHT) // right adjusted leader
1883 {
1884 // find last non-white in the leader to line up with
1885 for (p = leader + lead_len - 1; p > leader
1886 && VIM_ISWHITE(*p); --p)
1887 ;
1888 ++p;
1889
1890 // Compute the length of the replaced characters in
1891 // screen characters, not bytes.
1892 {
1893 int repl_size = vim_strnsize(lead_repl,
1894 lead_repl_len);
1895 int old_size = 0;
1896 char_u *endp = p;
1897 int l;
1898
1899 while (old_size < repl_size && p > leader)
1900 {
1901 MB_PTR_BACK(leader, p);
1902 old_size += ptr2cells(p);
1903 }
1904 l = lead_repl_len - (int)(endp - p);
1905 if (l != 0)
1906 mch_memmove(endp + l, endp,
1907 (size_t)((leader + lead_len) - endp));
1908 lead_len += l;
1909 }
1910 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1911 if (p + lead_repl_len > leader + lead_len)
1912 p[lead_repl_len] = NUL;
1913
1914 // blank-out any other chars from the old leader.
1915 while (--p >= leader)
1916 {
1917 int l = mb_head_off(leader, p);
1918
1919 if (l > 1)
1920 {
1921 p -= l;
1922 if (ptr2cells(p) > 1)
1923 {
1924 p[1] = ' ';
1925 --l;
1926 }
1927 mch_memmove(p + 1, p + l + 1,
1928 (size_t)((leader + lead_len) - (p + l + 1)));
1929 lead_len -= l;
1930 *p = ' ';
1931 }
1932 else if (!VIM_ISWHITE(*p))
1933 *p = ' ';
1934 }
1935 }
1936 else // left adjusted leader
1937 {
1938 p = skipwhite(leader);
1939
1940 // Compute the length of the replaced characters in
1941 // screen characters, not bytes. Move the part that is
1942 // not to be overwritten.
1943 {
1944 int repl_size = vim_strnsize(lead_repl,
1945 lead_repl_len);
1946 int i;
1947 int l;
1948
1949 for (i = 0; i < lead_len && p[i] != NUL; i += l)
1950 {
1951 l = (*mb_ptr2len)(p + i);
1952 if (vim_strnsize(p, i + l) > repl_size)
1953 break;
1954 }
1955 if (i != lead_repl_len)
1956 {
1957 mch_memmove(p + lead_repl_len, p + i,
1958 (size_t)(lead_len - i - (p - leader)));
1959 lead_len += lead_repl_len - i;
1960 }
1961 }
1962 mch_memmove(p, lead_repl, (size_t)lead_repl_len);
1963
1964 // Replace any remaining non-white chars in the old
1965 // leader by spaces. Keep Tabs, the indent must
1966 // remain the same.
1967 for (p += lead_repl_len; p < leader + lead_len; ++p)
1968 if (!VIM_ISWHITE(*p))
1969 {
1970 // Don't put a space before a TAB.
1971 if (p + 1 < leader + lead_len && p[1] == TAB)
1972 {
1973 --lead_len;
1974 mch_memmove(p, p + 1,
1975 (leader + lead_len) - p);
1976 }
1977 else
1978 {
1979 int l = (*mb_ptr2len)(p);
1980
1981 if (l > 1)
1982 {
1983 if (ptr2cells(p) > 1)
1984 {
1985 // Replace a double-wide char with
1986 // two spaces
1987 --l;
1988 *p++ = ' ';
1989 }
1990 mch_memmove(p + 1, p + l,
1991 (leader + lead_len) - p);
1992 lead_len -= l - 1;
1993 }
1994 *p = ' ';
1995 }
1996 }
1997 *p = NUL;
1998 }
1999
2000 // Recompute the indent, it may have changed.
2001 if (curbuf->b_p_ai
2002#ifdef FEAT_SMARTINDENT
2003 || do_si
2004#endif
2005 )
2006#ifdef FEAT_VARTABS
2007 newindent = get_indent_str_vtab(leader, curbuf->b_p_ts,
2008 curbuf->b_p_vts_array, FALSE);
2009#else
2010 newindent = get_indent_str(leader,
2011 (int)curbuf->b_p_ts, FALSE);
2012#endif
2013
2014 // Add the indent offset
2015 if (newindent + off < 0)
2016 {
2017 off = -newindent;
2018 newindent = 0;
2019 }
2020 else
2021 newindent += off;
2022
2023 // Correct trailing spaces for the shift, so that
2024 // alignment remains equal.
2025 while (off > 0 && lead_len > 0
2026 && leader[lead_len - 1] == ' ')
2027 {
2028 // Don't do it when there is a tab before the space
2029 if (vim_strchr(skipwhite(leader), '\t') != NULL)
2030 break;
2031 --lead_len;
2032 --off;
2033 }
2034
2035 // If the leader ends in white space, don't add an
2036 // extra space
2037 if (lead_len > 0 && VIM_ISWHITE(leader[lead_len - 1]))
2038 extra_space = FALSE;
2039 leader[lead_len] = NUL;
2040 }
2041
2042 if (extra_space)
2043 {
2044 leader[lead_len++] = ' ';
2045 leader[lead_len] = NUL;
2046 }
2047
2048 newcol = lead_len;
2049
2050 // if a new indent will be set below, remove the indent that
2051 // is in the comment leader
2052 if (newindent
2053#ifdef FEAT_SMARTINDENT
2054 || did_si
2055#endif
2056 )
2057 {
2058 while (lead_len && VIM_ISWHITE(*leader))
2059 {
2060 --lead_len;
2061 --newcol;
2062 ++leader;
2063 }
2064 }
2065
2066 }
2067#ifdef FEAT_SMARTINDENT
2068 did_si = can_si = FALSE;
2069#endif
2070 }
2071 else if (comment_end != NULL)
2072 {
2073 // We have finished a comment, so we don't use the leader.
2074 // If this was a C-comment and 'ai' or 'si' is set do a normal
2075 // indent to align with the line containing the start of the
2076 // comment.
2077 if (comment_end[0] == '*' && comment_end[1] == '/' &&
2078 (curbuf->b_p_ai
2079#ifdef FEAT_SMARTINDENT
2080 || do_si
2081#endif
2082 ))
2083 {
2084 old_cursor = curwin->w_cursor;
2085 curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
2086 if ((pos = findmatch(NULL, NUL)) != NULL)
2087 {
2088 curwin->w_cursor.lnum = pos->lnum;
2089 newindent = get_indent();
2090 }
2091 curwin->w_cursor = old_cursor;
2092 }
2093 }
2094 }
2095#endif
2096
2097 // (State == INSERT || State == REPLACE), only when dir == FORWARD
2098 if (p_extra != NULL)
2099 {
2100 *p_extra = saved_char; // restore char that NUL replaced
2101
2102 // When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
2103 // non-blank.
2104 //
2105 // When in REPLACE mode, put the deleted blanks on the replace stack,
2106 // preceded by a NUL, so they can be put back when a BS is entered.
2107 if (REPLACE_NORMAL(State))
2108 replace_push(NUL); /* end of extra blanks */
2109 if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES))
2110 {
2111 while ((*p_extra == ' ' || *p_extra == '\t')
2112 && (!enc_utf8
2113 || !utf_iscomposing(utf_ptr2char(p_extra + 1))))
2114 {
2115 if (REPLACE_NORMAL(State))
2116 replace_push(*p_extra);
2117 ++p_extra;
2118 ++less_cols_off;
2119 }
2120 }
2121
2122 // columns for marks adjusted for removed columns
2123 less_cols = (int)(p_extra - saved_line);
2124 }
2125
2126 if (p_extra == NULL)
2127 p_extra = (char_u *)""; // append empty line
2128
2129#ifdef FEAT_COMMENTS
2130 // concatenate leader and p_extra, if there is a leader
2131 if (lead_len)
2132 {
2133 if (flags & OPENLINE_COM_LIST && second_line_indent > 0)
2134 {
2135 int i;
2136 int padding = second_line_indent
2137 - (newindent + (int)STRLEN(leader));
2138
2139 // Here whitespace is inserted after the comment char.
2140 // Below, set_indent(newindent, SIN_INSERT) will insert the
2141 // whitespace needed before the comment char.
2142 for (i = 0; i < padding; i++)
2143 {
2144 STRCAT(leader, " ");
2145 less_cols--;
2146 newcol++;
2147 }
2148 }
2149 STRCAT(leader, p_extra);
2150 p_extra = leader;
2151 did_ai = TRUE; // So truncating blanks works with comments
2152 less_cols -= lead_len;
2153 }
2154 else
2155 end_comment_pending = NUL; // turns out there was no leader
2156#endif
2157
2158 old_cursor = curwin->w_cursor;
2159 if (dir == BACKWARD)
2160 --curwin->w_cursor.lnum;
2161 if (!(State & VREPLACE_FLAG) || old_cursor.lnum >= orig_line_count)
2162 {
2163 if (ml_append(curwin->w_cursor.lnum, p_extra, (colnr_T)0, FALSE)
2164 == FAIL)
2165 goto theend;
2166 // Postpone calling changed_lines(), because it would mess up folding
2167 // with markers.
2168 // Skip mark_adjust when adding a line after the last one, there can't
2169 // be marks there. But still needed in diff mode.
2170 if (curwin->w_cursor.lnum + 1 < curbuf->b_ml.ml_line_count
2171#ifdef FEAT_DIFF
2172 || curwin->w_p_diff
2173#endif
2174 )
2175 mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1L, 0L);
2176 did_append = TRUE;
Bram Moolenaar45dd07f2019-05-15 22:45:37 +02002177#ifdef FEAT_TEXT_PROP
2178 if ((State & INSERT) && !(State & VREPLACE_FLAG))
2179 // properties after the split move to the next line
2180 adjust_props_for_split(curwin->w_cursor.lnum, curwin->w_cursor.lnum,
2181 curwin->w_cursor.col + 1, 0);
2182#endif
Bram Moolenaar3f86ca02019-05-11 18:30:00 +02002183 }
2184 else
2185 {
2186 // In VREPLACE mode we are starting to replace the next line.
2187 curwin->w_cursor.lnum++;
2188 if (curwin->w_cursor.lnum >= Insstart.lnum + vr_lines_changed)
2189 {
2190 // In case we NL to a new line, BS to the previous one, and NL
2191 // again, we don't want to save the new line for undo twice.
2192 (void)u_save_cursor(); /* errors are ignored! */
2193 vr_lines_changed++;
2194 }
2195 ml_replace(curwin->w_cursor.lnum, p_extra, TRUE);
2196 changed_bytes(curwin->w_cursor.lnum, 0);
2197 curwin->w_cursor.lnum--;
2198 did_append = FALSE;
2199 }
2200
2201 if (newindent
2202#ifdef FEAT_SMARTINDENT
2203 || did_si
2204#endif
2205 )
2206 {
2207 ++curwin->w_cursor.lnum;
2208#ifdef FEAT_SMARTINDENT
2209 if (did_si)
2210 {
2211 int sw = (int)get_sw_value(curbuf);
2212
2213 if (p_sr)
2214 newindent -= newindent % sw;
2215 newindent += sw;
2216 }
2217#endif
2218 // Copy the indent
2219 if (curbuf->b_p_ci)
2220 {
2221 (void)copy_indent(newindent, saved_line);
2222
2223 // Set the 'preserveindent' option so that any further screwing
2224 // with the line doesn't entirely destroy our efforts to preserve
2225 // it. It gets restored at the function end.
2226 curbuf->b_p_pi = TRUE;
2227 }
2228 else
2229 (void)set_indent(newindent, SIN_INSERT);
2230 less_cols -= curwin->w_cursor.col;
2231
2232 ai_col = curwin->w_cursor.col;
2233
2234 // In REPLACE mode, for each character in the new indent, there must
2235 // be a NUL on the replace stack, for when it is deleted with BS
2236 if (REPLACE_NORMAL(State))
2237 for (n = 0; n < (int)curwin->w_cursor.col; ++n)
2238 replace_push(NUL);
2239 newcol += curwin->w_cursor.col;
2240#ifdef FEAT_SMARTINDENT
2241 if (no_si)
2242 did_si = FALSE;
2243#endif
2244 }
2245
2246#ifdef FEAT_COMMENTS
2247 // In REPLACE mode, for each character in the extra leader, there must be
2248 // a NUL on the replace stack, for when it is deleted with BS.
2249 if (REPLACE_NORMAL(State))
2250 while (lead_len-- > 0)
2251 replace_push(NUL);
2252#endif
2253
2254 curwin->w_cursor = old_cursor;
2255
2256 if (dir == FORWARD)
2257 {
2258 if (trunc_line || (State & INSERT))
2259 {
2260 // truncate current line at cursor
2261 saved_line[curwin->w_cursor.col] = NUL;
2262 // Remove trailing white space, unless OPENLINE_KEEPTRAIL used.
2263 if (trunc_line && !(flags & OPENLINE_KEEPTRAIL))
2264 truncate_spaces(saved_line);
2265 ml_replace(curwin->w_cursor.lnum, saved_line, FALSE);
2266 saved_line = NULL;
2267 if (did_append)
2268 {
2269 changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col,
2270 curwin->w_cursor.lnum + 1, 1L);
2271 did_append = FALSE;
2272
2273 // Move marks after the line break to the new line.
2274 if (flags & OPENLINE_MARKFIX)
2275 mark_col_adjust(curwin->w_cursor.lnum,
2276 curwin->w_cursor.col + less_cols_off,
2277 1L, (long)-less_cols, 0);
2278 }
2279 else
2280 changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
2281 }
2282
2283 // Put the cursor on the new line. Careful: the scrollup() above may
2284 // have moved w_cursor, we must use old_cursor.
2285 curwin->w_cursor.lnum = old_cursor.lnum + 1;
2286 }
2287 if (did_append)
2288 changed_lines(curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1L);
2289
2290 curwin->w_cursor.col = newcol;
2291 curwin->w_cursor.coladd = 0;
2292
2293#if defined(FEAT_LISP) || defined(FEAT_CINDENT)
2294 // In VREPLACE mode, we are handling the replace stack ourselves, so stop
2295 // fixthisline() from doing it (via change_indent()) by telling it we're in
2296 // normal INSERT mode.
2297 if (State & VREPLACE_FLAG)
2298 {
2299 vreplace_mode = State; // So we know to put things right later
2300 State = INSERT;
2301 }
2302 else
2303 vreplace_mode = 0;
2304#endif
2305#ifdef FEAT_LISP
2306 // May do lisp indenting.
2307 if (!p_paste
2308# ifdef FEAT_COMMENTS
2309 && leader == NULL
2310# endif
2311 && curbuf->b_p_lisp
2312 && curbuf->b_p_ai)
2313 {
2314 fixthisline(get_lisp_indent);
2315 ai_col = (colnr_T)getwhitecols_curline();
2316 }
2317#endif
2318#ifdef FEAT_CINDENT
2319 // May do indenting after opening a new line.
2320 if (!p_paste
2321 && (curbuf->b_p_cin
2322# ifdef FEAT_EVAL
2323 || *curbuf->b_p_inde != NUL
2324# endif
2325 )
2326 && in_cinkeys(dir == FORWARD
2327 ? KEY_OPEN_FORW
2328 : KEY_OPEN_BACK, ' ', linewhite(curwin->w_cursor.lnum)))
2329 {
2330 do_c_expr_indent();
2331 ai_col = (colnr_T)getwhitecols_curline();
2332 }
2333#endif
2334#if defined(FEAT_LISP) || defined(FEAT_CINDENT)
2335 if (vreplace_mode != 0)
2336 State = vreplace_mode;
2337#endif
2338
2339 // Finally, VREPLACE gets the stuff on the new line, then puts back the
2340 // original line, and inserts the new stuff char by char, pushing old stuff
2341 // onto the replace stack (via ins_char()).
2342 if (State & VREPLACE_FLAG)
2343 {
2344 // Put new line in p_extra
2345 p_extra = vim_strsave(ml_get_curline());
2346 if (p_extra == NULL)
2347 goto theend;
2348
2349 // Put back original line
2350 ml_replace(curwin->w_cursor.lnum, next_line, FALSE);
2351
2352 // Insert new stuff into line again
2353 curwin->w_cursor.col = 0;
2354 curwin->w_cursor.coladd = 0;
2355 ins_bytes(p_extra); // will call changed_bytes()
2356 vim_free(p_extra);
2357 next_line = NULL;
2358 }
2359
2360 retval = OK; // success!
2361theend:
2362 curbuf->b_p_pi = saved_pi;
2363 vim_free(saved_line);
2364 vim_free(next_line);
2365 vim_free(allocated);
2366 return retval;
2367}
2368
2369/*
2370 * Delete from cursor to end of line.
2371 * Caller must have prepared for undo.
2372 * If "fixpos" is TRUE fix the cursor position when done.
2373 *
2374 * Return FAIL for failure, OK otherwise.
2375 */
2376 int
2377truncate_line(int fixpos)
2378{
2379 char_u *newp;
2380 linenr_T lnum = curwin->w_cursor.lnum;
2381 colnr_T col = curwin->w_cursor.col;
2382
2383 if (col == 0)
2384 newp = vim_strsave((char_u *)"");
2385 else
2386 newp = vim_strnsave(ml_get(lnum), col);
2387
2388 if (newp == NULL)
2389 return FAIL;
2390
2391 ml_replace(lnum, newp, FALSE);
2392
2393 // mark the buffer as changed and prepare for displaying
2394 changed_bytes(lnum, curwin->w_cursor.col);
2395
2396 // If "fixpos" is TRUE we don't want to end up positioned at the NUL.
2397 if (fixpos && curwin->w_cursor.col > 0)
2398 --curwin->w_cursor.col;
2399
2400 return OK;
2401}
2402
2403/*
2404 * Delete "nlines" lines at the cursor.
2405 * Saves the lines for undo first if "undo" is TRUE.
2406 */
2407 void
2408del_lines(long nlines, int undo)
2409{
2410 long n;
2411 linenr_T first = curwin->w_cursor.lnum;
2412
2413 if (nlines <= 0)
2414 return;
2415
2416 // save the deleted lines for undo
2417 if (undo && u_savedel(first, nlines) == FAIL)
2418 return;
2419
2420 for (n = 0; n < nlines; )
2421 {
2422 if (curbuf->b_ml.ml_flags & ML_EMPTY) // nothing to delete
2423 break;
2424
2425 ml_delete(first, TRUE);
2426 ++n;
2427
2428 // If we delete the last line in the file, stop
2429 if (first > curbuf->b_ml.ml_line_count)
2430 break;
2431 }
2432
2433 // Correct the cursor position before calling deleted_lines_mark(), it may
2434 // trigger a callback to display the cursor.
2435 curwin->w_cursor.col = 0;
2436 check_cursor_lnum();
2437
2438 // adjust marks, mark the buffer as changed and prepare for displaying
2439 deleted_lines_mark(first, n);
2440}