robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
74.8 KiB2208 linesraw
1/// change.c: functions related to changing text
2
3#include <assert.h>
4#include <stdbool.h>
5#include <stdint.h>
6#include <string.h>
7
8#include "nvim/ascii_defs.h"
9#include "nvim/assert_defs.h"
10#include "nvim/autocmd.h"
11#include "nvim/autocmd_defs.h"
12#include "nvim/buffer.h"
13#include "nvim/buffer_defs.h"
14#include "nvim/buffer_updates.h"
15#include "nvim/change.h"
16#include "nvim/charset.h"
17#include "nvim/cursor.h"
18#include "nvim/diff.h"
19#include "nvim/drawscreen.h"
20#include "nvim/eval/vars.h"
21#include "nvim/ex_cmds_defs.h"
22#include "nvim/extmark.h"
23#include "nvim/extmark_defs.h"
24#include "nvim/fold.h"
25#include "nvim/gettext_defs.h"
26#include "nvim/globals.h"
27#include "nvim/highlight_defs.h"
28#include "nvim/indent.h"
29#include "nvim/indent_c.h"
30#include "nvim/insert.h"
31#include "nvim/insexpand.h"
32#include "nvim/macros_defs.h"
33#include "nvim/mark.h"
34#include "nvim/mark_defs.h"
35#include "nvim/marktree_defs.h"
36#include "nvim/mbyte.h"
37#include "nvim/mbyte_defs.h"
38#include "nvim/mcursor.h"
39#include "nvim/memline.h"
40#include "nvim/memline_defs.h"
41#include "nvim/memory.h"
42#include "nvim/message.h"
43#include "nvim/move.h"
44#include "nvim/option.h"
45#include "nvim/option_vars.h"
46#include "nvim/os/time.h"
47#include "nvim/plines.h"
48#include "nvim/pos_defs.h"
49#include "nvim/search.h"
50#include "nvim/spell.h"
51#include "nvim/state.h"
52#include "nvim/state_defs.h"
53#include "nvim/strings.h"
54#include "nvim/textformat.h"
55#include "nvim/types_defs.h"
56#include "nvim/ui.h"
57#include "nvim/undo.h"
58#include "nvim/vim_defs.h"
59
60#include "change.c.generated.h"
61
62/// If the file is readonly, give a warning message with the first change.
63/// Don't do this for autocommands.
64/// Doesn't use emsg(), because it flushes the macro buffer.
65/// If we have undone all changes b_changed will be false, but "b_did_warn"
66/// will be true.
67/// "col" is the column for the message; non-zero when in insert mode and
68/// 'showmode' is on.
69/// Careful: may trigger autocommands that reload the buffer.
70void change_warning(buf_T *buf, int col)
71{
72  static const char *w_readonly = N_("W10: Warning: Changing a readonly file");
73
74  if (buf->b_did_warn == false
75      && curbufIsChanged() == 0
76      && !autocmd_busy
77      && buf->b_p_ro) {
78    buf->b_ro_locked++;
79    apply_autocmds(EVENT_FILECHANGEDRO, NULL, NULL, false, buf);
80    buf->b_ro_locked--;
81    if (!buf->b_p_ro) {
82      return;
83    }
84    // Do what msg() does, but with a column offset if the warning should
85    // be after the mode message.
86    msg_start();
87    if (msg_row == Rows - 1) {
88      msg_col = col;
89    }
90    msg_source(HLF_W);
91    msg_ext_set_kind("wmsg");
92    msg_puts_hl(_(w_readonly), HLF_W, true);
93    set_vim_var_string(VV_WARNINGMSG, _(w_readonly), -1);
94    msg_clr_eos();
95    msg_end();
96    if (msg_silent == 0 && !silent_mode && ui_active()) {
97      msg_delay(1002, true);  // give the user time to think about it
98    }
99    buf->b_did_warn = true;
100    redraw_cmdline = false;  // don't redraw and erase the message
101    if (msg_row < Rows - 1) {
102      showmode();
103    }
104  }
105}
106
107/// Call this function when something in a buffer is changed.
108///
109/// Most often called through changed_bytes() and changed_lines(), which also
110/// mark the area of the display to be redrawn.
111///
112/// Careful: may trigger autocommands that reload the buffer.
113void changed(buf_T *buf)
114{
115  if (!buf->b_changed) {
116    int save_msg_scroll = msg_scroll;
117
118    // Give a warning about changing a read-only file.  This may also
119    // check-out the file, thus change "curbuf"!
120    change_warning(buf, 0);
121
122    // Create a swap file if that is wanted.
123    // Don't do this for "nofile" and "nowrite" buffer types.
124    if (buf->b_may_swap && !bt_dontwrite(buf)) {
125      bool save_need_wait_return = need_wait_return;
126
127      need_wait_return = false;
128      ml_open_file(buf);
129
130      // The ml_open_file() can cause an ATTENTION message.
131      // Wait two seconds, to make sure the user reads this unexpected
132      // message.  Since we could be anywhere, call wait_return() now,
133      // and don't let the emsg() set msg_scroll.
134      if (need_wait_return && emsg_silent == 0 && !in_assert_fails && !ui_has(kUIMessages)) {
135        msg_delay(2002, true);
136        wait_return(true);
137        msg_scroll = save_msg_scroll;
138      } else {
139        need_wait_return = save_need_wait_return;
140      }
141    }
142    changed_internal(buf);
143  }
144  buf_inc_changedtick(buf);
145
146  // A match highlight can only be invalidated by changes to the current buffer.
147  if (buf == curbuf) {
148    Search.hl_match = false;
149  }
150}
151
152/// Internal part of changed(), no user interaction.
153/// Also used for recovery.
154void changed_internal(buf_T *buf)
155{
156  bool was_changed = buf->b_changed;
157  buf->b_changed = true;
158  ml_setflags(buf);
159  redraw_buf_status_later(buf);
160  redraw_tabline = true;
161  need_maketitle = true;  // set window title later
162  if (!was_changed) {
163    aucmd_defer_modified(buf, true);
164  }
165}
166
167/// Invalidate a window's w_valid flags and w_lines[] entries after changing lines.
168static void changed_lines_invalidate_win(win_T *wp, linenr_T lnum, colnr_T col, linenr_T lnume,
169                                         linenr_T xtra)
170{
171  // If the changed line is in a range of previously folded lines,
172  // compare with the first line in that range.
173  if (wp->w_cursor.lnum <= lnum) {
174    int i = find_wl_entry(wp, lnum);
175    if (i >= 0 && wp->w_cursor.lnum > wp->w_lines[i].wl_lnum) {
176      changed_line_abv_curs_win(wp);
177    }
178  }
179
180  if (wp->w_cursor.lnum > lnum) {
181    changed_line_abv_curs_win(wp);
182  } else if (wp->w_cursor.lnum == lnum && wp->w_cursor.col >= col) {
183    changed_cline_bef_curs(wp);
184  }
185  if (wp->w_botline >= lnum) {
186    if (xtra < 0) {
187      invalidate_botline_win(wp);
188    } else {
189      // Assume that botline doesn't change (inserted lines make
190      // other lines scroll down below botline).
191      approximate_botline_win(wp);
192    }
193  }
194
195  // If lines have been inserted/deleted and the buffer has virt_lines, or
196  // inline virt_text with 'wrap' enabled, invalidate the line after the changed
197  // lines. virt_lines may now be drawn above that line, and inline virt_text
198  // may cause that line to wrap.
199  if ((xtra < 0 && wp->w_p_wrap && buf_meta_total(wp->w_buffer, kMTMetaInline))
200      || (xtra != 0 && buf_meta_total(wp->w_buffer, kMTMetaLines))) {
201    lnume++;
202  }
203  // Check if any w_lines[] entries have become invalid.
204  // For entries below the change: Correct the lnums for inserted/deleted lines.
205  // Makes it possible to stop displaying after the change.
206  for (int i = 0; i < wp->w_lines_valid; i++) {
207    if (wp->w_lines[i].wl_valid) {
208      if (wp->w_lines[i].wl_lnum >= lnum) {
209        // Do not change wl_lnum at index zero, it is used to compare with w_topline.
210        // Invalidate it instead.
211        if (i == 0 || wp->w_lines[i].wl_lnum < lnume) {
212          // line included in change
213          wp->w_lines[i].wl_valid = false;
214        } else if (xtra != 0) {
215          // line below change
216          wp->w_lines[i].wl_lnum += xtra;
217          wp->w_lines[i].wl_foldend += xtra;
218          wp->w_lines[i].wl_lastlnum += xtra;
219        }
220      } else if (wp->w_lines[i].wl_lastlnum >= lnum) {
221        // change somewhere inside this range of folded or concealed lines,
222        // may need to be redrawn
223        wp->w_lines[i].wl_valid = false;
224      }
225    }
226  }
227}
228
229/// Line changed_lines_invalidate_win(), but for all windows displaying a buffer.
230void changed_lines_invalidate_buf(buf_T *buf, linenr_T lnum, colnr_T col, linenr_T lnume,
231                                  linenr_T xtra)
232{
233  FOR_ALL_TAB_WINDOWS(tp, wp) {
234    if (wp->w_buffer == buf) {
235      changed_lines_invalidate_win(wp, lnum, col, lnume, xtra);
236    }
237  }
238}
239
240/// Common code for when a change was made.
241/// See changed_lines() for the arguments.
242/// Careful: may trigger autocommands that reload the buffer.
243static void changed_common(buf_T *buf, linenr_T lnum, colnr_T col, linenr_T lnume, linenr_T xtra)
244{
245  // mark the buffer as modified
246  changed(buf);
247
248  FOR_ALL_WINDOWS_IN_TAB(win, curtab) {
249    if (win->w_buffer == buf) {
250      if (win->w_p_diff && diff_internal()) {
251        curtab->tp_diff_update = true;
252        diff_update_line(lnum);
253      }
254
255      // Redraw status when line count changes to prevent 'statusline' or
256      // 'rulerformat' items becoming invalid.
257      if (xtra != 0) {
258        win->w_redr_status = true;
259      }
260    }
261  }
262
263  // Set the '. mark.
264  if ((cmdmod.cmod_flags & CMOD_KEEPJUMPS) == 0) {
265    fmarkv_T view = INIT_FMARKV;
266    // Set the markview only if lnum is visible, as changes might be done
267    // outside of the current window view.
268
269    if (curwin->w_buffer == buf) {
270      if (lnum >= curwin->w_topline && lnum <= curwin->w_botline) {
271        view = mark_view_make(curwin, curwin->w_cursor);
272      }
273    }
274    RESET_FMARK(&buf->b_last_change, ((pos_T) { lnum, col, 0 }), buf->handle, view);
275  }
276
277  // Update the changelist (g;). Its last entry follows the '. mark.
278  if ((cmdmod.cmod_flags & CMOD_KEEPJUMPS) == 0 && !mc_replaying()) {
279    // Create a new entry if a new undo-able change was started or we
280    // don't have an entry yet.
281    if (buf->b_new_change || buf->b_changelistlen == 0) {
282      bool add;
283      if (buf->b_changelistlen == 0) {
284        add = true;
285      } else {
286        // Don't create a new entry when the line number is the same
287        // as the last one and the column is not too far away.  Avoids
288        // creating many entries for typing "xxxxx".
289        pos_T *p = &buf->b_changelist[buf->b_changelistlen - 1].mark;
290        if (p->lnum != lnum) {
291          add = true;
292        } else {
293          int cols = comp_textwidth(false);
294          if (cols == 0) {
295            cols = 79;
296          }
297          add = (p->col + cols < col || col + cols < p->col);
298        }
299      }
300      if (add) {
301        // This is the first of a new sequence of undo-able changes
302        // and it's at some distance of the last change.  Use a new
303        // position in the changelist.
304        buf->b_new_change = false;
305
306        if (buf->b_changelistlen == JUMPLISTSIZE) {
307          // changelist is full: remove oldest entry
308          buf->b_changelistlen = JUMPLISTSIZE - 1;
309          memmove(buf->b_changelist, buf->b_changelist + 1,
310                  sizeof(buf->b_changelist[0]) * (JUMPLISTSIZE - 1));
311          FOR_ALL_TAB_WINDOWS(tp, wp) {
312            // Correct position in changelist for other windows on
313            // this buffer.
314            if (wp->w_buffer == buf && wp->w_changelistidx > 0) {
315              wp->w_changelistidx--;
316            }
317          }
318        }
319        FOR_ALL_TAB_WINDOWS(tp, wp) {
320          // For other windows, if the position in the changelist is
321          // at the end it stays at the end.
322          if (wp->w_buffer == buf
323              && wp->w_changelistidx == buf->b_changelistlen) {
324            wp->w_changelistidx++;
325          }
326        }
327        buf->b_changelistlen++;
328      }
329    }
330    buf->b_changelist[buf->b_changelistlen - 1] =
331      buf->b_last_change;
332    // The current window is always after the last change, so that "g,"
333    // takes you back to it.
334    if (curwin->w_buffer == buf) {
335      curwin->w_changelistidx = buf->b_changelistlen;
336    }
337  }
338
339  if (curwin->w_buffer == buf && Visual.active) {
340    check_visual_pos();
341  }
342
343  FOR_ALL_TAB_WINDOWS(tp, wp) {
344    if (wp->w_buffer == buf) {
345      // Mark this window to be redrawn later.
346      if (!redraw_not_allowed && wp->w_redr_type < UPD_VALID) {
347        wp->w_redr_type = UPD_VALID;
348      }
349
350      // When inserting/deleting lines and the window has specific lines
351      // to be redrawn, w_redraw_top and w_redraw_bot may now be invalid,
352      // so just redraw everything.
353      if (xtra != 0 && wp->w_redraw_top != 0) {
354        redraw_later(wp, UPD_NOT_VALID);
355      }
356
357      linenr_T last = lnume + xtra - 1;  // last line after the change
358
359      // Reset "w_skipcol" if the topline length has become smaller to
360      // such a degree that nothing will be visible anymore, accounting
361      // for 'smoothscroll' <<< or 'listchars' "precedes" marker.
362      if (wp->w_skipcol > 0
363          && (last < wp->w_topline
364              || (wp->w_topline >= lnum
365                  && wp->w_topline < lnume
366                  && (linetabsize_eol(wp, wp->w_topline)
367                      <= wp->w_skipcol + sms_marker_overlap(wp, -1))))) {
368        wp->w_skipcol = 0;
369      }
370
371      // Check if a change in the buffer has invalidated the cached
372      // values for the cursor.
373      // Update the folds for this window.  Can't postpone this, because
374      // a following operator might work on the whole fold: ">>dd".
375      foldUpdate(wp, lnum, last);
376
377      // The change may cause lines above or below the change to become
378      // included in a fold.  Set lnum/lnume to the first/last line that
379      // might be displayed differently.
380      // Set w_cline_folded here as an efficient way to update it when
381      // inserting lines just above a closed fold.
382      bool folded = hasFoldingWin(wp, lnum, &lnum, NULL, false, NULL);
383      if (wp->w_cursor.lnum == lnum) {
384        wp->w_cline_folded = folded;
385      }
386      folded = hasFoldingWin(wp, last, NULL, &last, false, NULL);
387      if (wp->w_cursor.lnum == last) {
388        wp->w_cline_folded = folded;
389      }
390
391      changed_lines_invalidate_win(wp, lnum, col, lnume, xtra);
392
393      // Take care of side effects for setting w_topline when folds have
394      // changed.  Esp. when the buffer was changed in another window.
395      if (hasAnyFolding(wp)) {
396        set_topline(wp, wp->w_topline);
397      }
398
399      // If lines have been added or removed, relative numbering always
400      // requires an update even if cursor didn't move.
401      if (wp->w_p_rnu && xtra != 0) {
402        wp->w_last_cursor_lnum_rnu = 0;
403      }
404
405      if (wp->w_p_cul && wp->w_last_cursorline >= lnum) {
406        if (wp->w_last_cursorline < lnume) {
407          // If 'cursorline' was inside the change, it has already
408          // been invalidated in w_lines[] by the loop above.
409          wp->w_last_cursorline = 0;
410        } else {
411          // If 'cursorline' was below the change, adjust its lnum.
412          wp->w_last_cursorline += xtra;
413        }
414      }
415    }
416
417    if (wp == curwin && xtra != 0 && search_hl_has_cursor_lnum >= lnum) {
418      search_hl_has_cursor_lnum += xtra;
419    }
420  }
421
422  // Call update_screen() later, which checks out what needs to be redrawn,
423  // since it notices b_mod_set and then uses b_mod_*.
424  set_must_redraw(UPD_VALID);
425
426  // when the cursor line is changed always trigger CursorMoved
427  if (last_cursormoved_win == curwin && curwin->w_buffer == buf
428      && lnum <= curwin->w_cursor.lnum
429      && lnume + (xtra < 0 ? -xtra : xtra) > curwin->w_cursor.lnum) {
430    last_cursormoved.lnum = 0;
431  }
432}
433
434/// Changed bytes within a single line for the current buffer.
435/// - marks the windows on this buffer to be redisplayed
436/// - marks the buffer changed by calling changed()
437/// - invalidates cached values
438/// Careful: may trigger autocommands that reload the buffer.
439void changed_bytes(linenr_T lnum, colnr_T col)
440{
441  changed_lines_redraw_buf(curbuf, lnum, lnum + 1, 0);
442  changed_common(curbuf, lnum, col, lnum + 1, 0);
443  // When text has been changed at the end of the line, possibly the start of
444  // the next line may have SpellCap that should be removed or it needs to be
445  // displayed.  Schedule the next line for redrawing just in case.
446  // Don't do this when displaying '$' at the end of changed text.
447  if (spell_check_window(curwin)
448      && lnum < curbuf->b_ml.ml_line_count
449      && vim_strchr(p_cpo, kCpoDollar) == NULL) {
450    redrawWinline(curwin, lnum + 1);
451  }
452  // notify any channels that are watching
453  buf_updates_send_changes(curbuf, lnum, 1, 1);
454
455  // Diff highlighting in other diff windows may need to be updated too.
456  if (curwin->w_p_diff) {
457    FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
458      if (wp->w_p_diff && wp != curwin) {
459        redraw_later(wp, UPD_VALID);
460        linenr_T wlnum = diff_lnum_win(lnum, wp);
461        if (wlnum > 0) {
462          changed_lines_redraw_buf(wp->w_buffer, wlnum, wlnum + 1, 0);
463        }
464      }
465    }
466  }
467}
468
469/// insert/delete bytes at column
470///
471/// Like changed_bytes() but also adjust extmark for "new" bytes.
472void inserted_bytes(linenr_T lnum, colnr_T start_col, int old_col, int new_col)
473{
474  if (curbuf_splice_pending == 0) {
475    extmark_splice_cols(curbuf, (int)lnum - 1, start_col, old_col, new_col, kExtmarkUndo);
476  }
477
478  changed_bytes(lnum, start_col);
479}
480
481/// Appended "count" lines below line "lnum" in the given buffer.
482/// Must be called AFTER the change and after mark_adjust().
483/// Takes care of marking the buffer to be redrawn and sets the changed flag.
484void appended_lines_buf(buf_T *buf, linenr_T lnum, linenr_T count)
485{
486  changed_lines(buf, lnum + 1, 0, lnum + 1, count, true);
487}
488
489/// Appended "count" lines below line "lnum" in the current buffer.
490/// Must be called AFTER the change and after mark_adjust().
491/// Takes care of marking the buffer to be redrawn and sets the changed flag.
492void appended_lines(linenr_T lnum, linenr_T count)
493{
494  appended_lines_buf(curbuf, lnum, count);
495}
496
497/// Like appended_lines(), but adjust marks first.
498void appended_lines_mark(linenr_T lnum, int count)
499{
500  mark_adjust(lnum + 1, (linenr_T)MAXLNUM, (linenr_T)count, 0, kExtmarkUndo);
501  changed_lines(curbuf, lnum + 1, 0, lnum + 1, (linenr_T)count, true);
502}
503
504/// Deleted "count" lines at line "lnum" in the given buffer.
505/// Must be called AFTER the change and after mark_adjust().
506/// Takes care of marking the buffer to be redrawn and sets the changed flag.
507void deleted_lines_buf(buf_T *buf, linenr_T lnum, linenr_T count)
508{
509  changed_lines(buf, lnum, 0, lnum + count, -count, true);
510}
511
512/// Deleted "count" lines at line "lnum" in the current buffer.
513/// Must be called AFTER the change and after mark_adjust().
514/// Takes care of marking the buffer to be redrawn and sets the changed flag.
515void deleted_lines(linenr_T lnum, linenr_T count)
516{
517  deleted_lines_buf(curbuf, lnum, count);
518}
519
520/// Like deleted_lines(), but adjust marks first.
521/// Make sure the cursor is on a valid line before calling, a GUI callback may
522/// be triggered to display the cursor.
523void deleted_lines_mark(linenr_T lnum, int count)
524{
525  bool made_empty = (count > 0) && curbuf->b_ml.ml_flags & ML_EMPTY;
526
527  mark_adjust(lnum, (linenr_T)(lnum + count - 1), MAXLNUM, -(linenr_T)count, kExtmarkNOOP);
528  // if we deleted the entire buffer, we need to implicitly add a new empty line
529  extmark_adjust(curbuf, lnum, (linenr_T)(lnum + count - 1), MAXLNUM,
530                 -(linenr_T)count + (made_empty ? 1 : 0), kExtmarkUndo);
531  changed_lines(curbuf, lnum, 0, lnum + (linenr_T)count, (linenr_T)(-count), true);
532}
533
534/// Marks the area to be redrawn after a change.
535/// Consider also calling changed_lines_invalidate_buf().
536///
537/// @param buf the buffer where lines were changed
538/// @param lnum first line with change
539/// @param lnume line below last changed line
540/// @param xtra number of extra lines (negative when deleting)
541void changed_lines_redraw_buf(buf_T *buf, linenr_T lnum, linenr_T lnume, linenr_T xtra)
542{
543  // If lines have been deleted and there may be decorations in the buffer, ensure
544  // win_update() calculates the height of, and redraws the line to which or whence
545  // from its mark may have moved. When lines are deleted, a virt_line mark may
546  // have moved be drawn two lines below so increase by one more.
547  if (xtra != 0 && buf->b_marktree->n_keys > 0) {
548    lnume += 1 + (xtra < 0 && buf_meta_total(buf, kMTMetaLines));
549  }
550
551  if (buf->b_mod_set) {
552    // find the maximum area that must be redisplayed
553    buf->b_mod_top = MIN(buf->b_mod_top, lnum);
554    if (lnum < buf->b_mod_bot) {
555      // adjust old bot position for xtra lines
556      buf->b_mod_bot += xtra;
557      buf->b_mod_bot = MAX(buf->b_mod_bot, lnum);
558    }
559    buf->b_mod_bot = MAX(buf->b_mod_bot, lnume + xtra);
560    buf->b_mod_xlines += xtra;
561  } else {
562    // set the area that must be redisplayed
563    buf->b_mod_set = true;
564    buf->b_mod_top = lnum;
565    buf->b_mod_bot = lnume + xtra;
566    buf->b_mod_xlines = xtra;
567  }
568}
569
570/// Changed lines for a buffer.
571/// Must be called AFTER the change and after mark_adjust().
572/// - mark the buffer changed by calling changed()
573/// - mark the windows on this buffer to be redisplayed
574/// - invalidate cached values
575/// "lnum" is the first line that needs displaying, "lnume" the first line
576/// below the changed lines (BEFORE the change).
577/// When only inserting lines, "lnum" and "lnume" are equal.
578/// Takes care of calling changed() and updating b_mod_*.
579/// Careful: may trigger autocommands that reload the buffer.
580///
581/// @param lnum  first line with change
582/// @param col  column in first line with change
583/// @param lnume  line below last changed line
584/// @param xtra  number of extra lines (negative when deleting)
585/// @param do_buf_event  some callers like undo/redo call changed_lines() and
586/// then increment changedtick *again*. This flag allows these callers to send
587/// the nvim_buf_lines_event events after they're done modifying changedtick.
588void changed_lines(buf_T *buf, linenr_T lnum, colnr_T col, linenr_T lnume, linenr_T xtra,
589                   bool do_buf_event)
590{
591  changed_lines_redraw_buf(buf, lnum, lnume, xtra);
592
593  if (xtra == 0 && curwin->w_p_diff && curwin->w_buffer == buf && !diff_internal()) {
594    // When the number of lines doesn't change then mark_adjust() isn't
595    // called and other diff buffers still need to be marked for
596    // displaying.
597    linenr_T wlnum;
598
599    FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
600      if (wp->w_p_diff && wp != curwin) {
601        redraw_later(wp, UPD_VALID);
602        wlnum = diff_lnum_win(lnum, wp);
603        if (wlnum > 0) {
604          changed_lines_redraw_buf(wp->w_buffer, wlnum, lnume - lnum + wlnum, 0);
605        }
606      }
607    }
608  }
609
610  changed_common(buf, lnum, col, lnume, xtra);
611
612  if (do_buf_event) {
613    int64_t num_added = (int64_t)(lnume + xtra - lnum);
614    int64_t num_removed = lnume - lnum;
615    buf_updates_send_changes(buf, lnum, num_added, num_removed);
616  }
617}
618
619/// Called when the changed flag must be reset for buffer `buf`.
620/// When `ff` is true also reset 'fileformat'.
621/// When `always_inc_changedtick` is true b:changedtick is incremented even
622/// when the changed flag was off.
623void unchanged(buf_T *buf, bool ff, bool always_inc_changedtick)
624{
625  if (buf->b_changed || (ff && file_ff_differs(buf, false))) {
626    bool was_changed = buf->b_changed;
627    buf->b_changed = false;
628    ml_setflags(buf);
629    if (ff) {
630      save_file_ff(buf);
631    }
632    redraw_buf_status_later(buf);
633    redraw_tabline = true;
634    need_maketitle = true;  // set window title later
635    buf_inc_changedtick(buf);
636    if (was_changed) {
637      aucmd_defer_modified(buf, false);
638    }
639  } else if (always_inc_changedtick) {
640    buf_inc_changedtick(buf);
641  }
642}
643
644/// Save the current values of 'fileformat' and 'fileencoding', so that we know
645/// the file must be considered changed when the value is different.
646void save_file_ff(buf_T *buf)
647{
648  buf->b_start_ffc = (unsigned char)(*buf->b_p_ff);
649  buf->b_start_eof = buf->b_p_eof;
650  buf->b_start_eol = buf->b_p_eol;
651  buf->b_start_bomb = buf->b_p_bomb;
652
653  // Only use free/alloc when necessary, they take time.
654  if (buf->b_start_fenc == NULL
655      || strcmp(buf->b_start_fenc, buf->b_p_fenc) != 0) {
656    xfree(buf->b_start_fenc);
657    buf->b_start_fenc = xstrdup(buf->b_p_fenc);
658  }
659}
660
661/// Return true if 'fileformat' and/or 'fileencoding' has a different value
662/// from when editing started (save_file_ff() called).
663/// Also when 'endofline' was changed and 'binary' is set, or when 'bomb' was
664/// changed and 'binary' is not set.
665/// Also when 'endofline' was changed and 'fixeol' is not set.
666/// When "ignore_empty" is true don't consider a new, empty buffer to be
667/// changed.
668bool file_ff_differs(buf_T *buf, bool ignore_empty)
669  FUNC_ATTR_NONNULL_ALL FUNC_ATTR_WARN_UNUSED_RESULT
670{
671  // In a buffer that was never loaded the options are not valid.
672  if (buf->b_flags & BF_NEVERLOADED) {
673    return false;
674  }
675  if (ignore_empty
676      && (buf->b_flags & BF_NEW)
677      && buf->b_ml.ml_line_count == 1
678      && *ml_get_buf(buf, 1) == NUL) {
679    return false;
680  }
681  if (buf->b_start_ffc != *buf->b_p_ff) {
682    return true;
683  }
684  if ((buf->b_p_bin || !buf->b_p_fixeol)
685      && (buf->b_start_eof != buf->b_p_eof || buf->b_start_eol != buf->b_p_eol)) {
686    return true;
687  }
688  if (!buf->b_p_bin && buf->b_start_bomb != buf->b_p_bomb) {
689    return true;
690  }
691  if (buf->b_start_fenc == NULL) {
692    return *buf->b_p_fenc != NUL;
693  }
694  return strcmp(buf->b_start_fenc, buf->b_p_fenc) != 0;
695}
696
697/// Insert string "p" at the cursor position.  Stops at a NUL byte.
698/// Handles Replace mode and multi-byte characters.
699void ins_bytes(char *p)
700{
701  ins_bytes_len(p, strlen(p));
702}
703
704/// Insert string "p" with length "len" at the cursor position.
705/// Handles Replace mode and multi-byte characters.
706void ins_bytes_len(char *p, size_t len)
707{
708  size_t n;
709  for (size_t i = 0; i < len; i += n) {
710    // avoid reading past p[len]
711    n = (size_t)utfc_ptr2len_len(p + i, (int)(len - i));
712    ins_char_bytes(p + i, n);
713  }
714}
715
716/// Insert or replace a single character at the cursor position.
717/// When in MODE_REPLACE or MODE_VREPLACE state, replace any existing character.
718/// Caller must have prepared for undo.
719/// For multi-byte characters we get the whole character, the caller must
720/// convert bytes to a character.
721void ins_char(int c)
722{
723  char buf[MB_MAXCHAR + 1];
724  size_t n = (size_t)utf_char2bytes(c, buf);
725
726  // When "c" is 0x100, 0x200, etc. we don't want to insert a NUL byte.
727  // Happens for CTRL-Vu9900.
728  if (buf[0] == 0) {
729    buf[0] = '\n';
730  }
731  ins_char_bytes(buf, n);
732}
733
734void ins_char_bytes(char *buf, size_t charlen)
735{
736  // Break tabs if needed.
737  if (virtual_active(curwin) && curwin->w_cursor.coladd > 0) {
738    coladvance_force(getviscol());
739  }
740
741  size_t col = (size_t)curwin->w_cursor.col;
742  linenr_T lnum = curwin->w_cursor.lnum;
743  char *oldp = ml_get(lnum);
744  size_t linelen = (size_t)ml_get_len(lnum) + 1;  // length of old line including NUL
745
746  // The lengths default to the values for when not replacing.
747  size_t oldlen = 0;        // nr of bytes inserted
748  size_t newlen = charlen;  // nr of bytes deleted (0 when not replacing)
749
750  if (State & REPLACE_FLAG) {
751    if (State & VREPLACE_FLAG) {
752      // Disable 'list' temporarily, unless 'cpo' contains the 'L' flag.
753      // Returns the old value of list, so when finished,
754      // curwin->w_p_list should be set back to this.
755      int old_list = curwin->w_p_list;
756      if (old_list && vim_strchr(p_cpo, kCpoListwm) == NULL) {
757        curwin->w_p_list = false;
758      }
759      // In virtual replace mode each character may replace one or more
760      // characters (zero if it's a TAB).  Count the number of bytes to
761      // be deleted to make room for the new character, counting screen
762      // cells.  May result in adding spaces to fill a gap.
763      colnr_T vcol;
764      getvcol(curwin, &curwin->w_cursor, NULL, &vcol, NULL, 0);
765      colnr_T new_vcol = vcol + win_chartabsize(curwin, buf, vcol);
766      while (oldp[col + oldlen] != NUL && vcol < new_vcol) {
767        vcol += win_chartabsize(curwin, oldp + col + oldlen, vcol);
768        // Don't need to remove a TAB that takes us to the right
769        // position.
770        if (vcol > new_vcol && oldp[col + oldlen] == TAB) {
771          break;
772        }
773        oldlen += (size_t)utfc_ptr2len(oldp + col + oldlen);
774        // Deleted a bit too much, insert spaces.
775        if (vcol > new_vcol) {
776          newlen += (size_t)(vcol - new_vcol);
777        }
778      }
779      curwin->w_p_list = old_list;
780    } else if (oldp[col] != NUL) {
781      // normal replace
782      oldlen = (size_t)utfc_ptr2len(oldp + col);
783    }
784
785    // Push the replaced bytes onto the replace stack, so that they can be
786    // put back when BS is used.  The bytes of a multi-byte character are
787    // done the other way around, so that the first byte is popped off
788    // first (it tells the byte length of the character).
789    replace_push_nul();
790    replace_push(oldp + col, oldlen);
791  }
792
793  char *newp = xmalloc(linelen + newlen - oldlen);
794
795  // Copy bytes before the cursor.
796  if (col > 0) {
797    memmove(newp, oldp, col);
798  }
799
800  // Copy bytes after the changed character(s).
801  char *p = newp + col;
802  if (linelen > col + oldlen) {
803    memmove(p + newlen, oldp + col + oldlen, linelen - col - oldlen);
804  }
805
806  // Insert or overwrite the new character.
807  memmove(p, buf, charlen);
808
809  // Fill with spaces when necessary.
810  for (size_t i = charlen; i < newlen; i++) {
811    p[i] = ' ';
812  }
813
814  // Replace the line in the buffer.
815  ml_replace(lnum, newp, false);
816
817  // mark the buffer as changed and prepare for displaying
818  inserted_bytes(lnum, (colnr_T)col, (int)oldlen, (int)newlen);
819
820  // If we're in Insert or Replace mode and 'showmatch' is set, then briefly
821  // show the match for right parens and braces.
822  if (p_sm && (State & MODE_INSERT)
823      && msg_silent == 0
824      && !ins_compl_active()) {
825    showmatch(utf_ptr2char(buf));
826  }
827
828  if (!p_ri || (State & REPLACE_FLAG)) {
829    // Normal insert: move cursor right
830    curwin->w_cursor.col += (colnr_T)charlen;
831  }
832  // TODO(Bram): should try to update w_row here, to avoid recomputing it later.
833}
834
835/// Insert a string at the cursor position.
836/// Note: Does NOT handle Replace mode.
837/// Caller must have prepared for undo.
838void ins_str(char *s, size_t slen)
839{
840  linenr_T lnum = curwin->w_cursor.lnum;
841
842  if (virtual_active(curwin) && curwin->w_cursor.coladd > 0) {
843    coladvance_force(getviscol());
844  }
845
846  colnr_T col = curwin->w_cursor.col;
847  char *oldp = ml_get(lnum);
848  int oldlen = ml_get_len(lnum);
849
850  char *newp = xmalloc((size_t)oldlen + slen + 1);
851  if (col > 0) {
852    memmove(newp, oldp, (size_t)col);
853  }
854  memmove(newp + col, s, slen);
855  int bytes = oldlen - col + 1;
856  assert(bytes >= 0);
857  memmove(newp + col + slen, oldp + col, (size_t)bytes);
858  ml_replace(lnum, newp, false);
859  inserted_bytes(lnum, col, 0, (int)slen);
860  curwin->w_cursor.col += (colnr_T)slen;
861}
862
863// Delete one character under the cursor.
864// If "fixpos" is true, don't leave the cursor on the NUL after the line.
865// Caller must have prepared for undo.
866//
867// return FAIL for failure, OK otherwise
868int del_char(bool fixpos)
869{
870  // Make sure the cursor is at the start of a character.
871  mb_adjust_cursor();
872  if (*get_cursor_pos_ptr() == NUL) {
873    return FAIL;
874  }
875  return del_chars(1, fixpos);
876}
877
878/// Like del_bytes(), but delete characters instead of bytes.
879int del_chars(int count, int fixpos)
880{
881  int bytes = 0;
882  char *p = get_cursor_pos_ptr();
883  for (int i = 0; i < count && *p != NUL; i++) {
884    int l = utfc_ptr2len(p);
885    bytes += l;
886    p += l;
887  }
888  return del_bytes(bytes, fixpos, true);
889}
890
891/// Delete "count" bytes under the cursor.
892/// If "fixpos" is true, don't leave the cursor on the NUL after the line.
893/// Caller must have prepared for undo.
894///
895/// @param  count           number of bytes to be deleted
896/// @param  fixpos_arg      leave the cursor on the NUL after the line
897/// @param  use_delcombine  'delcombine' option applies
898///
899/// @return FAIL for failure, OK otherwise
900int del_bytes(colnr_T count, bool fixpos_arg, bool use_delcombine)
901{
902  linenr_T lnum = curwin->w_cursor.lnum;
903  colnr_T col = curwin->w_cursor.col;
904  bool fixpos = fixpos_arg;
905  char *oldp = ml_get(lnum);
906  colnr_T oldlen = ml_get_len(lnum);
907
908  // Can't do anything when the cursor is on the NUL after the line.
909  if (col >= oldlen) {
910    return FAIL;
911  }
912  // If "count" is zero there is nothing to do.
913  if (count == 0) {
914    return OK;
915  }
916  // If "count" is negative the caller must be doing something wrong.
917  if (count < 1) {
918    siemsg("E292: Invalid count for del_bytes(): %ld", (int64_t)count);
919    return FAIL;
920  }
921
922  // If 'delcombine' is set and deleting (less than) one character, only
923  // delete the last combining character.
924  if (p_deco && use_delcombine && utfc_ptr2len(oldp + col) >= count) {
925    char *p0 = oldp + col;
926    GraphemeState state = GRAPHEME_STATE_INIT;
927    if (utf_composinglike(p0, p0 + utf_ptr2len(p0), &state)) {
928      // Find the last composing char, there can be several.
929      int n = col;
930      do {
931        col = n;
932        count = utf_ptr2len(oldp + n);
933        n += count;
934      } while (utf_composinglike(oldp + col, oldp + n, &state));
935      fixpos = false;
936    }
937  }
938
939  // When count is too big, reduce it.
940  int movelen = oldlen - col - count + 1;  // includes trailing NUL
941  if (movelen <= 1) {
942    // If we just took off the last character of a non-blank line, and
943    // fixpos is true, we don't want to end up positioned at the NUL,
944    // unless "restart_edit" is set or 'virtualedit' contains "onemore".
945    if (col > 0 && fixpos && restart_edit == 0
946        && (get_ve_flags(curwin) & kOptVeFlagOnemore) == 0) {
947      curwin->w_cursor.col--;
948      curwin->w_cursor.coladd = 0;
949      curwin->w_cursor.col -= utf_head_off(oldp, oldp + curwin->w_cursor.col);
950    }
951    count = oldlen - col;
952    movelen = 1;
953  }
954  colnr_T newlen = oldlen - count;
955
956  // If the old line has been allocated the deletion can be done in the
957  // existing line. Otherwise a new line has to be allocated.
958  bool alloc_newp = !ml_line_alloced();     // check if oldp was allocated
959  char *newp;
960  if (!alloc_newp) {
961    ml_add_deleted_len(curbuf->b_ml.ml_line_ptr, oldlen);
962    newp = oldp;                            // use same allocated memory
963  } else {                                  // need to allocate a new line
964    newp = xmallocz((size_t)newlen);
965    memmove(newp, oldp, (size_t)col);
966  }
967  memmove(newp + col, oldp + col + count, (size_t)movelen);
968  if (alloc_newp) {
969    ml_replace(lnum, newp, false);
970  } else {
971    curbuf->b_ml.ml_line_textlen = newlen + 1;
972  }
973
974  // mark the buffer as changed and prepare for displaying
975  inserted_bytes(lnum, col, count, 0);
976
977  return OK;
978}
979
980/// open_line: Add a new line below or above the current line.
981///
982/// For MODE_VREPLACE state, we only add a new line when we get to the end of
983/// the file, otherwise we just start replacing the next line.
984///
985/// Caller must take care of undo.  Since MODE_VREPLACE may affect any number of
986/// lines however, it may call u_save_cursor() again when starting to change a
987/// new line.
988/// "flags": OPENLINE_DELSPACES delete spaces after cursor
989///          OPENLINE_DO_COM    format comments
990///          OPENLINE_KEEPTRAIL keep trailing spaces
991///          OPENLINE_MARKFIX   adjust mark positions after the line break
992///          OPENLINE_COM_LIST  format comments with list or 2nd line indent
993///          OPENLINE_FORCE_INDENT  set indent from second_line_indent, ignore 'autoindent'
994///
995/// "second_line_indent": indent for after ^^D in Insert mode or if flag
996///                       OPENLINE_COM_LIST
997/// "did_do_comment" is set to true when intentionally putting the comment
998/// leader in front of the new line.
999///
1000/// @param dir  FORWARD or BACKWARD
1001///
1002/// @return true on success, false on failure
1003bool open_line(int dir, int flags, int second_line_indent, bool *did_do_comment)
1004{
1005  char *next_line = NULL;         // copy of the next line
1006  char *p_extra = NULL;           // what goes to next line
1007  colnr_T less_cols = 0;          // less columns for mark in new line
1008  colnr_T less_cols_off = 0;      // columns to skip for mark and
1009                                  // extmark adjustment
1010  pos_T old_cursor;               // old cursor position
1011  colnr_T newcol = 0;             // new cursor column
1012  int newindent = 0;              // auto-indent of the new line
1013  bool trunc_line = false;        // truncate current line afterwards
1014  bool retval = false;            // return value
1015  int extra_len = 0;              // length of p_extra string
1016  int lead_len;                   // length of comment leader
1017  int comment_start = 0;          // start index of the comment leader
1018  char *lead_flags;               // position in 'comments' for comment leader
1019  char *leader = NULL;            // copy of comment leader
1020  char *allocated = NULL;         // allocated memory
1021  char *p;
1022  char saved_char = NUL;          // init for GCC
1023  pos_T *pos;
1024  bool do_si = may_do_si();
1025  bool no_si = false;             // reset Ins.did_si afterwards
1026  int first_char = NUL;           // init for GCC
1027  int vreplace_mode;
1028  bool did_append;                // appended a new line
1029  int saved_pi = curbuf->b_p_pi;  // copy of preserveindent setting
1030
1031  linenr_T lnum = curwin->w_cursor.lnum;
1032  colnr_T mincol = curwin->w_cursor.col + 1;
1033
1034  // make a copy of the current line so we can mess with it
1035  char *saved_line = xstrnsave(get_cursor_line_ptr(), (size_t)get_cursor_line_len());
1036
1037  if (State & VREPLACE_FLAG) {
1038    // With MODE_VREPLACE we make a copy of the next line, which we will be
1039    // starting to replace.  First make the new line empty and let vim play
1040    // with the indenting and comment leader to its heart's content.  Then
1041    // we grab what it ended up putting on the new line, put back the
1042    // original line, and call ins_char() to put each new character onto
1043    // the line, replacing what was there before and pushing the right
1044    // stuff onto the replace stack.  -- webb.
1045    if (curwin->w_cursor.lnum < orig_line_count) {
1046      next_line = xstrnsave(ml_get(curwin->w_cursor.lnum + 1),
1047                            (size_t)ml_get_len(curwin->w_cursor.lnum + 1));
1048    } else {
1049      next_line = xstrdup("");
1050    }
1051
1052    // In MODE_VREPLACE state, a NL replaces the rest of the line, and
1053    // starts replacing the next line, so push all of the characters left
1054    // on the line onto the replace stack.  We'll push any other characters
1055    // that might be replaced at the start of the next line (due to
1056    // autoindent etc) a bit later.
1057    replace_push_nul();      // Call twice because BS over NL expects it
1058    replace_push_nul();
1059    p = saved_line + curwin->w_cursor.col;
1060    replace_push(p, strlen(p));
1061    saved_line[curwin->w_cursor.col] = NUL;
1062  }
1063
1064  if ((State & MODE_INSERT) && (State & VREPLACE_FLAG) == 0) {
1065    p_extra = saved_line + curwin->w_cursor.col;
1066    if (do_si) {  // need first char after new line break
1067      p = skipwhite(p_extra);
1068      first_char = (unsigned char)(*p);
1069    }
1070    extra_len = (int)strlen(p_extra);
1071    saved_char = *p_extra;
1072    *p_extra = NUL;
1073  }
1074
1075  u_clearline(curbuf);  // cannot do "U" command when adding lines
1076  Ins.did_si = false;
1077  Ins.ai_col = 0;
1078
1079  // If we just did an auto-indent, then we didn't type anything on
1080  // the prior line, and it should be truncated.  Do this even if 'ai' is not
1081  // set because automatically inserting a comment leader also sets Ins.did_ai.
1082  if (dir == FORWARD && Ins.did_ai) {
1083    trunc_line = true;
1084  }
1085
1086  if ((flags & OPENLINE_FORCE_INDENT)) {
1087    newindent = second_line_indent;
1088  } else if (curbuf->b_p_ai || do_si) {
1089    // If 'autoindent' and/or 'smartindent' is set, try to figure out what
1090    // indent to use for the new line.
1091    // count white space on current line
1092    newindent = indent_size_ts(saved_line, curbuf->b_p_ts, curbuf->b_p_vts_array);
1093    if (newindent == 0 && !(flags & OPENLINE_COM_LIST)) {
1094      newindent = second_line_indent;  // for ^^D command in insert mode
1095    }
1096
1097    // Do smart indenting.
1098    // In insert/replace mode (only when dir == FORWARD)
1099    // we may move some text to the next line. If it starts with '{'
1100    // don't add an indent. Fixes inserting a NL before '{' in line
1101    //   "if (condition) {"
1102    if (!trunc_line && do_si && *saved_line != NUL
1103        && (p_extra == NULL || first_char != '{')) {
1104      old_cursor = curwin->w_cursor;
1105      char *ptr = saved_line;
1106      if (flags & OPENLINE_DO_COM) {
1107        lead_len = get_leader_len(ptr, NULL, false, true);
1108      } else {
1109        lead_len = 0;
1110      }
1111      if (dir == FORWARD) {
1112        // Skip preprocessor directives, unless they are recognised as comments.
1113        if (lead_len == 0 && ptr[0] == '#') {
1114          while (ptr[0] == '#' && curwin->w_cursor.lnum > 1) {
1115            ptr = ml_get(--curwin->w_cursor.lnum);
1116          }
1117          newindent = get_indent();
1118        }
1119        if (flags & OPENLINE_DO_COM) {
1120          lead_len = get_leader_len(ptr, NULL, false, true);
1121        } else {
1122          lead_len = 0;
1123        }
1124        if (lead_len > 0) {
1125          // This case gets the following right:
1126          //     \*
1127          //      * A comment (read '\' as '/').
1128          //      */
1129          //     #define IN_THE_WAY
1130          //     This should line up here;
1131          p = skipwhite(ptr);
1132          if (p[0] == '/' && p[1] == '*') {
1133            p++;
1134          }
1135          if (p[0] == '*') {
1136            for (p++; *p; p++) {
1137              if (p[0] == '/' && p[-1] == '*') {
1138                // End of C comment, indent should line up
1139                // with the line containing the start of
1140                // the comment.
1141                curwin->w_cursor.col = (colnr_T)(p - ptr);
1142                if ((pos = findmatch(NULL, NUL)) != NULL) {
1143                  curwin->w_cursor.lnum = pos->lnum;
1144                  newindent = get_indent();
1145                  break;
1146                }
1147                // this may make "ptr" invalid, get it again
1148                ptr = ml_get(curwin->w_cursor.lnum);
1149                p = ptr + curwin->w_cursor.col;
1150              }
1151            }
1152          }
1153        } else {      // Not a comment line
1154          // Find last non-blank in line
1155          p = ptr + strlen(ptr) - 1;
1156          while (p > ptr && ascii_iswhite(*p)) {
1157            p--;
1158          }
1159          char last_char = *p;
1160
1161          // find the character just before the '{' or ';'
1162          if (last_char == '{' || last_char == ';') {
1163            if (p > ptr) {
1164              p--;
1165            }
1166            while (p > ptr && ascii_iswhite(*p)) {
1167              p--;
1168            }
1169          }
1170          // Try to catch lines that are split over multiple
1171          // lines.  eg:
1172          //     if (condition &&
1173          //             condition) {
1174          //         Should line up here!
1175          //     }
1176          if (*p == ')') {
1177            curwin->w_cursor.col = (colnr_T)(p - ptr);
1178            if ((pos = findmatch(NULL, '(')) != NULL) {
1179              curwin->w_cursor.lnum = pos->lnum;
1180              newindent = get_indent();
1181              ptr = get_cursor_line_ptr();
1182            }
1183          }
1184          // If last character is '{' do indent, without
1185          // checking for "if" and the like.
1186          if (last_char == '{') {
1187            Ins.did_si = true;              // do indent
1188            no_si = true;               // don't delete it when '{' typed
1189            // Look for "if" and the like, use 'cinwords'.
1190            // Don't do this if the previous line ended in ';' or
1191            // '}'.
1192          } else if (last_char != ';' && last_char != '}'
1193                     && cin_is_cinword(ptr)) {
1194            Ins.did_si = true;
1195          }
1196        }
1197      } else {  // dir == BACKWARD
1198        // Skip preprocessor directives, unless they are
1199        // recognised as comments.
1200        if (lead_len == 0 && ptr[0] == '#') {
1201          bool was_backslashed = false;
1202
1203          while ((ptr[0] == '#' || was_backslashed)
1204                 && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count) {
1205            if (*ptr && ptr[strlen(ptr) - 1] == '\\') {
1206              was_backslashed = true;
1207            } else {
1208              was_backslashed = false;
1209            }
1210            ptr = ml_get(++curwin->w_cursor.lnum);
1211          }
1212          if (was_backslashed) {
1213            newindent = 0;  // Got to end of file
1214          } else {
1215            newindent = get_indent();
1216          }
1217        }
1218        p = skipwhite(ptr);
1219        if (*p == '}') {            // if line starts with '}': do indent
1220          Ins.did_si = true;
1221        } else {                    // can delete indent when '{' typed
1222          Ins.can_si_back = true;
1223        }
1224      }
1225      curwin->w_cursor = old_cursor;
1226    }
1227    if (do_si) {
1228      Ins.can_si = true;
1229    }
1230
1231    Ins.did_ai = true;
1232  }
1233
1234  // May do indenting after opening a new line.
1235  bool do_cindent = !p_paste && (curbuf->b_p_cin || curbuf->b_p_inde.type != kCallbackNone)
1236                    && in_cinkeys(dir == FORWARD ? KEY_OPEN_FORW : KEY_OPEN_BACK,
1237                                  ' ', linewhite(curwin->w_cursor.lnum))
1238                    && !(flags & OPENLINE_FORCE_INDENT);
1239
1240  // Find out if the current line starts with a comment leader.
1241  // This may then be inserted in front of the new line.
1242  Ins.end_comment_pending = NUL;
1243  if (flags & OPENLINE_DO_COM) {
1244    lead_len = get_leader_len(saved_line, &lead_flags, dir == BACKWARD, true);
1245    if (lead_len == 0 && curbuf->b_p_cin && do_cindent && dir == FORWARD
1246        && (!has_format_option(kFoNoOpenComs) || (flags & OPENLINE_FORMAT))) {
1247      // Check for a line comment after code.
1248      comment_start = check_linecomment(saved_line);
1249      if (comment_start != MAXCOL) {
1250        lead_len = get_leader_len(saved_line + comment_start, &lead_flags, false, true);
1251        if (lead_len != 0) {
1252          lead_len += comment_start;
1253          if (did_do_comment != NULL) {
1254            *did_do_comment = true;
1255          }
1256        }
1257      }
1258    }
1259  } else {
1260    lead_len = 0;
1261  }
1262  if (lead_len > 0) {
1263    char *lead_repl = NULL;                 // replaces comment leader
1264    int lead_repl_len = 0;                  // length of *lead_repl
1265    char lead_middle[COM_MAX_LEN];          // middle-comment string
1266    int lead_middle_len;                    // length of the lead_middle
1267    char lead_end[COM_MAX_LEN];             // end-comment string
1268    char *comment_end = NULL;               // where lead_end has been found
1269    int extra_space = false;                // append extra space
1270    bool require_blank = false;             // requires blank after middle
1271    char *p2;
1272
1273    // If the comment leader has the start, middle or end flag, it may not
1274    // be used or may be replaced with the middle leader.
1275    for (p = lead_flags; *p && *p != ':'; p++) {
1276      if (*p == COM_BLANK) {
1277        require_blank = true;
1278        continue;
1279      }
1280      if (*p == COM_START || *p == COM_MIDDLE) {
1281        int current_flag = (unsigned char)(*p);
1282        if (*p == COM_START) {
1283          // Doing "O" on a start of comment does not insert leader.
1284          if (dir == BACKWARD) {
1285            lead_len = 0;
1286            break;
1287          }
1288
1289          // find start of middle part
1290          copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
1291          require_blank = false;
1292        }
1293
1294        // Isolate the strings of the middle and end leader.
1295        while (*p && p[-1] != ':') {  // find end of middle flags
1296          if (*p == COM_BLANK) {
1297            require_blank = true;
1298          }
1299          p++;
1300        }
1301        lead_middle_len = (int)copy_option_part(&p, lead_middle, COM_MAX_LEN, ",");
1302
1303        while (*p && p[-1] != ':') {  // find end of end flags
1304          // Check whether we allow automatic ending of comments
1305          if (*p == COM_AUTO_END) {
1306            Ins.end_comment_pending = -1;  // means we want to set it
1307          }
1308          p++;
1309        }
1310        size_t n = copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
1311
1312        if (Ins.end_comment_pending == -1) {  // we can set it now
1313          Ins.end_comment_pending = (unsigned char)lead_end[n - 1];
1314        }
1315
1316        // If the end of the comment is in the same line, don't use
1317        // the comment leader.
1318        if (dir == FORWARD) {
1319          for (p = saved_line + lead_len; *p; p++) {
1320            if (strncmp(p, lead_end, n) == 0) {
1321              comment_end = p;
1322              lead_len = 0;
1323              break;
1324            }
1325          }
1326        }
1327
1328        // Doing "o" on a start of comment inserts the middle leader.
1329        if (lead_len > 0) {
1330          if (current_flag == COM_START) {
1331            lead_repl = lead_middle;
1332            lead_repl_len = lead_middle_len;
1333          }
1334
1335          // If we have hit RETURN immediately after the start
1336          // comment leader, then put a space after the middle
1337          // comment leader on the next line.
1338          if (!ascii_iswhite(saved_line[lead_len - 1])
1339              && ((p_extra != NULL
1340                   && (int)curwin->w_cursor.col == lead_len)
1341                  || (p_extra == NULL
1342                      && saved_line[lead_len] == NUL)
1343                  || require_blank)) {
1344            extra_space = true;
1345          }
1346        }
1347        break;
1348      }
1349      if (*p == COM_END) {
1350        // Doing "o" on the end of a comment does not insert leader.
1351        // Remember where the end is, might want to use it to find the
1352        // start (for C-comments).
1353        if (dir == FORWARD) {
1354          comment_end = skipwhite(saved_line);
1355          lead_len = 0;
1356          break;
1357        }
1358
1359        // Doing "O" on the end of a comment inserts the middle leader.
1360        // Find the string for the middle leader, searching backwards.
1361        while (p > curbuf->b_p_com && *p != ',') {
1362          p--;
1363        }
1364        for (lead_repl = p; lead_repl > curbuf->b_p_com
1365             && lead_repl[-1] != ':'; lead_repl--) {}
1366        lead_repl_len = (int)(p - lead_repl);
1367
1368        // We can probably always add an extra space when doing "O" on
1369        // the comment-end
1370        extra_space = true;
1371
1372        // Check whether we allow automatic ending of comments
1373        for (p2 = p; *p2 && *p2 != ':'; p2++) {
1374          if (*p2 == COM_AUTO_END) {
1375            Ins.end_comment_pending = -1;  // means we want to set it
1376          }
1377        }
1378        if (Ins.end_comment_pending == -1) {
1379          // Find last character in end-comment string
1380          while (*p2 && *p2 != ',') {
1381            p2++;
1382          }
1383          Ins.end_comment_pending = (unsigned char)p2[-1];
1384        }
1385        break;
1386      }
1387      if (*p == COM_FIRST) {
1388        // Comment leader for first line only: Don't repeat leader
1389        // when using "O", blank out leader when using "o".
1390        if (dir == BACKWARD) {
1391          lead_len = 0;
1392        } else {
1393          lead_repl = "";
1394          lead_repl_len = 0;
1395        }
1396        break;
1397      }
1398    }
1399    if (lead_len > 0) {
1400      // allocate buffer (may concatenate p_extra later)
1401      int bytes = lead_len
1402                  + lead_repl_len
1403                  + extra_space
1404                  + extra_len
1405                  + (second_line_indent > 0 ? second_line_indent : 0)
1406                  + 1;
1407      assert(bytes >= 0);
1408      leader = xmalloc((size_t)bytes);
1409      allocated = leader;  // remember to free it later
1410
1411      xmemcpyz(leader, saved_line, (size_t)lead_len);
1412
1413      // TODO(vim): handle multi-byte and double width chars
1414      for (int li = 0; li < comment_start; li++) {
1415        if (!ascii_iswhite(leader[li])) {
1416          leader[li] = ' ';
1417        }
1418      }
1419
1420      // Replace leader with lead_repl, right or left adjusted
1421      if (lead_repl != NULL) {
1422        int c = 0;
1423        int off = 0;
1424
1425        for (p = lead_flags; *p != NUL && *p != ':';) {
1426          if (*p == COM_RIGHT || *p == COM_LEFT) {
1427            c = (unsigned char)(*p++);
1428          } else if (ascii_isdigit(*p) || *p == '-') {
1429            off = getdigits_int(&p, true, 0);
1430          } else {
1431            p++;
1432          }
1433        }
1434        if (c == COM_RIGHT) {  // right adjusted leader
1435          // find last non-white in the leader to line up with
1436          for (p = leader + lead_len - 1; p > leader
1437               && ascii_iswhite(*p); p--) {}
1438          p++;
1439
1440          // Compute the length of the replaced characters in
1441          // screen characters, not bytes.
1442          {
1443            int repl_size = vim_strnsize(lead_repl, lead_repl_len);
1444            int old_size = 0;
1445            char *endp = p;
1446
1447            while (old_size < repl_size && p > leader) {
1448              MB_PTR_BACK(leader, p);
1449              old_size += ptr2cells(p);
1450            }
1451            int l = lead_repl_len - (int)(endp - p);
1452            if (l != 0) {
1453              memmove(endp + l, endp,
1454                      (size_t)((leader + lead_len) - endp));
1455            }
1456            lead_len += l;
1457          }
1458          memmove(p, lead_repl, (size_t)lead_repl_len);
1459          if (p + lead_repl_len > leader + lead_len) {
1460            p[lead_repl_len] = NUL;
1461          }
1462
1463          // blank-out any other chars from the old leader.
1464          while (--p >= leader) {
1465            int l = utf_head_off(leader, p);
1466
1467            if (l > 1) {
1468              p -= l;
1469              if (ptr2cells(p) > 1) {
1470                p[1] = ' ';
1471                l--;
1472              }
1473              memmove(p + 1, p + l + 1,
1474                      (size_t)((leader + lead_len) - (p + l + 1)));
1475              lead_len -= l;
1476              *p = ' ';
1477            } else if (!ascii_iswhite(*p)) {
1478              *p = ' ';
1479            }
1480          }
1481        } else {  // left adjusted leader
1482          p = skipwhite(leader);
1483          // Compute the length of the replaced characters in
1484          // screen characters, not bytes. Move the part that is
1485          // not to be overwritten.
1486          {
1487            int repl_size = vim_strnsize(lead_repl, lead_repl_len);
1488            int i;
1489            int l;
1490
1491            for (i = 0; i < lead_len && p[i] != NUL; i += l) {
1492              l = utfc_ptr2len(p + i);
1493              if (vim_strnsize(p, i + l) > repl_size) {
1494                break;
1495              }
1496            }
1497            if (i != lead_repl_len) {
1498              memmove(p + lead_repl_len, p + i,
1499                      (size_t)(lead_len - i - (p - leader)));
1500              lead_len += lead_repl_len - i;
1501            }
1502          }
1503          memmove(p, lead_repl, (size_t)lead_repl_len);
1504
1505          // Replace any remaining non-white chars in the old
1506          // leader by spaces.  Keep Tabs, the indent must
1507          // remain the same.
1508          for (p += lead_repl_len; p < leader + lead_len; p++) {
1509            if (!ascii_iswhite(*p)) {
1510              // Don't put a space before a TAB.
1511              if (p + 1 < leader + lead_len && p[1] == TAB) {
1512                lead_len--;
1513                memmove(p, p + 1, (size_t)(leader + lead_len - p));
1514              } else {
1515                int l = utfc_ptr2len(p);
1516
1517                if (l > 1) {
1518                  if (ptr2cells(p) > 1) {
1519                    // Replace a double-wide char with
1520                    // two spaces
1521                    l--;
1522                    *p++ = ' ';
1523                  }
1524                  memmove(p + 1, p + l, (size_t)(leader + lead_len - p));
1525                  lead_len -= l - 1;
1526                }
1527                *p = ' ';
1528              }
1529            }
1530          }
1531          *p = NUL;
1532        }
1533
1534        // Recompute the indent, it may have changed.
1535        if (curbuf->b_p_ai || do_si) {
1536          newindent = indent_size_ts(leader, curbuf->b_p_ts, curbuf->b_p_vts_array);
1537        }
1538
1539        // Add the indent offset
1540        if (newindent + off < 0) {
1541          off = -newindent;
1542          newindent = 0;
1543        } else {
1544          newindent += off;
1545        }
1546
1547        // Correct trailing spaces for the shift, so that
1548        // alignment remains equal.
1549        while (off > 0 && lead_len > 0
1550               && leader[lead_len - 1] == ' ') {
1551          // Don't do it when there is a tab before the space
1552          if (vim_strchr(skipwhite(leader), '\t') != NULL) {
1553            break;
1554          }
1555          lead_len--;
1556          off--;
1557        }
1558
1559        // If the leader ends in white space, don't add an
1560        // extra space
1561        if (lead_len > 0 && ascii_iswhite(leader[lead_len - 1])) {
1562          extra_space = false;
1563        }
1564        leader[lead_len] = NUL;
1565      }
1566
1567      if (extra_space) {
1568        leader[lead_len++] = ' ';
1569        leader[lead_len] = NUL;
1570      }
1571
1572      newcol = lead_len;
1573
1574      // if a new indent will be set below, remove the indent that
1575      // is in the comment leader
1576      if (newindent || Ins.did_si) {
1577        while (lead_len && ascii_iswhite(*leader)) {
1578          lead_len--;
1579          newcol--;
1580          leader++;
1581        }
1582      }
1583      Ins.did_si = Ins.can_si = false;
1584    } else if (comment_end != NULL) {
1585      // We have finished a comment, so we don't use the leader.
1586      // If this was a C-comment and 'ai' or 'si' is set do a normal
1587      // indent to align with the line containing the start of the
1588      // comment.
1589      if (comment_end[0] == '*' && comment_end[1] == '/'
1590          && (curbuf->b_p_ai || do_si)) {
1591        old_cursor = curwin->w_cursor;
1592        curwin->w_cursor.col = (colnr_T)(comment_end - saved_line);
1593        if ((pos = findmatch(NULL, NUL)) != NULL) {
1594          curwin->w_cursor.lnum = pos->lnum;
1595          newindent = get_indent();
1596        }
1597        curwin->w_cursor = old_cursor;
1598      }
1599    }
1600  }
1601
1602  // (State == MODE_INSERT || State == MODE_REPLACE), only when dir == FORWARD
1603  if (p_extra != NULL) {
1604    *p_extra = saved_char;              // restore char that NUL replaced
1605
1606    // When 'ai' set or "flags" has OPENLINE_DELSPACES, skip to the first
1607    // non-blank.
1608    //
1609    // When in MODE_REPLACE state, put the deleted blanks on the replace
1610    // stack, preceded by a NUL, so they can be put back when a BS is
1611    // entered.
1612    if (REPLACE_NORMAL(State)) {
1613      replace_push_nul();            // end of extra blanks
1614    }
1615    if (curbuf->b_p_ai || (flags & OPENLINE_DELSPACES)) {
1616      while ((*p_extra == ' ' || *p_extra == '\t')
1617             && !utf_iscomposing_first(utf_ptr2char(p_extra + 1))) {
1618        if (REPLACE_NORMAL(State)) {
1619          replace_push(p_extra, 1);  // always ascii, len = 1
1620        }
1621        p_extra++;
1622        less_cols_off++;
1623      }
1624    }
1625
1626    // columns for marks adjusted for removed columns
1627    less_cols = (int)(p_extra - saved_line);
1628  }
1629
1630  if (p_extra == NULL) {
1631    p_extra = "";                 // append empty line
1632  }
1633
1634  // concatenate leader and p_extra, if there is a leader
1635  if (lead_len > 0) {
1636    if (flags & OPENLINE_COM_LIST && second_line_indent > 0) {
1637      int padding = second_line_indent
1638                    - (newindent + (int)strlen(leader));
1639
1640      // Here whitespace is inserted after the comment char.
1641      // Below, set_indent(newindent, SIN_INSERT) will insert the
1642      // whitespace needed before the comment char.
1643      for (int i = 0; i < padding; i++) {
1644        strcat(leader, " ");
1645        less_cols--;
1646        newcol++;
1647      }
1648    }
1649    strcat(leader, p_extra);
1650    p_extra = leader;
1651    Ins.did_ai = true;          // So truncating blanks works with comments
1652    less_cols -= lead_len;
1653  } else {
1654    Ins.end_comment_pending = NUL;  // turns out there was no leader
1655  }
1656
1657  curbuf_splice_pending++;
1658  old_cursor = curwin->w_cursor;
1659  int old_cmod_flags = cmdmod.cmod_flags;
1660  char *prompt_moved = NULL;
1661  if (dir == BACKWARD) {
1662    // In case of prompt buffer, when we are applying 'normal O' operation on line of prompt,
1663    // we can't add a new line before the prompt. In this case, we move the prompt text one
1664    // line below and create a new prompt line as current line.
1665    if (bt_prompt(curbuf) && curwin->w_cursor.lnum == curbuf->b_prompt_start.mark.lnum) {
1666      char *prompt_line = ml_get(curwin->w_cursor.lnum);
1667      char *prompt = prompt_text();
1668      size_t prompt_len = strlen(prompt);
1669
1670      if (strncmp(prompt_line, prompt, prompt_len) == 0) {
1671        STRMOVE(prompt_line, prompt_line + prompt_len);
1672        // We are moving the lines but the b_prompt_start mark needs to stay in
1673        // place so freezing marks before making the move.
1674        cmdmod.cmod_flags = cmdmod.cmod_flags | CMOD_LOCKMARKS;
1675        ml_replace(curwin->w_cursor.lnum, prompt_line, true);
1676        prompt_moved = concat_str(prompt, p_extra);
1677        p_extra = prompt_moved;
1678      }
1679    }
1680    curwin->w_cursor.lnum--;
1681  }
1682  if ((State & VREPLACE_FLAG) == 0 || old_cursor.lnum >= orig_line_count) {
1683    if (ml_append(curwin->w_cursor.lnum, p_extra, 0, false) == FAIL) {
1684      goto theend;
1685    }
1686    // Postpone calling changed_lines(), because it would mess up folding
1687    // with markers.
1688    mark_adjust(curwin->w_cursor.lnum + 1, (linenr_T)MAXLNUM, 1, 0, kExtmarkNOOP);
1689    did_append = true;
1690  } else {
1691    // In MODE_VREPLACE state we are starting to replace the next line.
1692    curwin->w_cursor.lnum++;
1693    if (curwin->w_cursor.lnum >= Ins.start.lnum + vr_lines_changed) {
1694      // In case we NL to a new line, BS to the previous one, and NL
1695      // again, we don't want to save the new line for undo twice.
1696      u_save_cursor();  // errors are ignored!
1697      vr_lines_changed++;
1698    }
1699    ml_replace(curwin->w_cursor.lnum, p_extra, true);
1700    changed_bytes(curwin->w_cursor.lnum, 0);
1701    // TODO(vigoux): extmark_splice_cols here??
1702    curwin->w_cursor.lnum--;
1703    did_append = false;
1704  }
1705
1706  inhibit_delete_count++;
1707  if (newindent || Ins.did_si) {
1708    curwin->w_cursor.lnum++;
1709    if (Ins.did_si) {
1710      int sw = get_sw_value(curbuf);
1711
1712      if (p_sr) {
1713        newindent -= newindent % sw;
1714      }
1715      newindent += sw;
1716    }
1717    // Copy the indent
1718    if (curbuf->b_p_ci) {
1719      copy_indent(newindent, saved_line);
1720
1721      // Set the 'preserveindent' option so that any further screwing
1722      // with the line doesn't entirely destroy our efforts to preserve
1723      // it.  It gets restored at the function end.
1724      curbuf->b_p_pi = true;
1725    } else {
1726      set_indent(newindent, SIN_INSERT|SIN_NOMARK);
1727    }
1728    less_cols -= curwin->w_cursor.col;
1729
1730    Ins.ai_col = curwin->w_cursor.col;
1731
1732    // In MODE_REPLACE state, for each character in the new indent, there
1733    // must be a NUL on the replace stack, for when it is deleted with BS
1734    if (REPLACE_NORMAL(State)) {
1735      for (colnr_T n = 0; n < curwin->w_cursor.col; n++) {
1736        replace_push_nul();
1737      }
1738    }
1739    newcol += curwin->w_cursor.col;
1740    if (no_si) {
1741      Ins.did_si = false;
1742    }
1743  }
1744  inhibit_delete_count--;
1745
1746  // In MODE_REPLACE state, for each character in the extra leader, there
1747  // must be a NUL on the replace stack, for when it is deleted with BS.
1748  if (REPLACE_NORMAL(State)) {
1749    while (lead_len-- > 0) {
1750      replace_push_nul();
1751    }
1752  }
1753
1754  curwin->w_cursor = old_cursor;
1755
1756  if (dir == FORWARD) {
1757    if (trunc_line || (State & MODE_INSERT)) {
1758      // truncate current line at cursor
1759      saved_line[curwin->w_cursor.col] = NUL;
1760      // Remove trailing white space, unless OPENLINE_KEEPTRAIL used.
1761      if (trunc_line && !(flags & OPENLINE_KEEPTRAIL)) {
1762        truncate_spaces(saved_line, (size_t)curwin->w_cursor.col);
1763      }
1764      ml_replace(curwin->w_cursor.lnum, saved_line, false);
1765
1766      int new_len = (int)strlen(saved_line);
1767
1768      // TODO(vigoux): maybe there is issues there with expandtabs ?
1769      int cols_spliced = 0;
1770      if (new_len < curwin->w_cursor.col) {
1771        extmark_splice_cols(curbuf, (int)curwin->w_cursor.lnum - 1,
1772                            new_len, curwin->w_cursor.col - new_len, 0, kExtmarkUndo);
1773        cols_spliced = curwin->w_cursor.col - new_len;
1774      }
1775
1776      saved_line = NULL;
1777      if (did_append) {
1778        // Always move extmarks - Here we move only the line where the cursor is,
1779        // the previous mark_adjust() took care of the lines after.
1780        int cols_added = mincol - 1 + less_cols_off - less_cols;
1781        extmark_splice(curbuf, (int)lnum - 1, mincol - 1 - cols_spliced,
1782                       0, less_cols_off, less_cols_off,
1783                       1, cols_added, 1 + cols_added, kExtmarkUndo);
1784
1785        changed_lines(curbuf, curwin->w_cursor.lnum, curwin->w_cursor.col,
1786                      curwin->w_cursor.lnum + 1, 1, true);
1787        did_append = false;
1788
1789        // Move marks after the line break to the new line.
1790        if (flags & OPENLINE_MARKFIX) {
1791          mark_col_adjust(curwin->w_cursor.lnum,
1792                          curwin->w_cursor.col + less_cols_off,
1793                          1, -less_cols, 0);
1794        }
1795      } else {
1796        changed_bytes(curwin->w_cursor.lnum, curwin->w_cursor.col);
1797      }
1798    }
1799
1800    // Put the cursor on the new line.  Careful: the scrollup() above may
1801    // have moved w_cursor, we must use old_cursor.
1802    curwin->w_cursor.lnum = old_cursor.lnum + 1;
1803  }
1804  if (did_append) {
1805    // bail out and just get the final length of the line we just manipulated
1806    bcount_t extra = ml_get_len(curwin->w_cursor.lnum);
1807    extmark_splice(curbuf, (int)curwin->w_cursor.lnum - 1, 0,
1808                   0, 0, 0, 1, 0, 1 + extra, kExtmarkUndo);
1809    changed_lines(curbuf, curwin->w_cursor.lnum, 0, curwin->w_cursor.lnum, 1, true);
1810  }
1811  curbuf_splice_pending--;
1812
1813  curwin->w_cursor.col = newcol;
1814  curwin->w_cursor.coladd = 0;
1815
1816  // In MODE_VREPLACE state, we are handling the replace stack ourselves, so
1817  // stop fixthisline() from doing it (via change_indent()) by telling it
1818  // we're in normal MODE_INSERT state.
1819  if (State & VREPLACE_FLAG) {
1820    vreplace_mode = State;  // So we know to put things right later
1821    State = MODE_INSERT;
1822  } else {
1823    vreplace_mode = 0;
1824  }
1825
1826  if (!p_paste) {
1827    if (leader == NULL
1828        && !use_indentexpr_for_lisp()
1829        && curbuf->b_p_lisp
1830        && curbuf->b_p_ai) {
1831      // do lisp indenting
1832      fixthisline(get_lisp_indent);
1833      Ins.ai_col = (colnr_T)getwhitecols_curline();
1834    } else if (do_cindent || (curbuf->b_p_ai && use_indentexpr_for_lisp())) {
1835      // do 'cindent' or 'indentexpr' indenting
1836      do_c_expr_indent();
1837      Ins.ai_col = (colnr_T)getwhitecols_curline();
1838    }
1839  }
1840
1841  if (vreplace_mode != 0) {
1842    State = vreplace_mode;
1843  }
1844
1845  // Finally, MODE_VREPLACE gets the stuff on the new line, then puts back
1846  // the original line, and inserts the new stuff char by char, pushing old
1847  // stuff onto the replace stack (via ins_char()).
1848  if (State & VREPLACE_FLAG) {
1849    // Put new line in p_extra
1850    p_extra = xstrnsave(get_cursor_line_ptr(), (size_t)get_cursor_line_len());
1851
1852    // Put back original line
1853    ml_replace(curwin->w_cursor.lnum, next_line, false);
1854
1855    // Insert new stuff into line again
1856    curwin->w_cursor.col = 0;
1857    curwin->w_cursor.coladd = 0;
1858    ins_bytes(p_extra);         // will call changed_bytes()
1859    xfree(p_extra);
1860    next_line = NULL;
1861  }
1862
1863  retval = true;                // success!
1864theend:
1865  curbuf->b_p_pi = saved_pi;
1866  xfree(saved_line);
1867  xfree(next_line);
1868  xfree(allocated);
1869  xfree(prompt_moved);
1870  cmdmod.cmod_flags = old_cmod_flags;
1871  return retval;
1872}
1873
1874/// Delete from cursor to end of line.
1875/// Caller must have prepared for undo.
1876/// If "fixpos" is true fix the cursor position when done.
1877void truncate_line(int fixpos)
1878{
1879  linenr_T lnum = curwin->w_cursor.lnum;
1880  colnr_T col = curwin->w_cursor.col;
1881  char *old_line = ml_get(lnum);
1882  char *newp = col == 0 ? xstrdup("") : xstrnsave(old_line, (size_t)col);
1883  int deleted = ml_get_len(lnum) - col;
1884
1885  ml_replace(lnum, newp, false);
1886
1887  // mark the buffer as changed and prepare for displaying
1888  inserted_bytes(lnum, curwin->w_cursor.col, deleted, 0);
1889
1890  // If "fixpos" is true we don't want to end up positioned at the NUL.
1891  if (fixpos && curwin->w_cursor.col > 0) {
1892    curwin->w_cursor.col--;
1893  }
1894}
1895
1896/// Delete "nlines" lines at the cursor.
1897/// Saves the lines for undo first if "undo" is true.
1898void del_lines(linenr_T nlines, bool undo)
1899{
1900  int n;
1901  linenr_T first = curwin->w_cursor.lnum;
1902
1903  if (nlines <= 0) {
1904    return;
1905  }
1906
1907  // save the deleted lines for undo
1908  if (undo && u_savedel(first, nlines) == FAIL) {
1909    return;
1910  }
1911
1912  for (n = 0; n < nlines;) {
1913    if (curbuf->b_ml.ml_flags & ML_EMPTY) {  // nothing to delete
1914      break;
1915    }
1916
1917    ml_delete_flags(first, ML_DEL_MESSAGE);
1918    n++;
1919
1920    // If we delete the last line in the file, stop
1921    if (first > curbuf->b_ml.ml_line_count) {
1922      break;
1923    }
1924  }
1925
1926  // Correct the cursor position before calling deleted_lines_mark(), it may
1927  // trigger a callback to display the cursor.
1928  curwin->w_cursor.col = 0;
1929  check_cursor_lnum(curwin);
1930
1931  // adjust marks, mark the buffer as changed and prepare for displaying
1932  deleted_lines_mark(first, n);
1933}
1934
1935/// Returns the length in bytes of the prefix of the given string which introduces a comment.
1936///
1937/// If this string is not a comment then 0 is returned.
1938/// When "flags" is not NULL, it is set to point to the flags of the recognized comment leader.
1939/// "backward" must be true for the "O" command.
1940/// If "include_space" is set, include trailing whitespace while calculating the length.
1941int get_leader_len(char *line, char **flags, bool backward, bool include_space)
1942{
1943  int j;
1944  bool got_com = false;
1945  char part_buf[COM_MAX_LEN];         // buffer for one option part
1946  char *string;                  // pointer to comment string
1947  int middle_match_len = 0;
1948  char *saved_flags = NULL;
1949
1950  int result = 0;
1951  int i = 0;
1952  while (ascii_iswhite(line[i])) {  // leading white space is ignored
1953    i++;
1954  }
1955
1956  // Repeat to match several nested comment strings.
1957  while (line[i] != NUL) {
1958    // scan through the 'comments' option for a match
1959    bool found_one = false;
1960    for (char *list = curbuf->b_p_com; *list;) {
1961      // Get one option part into part_buf[].  Advance "list" to next
1962      // one.  Put "string" at start of string.
1963      if (!got_com && flags != NULL) {
1964        *flags = list;              // remember where flags started
1965      }
1966      char *prev_list = list;
1967      copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
1968      string = vim_strchr(part_buf, ':');
1969      if (string == NULL) {         // missing ':', ignore this part
1970        continue;
1971      }
1972      *string++ = NUL;              // isolate flags from string
1973
1974      // If we found a middle match previously, use that match when this
1975      // is not a middle or end.
1976      if (middle_match_len != 0
1977          && vim_strchr(part_buf, COM_MIDDLE) == NULL
1978          && vim_strchr(part_buf, COM_END) == NULL) {
1979        break;
1980      }
1981
1982      // When we already found a nested comment, only accept further
1983      // nested comments.
1984      if (got_com && vim_strchr(part_buf, COM_NEST) == NULL) {
1985        continue;
1986      }
1987
1988      // When 'O' flag present and using "O" command skip this one.
1989      if (backward && vim_strchr(part_buf, COM_NOBACK) != NULL) {
1990        continue;
1991      }
1992
1993      // Line contents and string must match.
1994      // When string starts with white space, must have some white space
1995      // (but the amount does not need to match, there might be a mix of
1996      // TABs and spaces).
1997      if (ascii_iswhite(string[0])) {
1998        if (i == 0 || !ascii_iswhite(line[i - 1])) {
1999          continue;            // missing white space
2000        }
2001        while (ascii_iswhite(string[0])) {
2002          string++;
2003        }
2004      }
2005      for (j = 0; string[j] != NUL && string[j] == line[i + j]; j++) {}
2006      if (string[j] != NUL) {
2007        continue;          // string doesn't match
2008      }
2009      // When 'b' flag used, there must be white space or an
2010      // end-of-line after the string in the line.
2011      if (vim_strchr(part_buf, COM_BLANK) != NULL
2012          && !ascii_iswhite(line[i + j]) && line[i + j] != NUL) {
2013        continue;
2014      }
2015
2016      // We have found a match, stop searching unless this is a middle
2017      // comment. The middle comment can be a substring of the end
2018      // comment in which case it's better to return the length of the
2019      // end comment and its flags.  Thus we keep searching with middle
2020      // and end matches and use an end match if it matches better.
2021      if (vim_strchr(part_buf, COM_MIDDLE) != NULL) {
2022        if (middle_match_len == 0) {
2023          middle_match_len = j;
2024          saved_flags = prev_list;
2025        }
2026        continue;
2027      }
2028      if (middle_match_len != 0 && j > middle_match_len) {
2029        // Use this match instead of the middle match, since it's a
2030        // longer thus better match.
2031        middle_match_len = 0;
2032      }
2033
2034      if (middle_match_len == 0) {
2035        i += j;
2036      }
2037      found_one = true;
2038      break;
2039    }
2040
2041    if (middle_match_len != 0) {
2042      // Use the previously found middle match after failing to find a
2043      // match with an end.
2044      if (!got_com && flags != NULL) {
2045        *flags = saved_flags;
2046      }
2047      i += middle_match_len;
2048      found_one = true;
2049    }
2050
2051    // No match found, stop scanning.
2052    if (!found_one) {
2053      break;
2054    }
2055
2056    result = i;
2057
2058    // Include any trailing white space.
2059    while (ascii_iswhite(line[i])) {
2060      i++;
2061    }
2062
2063    if (include_space) {
2064      result = i;
2065    }
2066
2067    // If this comment doesn't nest, stop here.
2068    got_com = true;
2069    if (vim_strchr(part_buf, COM_NEST) == NULL) {
2070      break;
2071    }
2072  }
2073  return result;
2074}
2075
2076/// Return the offset at which the last comment in line starts. If there is no
2077/// comment in the whole line, -1 is returned.
2078///
2079/// When "flags" is not null, it is set to point to the flags describing the
2080/// recognized comment leader.
2081int get_last_leader_offset(char *line, char **flags)
2082{
2083  int result = -1;
2084  int j;
2085  int lower_check_bound = 0;
2086  char *com_leader;
2087  char *com_flags;
2088  char part_buf[COM_MAX_LEN];         // buffer for one option part
2089
2090  // Repeat to match several nested comment strings.
2091  int i = (int)strlen(line);
2092  while (--i >= lower_check_bound) {
2093    // scan through the 'comments' option for a match
2094    bool found_one = false;
2095    for (char *list = curbuf->b_p_com; *list;) {
2096      char *flags_save = list;
2097
2098      // Get one option part into part_buf[].  Advance list to next one.
2099      // put string at start of string.
2100      copy_option_part(&list, part_buf, COM_MAX_LEN, ",");
2101      char *string = vim_strchr(part_buf, ':');
2102      if (string == NULL) {  // If everything is fine, this cannot actually
2103                             // happen.
2104        continue;
2105      }
2106      *string++ = NUL;          // Isolate flags from string.
2107      com_leader = string;
2108
2109      // Line contents and string must match.
2110      // When string starts with white space, must have some white space
2111      // (but the amount does not need to match, there might be a mix of
2112      // TABs and spaces).
2113      if (ascii_iswhite(string[0])) {
2114        if (i == 0 || !ascii_iswhite(line[i - 1])) {
2115          continue;
2116        }
2117        while (ascii_iswhite(*string)) {
2118          string++;
2119        }
2120      }
2121      for (j = 0; string[j] != NUL && string[j] == line[i + j]; j++) {
2122        // do nothing
2123      }
2124      if (string[j] != NUL) {
2125        continue;
2126      }
2127
2128      // When 'b' flag used, there must be white space or an
2129      // end-of-line after the string in the line.
2130      if (vim_strchr(part_buf, COM_BLANK) != NULL
2131          && !ascii_iswhite(line[i + j]) && line[i + j] != NUL) {
2132        continue;
2133      }
2134
2135      if (vim_strchr(part_buf, COM_MIDDLE) != NULL) {
2136        // For a middlepart comment, only consider it to match if
2137        // everything before the current position in the line is
2138        // whitespace.  Otherwise we would think we are inside a
2139        // comment if the middle part appears somewhere in the middle
2140        // of the line.  E.g. for C the "*" appears often.
2141        for (j = 0; j <= i && ascii_iswhite(line[j]); j++) {}
2142        if (j < i) {
2143          continue;
2144        }
2145      }
2146
2147      // We have found a match, stop searching.
2148      found_one = true;
2149
2150      if (flags) {
2151        *flags = flags_save;
2152      }
2153      com_flags = flags_save;
2154
2155      break;
2156    }
2157
2158    if (found_one) {
2159      char part_buf2[COM_MAX_LEN];            // buffer for one option part
2160
2161      result = i;
2162      // If this comment nests, continue searching.
2163      if (vim_strchr(part_buf, COM_NEST) != NULL) {
2164        continue;
2165      }
2166
2167      lower_check_bound = i;
2168
2169      // Let's verify whether the comment leader found is a substring
2170      // of other comment leaders. If it is, let's adjust the
2171      // lower_check_bound so that we make sure that we have determined
2172      // the comment leader correctly.
2173
2174      while (ascii_iswhite(*com_leader)) {
2175        com_leader++;
2176      }
2177      int len1 = (int)strlen(com_leader);
2178
2179      for (char *list = curbuf->b_p_com; *list;) {
2180        char *flags_save = list;
2181
2182        copy_option_part(&list, part_buf2, COM_MAX_LEN, ",");
2183        if (flags_save == com_flags) {
2184          continue;
2185        }
2186        char *string = vim_strchr(part_buf2, ':');
2187        string++;
2188        while (ascii_iswhite(*string)) {
2189          string++;
2190        }
2191        int len2 = (int)strlen(string);
2192        if (len2 == 0) {
2193          continue;
2194        }
2195
2196        // Now we have to verify whether string ends with a substring
2197        // beginning the com_leader.
2198        for (int off = (len2 > i ? i : len2); off > 0 && off + len1 > len2;) {
2199          off--;
2200          if (strncmp(string + off, com_leader, (size_t)(len2 - off)) == 0) {
2201            lower_check_bound = MIN(lower_check_bound, i - off);
2202          }
2203        }
2204      }
2205    }
2206  }
2207  return result;
2208}