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