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