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