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