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