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