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