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