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