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