robin/laufey

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

Justin M. KeyesMerge #41065 from justinmk/optionfunc4836ecad1f

master
35.9 KiB1116 linesraw
1// textformat.c: text formatting functions
2
3#include <stdbool.h>
4#include <stdint.h>
5#include <string.h>
6
7#include "nvim/ascii_defs.h"
8#include "nvim/buffer_defs.h"
9#include "nvim/change.h"
10#include "nvim/charset.h"
11#include "nvim/cursor.h"
12#include "nvim/drawscreen.h"
13#include "nvim/eval.h"
14#include "nvim/eval/typval.h"
15#include "nvim/eval/typval_defs.h"
16#include "nvim/eval/vars.h"
17#include "nvim/ex_cmds_defs.h"
18#include "nvim/globals.h"
19#include "nvim/indent.h"
20#include "nvim/indent_c.h"
21#include "nvim/input.h"
22#include "nvim/insert.h"
23#include "nvim/macros_defs.h"
24#include "nvim/mark.h"
25#include "nvim/mbyte.h"
26#include "nvim/memline.h"
27#include "nvim/memory.h"
28#include "nvim/message.h"
29#include "nvim/move.h"
30#include "nvim/ops.h"
31#include "nvim/option.h"
32#include "nvim/option_defs.h"
33#include "nvim/option_vars.h"
34#include "nvim/os/input.h"
35#include "nvim/pos_defs.h"
36#include "nvim/search.h"
37#include "nvim/state_defs.h"
38#include "nvim/strings.h"
39#include "nvim/textformat.h"
40#include "nvim/textobject.h"
41#include "nvim/ui.h"
42#include "nvim/undo.h"
43#include "nvim/vim_defs.h"
44#include "nvim/window.h"
45
46#include "textformat.c.generated.h"
47
48static bool did_add_space = false;  ///< auto_format() added an extra space
49                                    ///< under the cursor
50
51#define WHITECHAR(cc) (ascii_iswhite(cc) \
52                       && !utf_iscomposing_first(utf_ptr2char((char *)get_cursor_pos_ptr() + 1)))
53
54/// Return true if format option 'x' is in effect.
55/// Take care of no formatting when 'paste' is set.
56bool has_format_option(int x)
57  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
58{
59  if (p_paste) {
60    return false;
61  }
62  return vim_strchr(curbuf->b_p_fo, x) != NULL;
63}
64
65/// Format text at the current insert position.
66///
67/// If the INSCHAR_COM_LIST flag is present, then the value of second_indent
68/// will be the comment leader length sent to open_line().
69///
70/// @param c  character to be inserted (can be NUL)
71void internal_format(int textwidth, int second_indent, int flags, bool format_only, int c)
72{
73  int cc;
74  char save_char = NUL;
75  bool haveto_redraw = false;
76  const bool fo_ins_blank = has_format_option(kFoInsBlank);
77  const bool fo_multibyte = has_format_option(kFoMbyteBreak);
78  const bool fo_rigor_tw = has_format_option(kFoRigorousTw);
79  const bool fo_white_par = has_format_option(kFoWhitePar);
80  bool first_line = true;
81  colnr_T leader_len;
82  bool no_leader = false;
83  bool do_comments = (flags & INSCHAR_DO_COM);
84  int has_lbr = curwin->w_p_lbr;
85
86  // make sure win_charsize() counts correctly
87  curwin->w_p_lbr = false;
88
89  // When 'ai' is off we don't want a space under the cursor to be
90  // deleted.  Replace it with an 'x' temporarily.
91  if (!curbuf->b_p_ai && !(State & VREPLACE_FLAG)) {
92    cc = gchar_cursor();
93    if (ascii_iswhite(cc)) {
94      save_char = (char)cc;
95      pchar_cursor('x');
96    }
97  }
98
99  // Repeat breaking lines, until the current line is not too long.
100  while (!got_int) {
101    int startcol;                       // Cursor column at entry
102    int wantcol;                        // column at textwidth border
103    int foundcol;                       // column for start of spaces
104    int end_foundcol = 0;               // column for start of word
105    int orig_col = 0;
106    char *saved_text = NULL;
107    colnr_T col;
108    bool did_do_comment = false;
109
110    colnr_T virtcol = get_nolist_virtcol() + char2cells(c != NUL ? c : gchar_cursor());
111    if (virtcol <= (colnr_T)textwidth) {
112      break;
113    }
114
115    if (no_leader) {
116      do_comments = false;
117    } else if (!(flags & INSCHAR_FORMAT)
118               && has_format_option(kFoWrapComs)) {
119      do_comments = true;
120    }
121
122    // Don't break until after the comment leader
123    if (do_comments) {
124      char *line = get_cursor_line_ptr();
125      leader_len = get_leader_len(line, NULL, false, true);
126      if (leader_len == 0 && curbuf->b_p_cin) {
127        // Check for a line comment after code.
128        int comment_start = check_linecomment(line);
129        if (comment_start != MAXCOL) {
130          leader_len = get_leader_len(line + comment_start, NULL, false, true);
131          if (leader_len != 0) {
132            leader_len += comment_start;
133          }
134        }
135      }
136    } else {
137      leader_len = 0;
138    }
139
140    // If the line doesn't start with a comment leader, then don't
141    // start one in a following broken line.  Avoids that a %word
142    // moved to the start of the next line causes all following lines
143    // to start with %.
144    if (leader_len == 0) {
145      no_leader = true;
146    }
147    if (!(flags & INSCHAR_FORMAT)
148        && leader_len == 0
149        && !has_format_option(kFoWrap)) {
150      break;
151    }
152    if ((startcol = curwin->w_cursor.col) == 0) {
153      break;
154    }
155
156    // find column of textwidth border
157    coladvance(curwin, (colnr_T)textwidth);
158    wantcol = curwin->w_cursor.col;
159
160    curwin->w_cursor.col = startcol;
161    foundcol = 0;
162    int skip_pos = 0;
163
164    // Find position to break at.
165    // Stop at first entered white when 'formatoptions' has 'v'
166    while ((!fo_ins_blank && !has_format_option(kFoInsVi))
167           || (flags & INSCHAR_FORMAT)
168           || curwin->w_cursor.lnum != Ins.start.lnum
169           || curwin->w_cursor.col >= Ins.start.col) {
170      if (curwin->w_cursor.col == startcol && c != NUL) {
171        cc = c;
172      } else {
173        cc = gchar_cursor();
174      }
175      if (WHITECHAR(cc)) {
176        // remember position of blank just before text
177        colnr_T end_col = curwin->w_cursor.col;
178
179        // find start of sequence of blanks
180        int wcc = 0;  // counter for whitespace chars
181        while (curwin->w_cursor.col > 0 && WHITECHAR(cc)) {
182          dec_cursor();
183          cc = gchar_cursor();
184
185          // Increment count of how many whitespace chars in this
186          // group; we only need to know if it's more than one.
187          if (wcc < 2) {
188            wcc++;
189          }
190        }
191        if (curwin->w_cursor.col == 0 && WHITECHAR(cc)) {
192          break;                        // only spaces in front of text
193        }
194
195        // Don't break after a period when 'formatoptions' has 'p' and
196        // there are less than two spaces.
197        if (has_format_option(kFoPeriodAbbr) && cc == '.' && wcc < 2) {
198          continue;
199        }
200
201        // Don't break until after the comment leader
202        if (curwin->w_cursor.col < leader_len) {
203          break;
204        }
205
206        if (has_format_option(kFoOneLetter)) {
207          // do not break after one-letter words
208          if (curwin->w_cursor.col == 0) {
209            break;              // one-letter word at begin
210          }
211          // do not break "#a b" when 'tw' is 2
212          if (curwin->w_cursor.col <= leader_len) {
213            break;
214          }
215          col = curwin->w_cursor.col;
216          dec_cursor();
217          cc = gchar_cursor();
218
219          if (WHITECHAR(cc)) {
220            continue;                   // one-letter, continue
221          }
222          curwin->w_cursor.col = col;
223        }
224
225        inc_cursor();
226
227        end_foundcol = end_col + 1;
228        foundcol = curwin->w_cursor.col;
229        if (curwin->w_cursor.col <= (colnr_T)wantcol) {
230          break;
231        }
232      } else if ((cc >= 0x100 || !utf_allow_break_before(cc)) && fo_multibyte) {
233        int ncc;
234        bool allow_break;
235
236        // Break after or before a multi-byte character.
237        if (curwin->w_cursor.col != startcol) {
238          // Don't break until after the comment leader
239          if (curwin->w_cursor.col < leader_len) {
240            break;
241          }
242          col = curwin->w_cursor.col;
243          inc_cursor();
244          ncc = gchar_cursor();
245          allow_break = utf_allow_break(cc, ncc);
246
247          // If we have already checked this position, skip!
248          if (curwin->w_cursor.col != skip_pos && allow_break) {
249            foundcol = curwin->w_cursor.col;
250            end_foundcol = foundcol;
251            if (curwin->w_cursor.col <= (colnr_T)wantcol) {
252              break;
253            }
254          }
255          curwin->w_cursor.col = col;
256        }
257
258        if (curwin->w_cursor.col == 0) {
259          break;
260        }
261
262        ncc = cc;
263        col = curwin->w_cursor.col;
264
265        dec_cursor();
266        cc = gchar_cursor();
267
268        if (WHITECHAR(cc)) {
269          continue;                     // break with space
270        }
271        // Don't break until after the comment leader.
272        if (curwin->w_cursor.col < leader_len) {
273          break;
274        }
275
276        curwin->w_cursor.col = col;
277        skip_pos = curwin->w_cursor.col;
278
279        allow_break = utf_allow_break(cc, ncc);
280
281        // Must handle this to respect line break prohibition.
282        if (allow_break) {
283          foundcol = curwin->w_cursor.col;
284          end_foundcol = foundcol;
285        }
286        if (curwin->w_cursor.col <= (colnr_T)wantcol) {
287          const bool ncc_allow_break = utf_allow_break_before(ncc);
288
289          if (allow_break) {
290            break;
291          }
292          if (!ncc_allow_break && !fo_rigor_tw) {
293            // Enable at most 1 punct hang outside of textwidth.
294            if (curwin->w_cursor.col == startcol) {
295              // We are inserting a non-breakable char, postpone
296              // line break check to next insert.
297              end_foundcol = foundcol = 0;
298              break;
299            }
300
301            // Neither cc nor ncc is NUL if we are here, so
302            // it's safe to inc_cursor.
303            col = curwin->w_cursor.col;
304
305            inc_cursor();
306            cc = ncc;
307            ncc = gchar_cursor();
308            // handle insert
309            ncc = (ncc != NUL) ? ncc : c;
310
311            allow_break = utf_allow_break(cc, ncc);
312
313            if (allow_break) {
314              // Break only when we are not at end of line.
315              end_foundcol = foundcol = ncc == NUL ? 0 : curwin->w_cursor.col;
316              break;
317            }
318            curwin->w_cursor.col = col;
319          }
320        }
321      }
322      if (curwin->w_cursor.col == 0) {
323        break;
324      }
325      dec_cursor();
326    }
327
328    if (foundcol == 0) {                // no spaces, cannot break line
329      curwin->w_cursor.col = startcol;
330      break;
331    }
332
333    // Going to break the line, remove any "$" now.
334    undisplay_dollar();
335
336    // Offset between cursor position and line break is used by replace
337    // stack functions.  MODE_VREPLACE does not use this, and backspaces
338    // over the text instead.
339    if (State & VREPLACE_FLAG) {
340      orig_col = startcol;              // Will start backspacing from here
341    } else {
342      replace_offset = startcol - end_foundcol;
343    }
344
345    // adjust startcol for spaces that will be deleted and
346    // characters that will remain on top line
347    curwin->w_cursor.col = foundcol;
348    while ((cc = gchar_cursor(), WHITECHAR(cc))
349           && (!fo_white_par || curwin->w_cursor.col < startcol)) {
350      inc_cursor();
351    }
352    startcol -= curwin->w_cursor.col;
353    startcol = MAX(startcol, 0);
354
355    if (State & VREPLACE_FLAG) {
356      // In MODE_VREPLACE state, we will backspace over the text to be
357      // wrapped, so save a copy now to put on the next line.
358      saved_text = xstrnsave(get_cursor_pos_ptr(), (size_t)get_cursor_pos_len());
359      curwin->w_cursor.col = orig_col;
360      saved_text[startcol] = NUL;
361
362      // Backspace over characters that will move to the next line
363      if (!fo_white_par) {
364        backspace_until_column(foundcol);
365      }
366    } else {
367      // put cursor after pos. to break line
368      if (!fo_white_par) {
369        curwin->w_cursor.col = foundcol;
370      }
371    }
372
373    // Split the line just before the margin.
374    // Only insert/delete lines, but don't really redraw the window.
375    open_line(FORWARD, OPENLINE_DELSPACES + OPENLINE_MARKFIX
376              + (fo_white_par ? OPENLINE_KEEPTRAIL : 0)
377              + (do_comments ? OPENLINE_DO_COM : 0)
378              + OPENLINE_FORMAT
379              + ((flags & INSCHAR_COM_LIST) ? OPENLINE_COM_LIST : 0),
380              ((flags & INSCHAR_COM_LIST) ? second_indent : old_indent),
381              &did_do_comment);
382    if (!(flags & INSCHAR_COM_LIST)) {
383      old_indent = 0;
384    }
385
386    // If a comment leader was inserted, may also do this on a following
387    // line.
388    if (did_do_comment) {
389      no_leader = false;
390    }
391
392    replace_offset = 0;
393    if (first_line) {
394      if (!(flags & INSCHAR_COM_LIST)) {
395        // This section is for auto-wrap of numeric lists.  When not
396        // in insert mode (i.e. format_lines()), the INSCHAR_COM_LIST
397        // flag will be set and open_line() will handle it (as seen
398        // above).  The code here (and in get_number_indent()) will
399        // recognize comments if needed...
400        if (second_indent < 0 && has_format_option(kFoQNumber)) {
401          second_indent = get_number_indent(curwin->w_cursor.lnum - 1);
402        }
403        if (second_indent >= 0) {
404          if (State & VREPLACE_FLAG) {
405            change_indent(INDENT_SET, second_indent, false, true);
406          } else if (leader_len > 0 && second_indent - leader_len > 0) {
407            int padding = second_indent - leader_len;
408
409            // We started at the first_line of a numbered list
410            // that has a comment.  the open_line() function has
411            // inserted the proper comment leader and positioned
412            // the cursor at the end of the split line.  Now we
413            // add the additional whitespace needed after the
414            // comment leader for the numbered list.
415            for (int i = 0; i < padding; i++) {
416              ins_str(S_LEN(" "));
417            }
418          } else {
419            set_indent(second_indent, SIN_CHANGED);
420          }
421        }
422      }
423      first_line = false;
424    }
425
426    if (State & VREPLACE_FLAG) {
427      // In MODE_VREPLACE state we have backspaced over the text to be
428      // moved, now we re-insert it into the new line.
429      ins_bytes(saved_text);
430      xfree(saved_text);
431    } else {
432      // Check if cursor is not past the NUL off the line, cindent
433      // may have added or removed indent.
434      curwin->w_cursor.col += startcol;
435      colnr_T len = get_cursor_line_len();
436      curwin->w_cursor.col = MIN(curwin->w_cursor.col, len);
437    }
438
439    haveto_redraw = true;
440    set_can_cindent(true);
441    // moved the cursor, don't autoindent or cindent now
442    Ins.did_ai = false;
443    Ins.did_si = false;
444    Ins.can_si = false;
445    Ins.can_si_back = false;
446    line_breakcheck();
447  }
448
449  if (save_char != NUL) {               // put back space after cursor
450    pchar_cursor(save_char);
451  }
452
453  curwin->w_p_lbr = has_lbr;
454
455  if (!format_only && haveto_redraw) {
456    update_topline(curwin);
457    redraw_curbuf_later(UPD_VALID);
458  }
459}
460
461/// Blank lines, and lines containing only the comment leader, are left
462/// untouched by the formatting.  The function returns true in this
463/// case.  It also returns true when a line starts with the end of a comment
464/// ('e' in comment flags), so that this line is skipped, and not joined to the
465/// previous line.  A new paragraph starts after a blank line, or when the
466/// comment leader changes.
467static int fmt_check_par(linenr_T lnum, int *leader_len, char **leader_flags, bool do_comments)
468{
469  char *flags = NULL;        // init for GCC
470  char *ptr = ml_get(lnum);
471  if (do_comments) {
472    *leader_len = get_leader_len(ptr, leader_flags, false, true);
473  } else {
474    *leader_len = 0;
475  }
476
477  if (*leader_len > 0) {
478    // Search for 'e' flag in comment leader flags.
479    flags = *leader_flags;
480    while (*flags && *flags != ':' && *flags != COM_END) {
481      flags++;
482    }
483  }
484
485  return *skipwhite(ptr + *leader_len) == NUL
486         || (*leader_len > 0 && *flags == COM_END)
487         || startPS(lnum, NUL, false);
488}
489
490/// @return  true if line "lnum" ends in a white character.
491static bool ends_in_white(linenr_T lnum)
492{
493  char *s = ml_get(lnum);
494
495  if (*s == NUL) {
496    return false;
497  }
498  colnr_T l = ml_get_len(lnum) - 1;
499  return ascii_iswhite((uint8_t)s[l]);
500}
501
502/// @return  true if the two comment leaders given are the same.
503///
504/// @param lnum  The first line.  White-space is ignored.
505///
506/// @note the whole of 'leader1' must match 'leader2_len' characters from 'leader2'.
507static bool same_leader(linenr_T lnum, int leader1_len, char *leader1_flags, int leader2_len,
508                        char *leader2_flags)
509{
510  int idx1 = 0;
511  int idx2 = 0;
512
513  if (leader1_len == 0) {
514    return leader2_len == 0;
515  }
516
517  // If first leader has 'f' flag, the lines can be joined only if the
518  // second line does not have a leader.
519  // If first leader has 'e' flag, the lines can never be joined.
520  // If first leader has 's' flag, the lines can only be joined if there is
521  // some text after it and the second line has the 'm' flag.
522  if (leader1_flags != NULL) {
523    for (char *p = leader1_flags; *p && *p != ':'; p++) {
524      if (*p == COM_FIRST) {
525        return leader2_len == 0;
526      }
527      if (*p == COM_END) {
528        return false;
529      }
530      if (*p == COM_START) {
531        int line_len = ml_get_len(lnum);
532        if (line_len <= leader1_len) {
533          return false;
534        }
535        if (leader2_flags == NULL || leader2_len == 0) {
536          return false;
537        }
538        for (p = leader2_flags; *p && *p != ':'; p++) {
539          if (*p == COM_MIDDLE) {
540            return true;
541          }
542        }
543        return false;
544      }
545    }
546  }
547
548  // Get current line and next line, compare the leaders.
549  // The first line has to be saved, only one line can be locked at a time.
550  char *line1 = xstrnsave(ml_get(lnum), (size_t)ml_get_len(lnum));
551  for (idx1 = 0; ascii_iswhite(line1[idx1]); idx1++) {}
552  char *line2 = ml_get(lnum + 1);
553  for (idx2 = 0; idx2 < leader2_len; idx2++) {
554    if (!ascii_iswhite(line2[idx2])) {
555      if (line1[idx1++] != line2[idx2]) {
556        break;
557      }
558    } else {
559      while (ascii_iswhite(line1[idx1])) {
560        idx1++;
561      }
562    }
563  }
564  xfree(line1);
565
566  return idx2 == leader2_len && idx1 == leader1_len;
567}
568
569/// Used for auto-formatting.
570///
571/// @return  true when a paragraph starts in line "lnum".
572///          false when the previous line is in the same paragraph.
573static bool paragraph_start(linenr_T lnum)
574{
575  int leader_len = 0;                // leader len of current line
576  char *leader_flags = NULL;         // flags for leader of current line
577  int next_leader_len = 0;           // leader len of next line
578  char *next_leader_flags = NULL;    // flags for leader of next line
579
580  if (lnum <= 1) {
581    return true;                // start of the file
582  }
583  char *p = ml_get(lnum - 1);
584  if (*p == NUL) {
585    return true;                // after empty line
586  }
587  const bool do_comments = has_format_option(kFoQComs);  // format comments
588  if (fmt_check_par(lnum - 1, &leader_len, &leader_flags, do_comments)) {
589    return true;  // after non-paragraph line
590  }
591
592  if (fmt_check_par(lnum, &next_leader_len, &next_leader_flags, do_comments)) {
593    return true;  // "lnum" is not a paragraph line
594  }
595
596  if (has_format_option(kFoWhitePar) && !ends_in_white(lnum - 1)) {
597    return true;                // missing trailing space in previous line.
598  }
599  if (has_format_option(kFoQNumber) && (get_number_indent(lnum) > 0)) {
600    return true;                // numbered item starts in "lnum".
601  }
602  if (!same_leader(lnum - 1, leader_len, leader_flags,
603                   next_leader_len, next_leader_flags)) {
604    return true;                // change of comment leader.
605  }
606  return false;
607}
608
609/// Called after inserting or deleting text: When 'formatoptions' includes the
610/// 'a' flag format from the current line until the end of the paragraph.
611/// Keep the cursor at the same position relative to the text.
612/// The caller must have saved the cursor line for undo, following ones will be
613/// saved here.
614///
615/// @param trailblank  when true also format with trailing blank
616/// @param prev_line   may start in previous line
617void auto_format(bool trailblank, bool prev_line)
618{
619  if (!has_format_option(kFoAuto)) {
620    return;
621  }
622
623  pos_T pos = curwin->w_cursor;
624  char *old = get_cursor_line_ptr();
625
626  // may remove added space
627  check_auto_format(false);
628
629  // Don't format in Insert mode when the cursor is on a trailing blank, the
630  // user might insert normal text next.  Also skip formatting when "1" is
631  // in 'formatoptions' and there is a single character before the cursor.
632  // Otherwise the line would be broken and when typing another non-white
633  // next they are not joined back together.
634  bool wasatend = (pos.col == get_cursor_line_len());
635  if (*old != NUL && !trailblank && wasatend) {
636    dec_cursor();
637    int cc = gchar_cursor();
638    if (!WHITECHAR(cc) && curwin->w_cursor.col > 0
639        && has_format_option(kFoOneLetter)) {
640      dec_cursor();
641    }
642    cc = gchar_cursor();
643    if (WHITECHAR(cc)) {
644      curwin->w_cursor = pos;
645      return;
646    }
647    curwin->w_cursor = pos;
648  }
649
650  // Also skip formatting when the user just typed whitespace in the
651  // middle of the line.  Reformatting would join all paragraph lines and
652  // re-wrap, consuming the space at the line break point via
653  // OPENLINE_DELSPACES.  By deferring, the next non-whitespace character
654  // will be inserted adjacent to the space, keeping it protected from
655  // being consumed at a line break.  auto_format() will then reformat
656  // properly on the next keystroke.
657  if (*old != NUL && !trailblank && !wasatend && pos.col > 0
658      && (State & MODE_INSERT)) {
659    char *line = get_cursor_line_ptr();
660    if (WHITECHAR(line[pos.col - 1])) {
661      curwin->w_cursor = pos;
662      return;
663    }
664  }
665
666  // With the 'c' flag in 'formatoptions' and 't' missing: only format
667  // comments.
668  if (has_format_option(kFoWrapComs) && !has_format_option(kFoWrap)
669      && get_leader_len(old, NULL, false, true) == 0) {
670    return;
671  }
672
673  // May start formatting in a previous line, so that after "x" a word is
674  // moved to the previous line if it fits there now.  Only when this is not
675  // the start of a paragraph.
676  if (prev_line && !paragraph_start(curwin->w_cursor.lnum)) {
677    curwin->w_cursor.lnum--;
678    if (u_save_cursor() == FAIL) {
679      return;
680    }
681  }
682
683  // Do the formatting and restore the cursor position.  "saved_cursor" will
684  // be adjusted for the text formatting.
685  saved_cursor = pos;
686  format_lines(-1, false);
687  curwin->w_cursor = saved_cursor;
688  saved_cursor.lnum = 0;
689
690  if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) {
691    // "cannot happen"
692    curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count;
693    coladvance(curwin, MAXCOL);
694  } else {
695    check_cursor_col(curwin);
696  }
697
698  // Insert mode: If the cursor is now after the end of the line while it
699  // previously wasn't, the line was broken.  Because of the rule above we
700  // need to add a space when 'w' is in 'formatoptions' to keep a paragraph
701  // formatted.
702  if (!wasatend && has_format_option(kFoWhitePar)) {
703    char *linep = get_cursor_line_ptr();
704    colnr_T len = get_cursor_line_len();
705    if (curwin->w_cursor.col == len) {
706      char *plinep = xstrnsave(linep, (size_t)len + 2);
707      plinep[len] = ' ';
708      plinep[len + 1] = NUL;
709      ml_replace(curwin->w_cursor.lnum, plinep, false);
710      // remove the space later
711      did_add_space = true;
712    } else {
713      // may remove added space
714      check_auto_format(false);
715    }
716  }
717
718  check_cursor(curwin);
719}
720
721/// When an extra space was added to continue a paragraph for auto-formatting,
722/// delete it now.  The space must be under the cursor, just after the insert
723/// position.
724///
725/// @param end_insert  true when ending Insert mode
726void check_auto_format(bool end_insert)
727{
728  if (!did_add_space) {
729    return;
730  }
731
732  int cc = gchar_cursor();
733  if (!WHITECHAR(cc)) {
734    // Somehow the space was removed already.
735    did_add_space = false;
736  } else {
737    int c = ' ';
738    if (!end_insert) {
739      inc_cursor();
740      c = gchar_cursor();
741      dec_cursor();
742    }
743    if (c != NUL) {
744      // The space is no longer at the end of the line, delete it.
745      del_char(false);
746      did_add_space = false;
747    }
748  }
749}
750
751/// Find out textwidth to be used for formatting:
752///      if 'textwidth' option is set, use it
753///      else if 'wrapmargin' option is set, use curwin->w_view_width-'wrapmargin'
754///      if invalid value, use 0.
755///      Set default to window width (maximum 79) for "gq" operator.
756///
757/// @param ff  force formatting (for "gq" command)
758int comp_textwidth(bool ff)
759{
760  int textwidth = (int)curbuf->b_p_tw;
761  if (textwidth == 0 && curbuf->b_p_wm) {
762    // The width is the window width minus 'wrapmargin' minus all the
763    // things that add to the margin.
764    textwidth = curwin->w_view_width - (int)curbuf->b_p_wm;
765    textwidth -= win_fdccol_count(curwin);
766    textwidth -= curwin->w_scwidth;
767
768    if (curwin->w_p_nu || curwin->w_p_rnu) {
769      textwidth -= 8;
770    }
771  }
772  textwidth = MAX(textwidth, 0);
773  if (ff && textwidth == 0) {
774    textwidth = MIN(curwin->w_view_width - 1, 79);
775  }
776  return textwidth;
777}
778
779/// Implementation of the format operator 'gq'.
780///
781/// @param keep_cursor  keep cursor on same text char
782void op_format(oparg_T *oap, bool keep_cursor)
783{
784  linenr_T old_line_count = curbuf->b_ml.ml_line_count;
785
786  // Place the cursor where the "gq" or "gw" command was given, so that "u"
787  // can put it back there.
788  curwin->w_cursor = oap->cursor_start;
789
790  if (u_save((linenr_T)(oap->start.lnum - 1),
791             (linenr_T)(oap->end.lnum + 1)) == FAIL) {
792    return;
793  }
794  curwin->w_cursor = oap->start;
795
796  if (oap->is_VIsual) {
797    // When there is no change: need to remove the Visual selection
798    redraw_curbuf_later(UPD_INVERTED);
799  }
800
801  if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) {
802    // Set '[ mark at the start of the formatted area
803    curbuf->b_op_start = oap->start;
804  }
805
806  // For "gw" remember the cursor position and put it back below (adjusted
807  // for joined and split lines).
808  if (keep_cursor) {
809    saved_cursor = oap->cursor_start;
810  }
811
812  format_lines(oap->line_count, keep_cursor);
813
814  // Leave the cursor at the first non-blank of the last formatted line.
815  // If the cursor was moved one line back (e.g. with "Q}") go to the next
816  // line, so "." will do the next lines.
817  if (oap->end_adjusted && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count) {
818    curwin->w_cursor.lnum++;
819  }
820  beginline(BL_WHITE | BL_FIX);
821  old_line_count = curbuf->b_ml.ml_line_count - old_line_count;
822  msgmore(old_line_count);
823
824  if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) {
825    // put '] mark on the end of the formatted area
826    curbuf->b_op_end = curwin->w_cursor;
827  }
828
829  if (keep_cursor) {
830    curwin->w_cursor = saved_cursor;
831    saved_cursor.lnum = 0;
832
833    // formatting may have made the cursor position invalid
834    check_cursor(curwin);
835  }
836
837  if (oap->is_VIsual) {
838    FOR_ALL_WINDOWS_IN_TAB(wp, curtab) {
839      if (wp->w_old_cursor_lnum != 0) {
840        // When lines have been inserted or deleted, adjust the end of
841        // the Visual area to be redrawn.
842        if (wp->w_old_cursor_lnum > wp->w_old_visual_lnum) {
843          wp->w_old_cursor_lnum += old_line_count;
844        } else {
845          wp->w_old_visual_lnum += old_line_count;
846        }
847      }
848    }
849  }
850}
851
852/// Implementation of the format operator 'gq' for when using 'formatexpr'.
853void op_formatexpr(oparg_T *oap)
854{
855  if (oap->is_VIsual) {
856    // When there is no change: need to remove the Visual selection
857    redraw_curbuf_later(UPD_INVERTED);
858  }
859
860  if (fex_format(oap->start.lnum, oap->line_count, NUL) != 0) {
861    // As documented: when 'formatexpr' returns non-zero fall back to
862    // internal formatting.
863    op_format(oap, false);
864  }
865}
866
867/// @param c  character to be inserted
868int fex_format(linenr_T lnum, long count, int c)
869{
870  bool use_sandbox = was_set_insecurely(curwin, kOptFormatexpr, OPT_LOCAL);
871  const sctx_T save_sctx = current_sctx;
872
873  // Set v:lnum to the first line number and v:count to the number of lines.
874  // Set v:char to the character to be inserted (can be NUL).
875  set_vim_var_nr(VV_LNUM, (varnumber_T)lnum);
876  set_vim_var_nr(VV_COUNT, (varnumber_T)count);
877  set_vim_var_char(c);
878
879  current_sctx = curbuf->b_p_script_ctx[kBufOptFormatexpr];
880
881  // 'formatexpr' may modify the buffer, so it runs without textlock.
882  int r = eval_expr_option_number(&curbuf->b_p_fex, use_sandbox);
883
884  set_vim_var_string(VV_CHAR, NULL, -1);
885  current_sctx = save_sctx;
886
887  return r;
888}
889
890/// @param line_count  number of lines to format, starting at the cursor position.
891///                    when negative, format until the end of the paragraph.
892///
893/// Lines after the cursor line are saved for undo, caller must have saved the
894/// first line.
895///
896/// @param avoid_fex  don't use 'formatexpr'
897void format_lines(linenr_T line_count, bool avoid_fex)
898{
899  bool is_not_par;                  // current line not part of parag.
900  bool next_is_not_par;             // next line not part of paragraph
901  bool is_end_par;                  // at end of paragraph
902  bool prev_is_end_par = false;     // prev. line not part of parag.
903  bool next_is_start_par = false;
904  int leader_len = 0;               // leader len of current line
905  int next_leader_len;              // leader len of next line
906  char *leader_flags = NULL;        // flags for leader of current line
907  char *next_leader_flags = NULL;   // flags for leader of next line
908  bool advance = true;
909  int second_indent = -1;           // indent for second line (comment aware)
910  bool first_par_line = true;
911  int smd_save;
912  long count;
913  bool need_set_indent = true;      // set indent of next paragraph
914  linenr_T first_line = curwin->w_cursor.lnum;
915  bool force_format = false;
916  const int old_State = State;
917
918  // length of a line to force formatting: 3 * 'tw'
919  const int max_len = comp_textwidth(true) * 3;
920
921  // check for 'q', '2', 'n' and 'w' in 'formatoptions'
922  const bool do_comments = has_format_option(kFoQComs);  // format comments
923  int do_comments_list = 0;  // format comments with 'n' or '2'
924  const bool do_second_indent = has_format_option(kFoQSecond);
925  const bool do_number_indent = has_format_option(kFoQNumber);
926  const bool do_trail_white = has_format_option(kFoWhitePar);
927
928  // Get info about the previous and current line.
929  if (curwin->w_cursor.lnum > 1) {
930    is_not_par = fmt_check_par(curwin->w_cursor.lnum - 1,
931                               &leader_len, &leader_flags, do_comments);
932  } else {
933    is_not_par = true;
934  }
935  next_is_not_par = fmt_check_par(curwin->w_cursor.lnum,
936                                  &next_leader_len, &next_leader_flags, do_comments);
937  is_end_par = (is_not_par || next_is_not_par);
938  if (!is_end_par && do_trail_white) {
939    is_end_par = !ends_in_white(curwin->w_cursor.lnum - 1);
940  }
941
942  curwin->w_cursor.lnum--;
943  for (count = line_count; count != 0 && !got_int; count--) {
944    // Advance to next paragraph.
945    if (advance) {
946      curwin->w_cursor.lnum++;
947      prev_is_end_par = is_end_par;
948      is_not_par = next_is_not_par;
949      leader_len = next_leader_len;
950      leader_flags = next_leader_flags;
951    }
952
953    // The last line to be formatted.
954    if (count == 1 || curwin->w_cursor.lnum == curbuf->b_ml.ml_line_count) {
955      next_is_not_par = true;
956      next_leader_len = 0;
957      next_leader_flags = NULL;
958    } else {
959      next_is_not_par = fmt_check_par(curwin->w_cursor.lnum + 1,
960                                      &next_leader_len, &next_leader_flags, do_comments);
961      if (do_number_indent) {
962        next_is_start_par =
963          (get_number_indent(curwin->w_cursor.lnum + 1) > 0);
964      }
965    }
966    advance = true;
967    is_end_par = (is_not_par || next_is_not_par || next_is_start_par);
968    if (!is_end_par && do_trail_white) {
969      is_end_par = !ends_in_white(curwin->w_cursor.lnum);
970    }
971
972    // Skip lines that are not in a paragraph.
973    if (is_not_par) {
974      if (line_count < 0) {
975        break;
976      }
977    } else {
978      // For the first line of a paragraph, check indent of second line.
979      // Don't do this for comments and empty lines.
980      if (first_par_line
981          && (do_second_indent || do_number_indent)
982          && prev_is_end_par
983          && curwin->w_cursor.lnum < curbuf->b_ml.ml_line_count) {
984        if (do_second_indent && !LINEEMPTY(curwin->w_cursor.lnum + 1)) {
985          if (leader_len == 0 && next_leader_len == 0) {
986            // no comment found
987            second_indent =
988              get_indent_lnum(curwin->w_cursor.lnum + 1);
989          } else {
990            second_indent = next_leader_len;
991            do_comments_list = 1;
992          }
993        } else if (do_number_indent) {
994          if (leader_len == 0 && next_leader_len == 0) {
995            // no comment found
996            second_indent =
997              get_number_indent(curwin->w_cursor.lnum);
998          } else {
999            // get_number_indent() is now "comment aware"...
1000            second_indent =
1001              get_number_indent(curwin->w_cursor.lnum);
1002            do_comments_list = 1;
1003          }
1004        }
1005      }
1006
1007      // When the comment leader changes, it's the end of the paragraph.
1008      if (curwin->w_cursor.lnum >= curbuf->b_ml.ml_line_count
1009          || !same_leader(curwin->w_cursor.lnum,
1010                          leader_len, leader_flags,
1011                          next_leader_len,
1012                          next_leader_flags)) {
1013        // Special case: If the next line starts with a line comment
1014        // and this line has a line comment after some text, the
1015        // paragraph doesn't really end.
1016        if (next_leader_flags == NULL
1017            || strncmp(next_leader_flags, "://", 3) != 0
1018            || check_linecomment(get_cursor_line_ptr()) == MAXCOL) {
1019          is_end_par = true;
1020        }
1021      }
1022
1023      // If we have got to the end of a paragraph, or the line is
1024      // getting long, format it.
1025      if (is_end_par || force_format) {
1026        if (need_set_indent) {
1027          int indent = 0;  // amount of indent needed
1028
1029          // Replace indent in first line of a paragraph with minimal
1030          // number of tabs and spaces, according to current options.
1031          // For the very first formatted line keep the current
1032          // indent.
1033          if (curwin->w_cursor.lnum == first_line) {
1034            indent = get_indent();
1035          } else if (curbuf->b_p_lisp) {
1036            indent = get_lisp_indent();
1037          } else {
1038            if (cindent_on()) {
1039              indent = curbuf->b_p_inde.type != kCallbackNone ? get_expr_indent() : get_c_indent();
1040            } else {
1041              indent = get_indent();
1042            }
1043          }
1044          set_indent(indent, SIN_CHANGED);
1045        }
1046
1047        // put cursor on last non-space
1048        State = MODE_NORMAL;  // don't go past end-of-line
1049        coladvance(curwin, MAXCOL);
1050        while (curwin->w_cursor.col && ascii_isspace(gchar_cursor())) {
1051          dec_cursor();
1052        }
1053
1054        // do the formatting, without 'showmode'
1055        State = MODE_INSERT;         // for open_line()
1056        smd_save = p_smd;
1057        p_smd = false;
1058
1059        insertchar(NUL, INSCHAR_FORMAT
1060                   + (do_comments ? INSCHAR_DO_COM : 0)
1061                   + (do_comments && do_comments_list ? INSCHAR_COM_LIST : 0)
1062                   + (avoid_fex ? INSCHAR_NO_FEX : 0), second_indent);
1063
1064        State = old_State;
1065        p_smd = smd_save;
1066        // Cursor shape may have been updated (e.g. by :normal) in insertchar(),
1067        // so it needs to be updated here.
1068        ui_cursor_shape();
1069
1070        second_indent = -1;
1071        // at end of par.: need to set indent of next par.
1072        need_set_indent = is_end_par;
1073        if (is_end_par) {
1074          // When called with a negative line count, break at the
1075          // end of the paragraph.
1076          if (line_count < 0) {
1077            break;
1078          }
1079          first_par_line = true;
1080        }
1081        force_format = false;
1082      }
1083
1084      // When still in same paragraph, join the lines together.  But
1085      // first delete the leader from the second line.
1086      if (!is_end_par) {
1087        advance = false;
1088        curwin->w_cursor.lnum++;
1089        curwin->w_cursor.col = 0;
1090        if (line_count < 0 && u_save_cursor() == FAIL) {
1091          break;
1092        }
1093        if (next_leader_len > 0) {
1094          del_bytes(next_leader_len, false, false);
1095          mark_col_adjust(curwin->w_cursor.lnum, 0, 0, -next_leader_len, 0);
1096        } else if (second_indent > 0) {   // the "leader" for kFoQSecond
1097          int indent = (int)getwhitecols_curline();
1098
1099          if (indent > 0) {
1100            del_bytes(indent, false, false);
1101            mark_col_adjust(curwin->w_cursor.lnum, 0, 0, -indent, 0);
1102          }
1103        }
1104        curwin->w_cursor.lnum--;
1105        if (do_join(2, true, false, false, false) == FAIL) {
1106          beep_flush();
1107          break;
1108        }
1109        first_par_line = false;
1110        // If the line is getting long, format it next time
1111        force_format = get_cursor_line_len() > max_len;
1112      }
1113    }
1114    line_breakcheck();
1115  }
1116}