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