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