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