blob: a9d406e3a0c6862f656f13d8f3860d4fd4b097aa [file] [log] [blame]
Bram Moolenaar4b471622019-01-31 13:48:09 +01001/* 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 * indent.c: Indentation related functions
12 */
13
14#include "vim.h"
15
Bram Moolenaare677df82019-09-02 22:31:11 +020016#if defined(FEAT_VARTABS) || defined(PROTO)
17
18/*
19 * Set the integer values corresponding to the string setting of 'vartabstop'.
20 * "array" will be set, caller must free it if needed.
21 */
22 int
23tabstop_set(char_u *var, int **array)
24{
25 int valcount = 1;
26 int t;
27 char_u *cp;
28
29 if (var[0] == NUL || (var[0] == '0' && var[1] == NUL))
30 {
31 *array = NULL;
32 return TRUE;
33 }
34
35 for (cp = var; *cp != NUL; ++cp)
36 {
37 if (cp == var || cp[-1] == ',')
38 {
39 char_u *end;
40
41 if (strtol((char *)cp, (char **)&end, 10) <= 0)
42 {
43 if (cp != end)
44 emsg(_(e_positive));
45 else
46 emsg(_(e_invarg));
47 return FALSE;
48 }
49 }
50
51 if (VIM_ISDIGIT(*cp))
52 continue;
53 if (cp[0] == ',' && cp > var && cp[-1] != ',' && cp[1] != NUL)
54 {
55 ++valcount;
56 continue;
57 }
58 emsg(_(e_invarg));
59 return FALSE;
60 }
61
62 *array = ALLOC_MULT(int, valcount + 1);
63 if (*array == NULL)
64 return FALSE;
65 (*array)[0] = valcount;
66
67 t = 1;
68 for (cp = var; *cp != NUL;)
69 {
70 (*array)[t++] = atoi((char *)cp);
71 while (*cp != NUL && *cp != ',')
72 ++cp;
73 if (*cp != NUL)
74 ++cp;
75 }
76
77 return TRUE;
78}
79
80/*
81 * Calculate the number of screen spaces a tab will occupy.
82 * If "vts" is set then the tab widths are taken from that array,
83 * otherwise the value of ts is used.
84 */
85 int
86tabstop_padding(colnr_T col, int ts_arg, int *vts)
87{
88 int ts = ts_arg == 0 ? 8 : ts_arg;
89 int tabcount;
90 colnr_T tabcol = 0;
91 int t;
92 int padding = 0;
93
94 if (vts == NULL || vts[0] == 0)
95 return ts - (col % ts);
96
97 tabcount = vts[0];
98
99 for (t = 1; t <= tabcount; ++t)
100 {
101 tabcol += vts[t];
102 if (tabcol > col)
103 {
104 padding = (int)(tabcol - col);
105 break;
106 }
107 }
108 if (t > tabcount)
109 padding = vts[tabcount] - (int)((col - tabcol) % vts[tabcount]);
110
111 return padding;
112}
113
114/*
115 * Find the size of the tab that covers a particular column.
116 */
117 int
118tabstop_at(colnr_T col, int ts, int *vts)
119{
120 int tabcount;
121 colnr_T tabcol = 0;
122 int t;
123 int tab_size = 0;
124
125 if (vts == 0 || vts[0] == 0)
126 return ts;
127
128 tabcount = vts[0];
129 for (t = 1; t <= tabcount; ++t)
130 {
131 tabcol += vts[t];
132 if (tabcol > col)
133 {
134 tab_size = vts[t];
135 break;
136 }
137 }
138 if (t > tabcount)
139 tab_size = vts[tabcount];
140
141 return tab_size;
142}
143
144/*
145 * Find the column on which a tab starts.
146 */
147 colnr_T
148tabstop_start(colnr_T col, int ts, int *vts)
149{
150 int tabcount;
151 colnr_T tabcol = 0;
152 int t;
153 int excess;
154
155 if (vts == NULL || vts[0] == 0)
156 return (col / ts) * ts;
157
158 tabcount = vts[0];
159 for (t = 1; t <= tabcount; ++t)
160 {
161 tabcol += vts[t];
162 if (tabcol > col)
163 return tabcol - vts[t];
164 }
165
166 excess = tabcol % vts[tabcount];
167 return excess + ((col - excess) / vts[tabcount]) * vts[tabcount];
168}
169
170/*
171 * Find the number of tabs and spaces necessary to get from one column
172 * to another.
173 */
174 void
175tabstop_fromto(
176 colnr_T start_col,
177 colnr_T end_col,
178 int ts_arg,
179 int *vts,
180 int *ntabs,
181 int *nspcs)
182{
183 int spaces = end_col - start_col;
184 colnr_T tabcol = 0;
185 int padding = 0;
186 int tabcount;
187 int t;
188 int ts = ts_arg == 0 ? curbuf->b_p_ts : ts_arg;
189
190 if (vts == NULL || vts[0] == 0)
191 {
192 int tabs = 0;
193 int initspc = 0;
194
195 initspc = ts - (start_col % ts);
196 if (spaces >= initspc)
197 {
198 spaces -= initspc;
199 tabs++;
200 }
201 tabs += spaces / ts;
202 spaces -= (spaces / ts) * ts;
203
204 *ntabs = tabs;
205 *nspcs = spaces;
206 return;
207 }
208
209 // Find the padding needed to reach the next tabstop.
210 tabcount = vts[0];
211 for (t = 1; t <= tabcount; ++t)
212 {
213 tabcol += vts[t];
214 if (tabcol > start_col)
215 {
216 padding = (int)(tabcol - start_col);
217 break;
218 }
219 }
220 if (t > tabcount)
221 padding = vts[tabcount] - (int)((start_col - tabcol) % vts[tabcount]);
222
223 // If the space needed is less than the padding no tabs can be used.
224 if (spaces < padding)
225 {
226 *ntabs = 0;
227 *nspcs = spaces;
228 return;
229 }
230
231 *ntabs = 1;
232 spaces -= padding;
233
234 // At least one tab has been used. See if any more will fit.
235 while (spaces != 0 && ++t <= tabcount)
236 {
237 padding = vts[t];
238 if (spaces < padding)
239 {
240 *nspcs = spaces;
241 return;
242 }
243 ++*ntabs;
244 spaces -= padding;
245 }
246
247 *ntabs += spaces / vts[tabcount];
248 *nspcs = spaces % vts[tabcount];
249}
250
251/*
252 * See if two tabstop arrays contain the same values.
253 */
Bram Moolenaar14c01f82019-10-09 22:53:08 +0200254 static int
Bram Moolenaare677df82019-09-02 22:31:11 +0200255tabstop_eq(int *ts1, int *ts2)
256{
257 int t;
258
259 if ((ts1 == 0 && ts2) || (ts1 && ts2 == 0))
260 return FALSE;
261 if (ts1 == ts2)
262 return TRUE;
263 if (ts1[0] != ts2[0])
264 return FALSE;
265
266 for (t = 1; t <= ts1[0]; ++t)
267 if (ts1[t] != ts2[t])
268 return FALSE;
269
270 return TRUE;
271}
272
Bram Moolenaar14c01f82019-10-09 22:53:08 +0200273# if defined(FEAT_BEVAL) || defined(PROTO)
Bram Moolenaare677df82019-09-02 22:31:11 +0200274/*
275 * Copy a tabstop array, allocating space for the new array.
276 */
277 int *
278tabstop_copy(int *oldts)
279{
280 int *newts;
281 int t;
282
283 if (oldts == NULL)
284 return NULL;
285 newts = ALLOC_MULT(int, oldts[0] + 1);
286 if (newts != NULL)
287 for (t = 0; t <= oldts[0]; ++t)
288 newts[t] = oldts[t];
289 return newts;
290}
Bram Moolenaar14c01f82019-10-09 22:53:08 +0200291# endif
Bram Moolenaare677df82019-09-02 22:31:11 +0200292
293/*
294 * Return a count of the number of tabstops.
295 */
296 int
297tabstop_count(int *ts)
298{
299 return ts != NULL ? ts[0] : 0;
300}
301
302/*
303 * Return the first tabstop, or 8 if there are no tabstops defined.
304 */
305 int
306tabstop_first(int *ts)
307{
308 return ts != NULL ? ts[1] : 8;
309}
310
311#endif
312
313/*
314 * Return the effective shiftwidth value for current buffer, using the
315 * 'tabstop' value when 'shiftwidth' is zero.
316 */
317 long
318get_sw_value(buf_T *buf)
319{
320 return get_sw_value_col(buf, 0);
321}
322
323/*
324 * Idem, using "pos".
325 */
326 static long
327get_sw_value_pos(buf_T *buf, pos_T *pos)
328{
329 pos_T save_cursor = curwin->w_cursor;
330 long sw_value;
331
332 curwin->w_cursor = *pos;
333 sw_value = get_sw_value_col(buf, get_nolist_virtcol());
334 curwin->w_cursor = save_cursor;
335 return sw_value;
336}
337
338/*
339 * Idem, using the first non-black in the current line.
340 */
341 long
342get_sw_value_indent(buf_T *buf)
343{
344 pos_T pos = curwin->w_cursor;
345
346 pos.col = getwhitecols_curline();
347 return get_sw_value_pos(buf, &pos);
348}
349
350/*
351 * Idem, using virtual column "col".
352 */
353 long
354get_sw_value_col(buf_T *buf, colnr_T col UNUSED)
355{
356 return buf->b_p_sw ? buf->b_p_sw :
Bram Moolenaar14c01f82019-10-09 22:53:08 +0200357#ifdef FEAT_VARTABS
Bram Moolenaare677df82019-09-02 22:31:11 +0200358 tabstop_at(col, buf->b_p_ts, buf->b_p_vts_array);
Bram Moolenaar14c01f82019-10-09 22:53:08 +0200359#else
Bram Moolenaare677df82019-09-02 22:31:11 +0200360 buf->b_p_ts;
Bram Moolenaar14c01f82019-10-09 22:53:08 +0200361#endif
Bram Moolenaare677df82019-09-02 22:31:11 +0200362}
363
364/*
365 * Return the effective softtabstop value for the current buffer, using the
366 * 'shiftwidth' value when 'softtabstop' is negative.
367 */
368 long
369get_sts_value(void)
370{
371 return curbuf->b_p_sts < 0 ? get_sw_value(curbuf) : curbuf->b_p_sts;
372}
Bram Moolenaar14c01f82019-10-09 22:53:08 +0200373
374/*
375 * Count the size (in window cells) of the indent in the current line.
376 */
377 int
378get_indent(void)
379{
380#ifdef FEAT_VARTABS
381 return get_indent_str_vtab(ml_get_curline(), (int)curbuf->b_p_ts,
382 curbuf->b_p_vts_array, FALSE);
383#else
384 return get_indent_str(ml_get_curline(), (int)curbuf->b_p_ts, FALSE);
385#endif
386}
387
388/*
389 * Count the size (in window cells) of the indent in line "lnum".
390 */
391 int
392get_indent_lnum(linenr_T lnum)
393{
394#ifdef FEAT_VARTABS
395 return get_indent_str_vtab(ml_get(lnum), (int)curbuf->b_p_ts,
396 curbuf->b_p_vts_array, FALSE);
397#else
398 return get_indent_str(ml_get(lnum), (int)curbuf->b_p_ts, FALSE);
399#endif
400}
401
402#if defined(FEAT_FOLDING) || defined(PROTO)
403/*
404 * Count the size (in window cells) of the indent in line "lnum" of buffer
405 * "buf".
406 */
407 int
408get_indent_buf(buf_T *buf, linenr_T lnum)
409{
410# ifdef FEAT_VARTABS
411 return get_indent_str_vtab(ml_get_buf(buf, lnum, FALSE),
412 (int)curbuf->b_p_ts, buf->b_p_vts_array, FALSE);
413# else
414 return get_indent_str(ml_get_buf(buf, lnum, FALSE), (int)buf->b_p_ts, FALSE);
415# endif
416}
417#endif
418
419/*
420 * count the size (in window cells) of the indent in line "ptr", with
421 * 'tabstop' at "ts"
422 */
423 int
424get_indent_str(
425 char_u *ptr,
426 int ts,
427 int list) // if TRUE, count only screen size for tabs
428{
429 int count = 0;
430
431 for ( ; *ptr; ++ptr)
432 {
433 if (*ptr == TAB)
434 {
435 if (!list || lcs_tab1) // count a tab for what it is worth
436 count += ts - (count % ts);
437 else
438 // In list mode, when tab is not set, count screen char width
439 // for Tab, displays: ^I
440 count += ptr2cells(ptr);
441 }
442 else if (*ptr == ' ')
443 ++count; // count a space for one
444 else
445 break;
446 }
447 return count;
448}
449
450#ifdef FEAT_VARTABS
451/*
452 * Count the size (in window cells) of the indent in line "ptr", using
453 * variable tabstops.
454 * if "list" is TRUE, count only screen size for tabs.
455 */
456 int
457get_indent_str_vtab(char_u *ptr, int ts, int *vts, int list)
458{
459 int count = 0;
460
461 for ( ; *ptr; ++ptr)
462 {
463 if (*ptr == TAB) // count a tab for what it is worth
464 {
465 if (!list || lcs_tab1)
466 count += tabstop_padding(count, ts, vts);
467 else
468 // In list mode, when tab is not set, count screen char width
469 // for Tab, displays: ^I
470 count += ptr2cells(ptr);
471 }
472 else if (*ptr == ' ')
473 ++count; // count a space for one
474 else
475 break;
476 }
477 return count;
478}
479#endif
480
481/*
482 * Set the indent of the current line.
483 * Leaves the cursor on the first non-blank in the line.
484 * Caller must take care of undo.
485 * "flags":
486 * SIN_CHANGED: call changed_bytes() if the line was changed.
487 * SIN_INSERT: insert the indent in front of the line.
488 * SIN_UNDO: save line for undo before changing it.
489 * Returns TRUE if the line was changed.
490 */
491 int
492set_indent(
493 int size, // measured in spaces
494 int flags)
495{
496 char_u *p;
497 char_u *newline;
498 char_u *oldline;
499 char_u *s;
500 int todo;
501 int ind_len; // measured in characters
502 int line_len;
503 int doit = FALSE;
504 int ind_done = 0; // measured in spaces
505#ifdef FEAT_VARTABS
506 int ind_col = 0;
507#endif
508 int tab_pad;
509 int retval = FALSE;
510 int orig_char_len = -1; // number of initial whitespace chars when
511 // 'et' and 'pi' are both set
512
513 // First check if there is anything to do and compute the number of
514 // characters needed for the indent.
515 todo = size;
516 ind_len = 0;
517 p = oldline = ml_get_curline();
518
519 // Calculate the buffer size for the new indent, and check to see if it
520 // isn't already set
521
522 // if 'expandtab' isn't set: use TABs; if both 'expandtab' and
523 // 'preserveindent' are set count the number of characters at the
524 // beginning of the line to be copied
525 if (!curbuf->b_p_et || (!(flags & SIN_INSERT) && curbuf->b_p_pi))
526 {
527 // If 'preserveindent' is set then reuse as much as possible of
528 // the existing indent structure for the new indent
529 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
530 {
531 ind_done = 0;
532
533 // count as many characters as we can use
534 while (todo > 0 && VIM_ISWHITE(*p))
535 {
536 if (*p == TAB)
537 {
538#ifdef FEAT_VARTABS
539 tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,
540 curbuf->b_p_vts_array);
541#else
542 tab_pad = (int)curbuf->b_p_ts
543 - (ind_done % (int)curbuf->b_p_ts);
544#endif
545 // stop if this tab will overshoot the target
546 if (todo < tab_pad)
547 break;
548 todo -= tab_pad;
549 ++ind_len;
550 ind_done += tab_pad;
551 }
552 else
553 {
554 --todo;
555 ++ind_len;
556 ++ind_done;
557 }
558 ++p;
559 }
560
561#ifdef FEAT_VARTABS
562 // These diverge from this point.
563 ind_col = ind_done;
564#endif
565 // Set initial number of whitespace chars to copy if we are
566 // preserving indent but expandtab is set
567 if (curbuf->b_p_et)
568 orig_char_len = ind_len;
569
570 // Fill to next tabstop with a tab, if possible
571#ifdef FEAT_VARTABS
572 tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,
573 curbuf->b_p_vts_array);
574#else
575 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
576#endif
577 if (todo >= tab_pad && orig_char_len == -1)
578 {
579 doit = TRUE;
580 todo -= tab_pad;
581 ++ind_len;
582 // ind_done += tab_pad;
583#ifdef FEAT_VARTABS
584 ind_col += tab_pad;
585#endif
586 }
587 }
588
589 // count tabs required for indent
590#ifdef FEAT_VARTABS
591 for (;;)
592 {
593 tab_pad = tabstop_padding(ind_col, curbuf->b_p_ts,
594 curbuf->b_p_vts_array);
595 if (todo < tab_pad)
596 break;
597 if (*p != TAB)
598 doit = TRUE;
599 else
600 ++p;
601 todo -= tab_pad;
602 ++ind_len;
603 ind_col += tab_pad;
604 }
605#else
606 while (todo >= (int)curbuf->b_p_ts)
607 {
608 if (*p != TAB)
609 doit = TRUE;
610 else
611 ++p;
612 todo -= (int)curbuf->b_p_ts;
613 ++ind_len;
614 // ind_done += (int)curbuf->b_p_ts;
615 }
616#endif
617 }
618 // count spaces required for indent
619 while (todo > 0)
620 {
621 if (*p != ' ')
622 doit = TRUE;
623 else
624 ++p;
625 --todo;
626 ++ind_len;
627 // ++ind_done;
628 }
629
630 // Return if the indent is OK already.
631 if (!doit && !VIM_ISWHITE(*p) && !(flags & SIN_INSERT))
632 return FALSE;
633
634 // Allocate memory for the new line.
635 if (flags & SIN_INSERT)
636 p = oldline;
637 else
638 p = skipwhite(p);
639 line_len = (int)STRLEN(p) + 1;
640
641 // If 'preserveindent' and 'expandtab' are both set keep the original
642 // characters and allocate accordingly. We will fill the rest with spaces
643 // after the if (!curbuf->b_p_et) below.
644 if (orig_char_len != -1)
645 {
646 newline = alloc(orig_char_len + size - ind_done + line_len);
647 if (newline == NULL)
648 return FALSE;
649 todo = size - ind_done;
650 ind_len = orig_char_len + todo; // Set total length of indent in
651 // characters, which may have been
652 // undercounted until now
653 p = oldline;
654 s = newline;
655 while (orig_char_len > 0)
656 {
657 *s++ = *p++;
658 orig_char_len--;
659 }
660
661 // Skip over any additional white space (useful when newindent is less
662 // than old)
663 while (VIM_ISWHITE(*p))
664 ++p;
665
666 }
667 else
668 {
669 todo = size;
670 newline = alloc(ind_len + line_len);
671 if (newline == NULL)
672 return FALSE;
673 s = newline;
674 }
675
676 // Put the characters in the new line.
677 // if 'expandtab' isn't set: use TABs
678 if (!curbuf->b_p_et)
679 {
680 // If 'preserveindent' is set then reuse as much as possible of
681 // the existing indent structure for the new indent
682 if (!(flags & SIN_INSERT) && curbuf->b_p_pi)
683 {
684 p = oldline;
685 ind_done = 0;
686
687 while (todo > 0 && VIM_ISWHITE(*p))
688 {
689 if (*p == TAB)
690 {
691#ifdef FEAT_VARTABS
692 tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,
693 curbuf->b_p_vts_array);
694#else
695 tab_pad = (int)curbuf->b_p_ts
696 - (ind_done % (int)curbuf->b_p_ts);
697#endif
698 // stop if this tab will overshoot the target
699 if (todo < tab_pad)
700 break;
701 todo -= tab_pad;
702 ind_done += tab_pad;
703 }
704 else
705 {
706 --todo;
707 ++ind_done;
708 }
709 *s++ = *p++;
710 }
711
712 // Fill to next tabstop with a tab, if possible
713#ifdef FEAT_VARTABS
714 tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,
715 curbuf->b_p_vts_array);
716#else
717 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
718#endif
719 if (todo >= tab_pad)
720 {
721 *s++ = TAB;
722 todo -= tab_pad;
723#ifdef FEAT_VARTABS
724 ind_done += tab_pad;
725#endif
726 }
727
728 p = skipwhite(p);
729 }
730
731#ifdef FEAT_VARTABS
732 for (;;)
733 {
734 tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,
735 curbuf->b_p_vts_array);
736 if (todo < tab_pad)
737 break;
738 *s++ = TAB;
739 todo -= tab_pad;
740 ind_done += tab_pad;
741 }
742#else
743 while (todo >= (int)curbuf->b_p_ts)
744 {
745 *s++ = TAB;
746 todo -= (int)curbuf->b_p_ts;
747 }
748#endif
749 }
750 while (todo > 0)
751 {
752 *s++ = ' ';
753 --todo;
754 }
755 mch_memmove(s, p, (size_t)line_len);
756
757 // Replace the line (unless undo fails).
758 if (!(flags & SIN_UNDO) || u_savesub(curwin->w_cursor.lnum) == OK)
759 {
Bram Moolenaarcf306432020-06-29 20:40:37 +0200760 colnr_T old_offset = (colnr_T)(p - oldline);
761 colnr_T new_offset = (colnr_T)(s - newline);
762
763 // this may free "newline"
Bram Moolenaar14c01f82019-10-09 22:53:08 +0200764 ml_replace(curwin->w_cursor.lnum, newline, FALSE);
765 if (flags & SIN_CHANGED)
766 changed_bytes(curwin->w_cursor.lnum, 0);
767
768 // Correct saved cursor position if it is in this line.
769 if (saved_cursor.lnum == curwin->w_cursor.lnum)
770 {
Bram Moolenaarcf306432020-06-29 20:40:37 +0200771 if (saved_cursor.col >= old_offset)
Bram Moolenaar14c01f82019-10-09 22:53:08 +0200772 // cursor was after the indent, adjust for the number of
773 // bytes added/removed
Bram Moolenaarcf306432020-06-29 20:40:37 +0200774 saved_cursor.col += ind_len - old_offset;
775 else if (saved_cursor.col >= new_offset)
Bram Moolenaar14c01f82019-10-09 22:53:08 +0200776 // cursor was in the indent, and is now after it, put it back
777 // at the start of the indent (replacing spaces with TAB)
Bram Moolenaarcf306432020-06-29 20:40:37 +0200778 saved_cursor.col = new_offset;
Bram Moolenaar14c01f82019-10-09 22:53:08 +0200779 }
Bram Moolenaar05ad5ff2019-11-30 22:48:27 +0100780#ifdef FEAT_PROP_POPUP
Bram Moolenaar14c01f82019-10-09 22:53:08 +0200781 {
Bram Moolenaarcf306432020-06-29 20:40:37 +0200782 int added = ind_len - old_offset;
Bram Moolenaar14c01f82019-10-09 22:53:08 +0200783
784 // When increasing indent this behaves like spaces were inserted at
785 // the old indent, when decreasing indent it behaves like spaces
786 // were deleted at the new indent.
787 adjust_prop_columns(curwin->w_cursor.lnum,
Bram Moolenaarcf306432020-06-29 20:40:37 +0200788 added > 0 ? old_offset : (colnr_T)ind_len, added, 0);
Bram Moolenaar14c01f82019-10-09 22:53:08 +0200789 }
790#endif
791 retval = TRUE;
792 }
793 else
794 vim_free(newline);
795
796 curwin->w_cursor.col = ind_len;
797 return retval;
798}
799
800/*
801 * Return the indent of the current line after a number. Return -1 if no
802 * number was found. Used for 'n' in 'formatoptions': numbered list.
803 * Since a pattern is used it can actually handle more than numbers.
804 */
805 int
806get_number_indent(linenr_T lnum)
807{
808 colnr_T col;
809 pos_T pos;
810
811 regmatch_T regmatch;
812 int lead_len = 0; // length of comment leader
813
814 if (lnum > curbuf->b_ml.ml_line_count)
815 return -1;
816 pos.lnum = 0;
817
818 // In format_lines() (i.e. not insert mode), fo+=q is needed too...
819 if ((State & INSERT) || has_format_option(FO_Q_COMS))
820 lead_len = get_leader_len(ml_get(lnum), NULL, FALSE, TRUE);
821
822 regmatch.regprog = vim_regcomp(curbuf->b_p_flp, RE_MAGIC);
823 if (regmatch.regprog != NULL)
824 {
825 regmatch.rm_ic = FALSE;
826
827 // vim_regexec() expects a pointer to a line. This lets us
828 // start matching for the flp beyond any comment leader...
829 if (vim_regexec(&regmatch, ml_get(lnum) + lead_len, (colnr_T)0))
830 {
831 pos.lnum = lnum;
832 pos.col = (colnr_T)(*regmatch.endp - ml_get(lnum));
833 pos.coladd = 0;
834 }
835 vim_regfree(regmatch.regprog);
836 }
837
838 if (pos.lnum == 0 || *ml_get_pos(&pos) == NUL)
839 return -1;
840 getvcol(curwin, &pos, &col, NULL, NULL);
841 return (int)col;
842}
843
844#if defined(FEAT_LINEBREAK) || defined(PROTO)
845/*
Bram Moolenaar7bae0b12019-11-21 22:14:18 +0100846 * This is called when 'breakindentopt' is changed and when a window is
847 * initialized.
848 */
849 int
850briopt_check(win_T *wp)
851{
852 char_u *p;
853 int bri_shift = 0;
854 long bri_min = 20;
855 int bri_sbr = FALSE;
856
857 p = wp->w_p_briopt;
858 while (*p != NUL)
859 {
860 if (STRNCMP(p, "shift:", 6) == 0
861 && ((p[6] == '-' && VIM_ISDIGIT(p[7])) || VIM_ISDIGIT(p[6])))
862 {
863 p += 6;
864 bri_shift = getdigits(&p);
865 }
866 else if (STRNCMP(p, "min:", 4) == 0 && VIM_ISDIGIT(p[4]))
867 {
868 p += 4;
869 bri_min = getdigits(&p);
870 }
871 else if (STRNCMP(p, "sbr", 3) == 0)
872 {
873 p += 3;
874 bri_sbr = TRUE;
875 }
876 if (*p != ',' && *p != NUL)
877 return FAIL;
878 if (*p == ',')
879 ++p;
880 }
881
Bram Moolenaarb81f56f2020-02-23 15:29:46 +0100882 wp->w_briopt_shift = bri_shift;
883 wp->w_briopt_min = bri_min;
884 wp->w_briopt_sbr = bri_sbr;
Bram Moolenaar7bae0b12019-11-21 22:14:18 +0100885
886 return OK;
887}
888
889/*
Bram Moolenaar14c01f82019-10-09 22:53:08 +0200890 * Return appropriate space number for breakindent, taking influencing
891 * parameters into account. Window must be specified, since it is not
892 * necessarily always the current one.
893 */
894 int
895get_breakindent_win(
896 win_T *wp,
897 char_u *line) // start of the line
898{
899 static int prev_indent = 0; // cached indent value
900 static long prev_ts = 0L; // cached tabstop value
901 static char_u *prev_line = NULL; // cached pointer to line
902 static varnumber_T prev_tick = 0; // changedtick of cached value
903# ifdef FEAT_VARTABS
904 static int *prev_vts = NULL; // cached vartabs values
905# endif
906 int bri = 0;
907 // window width minus window margin space, i.e. what rests for text
908 const int eff_wwidth = wp->w_width
909 - ((wp->w_p_nu || wp->w_p_rnu)
910 && (vim_strchr(p_cpo, CPO_NUMCOL) == NULL)
911 ? number_width(wp) + 1 : 0);
912
913 // used cached indent, unless pointer or 'tabstop' changed
914 if (prev_line != line || prev_ts != wp->w_buffer->b_p_ts
915 || prev_tick != CHANGEDTICK(wp->w_buffer)
916# ifdef FEAT_VARTABS
917 || prev_vts != wp->w_buffer->b_p_vts_array
918# endif
919 )
920 {
921 prev_line = line;
922 prev_ts = wp->w_buffer->b_p_ts;
923 prev_tick = CHANGEDTICK(wp->w_buffer);
924# ifdef FEAT_VARTABS
925 prev_vts = wp->w_buffer->b_p_vts_array;
926 prev_indent = get_indent_str_vtab(line,
927 (int)wp->w_buffer->b_p_ts,
928 wp->w_buffer->b_p_vts_array, wp->w_p_list);
929# else
930 prev_indent = get_indent_str(line,
931 (int)wp->w_buffer->b_p_ts, wp->w_p_list);
932# endif
933 }
Bram Moolenaarb81f56f2020-02-23 15:29:46 +0100934 bri = prev_indent + wp->w_briopt_shift;
Bram Moolenaar14c01f82019-10-09 22:53:08 +0200935
936 // indent minus the length of the showbreak string
Bram Moolenaarb81f56f2020-02-23 15:29:46 +0100937 if (wp->w_briopt_sbr)
Bram Moolenaar91e22eb2019-11-10 00:19:12 +0100938 bri -= vim_strsize(get_showbreak_value(wp));
Bram Moolenaar14c01f82019-10-09 22:53:08 +0200939
940 // Add offset for number column, if 'n' is in 'cpoptions'
941 bri += win_col_off2(wp);
942
943 // never indent past left window margin
944 if (bri < 0)
945 bri = 0;
946 // always leave at least bri_min characters on the left,
947 // if text width is sufficient
Bram Moolenaarb81f56f2020-02-23 15:29:46 +0100948 else if (bri > eff_wwidth - wp->w_briopt_min)
949 bri = (eff_wwidth - wp->w_briopt_min < 0)
950 ? 0 : eff_wwidth - wp->w_briopt_min;
Bram Moolenaar14c01f82019-10-09 22:53:08 +0200951
952 return bri;
953}
954#endif
955
956/*
957 * When extra == 0: Return TRUE if the cursor is before or on the first
958 * non-blank in the line.
959 * When extra == 1: Return TRUE if the cursor is before the first non-blank in
960 * the line.
961 */
962 int
963inindent(int extra)
964{
965 char_u *ptr;
966 colnr_T col;
967
968 for (col = 0, ptr = ml_get_curline(); VIM_ISWHITE(*ptr); ++col)
969 ++ptr;
970 if (col >= curwin->w_cursor.col + extra)
971 return TRUE;
972 else
973 return FALSE;
974}
975
976#if defined(FEAT_LISP) || defined(FEAT_CINDENT) || defined(PROTO)
977/*
978 * op_reindent - handle reindenting a block of lines.
979 */
980 void
981op_reindent(oparg_T *oap, int (*how)(void))
982{
983 long i;
984 char_u *l;
985 int amount;
986 linenr_T first_changed = 0;
987 linenr_T last_changed = 0;
988 linenr_T start_lnum = curwin->w_cursor.lnum;
989
990 // Don't even try when 'modifiable' is off.
991 if (!curbuf->b_p_ma)
992 {
993 emsg(_(e_modifiable));
994 return;
995 }
996
997 for (i = oap->line_count; --i >= 0 && !got_int; )
998 {
999 // it's a slow thing to do, so give feedback so there's no worry that
1000 // the computer's just hung.
1001
1002 if (i > 1
1003 && (i % 50 == 0 || i == oap->line_count - 1)
1004 && oap->line_count > p_report)
1005 smsg(_("%ld lines to indent... "), i);
1006
1007 // Be vi-compatible: For lisp indenting the first line is not
1008 // indented, unless there is only one line.
1009# ifdef FEAT_LISP
1010 if (i != oap->line_count - 1 || oap->line_count == 1
1011 || how != get_lisp_indent)
1012# endif
1013 {
1014 l = skipwhite(ml_get_curline());
1015 if (*l == NUL) // empty or blank line
1016 amount = 0;
1017 else
1018 amount = how(); // get the indent for this line
1019
1020 if (amount >= 0 && set_indent(amount, SIN_UNDO))
1021 {
1022 // did change the indent, call changed_lines() later
1023 if (first_changed == 0)
1024 first_changed = curwin->w_cursor.lnum;
1025 last_changed = curwin->w_cursor.lnum;
1026 }
1027 }
1028 ++curwin->w_cursor.lnum;
1029 curwin->w_cursor.col = 0; // make sure it's valid
1030 }
1031
1032 // put cursor on first non-blank of indented line
1033 curwin->w_cursor.lnum = start_lnum;
1034 beginline(BL_SOL | BL_FIX);
1035
1036 // Mark changed lines so that they will be redrawn. When Visual
1037 // highlighting was present, need to continue until the last line. When
1038 // there is no change still need to remove the Visual highlighting.
1039 if (last_changed != 0)
1040 changed_lines(first_changed, 0,
1041 oap->is_VIsual ? start_lnum + oap->line_count :
1042 last_changed + 1, 0L);
1043 else if (oap->is_VIsual)
1044 redraw_curbuf_later(INVERTED);
1045
1046 if (oap->line_count > p_report)
1047 {
1048 i = oap->line_count - (i + 1);
1049 smsg(NGETTEXT("%ld line indented ",
1050 "%ld lines indented ", i), i);
1051 }
Bram Moolenaare1004402020-10-24 20:49:43 +02001052 if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0)
Bram Moolenaarf4a1d1c2019-11-16 13:50:25 +01001053 {
1054 // set '[ and '] marks
1055 curbuf->b_op_start = oap->start;
1056 curbuf->b_op_end = oap->end;
1057 }
Bram Moolenaar14c01f82019-10-09 22:53:08 +02001058}
1059#endif // defined(FEAT_LISP) || defined(FEAT_CINDENT)
1060
1061#if defined(FEAT_SMARTINDENT) || defined(FEAT_CINDENT) || defined(PROTO)
1062/*
1063 * Return TRUE if lines starting with '#' should be left aligned.
1064 */
1065 int
1066preprocs_left(void)
1067{
1068 return
1069# ifdef FEAT_SMARTINDENT
1070# ifdef FEAT_CINDENT
1071 (curbuf->b_p_si && !curbuf->b_p_cin) ||
1072# else
1073 curbuf->b_p_si
1074# endif
1075# endif
1076# ifdef FEAT_CINDENT
1077 (curbuf->b_p_cin && in_cinkeys('#', ' ', TRUE)
1078 && curbuf->b_ind_hash_comment == 0)
1079# endif
1080 ;
1081}
1082#endif
1083
1084#ifdef FEAT_SMARTINDENT
1085/*
1086 * Try to do some very smart auto-indenting.
1087 * Used when inserting a "normal" character.
1088 */
1089 void
1090ins_try_si(int c)
1091{
1092 pos_T *pos, old_pos;
1093 char_u *ptr;
1094 int i;
1095 int temp;
1096
1097 // do some very smart indenting when entering '{' or '}'
1098 if (((did_si || can_si_back) && c == '{') || (can_si && c == '}'))
1099 {
1100 // for '}' set indent equal to indent of line containing matching '{'
1101 if (c == '}' && (pos = findmatch(NULL, '{')) != NULL)
1102 {
1103 old_pos = curwin->w_cursor;
1104 // If the matching '{' has a ')' immediately before it (ignoring
1105 // white-space), then line up with the start of the line
1106 // containing the matching '(' if there is one. This handles the
1107 // case where an "if (..\n..) {" statement continues over multiple
1108 // lines -- webb
1109 ptr = ml_get(pos->lnum);
1110 i = pos->col;
1111 if (i > 0) // skip blanks before '{'
1112 while (--i > 0 && VIM_ISWHITE(ptr[i]))
1113 ;
1114 curwin->w_cursor.lnum = pos->lnum;
1115 curwin->w_cursor.col = i;
1116 if (ptr[i] == ')' && (pos = findmatch(NULL, '(')) != NULL)
1117 curwin->w_cursor = *pos;
1118 i = get_indent();
1119 curwin->w_cursor = old_pos;
1120 if (State & VREPLACE_FLAG)
1121 change_indent(INDENT_SET, i, FALSE, NUL, TRUE);
1122 else
1123 (void)set_indent(i, SIN_CHANGED);
1124 }
1125 else if (curwin->w_cursor.col > 0)
1126 {
1127 // when inserting '{' after "O" reduce indent, but not
1128 // more than indent of previous line
1129 temp = TRUE;
1130 if (c == '{' && can_si_back && curwin->w_cursor.lnum > 1)
1131 {
1132 old_pos = curwin->w_cursor;
1133 i = get_indent();
1134 while (curwin->w_cursor.lnum > 1)
1135 {
1136 ptr = skipwhite(ml_get(--(curwin->w_cursor.lnum)));
1137
1138 // ignore empty lines and lines starting with '#'.
1139 if (*ptr != '#' && *ptr != NUL)
1140 break;
1141 }
1142 if (get_indent() >= i)
1143 temp = FALSE;
1144 curwin->w_cursor = old_pos;
1145 }
1146 if (temp)
1147 shift_line(TRUE, FALSE, 1, TRUE);
1148 }
1149 }
1150
1151 // set indent of '#' always to 0
1152 if (curwin->w_cursor.col > 0 && can_si && c == '#')
1153 {
1154 // remember current indent for next line
1155 old_indent = get_indent();
1156 (void)set_indent(0, SIN_CHANGED);
1157 }
1158
1159 // Adjust ai_col, the char at this position can be deleted.
1160 if (ai_col > curwin->w_cursor.col)
1161 ai_col = curwin->w_cursor.col;
1162}
1163#endif
1164
1165/*
1166 * Insert an indent (for <Tab> or CTRL-T) or delete an indent (for CTRL-D).
1167 * Keep the cursor on the same character.
1168 * type == INDENT_INC increase indent (for CTRL-T or <Tab>)
1169 * type == INDENT_DEC decrease indent (for CTRL-D)
1170 * type == INDENT_SET set indent to "amount"
1171 * if round is TRUE, round the indent to 'shiftwidth' (only with _INC and _Dec).
1172 */
1173 void
1174change_indent(
1175 int type,
1176 int amount,
1177 int round,
1178 int replaced, // replaced character, put on replace stack
1179 int call_changed_bytes) // call changed_bytes()
1180{
1181 int vcol;
1182 int last_vcol;
1183 int insstart_less; // reduction for Insstart.col
1184 int new_cursor_col;
1185 int i;
1186 char_u *ptr;
1187 int save_p_list;
1188 int start_col;
1189 colnr_T vc;
1190 colnr_T orig_col = 0; // init for GCC
1191 char_u *new_line, *orig_line = NULL; // init for GCC
1192
1193 // VREPLACE mode needs to know what the line was like before changing
1194 if (State & VREPLACE_FLAG)
1195 {
1196 orig_line = vim_strsave(ml_get_curline()); // Deal with NULL below
1197 orig_col = curwin->w_cursor.col;
1198 }
1199
1200 // for the following tricks we don't want list mode
1201 save_p_list = curwin->w_p_list;
1202 curwin->w_p_list = FALSE;
1203 vc = getvcol_nolist(&curwin->w_cursor);
1204 vcol = vc;
1205
1206 // For Replace mode we need to fix the replace stack later, which is only
1207 // possible when the cursor is in the indent. Remember the number of
1208 // characters before the cursor if it's possible.
1209 start_col = curwin->w_cursor.col;
1210
1211 // determine offset from first non-blank
1212 new_cursor_col = curwin->w_cursor.col;
1213 beginline(BL_WHITE);
1214 new_cursor_col -= curwin->w_cursor.col;
1215
1216 insstart_less = curwin->w_cursor.col;
1217
1218 // If the cursor is in the indent, compute how many screen columns the
1219 // cursor is to the left of the first non-blank.
1220 if (new_cursor_col < 0)
1221 vcol = get_indent() - vcol;
1222
1223 if (new_cursor_col > 0) // can't fix replace stack
1224 start_col = -1;
1225
1226 // Set the new indent. The cursor will be put on the first non-blank.
1227 if (type == INDENT_SET)
1228 (void)set_indent(amount, call_changed_bytes ? SIN_CHANGED : 0);
1229 else
1230 {
1231 int save_State = State;
1232
1233 // Avoid being called recursively.
1234 if (State & VREPLACE_FLAG)
1235 State = INSERT;
1236 shift_line(type == INDENT_DEC, round, 1, call_changed_bytes);
1237 State = save_State;
1238 }
1239 insstart_less -= curwin->w_cursor.col;
1240
1241 // Try to put cursor on same character.
1242 // If the cursor is at or after the first non-blank in the line,
1243 // compute the cursor column relative to the column of the first
1244 // non-blank character.
1245 // If we are not in insert mode, leave the cursor on the first non-blank.
1246 // If the cursor is before the first non-blank, position it relative
1247 // to the first non-blank, counted in screen columns.
1248 if (new_cursor_col >= 0)
1249 {
1250 // When changing the indent while the cursor is touching it, reset
1251 // Insstart_col to 0.
1252 if (new_cursor_col == 0)
1253 insstart_less = MAXCOL;
1254 new_cursor_col += curwin->w_cursor.col;
1255 }
1256 else if (!(State & INSERT))
1257 new_cursor_col = curwin->w_cursor.col;
1258 else
1259 {
1260 // Compute the screen column where the cursor should be.
1261 vcol = get_indent() - vcol;
1262 curwin->w_virtcol = (colnr_T)((vcol < 0) ? 0 : vcol);
1263
1264 // Advance the cursor until we reach the right screen column.
1265 vcol = last_vcol = 0;
1266 new_cursor_col = -1;
1267 ptr = ml_get_curline();
1268 while (vcol <= (int)curwin->w_virtcol)
1269 {
1270 last_vcol = vcol;
1271 if (has_mbyte && new_cursor_col >= 0)
1272 new_cursor_col += (*mb_ptr2len)(ptr + new_cursor_col);
1273 else
1274 ++new_cursor_col;
1275 vcol += lbr_chartabsize(ptr, ptr + new_cursor_col, (colnr_T)vcol);
1276 }
1277 vcol = last_vcol;
1278
1279 // May need to insert spaces to be able to position the cursor on
1280 // the right screen column.
1281 if (vcol != (int)curwin->w_virtcol)
1282 {
1283 curwin->w_cursor.col = (colnr_T)new_cursor_col;
1284 i = (int)curwin->w_virtcol - vcol;
1285 ptr = alloc(i + 1);
1286 if (ptr != NULL)
1287 {
1288 new_cursor_col += i;
1289 ptr[i] = NUL;
1290 while (--i >= 0)
1291 ptr[i] = ' ';
1292 ins_str(ptr);
1293 vim_free(ptr);
1294 }
1295 }
1296
1297 // When changing the indent while the cursor is in it, reset
1298 // Insstart_col to 0.
1299 insstart_less = MAXCOL;
1300 }
1301
1302 curwin->w_p_list = save_p_list;
1303
1304 if (new_cursor_col <= 0)
1305 curwin->w_cursor.col = 0;
1306 else
1307 curwin->w_cursor.col = (colnr_T)new_cursor_col;
1308 curwin->w_set_curswant = TRUE;
1309 changed_cline_bef_curs();
1310
1311 // May have to adjust the start of the insert.
1312 if (State & INSERT)
1313 {
1314 if (curwin->w_cursor.lnum == Insstart.lnum && Insstart.col != 0)
1315 {
1316 if ((int)Insstart.col <= insstart_less)
1317 Insstart.col = 0;
1318 else
1319 Insstart.col -= insstart_less;
1320 }
1321 if ((int)ai_col <= insstart_less)
1322 ai_col = 0;
1323 else
1324 ai_col -= insstart_less;
1325 }
1326
1327 // For REPLACE mode, may have to fix the replace stack, if it's possible.
1328 // If the number of characters before the cursor decreased, need to pop a
1329 // few characters from the replace stack.
1330 // If the number of characters before the cursor increased, need to push a
1331 // few NULs onto the replace stack.
1332 if (REPLACE_NORMAL(State) && start_col >= 0)
1333 {
1334 while (start_col > (int)curwin->w_cursor.col)
1335 {
1336 replace_join(0); // remove a NUL from the replace stack
1337 --start_col;
1338 }
1339 while (start_col < (int)curwin->w_cursor.col || replaced)
1340 {
1341 replace_push(NUL);
1342 if (replaced)
1343 {
1344 replace_push(replaced);
1345 replaced = NUL;
1346 }
1347 ++start_col;
1348 }
1349 }
1350
1351 // For VREPLACE mode, we also have to fix the replace stack. In this case
1352 // it is always possible because we backspace over the whole line and then
1353 // put it back again the way we wanted it.
1354 if (State & VREPLACE_FLAG)
1355 {
1356 // If orig_line didn't allocate, just return. At least we did the job,
1357 // even if you can't backspace.
1358 if (orig_line == NULL)
1359 return;
1360
1361 // Save new line
1362 new_line = vim_strsave(ml_get_curline());
1363 if (new_line == NULL)
1364 return;
1365
1366 // We only put back the new line up to the cursor
1367 new_line[curwin->w_cursor.col] = NUL;
1368
1369 // Put back original line
1370 ml_replace(curwin->w_cursor.lnum, orig_line, FALSE);
1371 curwin->w_cursor.col = orig_col;
1372
1373 // Backspace from cursor to start of line
1374 backspace_until_column(0);
1375
1376 // Insert new stuff into line again
1377 ins_bytes(new_line);
1378
1379 vim_free(new_line);
1380 }
1381}
1382
1383/*
1384 * Copy the indent from ptr to the current line (and fill to size)
1385 * Leaves the cursor on the first non-blank in the line.
1386 * Returns TRUE if the line was changed.
1387 */
1388 int
1389copy_indent(int size, char_u *src)
1390{
1391 char_u *p = NULL;
1392 char_u *line = NULL;
1393 char_u *s;
1394 int todo;
1395 int ind_len;
1396 int line_len = 0;
1397 int tab_pad;
1398 int ind_done;
1399 int round;
1400#ifdef FEAT_VARTABS
1401 int ind_col;
1402#endif
1403
1404 // Round 1: compute the number of characters needed for the indent
1405 // Round 2: copy the characters.
1406 for (round = 1; round <= 2; ++round)
1407 {
1408 todo = size;
1409 ind_len = 0;
1410 ind_done = 0;
1411#ifdef FEAT_VARTABS
1412 ind_col = 0;
1413#endif
1414 s = src;
1415
1416 // Count/copy the usable portion of the source line
1417 while (todo > 0 && VIM_ISWHITE(*s))
1418 {
1419 if (*s == TAB)
1420 {
1421#ifdef FEAT_VARTABS
1422 tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,
1423 curbuf->b_p_vts_array);
1424#else
1425 tab_pad = (int)curbuf->b_p_ts
1426 - (ind_done % (int)curbuf->b_p_ts);
1427#endif
1428 // Stop if this tab will overshoot the target
1429 if (todo < tab_pad)
1430 break;
1431 todo -= tab_pad;
1432 ind_done += tab_pad;
1433#ifdef FEAT_VARTABS
1434 ind_col += tab_pad;
1435#endif
1436 }
1437 else
1438 {
1439 --todo;
1440 ++ind_done;
1441#ifdef FEAT_VARTABS
1442 ++ind_col;
1443#endif
1444 }
1445 ++ind_len;
1446 if (p != NULL)
1447 *p++ = *s;
1448 ++s;
1449 }
1450
1451 // Fill to next tabstop with a tab, if possible
1452#ifdef FEAT_VARTABS
1453 tab_pad = tabstop_padding(ind_done, curbuf->b_p_ts,
1454 curbuf->b_p_vts_array);
1455#else
1456 tab_pad = (int)curbuf->b_p_ts - (ind_done % (int)curbuf->b_p_ts);
1457#endif
1458 if (todo >= tab_pad && !curbuf->b_p_et)
1459 {
1460 todo -= tab_pad;
1461 ++ind_len;
1462#ifdef FEAT_VARTABS
1463 ind_col += tab_pad;
1464#endif
1465 if (p != NULL)
1466 *p++ = TAB;
1467 }
1468
1469 // Add tabs required for indent
1470 if (!curbuf->b_p_et)
1471 {
1472#ifdef FEAT_VARTABS
1473 for (;;)
1474 {
1475 tab_pad = tabstop_padding(ind_col, curbuf->b_p_ts,
1476 curbuf->b_p_vts_array);
1477 if (todo < tab_pad)
1478 break;
1479 todo -= tab_pad;
1480 ++ind_len;
1481 ind_col += tab_pad;
1482 if (p != NULL)
1483 *p++ = TAB;
1484 }
1485#else
1486 while (todo >= (int)curbuf->b_p_ts)
1487 {
1488 todo -= (int)curbuf->b_p_ts;
1489 ++ind_len;
1490 if (p != NULL)
1491 *p++ = TAB;
1492 }
1493#endif
1494 }
1495
1496 // Count/add spaces required for indent
1497 while (todo > 0)
1498 {
1499 --todo;
1500 ++ind_len;
1501 if (p != NULL)
1502 *p++ = ' ';
1503 }
1504
1505 if (p == NULL)
1506 {
1507 // Allocate memory for the result: the copied indent, new indent
1508 // and the rest of the line.
1509 line_len = (int)STRLEN(ml_get_curline()) + 1;
1510 line = alloc(ind_len + line_len);
1511 if (line == NULL)
1512 return FALSE;
1513 p = line;
1514 }
1515 }
1516
1517 // Append the original line
1518 mch_memmove(p, ml_get_curline(), (size_t)line_len);
1519
1520 // Replace the line
1521 ml_replace(curwin->w_cursor.lnum, line, FALSE);
1522
1523 // Put the cursor after the indent.
1524 curwin->w_cursor.col = ind_len;
1525 return TRUE;
1526}
1527
1528/*
1529 * ":retab".
1530 */
1531 void
1532ex_retab(exarg_T *eap)
1533{
1534 linenr_T lnum;
1535 int got_tab = FALSE;
1536 long num_spaces = 0;
1537 long num_tabs;
1538 long len;
1539 long col;
1540 long vcol;
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +01001541 long start_col = 0; // For start of white-space string
1542 long start_vcol = 0; // For start of white-space string
Bram Moolenaar14c01f82019-10-09 22:53:08 +02001543 long old_len;
1544 char_u *ptr;
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +01001545 char_u *new_line = (char_u *)1; // init to non-NULL
1546 int did_undo; // called u_save for current line
Bram Moolenaar14c01f82019-10-09 22:53:08 +02001547#ifdef FEAT_VARTABS
1548 int *new_vts_array = NULL;
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +01001549 char_u *new_ts_str; // string value of tab argument
Bram Moolenaar14c01f82019-10-09 22:53:08 +02001550#else
1551 int temp;
1552 int new_ts;
1553#endif
1554 int save_list;
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +01001555 linenr_T first_line = 0; // first changed line
1556 linenr_T last_line = 0; // last changed line
Bram Moolenaar14c01f82019-10-09 22:53:08 +02001557
1558 save_list = curwin->w_p_list;
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +01001559 curwin->w_p_list = 0; // don't want list mode here
Bram Moolenaar14c01f82019-10-09 22:53:08 +02001560
1561#ifdef FEAT_VARTABS
1562 new_ts_str = eap->arg;
1563 if (!tabstop_set(eap->arg, &new_vts_array))
1564 return;
1565 while (vim_isdigit(*(eap->arg)) || *(eap->arg) == ',')
1566 ++(eap->arg);
1567
1568 // This ensures that either new_vts_array and new_ts_str are freshly
1569 // allocated, or new_vts_array points to an existing array and new_ts_str
1570 // is null.
1571 if (new_vts_array == NULL)
1572 {
1573 new_vts_array = curbuf->b_p_vts_array;
1574 new_ts_str = NULL;
1575 }
1576 else
1577 new_ts_str = vim_strnsave(new_ts_str, eap->arg - new_ts_str);
1578#else
1579 new_ts = getdigits(&(eap->arg));
1580 if (new_ts < 0)
1581 {
1582 emsg(_(e_positive));
1583 return;
1584 }
1585 if (new_ts == 0)
1586 new_ts = curbuf->b_p_ts;
1587#endif
1588 for (lnum = eap->line1; !got_int && lnum <= eap->line2; ++lnum)
1589 {
1590 ptr = ml_get(lnum);
1591 col = 0;
1592 vcol = 0;
1593 did_undo = FALSE;
1594 for (;;)
1595 {
1596 if (VIM_ISWHITE(ptr[col]))
1597 {
1598 if (!got_tab && num_spaces == 0)
1599 {
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +01001600 // First consecutive white-space
Bram Moolenaar14c01f82019-10-09 22:53:08 +02001601 start_vcol = vcol;
1602 start_col = col;
1603 }
1604 if (ptr[col] == ' ')
1605 num_spaces++;
1606 else
1607 got_tab = TRUE;
1608 }
1609 else
1610 {
1611 if (got_tab || (eap->forceit && num_spaces > 1))
1612 {
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +01001613 // Retabulate this string of white-space
Bram Moolenaar14c01f82019-10-09 22:53:08 +02001614
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +01001615 // len is virtual length of white string
Bram Moolenaar14c01f82019-10-09 22:53:08 +02001616 len = num_spaces = vcol - start_vcol;
1617 num_tabs = 0;
1618 if (!curbuf->b_p_et)
1619 {
1620#ifdef FEAT_VARTABS
1621 int t, s;
1622
1623 tabstop_fromto(start_vcol, vcol,
1624 curbuf->b_p_ts, new_vts_array, &t, &s);
1625 num_tabs = t;
1626 num_spaces = s;
1627#else
1628 temp = new_ts - (start_vcol % new_ts);
1629 if (num_spaces >= temp)
1630 {
1631 num_spaces -= temp;
1632 num_tabs++;
1633 }
1634 num_tabs += num_spaces / new_ts;
1635 num_spaces -= (num_spaces / new_ts) * new_ts;
1636#endif
1637 }
1638 if (curbuf->b_p_et || got_tab ||
1639 (num_spaces + num_tabs < len))
1640 {
1641 if (did_undo == FALSE)
1642 {
1643 did_undo = TRUE;
1644 if (u_save((linenr_T)(lnum - 1),
1645 (linenr_T)(lnum + 1)) == FAIL)
1646 {
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +01001647 new_line = NULL; // flag out-of-memory
Bram Moolenaar14c01f82019-10-09 22:53:08 +02001648 break;
1649 }
1650 }
1651
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +01001652 // len is actual number of white characters used
Bram Moolenaar14c01f82019-10-09 22:53:08 +02001653 len = num_spaces + num_tabs;
1654 old_len = (long)STRLEN(ptr);
1655 new_line = alloc(old_len - col + start_col + len + 1);
1656 if (new_line == NULL)
1657 break;
1658 if (start_col > 0)
1659 mch_memmove(new_line, ptr, (size_t)start_col);
1660 mch_memmove(new_line + start_col + len,
1661 ptr + col, (size_t)(old_len - col + 1));
1662 ptr = new_line + start_col;
1663 for (col = 0; col < len; col++)
1664 ptr[col] = (col < num_tabs) ? '\t' : ' ';
1665 ml_replace(lnum, new_line, FALSE);
1666 if (first_line == 0)
1667 first_line = lnum;
1668 last_line = lnum;
1669 ptr = new_line;
1670 col = start_col + len;
1671 }
1672 }
1673 got_tab = FALSE;
1674 num_spaces = 0;
1675 }
1676 if (ptr[col] == NUL)
1677 break;
1678 vcol += chartabsize(ptr + col, (colnr_T)vcol);
1679 if (has_mbyte)
1680 col += (*mb_ptr2len)(ptr + col);
1681 else
1682 ++col;
1683 }
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +01001684 if (new_line == NULL) // out of memory
Bram Moolenaar14c01f82019-10-09 22:53:08 +02001685 break;
1686 line_breakcheck();
1687 }
1688 if (got_int)
1689 emsg(_(e_interr));
1690
1691#ifdef FEAT_VARTABS
1692 // If a single value was given then it can be considered equal to
1693 // either the value of 'tabstop' or the value of 'vartabstop'.
1694 if (tabstop_count(curbuf->b_p_vts_array) == 0
1695 && tabstop_count(new_vts_array) == 1
1696 && curbuf->b_p_ts == tabstop_first(new_vts_array))
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +01001697 ; // not changed
Bram Moolenaar14c01f82019-10-09 22:53:08 +02001698 else if (tabstop_count(curbuf->b_p_vts_array) > 0
1699 && tabstop_eq(curbuf->b_p_vts_array, new_vts_array))
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +01001700 ; // not changed
Bram Moolenaar14c01f82019-10-09 22:53:08 +02001701 else
1702 redraw_curbuf_later(NOT_VALID);
1703#else
1704 if (curbuf->b_p_ts != new_ts)
1705 redraw_curbuf_later(NOT_VALID);
1706#endif
1707 if (first_line != 0)
1708 changed_lines(first_line, 0, last_line + 1, 0L);
1709
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +01001710 curwin->w_p_list = save_list; // restore 'list'
Bram Moolenaar14c01f82019-10-09 22:53:08 +02001711
1712#ifdef FEAT_VARTABS
Bram Moolenaaraa2f0ee2019-12-21 18:47:26 +01001713 if (new_ts_str != NULL) // set the new tabstop
Bram Moolenaar14c01f82019-10-09 22:53:08 +02001714 {
1715 // If 'vartabstop' is in use or if the value given to retab has more
1716 // than one tabstop then update 'vartabstop'.
1717 int *old_vts_ary = curbuf->b_p_vts_array;
1718
1719 if (tabstop_count(old_vts_ary) > 0 || tabstop_count(new_vts_array) > 1)
1720 {
1721 set_string_option_direct((char_u *)"vts", -1, new_ts_str,
1722 OPT_FREE|OPT_LOCAL, 0);
1723 curbuf->b_p_vts_array = new_vts_array;
1724 vim_free(old_vts_ary);
1725 }
1726 else
1727 {
1728 // 'vartabstop' wasn't in use and a single value was given to
1729 // retab then update 'tabstop'.
1730 curbuf->b_p_ts = tabstop_first(new_vts_array);
1731 vim_free(new_vts_array);
1732 }
1733 vim_free(new_ts_str);
1734 }
1735#else
1736 curbuf->b_p_ts = new_ts;
1737#endif
1738 coladvance(curwin->w_curswant);
1739
1740 u_clearline();
1741}
1742
1743#if (defined(FEAT_CINDENT) && defined(FEAT_EVAL)) || defined(PROTO)
1744/*
1745 * Get indent level from 'indentexpr'.
1746 */
1747 int
1748get_expr_indent(void)
1749{
1750 int indent = -1;
1751 char_u *inde_copy;
1752 pos_T save_pos;
1753 colnr_T save_curswant;
1754 int save_set_curswant;
1755 int save_State;
1756 int use_sandbox = was_set_insecurely((char_u *)"indentexpr",
1757 OPT_LOCAL);
1758
1759 // Save and restore cursor position and curswant, in case it was changed
1760 // via :normal commands
1761 save_pos = curwin->w_cursor;
1762 save_curswant = curwin->w_curswant;
1763 save_set_curswant = curwin->w_set_curswant;
1764 set_vim_var_nr(VV_LNUM, curwin->w_cursor.lnum);
1765 if (use_sandbox)
1766 ++sandbox;
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +02001767 ++textwinlock;
Bram Moolenaar14c01f82019-10-09 22:53:08 +02001768
1769 // Need to make a copy, the 'indentexpr' option could be changed while
1770 // evaluating it.
1771 inde_copy = vim_strsave(curbuf->b_p_inde);
1772 if (inde_copy != NULL)
1773 {
1774 indent = (int)eval_to_number(inde_copy);
1775 vim_free(inde_copy);
1776 }
1777
1778 if (use_sandbox)
1779 --sandbox;
Bram Moolenaar6adb9ea2020-04-30 22:31:18 +02001780 --textwinlock;
Bram Moolenaar14c01f82019-10-09 22:53:08 +02001781
1782 // Restore the cursor position so that 'indentexpr' doesn't need to.
1783 // Pretend to be in Insert mode, allow cursor past end of line for "o"
1784 // command.
1785 save_State = State;
1786 State = INSERT;
1787 curwin->w_cursor = save_pos;
1788 curwin->w_curswant = save_curswant;
1789 curwin->w_set_curswant = save_set_curswant;
1790 check_cursor();
1791 State = save_State;
1792
1793 // If there is an error, just keep the current indent.
1794 if (indent < 0)
1795 indent = get_indent();
1796
1797 return indent;
1798}
1799#endif
1800
1801#if defined(FEAT_LISP) || defined(PROTO)
1802
1803 static int
1804lisp_match(char_u *p)
1805{
1806 char_u buf[LSIZE];
1807 int len;
1808 char_u *word = *curbuf->b_p_lw != NUL ? curbuf->b_p_lw : p_lispwords;
1809
1810 while (*word != NUL)
1811 {
1812 (void)copy_option_part(&word, buf, LSIZE, ",");
1813 len = (int)STRLEN(buf);
1814 if (STRNCMP(buf, p, len) == 0 && p[len] == ' ')
1815 return TRUE;
1816 }
1817 return FALSE;
1818}
1819
1820/*
1821 * When 'p' is present in 'cpoptions, a Vi compatible method is used.
1822 * The incompatible newer method is quite a bit better at indenting
1823 * code in lisp-like languages than the traditional one; it's still
1824 * mostly heuristics however -- Dirk van Deun, dirk@rave.org
1825 *
1826 * TODO:
1827 * Findmatch() should be adapted for lisp, also to make showmatch
1828 * work correctly: now (v5.3) it seems all C/C++ oriented:
1829 * - it does not recognize the #\( and #\) notations as character literals
1830 * - it doesn't know about comments starting with a semicolon
1831 * - it incorrectly interprets '(' as a character literal
1832 * All this messes up get_lisp_indent in some rare cases.
1833 * Update from Sergey Khorev:
1834 * I tried to fix the first two issues.
1835 */
1836 int
1837get_lisp_indent(void)
1838{
1839 pos_T *pos, realpos, paren;
1840 int amount;
1841 char_u *that;
1842 colnr_T col;
1843 colnr_T firsttry;
1844 int parencount, quotecount;
1845 int vi_lisp;
1846
1847 // Set vi_lisp to use the vi-compatible method
1848 vi_lisp = (vim_strchr(p_cpo, CPO_LISP) != NULL);
1849
1850 realpos = curwin->w_cursor;
1851 curwin->w_cursor.col = 0;
1852
1853 if ((pos = findmatch(NULL, '(')) == NULL)
1854 pos = findmatch(NULL, '[');
1855 else
1856 {
1857 paren = *pos;
1858 pos = findmatch(NULL, '[');
1859 if (pos == NULL || LT_POSP(pos, &paren))
1860 pos = &paren;
1861 }
1862 if (pos != NULL)
1863 {
1864 // Extra trick: Take the indent of the first previous non-white
1865 // line that is at the same () level.
1866 amount = -1;
1867 parencount = 0;
1868
1869 while (--curwin->w_cursor.lnum >= pos->lnum)
1870 {
1871 if (linewhite(curwin->w_cursor.lnum))
1872 continue;
1873 for (that = ml_get_curline(); *that != NUL; ++that)
1874 {
1875 if (*that == ';')
1876 {
1877 while (*(that + 1) != NUL)
1878 ++that;
1879 continue;
1880 }
1881 if (*that == '\\')
1882 {
1883 if (*(that + 1) != NUL)
1884 ++that;
1885 continue;
1886 }
1887 if (*that == '"' && *(that + 1) != NUL)
1888 {
1889 while (*++that && *that != '"')
1890 {
1891 // skipping escaped characters in the string
1892 if (*that == '\\')
1893 {
1894 if (*++that == NUL)
1895 break;
1896 if (that[1] == NUL)
1897 {
1898 ++that;
1899 break;
1900 }
1901 }
1902 }
1903 }
1904 if (*that == '(' || *that == '[')
1905 ++parencount;
1906 else if (*that == ')' || *that == ']')
1907 --parencount;
1908 }
1909 if (parencount == 0)
1910 {
1911 amount = get_indent();
1912 break;
1913 }
1914 }
1915
1916 if (amount == -1)
1917 {
1918 curwin->w_cursor.lnum = pos->lnum;
1919 curwin->w_cursor.col = pos->col;
1920 col = pos->col;
1921
1922 that = ml_get_curline();
1923
1924 if (vi_lisp && get_indent() == 0)
1925 amount = 2;
1926 else
1927 {
1928 char_u *line = that;
1929
1930 amount = 0;
1931 while (*that && col)
1932 {
1933 amount += lbr_chartabsize_adv(line, &that, (colnr_T)amount);
1934 col--;
1935 }
1936
1937 // Some keywords require "body" indenting rules (the
1938 // non-standard-lisp ones are Scheme special forms):
1939 //
1940 // (let ((a 1)) instead (let ((a 1))
1941 // (...)) of (...))
1942
1943 if (!vi_lisp && (*that == '(' || *that == '[')
1944 && lisp_match(that + 1))
1945 amount += 2;
1946 else
1947 {
1948 that++;
1949 amount++;
1950 firsttry = amount;
1951
1952 while (VIM_ISWHITE(*that))
1953 {
1954 amount += lbr_chartabsize(line, that, (colnr_T)amount);
1955 ++that;
1956 }
1957
1958 if (*that && *that != ';') // not a comment line
1959 {
1960 // test *that != '(' to accommodate first let/do
1961 // argument if it is more than one line
1962 if (!vi_lisp && *that != '(' && *that != '[')
1963 firsttry++;
1964
1965 parencount = 0;
1966 quotecount = 0;
1967
1968 if (vi_lisp
1969 || (*that != '"'
1970 && *that != '\''
1971 && *that != '#'
1972 && (*that < '0' || *that > '9')))
1973 {
1974 while (*that
1975 && (!VIM_ISWHITE(*that)
1976 || quotecount
1977 || parencount)
1978 && (!((*that == '(' || *that == '[')
1979 && !quotecount
1980 && !parencount
1981 && vi_lisp)))
1982 {
1983 if (*that == '"')
1984 quotecount = !quotecount;
1985 if ((*that == '(' || *that == '[')
1986 && !quotecount)
1987 ++parencount;
1988 if ((*that == ')' || *that == ']')
1989 && !quotecount)
1990 --parencount;
1991 if (*that == '\\' && *(that+1) != NUL)
1992 amount += lbr_chartabsize_adv(
1993 line, &that, (colnr_T)amount);
1994 amount += lbr_chartabsize_adv(
1995 line, &that, (colnr_T)amount);
1996 }
1997 }
1998 while (VIM_ISWHITE(*that))
1999 {
2000 amount += lbr_chartabsize(
2001 line, that, (colnr_T)amount);
2002 that++;
2003 }
2004 if (!*that || *that == ';')
2005 amount = firsttry;
2006 }
2007 }
2008 }
2009 }
2010 }
2011 else
2012 amount = 0; // no matching '(' or '[' found, use zero indent
2013
2014 curwin->w_cursor = realpos;
2015
2016 return amount;
2017}
2018#endif // FEAT_LISP
2019
2020#if defined(FEAT_LISP) || defined(FEAT_CINDENT) || defined(PROTO)
2021/*
2022 * Re-indent the current line, based on the current contents of it and the
2023 * surrounding lines. Fixing the cursor position seems really easy -- I'm very
2024 * confused what all the part that handles Control-T is doing that I'm not.
2025 * "get_the_indent" should be get_c_indent, get_expr_indent or get_lisp_indent.
2026 */
2027
2028 void
2029fixthisline(int (*get_the_indent)(void))
2030{
2031 int amount = get_the_indent();
2032
2033 if (amount >= 0)
2034 {
2035 change_indent(INDENT_SET, amount, FALSE, 0, TRUE);
2036 if (linewhite(curwin->w_cursor.lnum))
2037 did_ai = TRUE; // delete the indent if the line stays empty
2038 }
2039}
2040
2041 void
2042fix_indent(void)
2043{
2044 if (p_paste)
2045 return;
2046# ifdef FEAT_LISP
2047 if (curbuf->b_p_lisp && curbuf->b_p_ai)
2048 fixthisline(get_lisp_indent);
2049# endif
2050# if defined(FEAT_LISP) && defined(FEAT_CINDENT)
2051 else
2052# endif
2053# ifdef FEAT_CINDENT
2054 if (cindent_on())
2055 do_c_expr_indent();
2056# endif
2057}
2058#endif
2059
2060#if defined(FEAT_EVAL) || defined(PROTO)
2061/*
2062 * "indent()" function
2063 */
2064 void
2065f_indent(typval_T *argvars, typval_T *rettv)
2066{
2067 linenr_T lnum;
2068
2069 lnum = tv_get_lnum(argvars);
2070 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
2071 rettv->vval.v_number = get_indent_lnum(lnum);
2072 else
2073 rettv->vval.v_number = -1;
2074}
2075
2076/*
2077 * "lispindent(lnum)" function
2078 */
2079 void
2080f_lispindent(typval_T *argvars UNUSED, typval_T *rettv)
2081{
2082#ifdef FEAT_LISP
2083 pos_T pos;
2084 linenr_T lnum;
2085
2086 pos = curwin->w_cursor;
2087 lnum = tv_get_lnum(argvars);
2088 if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count)
2089 {
2090 curwin->w_cursor.lnum = lnum;
2091 rettv->vval.v_number = get_lisp_indent();
2092 curwin->w_cursor = pos;
2093 }
2094 else
2095#endif
2096 rettv->vval.v_number = -1;
2097}
2098#endif