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