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