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