robin/laufey

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

Justin M. KeyesMerge #41065 from justinmk/optionfunc4836ecad1f

master
121.9 KiB4073 linesraw
1#include <inttypes.h>
2#include <stdbool.h>
3#include <stddef.h>
4#include <stdlib.h>
5#include <string.h>
6
7#include "nvim/ascii_defs.h"
8#include "nvim/buffer_defs.h"
9#include "nvim/charset.h"
10#include "nvim/cursor.h"
11#include "nvim/eval/typval.h"
12#include "nvim/globals.h"
13#include "nvim/indent.h"
14#include "nvim/indent_c.h"
15#include "nvim/insert.h"
16#include "nvim/keycodes.h"
17#include "nvim/macros_defs.h"
18#include "nvim/mark_defs.h"
19#include "nvim/math.h"
20#include "nvim/mbyte.h"
21#include "nvim/memline.h"
22#include "nvim/memory.h"
23#include "nvim/option.h"
24#include "nvim/option_vars.h"
25#include "nvim/plines.h"
26#include "nvim/pos_defs.h"
27#include "nvim/search.h"
28#include "nvim/state_defs.h"
29#include "nvim/strings.h"
30#include "nvim/types_defs.h"
31#include "nvim/vim_defs.h"
32
33// Find result cache for cpp_baseclass
34typedef struct {
35  int found;
36  lpos_T lpos;
37} cpp_baseclass_cache_T;
38
39#include "indent_c.c.generated.h"
40
41/// Check if line[] contains a "//" comment, ignoring matches inside strings.
42/// Return MAXCOL if not, otherwise return the column.
43/// The line is scanned once (skipping strings), so this stays linear even on
44/// lines with many slashes (e.g. base64 data).
45int check_linecomment(const char *line)
46{
47  const char *p = line;  // scan from start
48  // skip Lispish one-line comments
49  if (curbuf->b_p_lisp) {
50    if (vim_strchr(p, ';') != NULL) {   // there may be comments
51      bool in_str = false;       // inside of string
52
53      while ((p = strpbrk(p, "\";")) != NULL) {
54        if (*p == '"') {
55          if (in_str) {
56            if (*(p - 1) != '\\') {             // skip escaped quote
57              in_str = false;
58            }
59          } else if (p == line || ((p - line) >= 2
60                                   // skip #\" form
61                                   && *(p - 1) != '\\' && *(p - 2) != '#')) {
62            in_str = true;
63          }
64        } else if (!in_str && ((p - line) < 2
65                               || (*(p - 1) != '\\' && *(p - 2) != '#'))
66                   && !is_pos_in_string(line, (colnr_T)(p - line))) {
67          break;                // found!
68        }
69        p++;
70      }
71    } else {
72      p = NULL;
73    }
74  } else {
75    // Scan the line once, skipping over strings, char constants and raw
76    // strings, instead of testing each '/' with is_pos_in_string() (which
77    // rescans from the start, making this quadratic on lines with many
78    // slashes).
79    for (; *p != NUL; p++) {
80      p = skip_string(p);
81      if (*p == NUL) {
82        break;
83      }
84      // Accept a double /, unless it's preceded with * and followed by
85      // *, because * / / * is an end and start of a C comment.
86      if (p[0] == '/' && p[1] == '/'
87          && (p == line || p[-1] != '*' || p[2] != '*')) {
88        break;
89      }
90    }
91    if (*p == NUL) {
92      p = NULL;
93    }
94  }
95
96  if (p == NULL) {
97    return MAXCOL;
98  }
99  return (int)(p - line);
100}
101
102// Find the start of a comment, not knowing if we are in a comment right now.
103// Search starts at w_cursor.lnum and goes backwards.
104// Return NULL when not inside a comment.
105static pos_T *ind_find_start_comment(void)  // XXX
106{
107  return find_start_comment(curbuf->b_ind_maxcomment);
108}
109
110pos_T *find_start_comment(int ind_maxcomment)  // XXX
111{
112  pos_T *pos;
113  int64_t cur_maxcomment = ind_maxcomment;
114
115  while (true) {
116    pos = findmatchlimit(NULL, '*', FM_BACKWARD, cur_maxcomment);
117    if (pos == NULL) {
118      break;
119    }
120
121    // Check if the comment start we found is inside a string.
122    // If it is then restrict the search to below this line and try again.
123    if (!is_pos_in_string(ml_get(pos->lnum), pos->col)) {
124      break;
125    }
126    cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
127    if (cur_maxcomment <= 0) {
128      pos = NULL;
129      break;
130    }
131  }
132  return pos;
133}
134
135/// Find the start of a comment or raw string, not knowing if we are in a
136/// comment or raw string right now.
137/// Search starts at w_cursor.lnum and goes backwards.
138/// If is_raw is given and returns start of raw_string, sets it to true.
139///
140/// @returns NULL when not inside a comment or raw string.
141///
142/// @note "CORS" -> Comment Or Raw String
143static pos_T *ind_find_start_CORS(linenr_T *is_raw)
144{
145  // XXX
146  static pos_T comment_pos_copy;
147
148  pos_T *comment_pos = find_start_comment(curbuf->b_ind_maxcomment);
149  if (comment_pos != NULL) {
150    // Need to make a copy of the static pos in findmatchlimit(),
151    // calling find_start_rawstring() may change it.
152    comment_pos_copy = *comment_pos;
153    comment_pos = &comment_pos_copy;
154  }
155  pos_T *rs_pos = find_start_rawstring(curbuf->b_ind_maxcomment);
156
157  // If comment_pos is before rs_pos the raw string is inside the comment.
158  // If rs_pos is before comment_pos the comment is inside the raw string.
159  if (comment_pos == NULL || (rs_pos != NULL && lt(*rs_pos, *comment_pos))) {
160    if (is_raw != NULL && rs_pos != NULL) {
161      *is_raw = rs_pos->lnum;
162    }
163    return rs_pos;
164  }
165  return comment_pos;
166}
167
168// Find the start of a raw string, not knowing if we are in one right now.
169// Search starts at w_cursor.lnum and goes backwards.
170// Return NULL when not inside a raw string.
171static pos_T *find_start_rawstring(int ind_maxcomment)  // XXX
172{
173  pos_T *pos;
174  int cur_maxcomment = ind_maxcomment;
175
176  while (true) {
177    pos = findmatchlimit(NULL, 'R', FM_BACKWARD, cur_maxcomment);
178    if (pos == NULL) {
179      break;
180    }
181
182    // Check if the raw string start we found is inside a string.
183    // If it is then restrict the search to below this line and try again.
184    if (!is_pos_in_string(ml_get(pos->lnum), pos->col)) {
185      break;
186    }
187    cur_maxcomment = curwin->w_cursor.lnum - pos->lnum - 1;
188    if (cur_maxcomment <= 0) {
189      pos = NULL;
190      break;
191    }
192  }
193  return pos;
194}
195
196// Skip to the end of a "string" and a 'c' character.
197// If there is no string or character, return argument unmodified.
198static const char *skip_string(const char *p)
199{
200  int i;
201
202  // We loop, because strings may be concatenated: "date""time".
203  for (;; p++) {
204    if (p[0] == '\'') {                     // 'c' or '\n' or '\000'
205      if (p[1] == NUL) {                    // ' at end of line
206        break;
207      }
208      i = 2;
209      if (p[1] == '\\' && p[2] != NUL) {    // '\n' or '\000'
210        i++;
211        while (ascii_isdigit(p[i - 1])) {   // '\000'
212          i++;
213        }
214      }
215      if (p[i - 1] != NUL && p[i] == '\'') {  // check for trailing '
216        p += i;
217        continue;
218      }
219    } else if (p[0] == '"') {             // start of string
220      for (++p; p[0]; p++) {
221        if (p[0] == '\\' && p[1] != NUL) {
222          p++;
223        } else if (p[0] == '"') {         // end of string
224          break;
225        }
226      }
227      if (p[0] == '"') {
228        continue;  // continue for another string
229      }
230    } else if (p[0] == 'R' && p[1] == '"') {
231      // Raw string: R"[delim](...)[delim]"
232      const char *delim = p + 2;
233      const char *paren = vim_strchr(delim, '(');
234
235      if (paren != NULL) {
236        const ptrdiff_t delim_len = paren - delim;
237
238        for (p += 3; *p; p++) {
239          if (p[0] == ')' && strncmp(p + 1, delim, (size_t)delim_len) == 0
240              && p[delim_len + 1] == '"') {
241            p += delim_len + 1;
242            break;
243          }
244        }
245        if (p[0] == '"') {
246          continue;  // continue for another string
247        }
248      }
249    }
250    break;                                  // no string found
251  }
252  if (!*p) {
253    p--;                                    // backup from NUL
254  }
255  return p;
256}
257
258/// @returns true if "line[col]" is inside a C string.
259int is_pos_in_string(const char *line, colnr_T col)
260{
261  const char *p;
262
263  for (p = line; *p && (colnr_T)(p - line) < col; p++) {
264    p = skip_string(p);
265  }
266  return !((colnr_T)(p - line) <= col);
267}
268
269// Functions for C-indenting.
270// Most of this originally comes from Eric Fischer.
271
272// Below "XXX" means that this function may unlock the current line.
273
274/// @return  true if the string "line" starts with a word from 'cinwords'.
275bool cin_is_cinword(const char *line)
276{
277  bool retval = false;
278
279  size_t cinw_len = strlen(curbuf->b_p_cinw) + 1;
280  char *cinw_buf = xmalloc(cinw_len);
281  line = skipwhite(line);
282
283  for (char *cinw = curbuf->b_p_cinw; *cinw;) {
284    size_t len = copy_option_part(&cinw, cinw_buf, cinw_len, ",");
285    if (strncmp(line, cinw_buf, len) == 0
286        && (!vim_iswordc((uint8_t)line[len]) || !vim_iswordc((uint8_t)line[len - 1]))) {
287      retval = true;
288      break;
289    }
290  }
291
292  xfree(cinw_buf);
293
294  return retval;
295}
296
297/// Check that C-indenting is on.
298bool cindent_on(void)
299  FUNC_ATTR_PURE FUNC_ATTR_WARN_UNUSED_RESULT
300{
301  return !p_paste && (curbuf->b_p_cin || curbuf->b_p_inde.type != kCallbackNone);
302}
303
304// Skip over white space and C comments within the line.
305// Also skip over Perl/shell comments if desired.
306static const char *cin_skipcomment(const char *s)
307{
308  while (*s) {
309    const char *prev_s = s;
310
311    s = skipwhite(s);
312
313    // Perl/shell # comment comment continues until eol.  Require a space
314    // before # to avoid recognizing $#array.
315    if (curbuf->b_ind_hash_comment != 0 && s != prev_s && *s == '#') {
316      s += strlen(s);
317      break;
318    }
319    if (*s != '/') {
320      break;
321    }
322    s++;
323    if (*s == '/') {            // slash-slash comment continues till eol
324      s += strlen(s);
325      break;
326    }
327    if (*s != '*') {
328      break;
329    }
330    for (++s; *s; s++) {        // skip slash-star comment
331      if (s[0] == '*' && s[1] == '/') {
332        s += 2;
333        break;
334      }
335    }
336  }
337  return s;
338}
339
340/// Return true if there is no code at *s.  White space and comments are
341/// not considered code.
342static int cin_nocode(const char *s)
343{
344  return *cin_skipcomment(s) == NUL;
345}
346
347// Check previous lines for a "//" line comment, skipping over blank lines.
348static pos_T *find_line_comment(void)  // XXX
349{
350  static pos_T pos;
351  char *line;
352  char *p;
353
354  pos = curwin->w_cursor;
355  while (--pos.lnum > 0) {
356    line = ml_get(pos.lnum);
357    p = skipwhite(line);
358    if (cin_islinecomment(p)) {
359      pos.col = (int)(p - line);
360      return &pos;
361    }
362    if (*p != NUL) {
363      break;
364    }
365  }
366  return NULL;
367}
368
369/// Checks if `text` starts with "key:".
370static bool cin_has_js_key(const char *text)
371{
372  const char *s = skipwhite(text);
373
374  char quote = 0;
375  if (*s == '\'' || *s == '"') {
376    // can be 'key': or "key":
377    quote = *s;
378    s++;
379  }
380  if (!vim_isIDc((uint8_t)(*s))) {     // need at least one ID character
381    return false;
382  }
383
384  while (vim_isIDc((uint8_t)(*s))) {
385    s++;
386  }
387  if (*s && *s == quote) {
388    s++;
389  }
390
391  s = cin_skipcomment(s);
392
393  // "::" is not a label, it's C++
394  return (*s == ':' && s[1] != ':');
395}
396
397/// Checks if string matches "label:"; move to character after ':' if true.
398/// "*s" must point to the start of the label, if there is one.
399static bool cin_islabel_skip(const char **s)
400  FUNC_ATTR_NONNULL_ALL
401{
402  if (!vim_isIDc((uint8_t)(**s))) {            // need at least one ID character
403    return false;
404  }
405
406  while (vim_isIDc((uint8_t)(**s))) {
407    (*s) += utfc_ptr2len(*s);
408  }
409
410  *s = cin_skipcomment(*s);
411
412  // "::" is not a label, it's C++
413  return **s == ':' && *++*s != ':';
414}
415
416// Recognize a label: "label:".
417// Note: curwin->w_cursor must be where we are looking for the label.
418static bool cin_islabel(void)  // XXX
419{
420  const char *s = cin_skipcomment(get_cursor_line_ptr());
421
422  // Exclude "default" from labels, since it should be indented
423  // like a switch label.  Same for C++ scope declarations.
424  if (cin_isdefault(s)) {
425    return false;
426  }
427  if (cin_isscopedecl(s)) {
428    return false;
429  }
430
431  if (!cin_islabel_skip(&s)) {
432    return false;
433  }
434
435  if (ind_find_start_CORS(NULL)) {
436    return false;  // Don't accept a label in a comment or a raw string.
437  }
438  // Only accept a label if the previous line is terminated or is a case
439  // label.
440  pos_T cursor_save;
441  pos_T *trypos;
442  const char *line;
443
444  cursor_save = curwin->w_cursor;
445  while (curwin->w_cursor.lnum > 1) {
446    curwin->w_cursor.lnum--;
447
448    // If we're in a comment or raw string now, skip to the start of
449    // it.
450    curwin->w_cursor.col = 0;
451    if ((trypos = ind_find_start_CORS(NULL)) != NULL) {   // XXX
452      curwin->w_cursor = *trypos;
453    }
454
455    line = get_cursor_line_ptr();
456    if (cin_ispreproc(line)) {        // ignore #defines, #if, etc.
457      continue;
458    }
459    if (*(line = cin_skipcomment(line)) == NUL) {
460      continue;
461    }
462
463    curwin->w_cursor = cursor_save;
464    if (cin_isterminated(line, true, false)
465        || cin_isscopedecl(line)
466        || cin_iscase(line, true)
467        || (cin_islabel_skip(&line) && cin_nocode(line))) {
468      return true;
469    }
470    return false;
471  }
472  curwin->w_cursor = cursor_save;
473  return true;  // label at start of file???
474}
475
476/// Strings can be concatenated with comments between:
477/// "string0" |*comment*| "string1"
478static const char *cin_skip_comment_and_string(const char *s)
479{
480  const char *r = NULL, *p = s;
481  do {
482    r = p;
483    p = cin_skipcomment(p);
484    if (*p) {
485      p = skip_string(p);
486    }
487  } while (p != r);
488  return p;
489}
490
491/// Recognize structure or compound literal initialization:
492/// =|return [&][(typecast)] [{]
493/// The number of opening braces is arbitrary.
494static bool cin_is_compound_init(const char *s)
495{
496  const char *p = s, *r = NULL;
497
498  while (*p) {
499    if (*p == '=') {
500      p = r = cin_skipcomment(p + 1);
501    } else if (strncmp(p, "return", 6) == 0 && !vim_isIDc(p[6])
502               && (p == s || (p > s && !vim_isIDc(p[-1])))) {
503      p = r = cin_skipcomment(p + 6);
504    } else {
505      p = cin_skip_comment_and_string(p + 1);
506    }
507  }
508  if (!r) {
509    return false;
510  }
511  p = r;  // p points now after '=' or "return"
512
513  if (cin_nocode(p)) {
514    return true;
515  }
516
517  if (*p == '&') {
518    p = cin_skipcomment(p + 1);
519  }
520
521  if (*p == '(') {  // skip a typecast
522    int open_count = 1;
523    do {
524      p = cin_skip_comment_and_string(p + 1);
525      if (cin_nocode(p)) {
526        return true;
527      }
528      open_count += (*p == '(') - (*p == ')');
529    } while (open_count);
530    p = cin_skipcomment(p + 1);
531    if (cin_nocode(p)) {
532      return true;
533    }
534  }
535
536  while (*p == '{') {
537    p = cin_skipcomment(p + 1);
538  }
539  return cin_nocode(p);
540}
541
542/// Recognize enumerations:
543/// "[typedef] [static|public|protected|private] enum"
544/// Calls another function to recognize structure initialization.
545static bool cin_isinit(void)
546{
547  const char *s;
548  static char *skip[] = { "static", "public", "protected", "private" };
549
550  s = cin_skipcomment(get_cursor_line_ptr());
551
552  if (cin_starts_with(s, "typedef")) {
553    s = cin_skipcomment(s + 7);
554  }
555
556  while (true) {
557    int i, l;
558
559    for (i = 0; i < (int)ARRAY_SIZE(skip); i++) {
560      l = (int)strlen(skip[i]);
561      if (cin_starts_with(s, skip[i])) {
562        s = cin_skipcomment(s + l);
563        l = 0;
564        break;
565      }
566    }
567    if (l != 0) {
568      break;
569    }
570  }
571
572  if (cin_starts_with(s, "enum")) {
573    return true;
574  }
575
576  return cin_is_compound_init(s);
577}
578
579/// Recognize a switch label: "case .*:" or "default:".
580///
581/// @param strict  Allow relaxed check of case statement for JS
582static bool cin_iscase(const char *s, bool strict)
583{
584  s = cin_skipcomment(s);
585  if (cin_starts_with(s, "case")) {
586    for (s += 4; *s; s++) {
587      s = cin_skipcomment(s);
588      if (*s == NUL) {
589        break;
590      }
591      if (*s == ':') {
592        if (s[1] == ':') {              // skip over "::" for C++
593          s++;
594        } else {
595          return true;
596        }
597      }
598      if (*s == '\'' && s[1] && s[2] == '\'') {
599        s += 2;                         // skip over ':'
600      } else if (*s == '/' && (s[1] == '*' || s[1] == '/')) {
601        return false;                   // stop at comment
602      } else if (*s == '"') {
603        // JS etc.
604        if (strict) {
605          return false;                 // stop at string
606        }
607        return true;
608      }
609    }
610    return false;
611  }
612
613  if (cin_isdefault(s)) {
614    return true;
615  }
616  return false;
617}
618
619// Recognize a "default" switch label.
620static int cin_isdefault(const char *s)
621{
622  return strncmp(s, "default", 7) == 0
623         && *(s = cin_skipcomment(s + 7)) == ':'
624         && s[1] != ':';
625}
626
627/// Recognize a scope declaration label from the 'cinscopedecls' option.
628static bool cin_isscopedecl(const char *p)
629{
630  const char *s = cin_skipcomment(p);
631
632  const size_t cinsd_len = strlen(curbuf->b_p_cinsd) + 1;
633  char *cinsd_buf = xmalloc(cinsd_len);
634
635  bool found = false;
636
637  for (char *cinsd = curbuf->b_p_cinsd; *cinsd;) {
638    const size_t len = copy_option_part(&cinsd, cinsd_buf, cinsd_len, ",");
639    if (strncmp(s, cinsd_buf, len) == 0) {
640      const char *skip = cin_skipcomment(s + len);
641      if (*skip == ':' && skip[1] != ':') {
642        found = true;
643        break;
644      }
645    }
646  }
647
648  xfree(cinsd_buf);
649
650  return found;
651}
652
653// Maximum number of lines to search back for a "namespace" line.
654#define FIND_NAMESPACE_LIM 20
655
656// Recognize a "namespace" scope declaration.
657static bool cin_is_cpp_namespace(const char *s)
658{
659  const char *p;
660  bool has_name = false;
661  bool has_name_start = false;
662
663  s = cin_skipcomment(s);
664
665  // skip over "inline" and "export" in any order
666  while ((strncmp(s, "inline", 6) == 0 || strncmp(s, "export", 6) == 0)
667         && (s[6] == NUL || !vim_iswordc((uint8_t)s[6]))) {
668    s = cin_skipcomment(skipwhite(s + 6));
669  }
670
671  if (strncmp(s, "namespace", 9) == 0 && (s[9] == NUL || !vim_iswordc((uint8_t)s[9]))) {
672    p = cin_skipcomment(skipwhite(s + 9));
673    while (*p != NUL) {
674      if (ascii_iswhite(*p)) {
675        has_name = true;         // found end of a name
676        p = cin_skipcomment(skipwhite(p));
677      } else if (*p == '{') {
678        break;
679      } else if (vim_iswordc((uint8_t)(*p))) {
680        has_name_start = true;
681        if (has_name) {
682          return false;           // word character after skipping past name
683        }
684        p++;
685      } else if (p[0] == ':' && p[1] == ':' && vim_iswordc((uint8_t)p[2])) {
686        if (!has_name_start || has_name) {
687          return false;
688        }
689        // C++ 17 nested namespace
690        p += 3;
691      } else {
692        return false;
693      }
694    }
695    return true;
696  }
697  return false;
698}
699
700// Return a pointer to the first non-empty non-comment character after a ':'.
701// Return NULL if not found.
702//        case 234:    a = b;
703//                     ^
704static const char *after_label(const char *l)
705{
706  for (; *l; l++) {
707    if (*l == ':') {
708      if (l[1] == ':') {            // skip over "::" for C++
709        l++;
710      } else if (!cin_iscase(l + 1, false)) {
711        break;
712      }
713    } else if (*l == '\'' && l[1] && l[2] == '\'') {
714      l += 2;                       // skip over 'x'
715    }
716  }
717  if (*l == NUL) {
718    return NULL;
719  }
720  l = cin_skipcomment(l + 1);
721  if (*l == NUL) {
722    return NULL;
723  }
724  return l;
725}
726
727// Get indent of line "lnum", skipping a label.
728// Return 0 if there is nothing after the label.
729static int get_indent_nolabel(linenr_T lnum)  // XXX
730{
731  const char *l;
732  pos_T fp;
733  colnr_T col;
734  const char *p;
735
736  l = ml_get(lnum);
737  p = after_label(l);
738  if (p == NULL) {
739    return 0;
740  }
741
742  fp.col = (colnr_T)(p - l);
743  fp.lnum = lnum;
744  getvcol(curwin, &fp, &col, NULL, NULL, 0);
745  return (int)col;
746}
747
748// Find indent for line "lnum", ignoring any case or jump label.
749// Also return a pointer to the text (after the label) in "pp".
750//   label:     if (asdf && asdfasdf)
751//              ^
752static int skip_label(linenr_T lnum, const char **pp)
753{
754  const char *l;
755  int amount;
756  pos_T cursor_save;
757
758  cursor_save = curwin->w_cursor;
759  curwin->w_cursor.lnum = lnum;
760  l = get_cursor_line_ptr();
761  // XXX
762  if (cin_iscase(l, false) || cin_isscopedecl(l) || cin_islabel()) {
763    amount = get_indent_nolabel(lnum);
764    l = after_label(get_cursor_line_ptr());
765    if (l == NULL) {            // just in case
766      l = get_cursor_line_ptr();
767    }
768  } else {
769    amount = get_indent();
770    l = get_cursor_line_ptr();
771  }
772  *pp = l;
773
774  curwin->w_cursor = cursor_save;
775  return amount;
776}
777
778// Return the indent of the first variable name after a type in a declaration.
779//  int     a,                  indent of "a"
780//  static struct foo    b,     indent of "b"
781//  enum bla    c,              indent of "c"
782// Returns zero when it doesn't look like a declaration.
783static int cin_first_id_amount(void)
784{
785  char *line, *p, *s;
786  int len;
787  pos_T fp;
788  colnr_T col;
789
790  line = get_cursor_line_ptr();
791  p = skipwhite(line);
792  len = (int)(skiptowhite(p) - p);
793  if (len == 6 && strncmp(p, "static", 6) == 0) {
794    p = skipwhite(p + 6);
795    len = (int)(skiptowhite(p) - p);
796  }
797  if (len == 6 && strncmp(p, "struct", 6) == 0) {
798    p = skipwhite(p + 6);
799  } else if (len == 4 && strncmp(p, "enum", 4) == 0) {
800    p = skipwhite(p + 4);
801  } else if ((len == 8 && strncmp(p, "unsigned", 8) == 0)
802             || (len == 6 && strncmp(p, "signed", 6) == 0)) {
803    s = skipwhite(p + len);
804    if ((strncmp(s, "int", 3) == 0 && ascii_iswhite(s[3]))
805        || (strncmp(s, "long", 4) == 0 && ascii_iswhite(s[4]))
806        || (strncmp(s, "short", 5) == 0 && ascii_iswhite(s[5]))
807        || (strncmp(s, "char", 4) == 0 && ascii_iswhite(s[4]))) {
808      p = s;
809    }
810  }
811  for (len = 0; vim_isIDc((uint8_t)p[len]); len++) {}
812  if (len == 0 || !ascii_iswhite(p[len]) || cin_nocode(p)) {
813    return 0;
814  }
815
816  p = skipwhite(p + len);
817  fp.lnum = curwin->w_cursor.lnum;
818  fp.col = (colnr_T)(p - line);
819  getvcol(curwin, &fp, &col, NULL, NULL, 0);
820  return (int)col;
821}
822
823// Return the indent of the first non-blank after an equal sign.
824//       char *foo = "here";
825// Return zero if no (useful) equal sign found.
826// Return -1 if the line above "lnum" ends in a backslash.
827//      foo = "asdf{backslash}
828//             asdf{backslash}
829//             here";
830static int cin_get_equal_amount(linenr_T lnum)
831{
832  const char *line;
833  const char *s;
834  colnr_T col;
835  pos_T fp;
836
837  if (lnum > 1) {
838    line = ml_get(lnum - 1);
839    if (*line != NUL && line[strlen(line) - 1] == '\\') {
840      return -1;
841    }
842  }
843
844  s = ml_get(lnum);
845  line = s;
846  while (*s != NUL && vim_strchr("=;{}\"'", (uint8_t)(*s)) == NULL) {
847    if (cin_iscomment(s)) {     // ignore comments
848      s = cin_skipcomment(s);
849    } else {
850      s++;
851    }
852  }
853  if (*s != '=') {
854    return 0;
855  }
856
857  s = skipwhite(s + 1);
858  if (cin_nocode(s)) {
859    return 0;
860  }
861
862  if (*s == '"') {      // nice alignment for continued strings
863    s++;
864  }
865
866  fp.lnum = lnum;
867  fp.col = (colnr_T)(s - line);
868  getvcol(curwin, &fp, &col, NULL, NULL, 0);
869  return (int)col;
870}
871
872// Recognize a preprocessor statement: Any line that starts with '#'.
873static int cin_ispreproc(const char *s)
874{
875  if (*skipwhite(s) == '#') {
876    return true;
877  }
878  return false;
879}
880
881/// Return true if line "*pp" at "*lnump" is a preprocessor statement or a
882/// continuation line of a preprocessor statement.  Decrease "*lnump" to the
883/// start and return the line in "*pp".
884/// Put the amount of indent in "*amount".
885static int cin_ispreproc_cont(const char **pp, linenr_T *lnump, int *amount)
886{
887  const char *line = *pp;
888  linenr_T lnum = *lnump;
889  int retval = false;
890  int candidate_amount = *amount;
891
892  if (*line != NUL && line[strlen(line) - 1] == '\\') {
893    candidate_amount = get_indent_lnum(lnum);
894  }
895
896  while (true) {
897    if (cin_ispreproc(line)) {
898      retval = true;
899      *lnump = lnum;
900      break;
901    }
902    if (lnum == 1) {
903      break;
904    }
905    line = ml_get(--lnum);
906    if (*line == NUL || line[strlen(line) - 1] != '\\') {
907      break;
908    }
909  }
910
911  if (lnum != *lnump) {
912    *pp = ml_get(*lnump);
913  }
914  if (retval) {
915    *amount = candidate_amount;
916  }
917  return retval;
918}
919
920// Recognize the start of a C or C++ comment.
921static int cin_iscomment(const char *p)
922{
923  return p[0] == '/' && (p[1] == '*' || p[1] == '/');
924}
925
926// Recognize the start of a "//" comment.
927static int cin_islinecomment(const char *p)
928{
929  return p[0] == '/' && p[1] == '/';
930}
931
932/// Recognize a line that starts with '{' or '}', or ends with ';', ',', '{' or
933/// '}'.
934/// Don't consider "} else" a terminated line.
935/// If a line begins with an "else", only consider it terminated if no unmatched
936/// opening braces follow (handle "else { foo();" correctly).
937///
938/// @param incl_open   include '{' at the end as terminator
939/// @param incl_comma  recognize a trailing comma
940///
941/// @return  the character terminating the line (ending char's have precedence if
942///          both apply in order to determine initializations).
943static char cin_isterminated(const char *s, int incl_open, int incl_comma)
944{
945  char found_start = 0;
946  unsigned n_open = 0;
947  int is_else = false;
948
949  s = cin_skipcomment(s);
950
951  if (*s == '{' || (*s == '}' && !cin_iselse(s))) {
952    found_start = *s;
953  }
954
955  if (!found_start) {
956    is_else = cin_iselse(s);
957  }
958
959  while (*s) {
960    // skip over comments, "" strings and 'c'haracters
961    s = skip_string(cin_skipcomment(s));
962    if (*s == '}' && n_open > 0) {
963      n_open--;
964    }
965    if ((!is_else || n_open == 0)
966        && (*s == ';' || *s == '}' || (incl_comma && *s == ','))
967        && cin_nocode(s + 1)) {
968      return *s;
969    } else if (*s == '{') {
970      if (incl_open && cin_nocode(s + 1)) {
971        return *s;
972      } else {
973        n_open++;
974      }
975    }
976
977    if (*s) {
978      s++;
979    }
980  }
981  return found_start;
982}
983
984/// Recognizes the basic picture of a function declaration -- it needs to
985/// have an open paren somewhere and a close paren at the end of the line and
986/// no semicolons anywhere.
987/// When a line ends in a comma we continue looking in the next line.
988///
989/// @param[in]  sp  Points to a string with the line. When looking at other
990///                 lines it must be restored to the line. When it's NULL fetch
991///                 lines here.
992/// @param[in]  first_lnum Where to start looking.
993/// @param[in]  min_lnum The line before which we will not be looking.
994static int cin_isfuncdecl(const char **sp, linenr_T first_lnum, linenr_T min_lnum)
995{
996  const char *s;
997  linenr_T lnum = first_lnum;
998  linenr_T save_lnum = curwin->w_cursor.lnum;
999  int retval = false;
1000  pos_T *trypos;
1001  int just_started = true;
1002
1003  if (sp == NULL) {
1004    s = ml_get(lnum);
1005  } else {
1006    s = *sp;
1007  }
1008
1009  curwin->w_cursor.lnum = lnum;
1010  if (find_last_paren(s, '(', ')')
1011      && (trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL) {
1012    lnum = trypos->lnum;
1013    if (lnum < min_lnum) {
1014      curwin->w_cursor.lnum = save_lnum;
1015      return false;
1016    }
1017    s = ml_get(lnum);
1018  }
1019
1020  curwin->w_cursor.lnum = save_lnum;
1021  // Ignore line starting with #.
1022  if (cin_ispreproc(s)) {
1023    return false;
1024  }
1025
1026  while (*s && *s != '(' && *s != ';' && *s != '\'' && *s != '"') {
1027    // ignore comments
1028    if (cin_iscomment(s)) {
1029      s = cin_skipcomment(s);
1030    } else if (*s == ':') {
1031      if (*(s + 1) == ':') {
1032        s += 2;
1033      } else {
1034        // To avoid a mistake in the following situation:
1035        // A::A(int a, int b)
1036        //     : a(0)  // <--not a function decl
1037        //     , b(0)
1038        // {...
1039        return false;
1040      }
1041    } else {
1042      s++;
1043    }
1044  }
1045  if (*s != '(') {
1046    return false;  // ';', ' or "  before any () or no '('
1047  }
1048
1049  while (*s && *s != ';' && *s != '\'' && *s != '"') {
1050    if (*s == ')' && cin_nocode(s + 1)) {
1051      // ')' at the end: may have found a match
1052      // Check for the previous line not to end in a backslash:
1053      //       #if defined(x) && {backslash}
1054      //           defined(y)
1055      lnum = first_lnum - 1;
1056      s = ml_get(lnum);
1057      if (*s == NUL || s[strlen(s) - 1] != '\\') {
1058        retval = true;
1059      }
1060      goto done;
1061    }
1062    if ((*s == ',' && cin_nocode(s + 1)) || s[1] == NUL || cin_nocode(s)) {
1063      int comma = (*s == ',');
1064
1065      // ',' at the end: continue looking in the next line.
1066      // At the end: check for ',' in the next line, for this style:
1067      // func(arg1
1068      //       , arg2)
1069      while (true) {
1070        if (lnum >= curbuf->b_ml.ml_line_count) {
1071          break;
1072        }
1073        s = ml_get(++lnum);
1074        if (!cin_ispreproc(s)) {
1075          break;
1076        }
1077      }
1078      if (lnum >= curbuf->b_ml.ml_line_count) {
1079        break;
1080      }
1081      // Require a comma at end of the line or a comma or ')' at the
1082      // start of next line.
1083      s = skipwhite(s);
1084      if (!just_started && (!comma && *s != ',' && *s != ')')) {
1085        break;
1086      }
1087      just_started = false;
1088    } else if (cin_iscomment(s)) {      // ignore comments
1089      s = cin_skipcomment(s);
1090    } else {
1091      s++;
1092      just_started = false;
1093    }
1094  }
1095
1096done:
1097  if (lnum != first_lnum && sp != NULL) {
1098    *sp = ml_get(first_lnum);
1099  }
1100
1101  return retval;
1102}
1103
1104static int cin_isif(const char *p)
1105{
1106  return strncmp(p, "if", 2) == 0 && !vim_isIDc((uint8_t)p[2]);
1107}
1108
1109static int cin_iselse(const char *p)
1110{
1111  if (*p == '}') {          // accept "} else"
1112    p = cin_skipcomment(p + 1);
1113  }
1114  return strncmp(p, "else", 4) == 0 && !vim_isIDc((uint8_t)p[4]);
1115}
1116
1117static int cin_isdo(const char *p)
1118{
1119  return strncmp(p, "do", 2) == 0 && !vim_isIDc((uint8_t)p[2]);
1120}
1121
1122// Check if this is a "while" that should have a matching "do".
1123// We only accept a "while (condition) ;", with only white space between the
1124// ')' and ';'. The condition may be spread over several lines.
1125static int cin_iswhileofdo(const char *p, linenr_T lnum)  // XXX
1126{
1127  pos_T cursor_save;
1128  pos_T *trypos;
1129  int retval = false;
1130
1131  p = cin_skipcomment(p);
1132  if (*p == '}') {              // accept "} while (cond);"
1133    p = cin_skipcomment(p + 1);
1134  }
1135  if (cin_starts_with(p, "while")) {
1136    cursor_save = curwin->w_cursor;
1137    curwin->w_cursor.lnum = lnum;
1138    curwin->w_cursor.col = 0;
1139    p = get_cursor_line_ptr();
1140    while (*p && *p != 'w') {   // skip any '}', until the 'w' of the "while"
1141      p++;
1142      curwin->w_cursor.col++;
1143    }
1144    if ((trypos = findmatchlimit(NULL, 0, FM_SKIPCOMM, curbuf->b_ind_maxparen)) != NULL
1145        && *cin_skipcomment(ml_get_pos(trypos) + 1) == ';') {
1146      retval = true;
1147    }
1148    curwin->w_cursor = cursor_save;
1149  }
1150  return retval;
1151}
1152
1153// Check whether in "p" there is an "if", "for" or "while" before "*poffset".
1154// Return 0 if there is none.
1155// Otherwise return !0 and update "*poffset" to point to the place where the
1156// string was found.
1157static int cin_is_if_for_while_before_offset(const char *line, int *poffset)
1158{
1159  int offset = *poffset;
1160
1161  if (offset-- < 2) {
1162    return 0;
1163  }
1164  while (offset > 2 && ascii_iswhite(line[offset])) {
1165    offset--;
1166  }
1167
1168  offset -= 1;
1169  if (strncmp(line + offset, "if", 2) == 0) {
1170    goto probablyFound;
1171  }
1172
1173  if (offset >= 1) {
1174    offset -= 1;
1175    if (strncmp(line + offset, "for", 3) == 0) {
1176      goto probablyFound;
1177    }
1178
1179    if (offset >= 2) {
1180      offset -= 2;
1181      if (strncmp(line + offset, "while", 5) == 0) {
1182        goto probablyFound;
1183      }
1184    }
1185  }
1186  return 0;
1187
1188probablyFound:
1189  if (!offset || !vim_isIDc((uint8_t)line[offset - 1])) {
1190    *poffset = offset;
1191    return 1;
1192  }
1193  return 0;
1194}
1195
1196/// Return true if we are at the end of a do-while.
1197///    do
1198///       nothing;
1199///    while (foo
1200///             && bar);  <-- here
1201/// Adjust the cursor to the line with "while".
1202static int cin_iswhileofdo_end(int terminated)
1203{
1204  const char *line;
1205  const char *p;
1206  const char *s;
1207  pos_T *trypos;
1208  int i;
1209
1210  if (terminated != ';') {      // there must be a ';' at the end
1211    return false;
1212  }
1213
1214  p = line = get_cursor_line_ptr();
1215  while (*p != NUL) {
1216    p = cin_skipcomment(p);
1217    if (*p == ')') {
1218      s = skipwhite(p + 1);
1219      if (*s == ';' && cin_nocode(s + 1)) {
1220        // Found ");" at end of the line, now check there is "while"
1221        // before the matching '('.  XXX
1222        i = (int)(p - line);
1223        curwin->w_cursor.col = i;
1224        trypos = find_match_paren(curbuf->b_ind_maxparen);
1225        if (trypos != NULL) {
1226          s = cin_skipcomment(ml_get(trypos->lnum));
1227          if (*s == '}') {                      // accept "} while (cond);"
1228            s = cin_skipcomment(s + 1);
1229          }
1230          if (cin_starts_with(s, "while")) {
1231            curwin->w_cursor.lnum = trypos->lnum;
1232            return true;
1233          }
1234        }
1235
1236        // Searching may have made "line" invalid, get it again.
1237        line = get_cursor_line_ptr();
1238        p = line + i;
1239      }
1240    }
1241    if (*p != NUL) {
1242      p++;
1243    }
1244  }
1245  return false;
1246}
1247
1248static int cin_isbreak(const char *p)
1249{
1250  return strncmp(p, "break", 5) == 0 && !vim_isIDc((uint8_t)p[5]);
1251}
1252
1253// Find the position of a C++ base-class declaration or
1254// constructor-initialization. eg:
1255//
1256// class MyClass :
1257//      baseClass               <-- here
1258// class MyClass : public baseClass,
1259//      anotherBaseClass        <-- here (should probably lineup ??)
1260// MyClass::MyClass(...) :
1261//      baseClass(...)          <-- here (constructor-initialization)
1262//
1263// This is a lot of guessing.  Watch out for "cond ? func() : foo".
1264static int cin_is_cpp_baseclass(cpp_baseclass_cache_T *cached)
1265{
1266  lpos_T *pos = &cached->lpos;  // find position
1267  const char *s;
1268  int class_or_struct, lookfor_ctor_init, cpp_base_class;
1269  linenr_T lnum = curwin->w_cursor.lnum;
1270  const char *line = get_cursor_line_ptr();
1271
1272  if (pos->lnum <= lnum) {
1273    return cached->found;  // Use the cached result
1274  }
1275
1276  pos->col = 0;
1277
1278  s = skipwhite(line);
1279  if (*s == '#') {              // skip #define FOO x ? (x) : x
1280    return false;
1281  }
1282  s = cin_skipcomment(s);
1283  if (*s == NUL) {
1284    return false;
1285  }
1286
1287  cpp_base_class = lookfor_ctor_init = class_or_struct = false;
1288
1289  // Search for a line starting with '#', empty, ending in ';' or containing
1290  // '{' or '}' and start below it.  This handles the following situations:
1291  //    a = cond ?
1292  //          func() :
1293  //               asdf;
1294  //    func::foo()
1295  //          : something
1296  //    {}
1297  //    Foo::Foo (int one, int two)
1298  //            : something(4),
1299  //            somethingelse(3)
1300  //    {}
1301  while (lnum > 1) {
1302    line = ml_get(lnum - 1);
1303    s = skipwhite(line);
1304    if (*s == '#' || *s == NUL) {
1305      break;
1306    }
1307    while (*s != NUL) {
1308      s = cin_skipcomment(s);
1309      if (*s == '{' || *s == '}'
1310          || (*s == ';' && cin_nocode(s + 1))) {
1311        break;
1312      }
1313      if (*s != NUL) {
1314        s++;
1315      }
1316    }
1317    if (*s != NUL) {
1318      break;
1319    }
1320    lnum--;
1321  }
1322
1323  pos->lnum = lnum;
1324  line = ml_get(lnum);
1325  s = line;
1326  while (true) {
1327    if (*s == NUL) {
1328      if (lnum == curwin->w_cursor.lnum) {
1329        break;
1330      }
1331      // Continue in the cursor line.
1332      line = ml_get(++lnum);
1333      s = line;
1334    }
1335    if (s == line) {
1336      // don't recognize "case (foo):" as a baseclass
1337      if (cin_iscase(s, false)) {
1338        break;
1339      }
1340      s = cin_skipcomment(line);
1341      if (*s == NUL) {
1342        continue;
1343      }
1344    }
1345
1346    if (s[0] == '"' || (s[0] == 'R' && s[1] == '"')) {
1347      s = skip_string(s) + 1;
1348    } else if (s[0] == ':') {
1349      if (s[1] == ':') {
1350        // skip double colon. It can't be a constructor
1351        // initialization any more
1352        lookfor_ctor_init = false;
1353        s = cin_skipcomment(s + 2);
1354      } else if (lookfor_ctor_init || class_or_struct) {
1355        // we have something found, that looks like the start of
1356        // cpp-base-class-declaration or constructor-initialization
1357        cpp_base_class = true;
1358        lookfor_ctor_init = class_or_struct = false;
1359        pos->col = 0;
1360        s = cin_skipcomment(s + 1);
1361      } else {
1362        s = cin_skipcomment(s + 1);
1363      }
1364    } else if ((strncmp(s, "class", 5) == 0 && !vim_isIDc((uint8_t)s[5]))
1365               || (strncmp(s, "struct", 6) == 0 && !vim_isIDc((uint8_t)s[6]))) {
1366      class_or_struct = true;
1367      lookfor_ctor_init = false;
1368
1369      if (*s == 'c') {
1370        s = cin_skipcomment(s + 5);
1371      } else {
1372        s = cin_skipcomment(s + 6);
1373      }
1374    } else {
1375      if (s[0] == '{' || s[0] == '}' || s[0] == ';') {
1376        cpp_base_class = lookfor_ctor_init = class_or_struct = false;
1377      } else if (s[0] == ')') {
1378        // Constructor-initialization is assumed if we come across
1379        // something like "):"
1380        class_or_struct = false;
1381        lookfor_ctor_init = true;
1382      } else if (s[0] == '?') {
1383        // Avoid seeing '() :' after '?' as constructor init.
1384        return false;
1385      } else if (!vim_isIDc((uint8_t)s[0])) {
1386        // if it is not an identifier, we are wrong
1387        class_or_struct = false;
1388        lookfor_ctor_init = false;
1389      } else if (pos->col == 0) {
1390        // it can't be a constructor-initialization any more
1391        lookfor_ctor_init = false;
1392
1393        // the first statement starts here: lineup with this one...
1394        if (cpp_base_class) {
1395          pos->col = (colnr_T)(s - line);
1396        }
1397      }
1398
1399      // When the line ends in a comma don't align with it.
1400      if (lnum == curwin->w_cursor.lnum && *s == ',' && cin_nocode(s + 1)) {
1401        pos->col = 0;
1402      }
1403
1404      s = cin_skipcomment(s + 1);
1405    }
1406  }
1407
1408  cached->found = cpp_base_class;
1409  if (cpp_base_class) {
1410    pos->lnum = lnum;
1411  }
1412  return cpp_base_class;
1413}
1414
1415static int get_baseclass_amount(int col)
1416{
1417  int amount;
1418  colnr_T vcol;
1419  pos_T *trypos;
1420
1421  if (col == 0) {
1422    amount = get_indent();
1423    if (find_last_paren(get_cursor_line_ptr(), '(', ')')
1424        && (trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL) {
1425      amount = get_indent_lnum(trypos->lnum);       // XXX
1426    }
1427    if (!cin_ends_in(get_cursor_line_ptr(), ",")) {
1428      amount += curbuf->b_ind_cpp_baseclass;
1429    }
1430  } else {
1431    curwin->w_cursor.col = col;
1432    getvcol(curwin, &curwin->w_cursor, &vcol, NULL, NULL, 0);
1433    amount = (int)vcol;
1434  }
1435  if (amount < curbuf->b_ind_cpp_baseclass) {
1436    amount = curbuf->b_ind_cpp_baseclass;
1437  }
1438  return amount;
1439}
1440
1441/// Return true if string "s" ends with the string "find", possibly followed by
1442/// white space and comments.  Skip strings and comments.
1443static int cin_ends_in(const char *s, const char *find)
1444{
1445  const char *p = s;
1446  const char *r;
1447  int len = (int)strlen(find);
1448
1449  while (*p != NUL) {
1450    p = cin_skipcomment(p);
1451    if (strncmp(p, find, (size_t)len) == 0) {
1452      r = skipwhite(p + len);
1453      if (cin_nocode(r)) {
1454        return true;
1455      }
1456    }
1457    if (*p != NUL) {
1458      p++;
1459    }
1460  }
1461  return false;
1462}
1463
1464/// Return true when "s" starts with "word" and then a non-ID character.
1465static int cin_starts_with(const char *s, const char *word)
1466{
1467  size_t l = strlen(word);
1468
1469  return strncmp(s, word, l) == 0 && !vim_isIDc((uint8_t)s[l]);
1470}
1471
1472/// Recognize a `extern "C"` or `extern "C++"` linkage specifications.
1473static int cin_is_cpp_extern_c(const char *s)
1474{
1475  const char *p;
1476  int has_string_literal = false;
1477
1478  s = cin_skipcomment(s);
1479  if (strncmp(s, "extern", 6) == 0 && (s[6] == NUL || !vim_iswordc((uint8_t)s[6]))) {
1480    p = cin_skipcomment(skipwhite(s + 6));
1481    while (*p != NUL) {
1482      if (ascii_iswhite(*p)) {
1483        p = cin_skipcomment(skipwhite(p));
1484      } else if (*p == '{') {
1485        break;
1486      } else if (p[0] == '"' && p[1] == 'C' && p[2] == '"') {
1487        if (has_string_literal) {
1488          return false;
1489        }
1490        has_string_literal = true;
1491        p += 3;
1492      } else if (p[0] == '"' && p[1] == 'C' && p[2] == '+' && p[3] == '+'
1493                 && p[4] == '"') {
1494        if (has_string_literal) {
1495          return false;
1496        }
1497        has_string_literal = true;
1498        p += 5;
1499      } else {
1500        return false;
1501      }
1502    }
1503    return has_string_literal ? true : false;
1504  }
1505  return false;
1506}
1507
1508// Skip strings, chars and comments until at or past "trypos".
1509// Return the column found.
1510static int cin_skip2pos(pos_T *trypos)
1511{
1512  const char *line;
1513  const char *p;
1514  const char *new_p;
1515
1516  line = ml_get(trypos->lnum);
1517  p = line;
1518  while (*p && (colnr_T)(p - line) < trypos->col) {
1519    if (cin_iscomment(p)) {
1520      p = cin_skipcomment(p);
1521    } else {
1522      new_p = skip_string(p);
1523      if (new_p == p) {
1524        p++;
1525      } else {
1526        p = new_p;
1527      }
1528    }
1529  }
1530  return (int)(p - line);
1531}
1532
1533// Find the '{' at the start of the block we are in.
1534// Return NULL if no match found.
1535// Ignore a '{' that is in a comment, makes indenting the next three lines
1536// work.
1537// foo()
1538// {
1539// }
1540
1541static pos_T *find_start_brace(void)  // XXX
1542{
1543  pos_T cursor_save;
1544  pos_T *trypos;
1545  pos_T *pos;
1546  static pos_T pos_copy;
1547
1548  cursor_save = curwin->w_cursor;
1549  while ((trypos = findmatchlimit(NULL, '{', FM_BLOCKSTOP | FM_SKIPCOMM, 0)) != NULL) {
1550    pos_copy = *trypos;         // copy pos_T, next findmatch will change it
1551    trypos = &pos_copy;
1552    curwin->w_cursor = *trypos;
1553    pos = NULL;
1554    // ignore the { if it's in a // or / *  * / comment
1555    if ((colnr_T)cin_skip2pos(trypos) == trypos->col
1556        && (pos = ind_find_start_CORS(NULL)) == NULL) {   // XXX
1557      break;
1558    }
1559    if (pos != NULL) {
1560      curwin->w_cursor = *pos;
1561    }
1562  }
1563  curwin->w_cursor = cursor_save;
1564  return trypos;
1565}
1566
1567/// Find the matching '(', ignoring it if it is in a comment.
1568/// @returns NULL or the found match.
1569static pos_T *find_match_paren(int ind_maxparen)
1570{
1571  return find_match_char('(', ind_maxparen);
1572}
1573
1574static pos_T *find_match_char(char c, int ind_maxparen)
1575{
1576  pos_T cursor_save;
1577  pos_T *trypos;
1578  static pos_T pos_copy;
1579  int ind_maxp_wk;
1580
1581  cursor_save = curwin->w_cursor;
1582  ind_maxp_wk = ind_maxparen;
1583retry:
1584  if ((trypos = findmatchlimit(NULL, (uint8_t)c, FM_SKIPCOMM, ind_maxp_wk)) != NULL) {
1585    // check if the ( is in a // comment
1586    if ((colnr_T)cin_skip2pos(trypos) > trypos->col) {
1587      ind_maxp_wk = ind_maxparen - (cursor_save.lnum - trypos->lnum);
1588      if (ind_maxp_wk > 0) {
1589        curwin->w_cursor = *trypos;
1590        curwin->w_cursor.col = 0;  // XXX
1591        goto retry;
1592      }
1593      trypos = NULL;
1594    } else {
1595      pos_T *trypos_wk;
1596
1597      pos_copy = *trypos;           // copy trypos, findmatch will change it
1598      trypos = &pos_copy;
1599      curwin->w_cursor = *trypos;
1600      if ((trypos_wk = ind_find_start_CORS(NULL)) != NULL) {  // XXX
1601        ind_maxp_wk = ind_maxparen - (cursor_save.lnum - trypos_wk->lnum);
1602        if (ind_maxp_wk > 0) {
1603          curwin->w_cursor = *trypos_wk;
1604          goto retry;
1605        }
1606        trypos = NULL;
1607      }
1608    }
1609  }
1610  curwin->w_cursor = cursor_save;
1611  return trypos;
1612}
1613
1614/// Find the matching '(', ignoring it if it is in a comment or before an
1615/// unmatched {.
1616/// @returns NULL or the found match.
1617static pos_T *find_match_paren_after_brace(int ind_maxparen)
1618{
1619  pos_T *trypos = find_match_paren(ind_maxparen);
1620  if (trypos == NULL) {
1621    return NULL;
1622  }
1623
1624  pos_T *tryposBrace = find_start_brace();
1625  // If both an unmatched '(' and '{' is found.  Ignore the '('
1626  // position if the '{' is further down.
1627  if (tryposBrace != NULL
1628      && (trypos->lnum != tryposBrace->lnum
1629          ? trypos->lnum < tryposBrace->lnum
1630          : trypos->col < tryposBrace->col)) {
1631    trypos = NULL;
1632  }
1633  return trypos;
1634}
1635
1636// Return ind_maxparen corrected for the difference in line number between the
1637// cursor position and "startpos".  This makes sure that searching for a
1638// matching paren above the cursor line doesn't find a match because of
1639// looking a few lines further.
1640static int corr_ind_maxparen(pos_T *startpos)
1641{
1642  int n = startpos->lnum - curwin->w_cursor.lnum;
1643
1644  if (n > 0 && n < curbuf->b_ind_maxparen / 2) {
1645    return curbuf->b_ind_maxparen - n;
1646  }
1647  return curbuf->b_ind_maxparen;
1648}
1649
1650// Set w_cursor.col to the column number of the last unmatched ')' or '{' in
1651// line "l".  "l" must point to the start of the line.
1652static int find_last_paren(const char *l, char start, char end)
1653{
1654  int i;
1655  int retval = false;
1656  int open_count = 0;
1657
1658  curwin->w_cursor.col = 0;                 // default is start of line
1659
1660  for (i = 0; l[i] != NUL; i++) {
1661    i = (int)(cin_skipcomment(l + i) - l);     // ignore parens in comments
1662    if (l[i] == NUL) {
1663      break;
1664    }
1665    i = (int)(skip_string(l + i) - l);        // ignore parens in quotes
1666    if (l[i] == start) {
1667      open_count++;
1668    } else if (l[i] == end) {
1669      if (open_count > 0) {
1670        open_count--;
1671      } else {
1672        curwin->w_cursor.col = i;
1673        retval = true;
1674      }
1675    }
1676  }
1677  return retval;
1678}
1679
1680// Parse 'cinoptions' and set the values in "curbuf".
1681// Must be called when 'cinoptions', 'shiftwidth' and/or 'tabstop' changes.
1682void parse_cino(buf_T *buf)
1683{
1684  char *p;
1685  char *l;
1686  int divider;
1687  int fraction = 0;
1688  int sw = get_sw_value(buf);
1689
1690  // Set the default values.
1691  // Spaces from a block's opening brace the prevailing indent for that
1692  // block should be.
1693  buf->b_ind_level = sw;
1694
1695  // Spaces from the edge of the line an open brace that's at the end of a
1696  // line is imagined to be.
1697  buf->b_ind_open_imag = 0;
1698
1699  // Spaces from the prevailing indent for a line that is not preceded by
1700  // an opening brace.
1701  buf->b_ind_no_brace = 0;
1702
1703  // Column where the first { of a function should be located }.
1704  buf->b_ind_first_open = 0;
1705
1706  // Spaces from the prevailing indent a leftmost open brace should be
1707  // located.
1708  buf->b_ind_open_extra = 0;
1709
1710  // Spaces from the matching open brace (real location for one at the left
1711  // edge; imaginary location from one that ends a line) the matching close
1712  // brace should be located.
1713  buf->b_ind_close_extra = 0;
1714
1715  // Spaces from the edge of the line an open brace sitting in the leftmost
1716  // column is imagined to be.
1717  buf->b_ind_open_left_imag = 0;
1718
1719  // Spaces jump labels should be shifted to the left if N is non-negative,
1720  // otherwise the jump label will be put to column 1.
1721  buf->b_ind_jump_label = -1;
1722
1723  // Spaces from the switch() indent a "case xx" label should be located.
1724  buf->b_ind_case = sw;
1725
1726  // Spaces from the "case xx:" code after a switch() should be located.
1727  buf->b_ind_case_code = sw;
1728
1729  // Lineup break at end of case in switch() with case label.
1730  buf->b_ind_case_break = 0;
1731
1732  // Spaces from the class declaration indent a scope declaration label
1733  // should be located.
1734  buf->b_ind_scopedecl = sw;
1735
1736  // Spaces from the scope declaration label code should be located.
1737  buf->b_ind_scopedecl_code = sw;
1738
1739  // Amount K&R-style parameters should be indented.
1740  buf->b_ind_param = sw;
1741
1742  // Amount a function type spec should be indented.
1743  buf->b_ind_func_type = sw;
1744
1745  // Amount a cpp base class declaration or constructor initialization
1746  // should be indented.
1747  buf->b_ind_cpp_baseclass = sw;
1748
1749  // additional spaces beyond the prevailing indent a continuation line
1750  // should be located.
1751  buf->b_ind_continuation = sw;
1752
1753  // Spaces from the indent of the line with an unclosed parentheses.
1754  buf->b_ind_unclosed = sw * 2;
1755
1756  // Spaces from the indent of the line with an unclosed parentheses, which
1757  // itself is also unclosed.
1758  buf->b_ind_unclosed2 = sw;
1759
1760  // Suppress ignoring spaces from the indent of a line starting with an
1761  // unclosed parenthesis.
1762  buf->b_ind_unclosed_noignore = 0;
1763
1764  // If the opening paren is the last nonwhite character on the line, and
1765  // b_ind_unclosed_wrapped is nonzero, use this indent relative to the outer
1766  // context (for very long lines).
1767  buf->b_ind_unclosed_wrapped = 0;
1768
1769  // Suppress ignoring white space when lining up with the character after
1770  // an unclosed parentheses.
1771  buf->b_ind_unclosed_whiteok = 0;
1772
1773  // Indent a closing parenthesis under the line start of the matching
1774  // opening parenthesis.
1775  buf->b_ind_matching_paren = 0;
1776
1777  // Indent a closing parenthesis under the previous line.
1778  buf->b_ind_paren_prev = 0;
1779
1780  // Extra indent for comments.
1781  buf->b_ind_comment = 0;
1782
1783  // Spaces from the comment opener when there is nothing after it.
1784  buf->b_ind_in_comment = 3;
1785
1786  // Boolean: if non-zero, use b_ind_in_comment even if there is something
1787  // after the comment opener.
1788  buf->b_ind_in_comment2 = 0;
1789
1790  // Max lines to search for an open paren.
1791  buf->b_ind_maxparen = 20;
1792
1793  // Max lines to search for an open comment.
1794  buf->b_ind_maxcomment = 70;
1795
1796  // Handle braces for java code.
1797  buf->b_ind_java = 0;
1798
1799  // Not to confuse JS object properties with labels.
1800  buf->b_ind_js = 0;
1801
1802  // Handle blocked cases correctly.
1803  buf->b_ind_keep_case_label = 0;
1804
1805  // Handle C++ namespace.
1806  buf->b_ind_cpp_namespace = 0;
1807
1808  // Handle continuation lines containing conditions of if(), for() and
1809  // while().
1810  buf->b_ind_if_for_while = 0;
1811
1812  // indentation for # comments
1813  buf->b_ind_hash_comment = 0;
1814
1815  // Handle C++ extern "C" or "C++"
1816  buf->b_ind_cpp_extern_c = 0;
1817
1818  // Handle C #pragma directives
1819  buf->b_ind_pragma = 0;
1820
1821  for (p = buf->b_p_cino; *p;) {
1822    l = p++;
1823    if (*p == '-') {
1824      p++;
1825    }
1826    char *digits_start = p;   // remember where the digits start
1827    int64_t n = getdigits_int(&p, true, 0);
1828    divider = 0;
1829    if (*p == '.') {        // ".5s" means a fraction.
1830      fraction = atoi(++p);
1831      while (ascii_isdigit(*p)) {
1832        p++;
1833        if (divider) {
1834          divider *= 10;
1835        } else {
1836          divider = 10;
1837        }
1838      }
1839    }
1840    if (*p == 's') {        // "2s" means two times 'shiftwidth'.
1841      if (p == digits_start) {
1842        n = sw;             // just "s" is one 'shiftwidth'.
1843      } else {
1844        n *= sw;
1845        if (divider) {
1846          n += ((int64_t)sw * fraction + divider / 2) / divider;
1847        }
1848      }
1849      p++;
1850    }
1851    if (l[1] == '-') {
1852      n = -n;
1853    }
1854
1855    n = trim_to_int(n);
1856
1857    // When adding an entry here, also update the default 'cinoptions' in
1858    // doc/indent.txt, and add explanation for it!
1859    switch (*l) {
1860    case '>':
1861      buf->b_ind_level = (int)n;
1862      break;
1863    case 'e':
1864      buf->b_ind_open_imag = (int)n;
1865      break;
1866    case 'n':
1867      buf->b_ind_no_brace = (int)n;
1868      break;
1869    case 'f':
1870      buf->b_ind_first_open = (int)n;
1871      break;
1872    case '{':
1873      buf->b_ind_open_extra = (int)n;
1874      break;
1875    case '}':
1876      buf->b_ind_close_extra = (int)n;
1877      break;
1878    case '^':
1879      buf->b_ind_open_left_imag = (int)n;
1880      break;
1881    case 'L':
1882      buf->b_ind_jump_label = (int)n;
1883      break;
1884    case ':':
1885      buf->b_ind_case = (int)n;
1886      break;
1887    case '=':
1888      buf->b_ind_case_code = (int)n;
1889      break;
1890    case 'b':
1891      buf->b_ind_case_break = (int)n;
1892      break;
1893    case 'p':
1894      buf->b_ind_param = (int)n;
1895      break;
1896    case 't':
1897      buf->b_ind_func_type = (int)n;
1898      break;
1899    case '/':
1900      buf->b_ind_comment = (int)n;
1901      break;
1902    case 'c':
1903      buf->b_ind_in_comment = (int)n;
1904      break;
1905    case 'C':
1906      buf->b_ind_in_comment2 = (int)n;
1907      break;
1908    case 'i':
1909      buf->b_ind_cpp_baseclass = (int)n;
1910      break;
1911    case '+':
1912      buf->b_ind_continuation = (int)n;
1913      break;
1914    case '(':
1915      buf->b_ind_unclosed = (int)n;
1916      break;
1917    case 'u':
1918      buf->b_ind_unclosed2 = (int)n;
1919      break;
1920    case 'U':
1921      buf->b_ind_unclosed_noignore = (int)n;
1922      break;
1923    case 'W':
1924      buf->b_ind_unclosed_wrapped = (int)n;
1925      break;
1926    case 'w':
1927      buf->b_ind_unclosed_whiteok = (int)n;
1928      break;
1929    case 'm':
1930      buf->b_ind_matching_paren = (int)n;
1931      break;
1932    case 'M':
1933      buf->b_ind_paren_prev = (int)n;
1934      break;
1935    case ')':
1936      buf->b_ind_maxparen = (int)n;
1937      break;
1938    case '*':
1939      buf->b_ind_maxcomment = (int)n;
1940      break;
1941    case 'g':
1942      buf->b_ind_scopedecl = (int)n;
1943      break;
1944    case 'h':
1945      buf->b_ind_scopedecl_code = (int)n;
1946      break;
1947    case 'j':
1948      buf->b_ind_java = (int)n;
1949      break;
1950    case 'J':
1951      buf->b_ind_js = (int)n;
1952      break;
1953    case 'l':
1954      buf->b_ind_keep_case_label = (int)n;
1955      break;
1956    case '#':
1957      buf->b_ind_hash_comment = (int)n;
1958      break;
1959    case 'N':
1960      buf->b_ind_cpp_namespace = (int)n;
1961      break;
1962    case 'k':
1963      buf->b_ind_if_for_while = (int)n;
1964      break;
1965    case 'E':
1966      buf->b_ind_cpp_extern_c = (int)n;
1967      break;
1968    case 'P':
1969      buf->b_ind_pragma = (int)n;
1970      break;
1971    }
1972    if (*p == ',') {
1973      p++;
1974    }
1975  }
1976}
1977
1978// Return the desired indent for C code.
1979// Return -1 if the indent should be left alone (inside a raw string).
1980int get_c_indent(void)
1981{
1982  pos_T cur_curpos;
1983  int amount;
1984  int scope_amount;
1985  int cur_amount = MAXCOL;
1986  colnr_T col;
1987  char *theline;
1988  char *linecopy;
1989  pos_T *trypos;
1990  pos_T *comment_pos;
1991  pos_T *tryposBrace = NULL;
1992  pos_T tryposCopy;
1993  pos_T our_paren_pos;
1994  char *start;
1995  int start_brace;
1996#define BRACE_IN_COL0           1           // '{' is in column 0
1997#define BRACE_AT_START          2           // '{' is at start of line
1998#define BRACE_AT_END            3           // '{' is at end of line
1999  linenr_T ourscope;
2000  const char *l;
2001  const char *look;
2002  char terminated;
2003  int lookfor;
2004#define LOOKFOR_INITIAL         0
2005#define LOOKFOR_IF              1
2006#define LOOKFOR_DO              2
2007#define LOOKFOR_CASE            3
2008#define LOOKFOR_ANY             4
2009#define LOOKFOR_TERM            5
2010#define LOOKFOR_UNTERM          6
2011#define LOOKFOR_SCOPEDECL       7
2012#define LOOKFOR_NOBREAK         8
2013#define LOOKFOR_CPP_BASECLASS   9
2014#define LOOKFOR_ENUM_OR_INIT    10
2015#define LOOKFOR_JS_KEY          11
2016#define LOOKFOR_COMMA           12
2017
2018  int whilelevel;
2019  linenr_T lnum;
2020  int n;
2021  int lookfor_break;
2022  bool lookfor_cpp_namespace = false;
2023  int cont_amount = 0;              // amount for continuation line
2024  int original_line_islabel;
2025  int added_to_amount = 0;
2026  linenr_T raw_string_start = 0;
2027  cpp_baseclass_cache_T cache_cpp_baseclass = { false, { MAXLNUM, 0 } };
2028
2029  // make a copy, value is changed below
2030  int ind_continuation = curbuf->b_ind_continuation;
2031
2032  // remember where the cursor was when we started
2033  cur_curpos = curwin->w_cursor;
2034
2035  // if we are at line 1 zero indent is fine, right?
2036  if (cur_curpos.lnum == 1) {
2037    return 0;
2038  }
2039
2040  // Get a copy of the current contents of the line.
2041  // This is required, because only the most recent line obtained with
2042  // ml_get is valid!
2043  linecopy = xstrdup(ml_get(cur_curpos.lnum));
2044
2045  // In insert mode and the cursor is on a ')' truncate the line at the
2046  // cursor position.  We don't want to line up with the matching '(' when
2047  // inserting new stuff.
2048  // For unknown reasons the cursor might be past the end of the line, thus
2049  // check for that.
2050  if ((State & MODE_INSERT)
2051      && curwin->w_cursor.col < (colnr_T)strlen(linecopy)
2052      && linecopy[curwin->w_cursor.col] == ')') {
2053    linecopy[curwin->w_cursor.col] = NUL;
2054  }
2055
2056  theline = skipwhite(linecopy);
2057
2058  // move the cursor to the start of the line
2059
2060  curwin->w_cursor.col = 0;
2061
2062  original_line_islabel = cin_islabel();    // XXX
2063
2064  // If we are inside a raw string don't change the indent.
2065  // Ignore a raw string inside a comment.
2066  comment_pos = ind_find_start_comment();
2067  if (comment_pos != NULL) {
2068    // findmatchlimit() static pos is overwritten, make a copy
2069    tryposCopy = *comment_pos;
2070    comment_pos = &tryposCopy;
2071  }
2072  trypos = find_start_rawstring(curbuf->b_ind_maxcomment);
2073  if (trypos != NULL && (comment_pos == NULL || lt(*trypos, *comment_pos))) {
2074    amount = -1;
2075    goto laterend;
2076  }
2077
2078  // #defines and so on go at the left when included in 'cinkeys',
2079  // excluding pragmas when customized in 'cinoptions'
2080  if (*theline == '#' && (*linecopy == '#' || in_cinkeys('#', ' ', true))) {
2081    const char *const directive = skipwhite(theline + 1);
2082    if (curbuf->b_ind_pragma == 0 || strncmp(directive, "pragma", 6) != 0) {
2083      amount = curbuf->b_ind_hash_comment;
2084      goto theend;
2085    }
2086  }
2087
2088  // Is it a non-case label? Then that goes at the left margin too unless:
2089  //  - JS flag is set.
2090  //  - 'L' item has a positive value.
2091  if (original_line_islabel && !curbuf->b_ind_js && curbuf->b_ind_jump_label < 0) {
2092    amount = 0;
2093    goto theend;
2094  }
2095  // If we're inside a "//" comment and there is a "//" comment in a
2096  // previous line, lineup with that one.
2097  if (cin_islinecomment(theline)) {
2098    pos_T linecomment_pos;
2099
2100    trypos = find_line_comment();  // XXX
2101    if (trypos == NULL && curwin->w_cursor.lnum > 1) {
2102      // There may be a statement before the comment, search from the end
2103      // of the line for a comment start.
2104      linecomment_pos.col = check_linecomment(ml_get(curwin->w_cursor.lnum - 1));
2105      if (linecomment_pos.col != MAXCOL) {
2106        trypos = &linecomment_pos;
2107        trypos->lnum = curwin->w_cursor.lnum - 1;
2108      }
2109    }
2110    if (trypos != NULL) {
2111      // find how indented the line beginning the comment is
2112      getvcol(curwin, trypos, &col, NULL, NULL, 0);
2113      amount = col;
2114      goto theend;
2115    }
2116  }
2117  // If we're inside a comment and not looking at the start of the
2118  // comment, try using the 'comments' option.
2119  if (!cin_iscomment(theline) && comment_pos != NULL) {  // XXX
2120    int lead_start_len = 2;
2121    int lead_middle_len = 1;
2122    char lead_start[COM_MAX_LEN];             // start-comment string
2123    char lead_middle[COM_MAX_LEN];            // middle-comment string
2124    char lead_end[COM_MAX_LEN];               // end-comment string
2125    int lead_end_len;
2126    char *p;
2127    int start_align = 0;
2128    int start_off = 0;
2129    int done = false;
2130
2131    // find how indented the line beginning the comment is
2132    getvcol(curwin, comment_pos, &col, NULL, NULL, 0);
2133    amount = col;
2134    *lead_start = NUL;
2135    *lead_middle = NUL;
2136
2137    p = curbuf->b_p_com;
2138    while (*p != NUL) {
2139      int align = 0;
2140      int off = 0;
2141      int what = 0;
2142
2143      while (*p != NUL && *p != ':') {
2144        if (*p == COM_START || *p == COM_END || *p == COM_MIDDLE) {
2145          what = (unsigned char)(*p++);
2146        } else if (*p == COM_LEFT || *p == COM_RIGHT) {
2147          align = (unsigned char)(*p++);
2148        } else if (ascii_isdigit(*p) || *p == '-') {
2149          off = getdigits_int(&p, true, 0);
2150        } else {
2151          p++;
2152        }
2153      }
2154
2155      if (*p == ':') {
2156        p++;
2157      }
2158      lead_end_len = (int)copy_option_part(&p, lead_end, COM_MAX_LEN, ",");
2159      if (what == COM_START) {
2160        STRCPY(lead_start, lead_end);
2161        lead_start_len = lead_end_len;
2162        start_off = off;
2163        start_align = align;
2164      } else if (what == COM_MIDDLE) {
2165        STRCPY(lead_middle, lead_end);
2166        lead_middle_len = lead_end_len;
2167      } else if (what == COM_END) {
2168        // If our line starts with the middle comment string, line it
2169        // up with the comment opener per the 'comments' option.
2170        if (strncmp(theline, lead_middle, (size_t)lead_middle_len) == 0
2171            && strncmp(theline, lead_end, (size_t)lead_end_len) != 0) {
2172          done = true;
2173          if (curwin->w_cursor.lnum > 1) {
2174            // If the start comment string matches in the previous
2175            // line, use the indent of that line plus offset.  If
2176            // the middle comment string matches in the previous
2177            // line, use the indent of that line.  XXX
2178            look = skipwhite(ml_get(curwin->w_cursor.lnum - 1));
2179            if (strncmp(look, lead_start, (size_t)lead_start_len) == 0) {
2180              amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
2181            } else if (strncmp(look, lead_middle, (size_t)lead_middle_len) == 0) {
2182              amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
2183              break;
2184            } else if (strncmp(ml_get(comment_pos->lnum) + comment_pos->col,
2185                               lead_start, (size_t)lead_start_len) != 0) {
2186              // If the start comment string doesn't match with the
2187              // start of the comment, skip this entry. XXX
2188              continue;
2189            }
2190          }
2191          if (start_off != 0) {
2192            amount += start_off;
2193          } else if (start_align == COM_RIGHT) {
2194            amount += vim_strsize(lead_start) - vim_strsize(lead_middle);
2195          }
2196          break;
2197        }
2198
2199        // If our line starts with the end comment string, line it up
2200        // with the middle comment
2201        if (strncmp(theline, lead_middle, (size_t)lead_middle_len) != 0
2202            && strncmp(theline, lead_end, (size_t)lead_end_len) == 0) {
2203          amount = get_indent_lnum(curwin->w_cursor.lnum - 1);
2204          // XXX
2205          if (off != 0) {
2206            amount += off;
2207          } else if (align == COM_RIGHT) {
2208            amount += vim_strsize(lead_start) - vim_strsize(lead_middle);
2209          }
2210          done = true;
2211          break;
2212        }
2213      }
2214    }
2215
2216    // If our line starts with an asterisk, line up with the
2217    // asterisk in the comment opener; otherwise, line up
2218    // with the first character of the comment text.
2219    if (done) {
2220      // skip
2221    } else if (theline[0] == '*') {
2222      amount += 1;
2223    } else {
2224      // If we are more than one line away from the comment opener, take
2225      // the indent of the previous non-empty line.  If 'cino' has "CO"
2226      // and we are just below the comment opener and there are any
2227      // white characters after it line up with the text after it;
2228      // otherwise, add the amount specified by "c" in 'cino'
2229      amount = -1;
2230      for (lnum = cur_curpos.lnum - 1; lnum > comment_pos->lnum; lnum--) {
2231        if (linewhite(lnum)) {                      // skip blank lines
2232          continue;
2233        }
2234        amount = get_indent_lnum(lnum);             // XXX
2235        break;
2236      }
2237      if (amount == -1) {                           // use the comment opener
2238        if (!curbuf->b_ind_in_comment2) {
2239          start = ml_get(comment_pos->lnum);
2240          look = start + comment_pos->col + 2;  // skip / and *
2241          if (*look != NUL) {                   // if something after it
2242            comment_pos->col = (colnr_T)(skipwhite(look) - start);
2243          }
2244        }
2245        getvcol(curwin, comment_pos, &col, NULL, NULL, 0);
2246        amount = col;
2247        if (curbuf->b_ind_in_comment2 || *look == NUL) {
2248          amount += curbuf->b_ind_in_comment;
2249        }
2250      }
2251    }
2252    goto theend;
2253  }
2254  // Are we looking at a ']' that has a match?
2255  if (*skipwhite(theline) == ']'
2256      && (trypos = find_match_char('[', curbuf->b_ind_maxparen)) != NULL) {
2257    // align with the line containing the '['.
2258    amount = get_indent_lnum(trypos->lnum);
2259    goto theend;
2260  }
2261  // Are we inside parentheses or braces?
2262  // XXX
2263  if (((trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL
2264       && curbuf->b_ind_java == 0)
2265      || (tryposBrace = find_start_brace()) != NULL
2266      || trypos != NULL) {
2267    if (trypos != NULL && tryposBrace != NULL) {
2268      // Both an unmatched '(' and '{' is found.  Use the one which is
2269      // closer to the current cursor position, set the other to NULL.
2270      if (trypos->lnum != tryposBrace->lnum
2271          ? trypos->lnum < tryposBrace->lnum
2272          : trypos->col < tryposBrace->col) {
2273        trypos = NULL;
2274      } else {
2275        tryposBrace = NULL;
2276      }
2277    }
2278
2279    if (trypos != NULL) {
2280      our_paren_pos = *trypos;
2281      // If the matching paren is more than one line away, use the indent of
2282      // a previous non-empty line that matches the same paren.
2283      if (theline[0] == ')' && curbuf->b_ind_paren_prev) {
2284        // Line up with the start of the matching paren line.
2285        amount = get_indent_lnum(curwin->w_cursor.lnum - 1);      // XXX
2286      } else {
2287        amount = -1;
2288        for (lnum = cur_curpos.lnum - 1; lnum > our_paren_pos.lnum; lnum--) {
2289          l = skipwhite(ml_get(lnum));
2290          if (cin_nocode(l)) {                   // skip comment lines
2291            continue;
2292          }
2293          if (cin_ispreproc_cont(&l, &lnum, &amount)) {
2294            continue;                           // ignore #define, #if, etc.
2295          }
2296          curwin->w_cursor.lnum = lnum;
2297
2298          // Skip a comment or raw string. XXX
2299          if ((trypos = ind_find_start_CORS(NULL)) != NULL) {
2300            lnum = trypos->lnum + 1;
2301            continue;
2302          }
2303
2304          // XXX
2305          if ((trypos = find_match_paren(corr_ind_maxparen(&cur_curpos))) != NULL
2306              && trypos->lnum == our_paren_pos.lnum
2307              && trypos->col == our_paren_pos.col) {
2308            amount = get_indent_lnum(lnum);             // XXX
2309
2310            if (theline[0] == ')') {
2311              if (our_paren_pos.lnum != lnum
2312                  && cur_amount > amount) {
2313                cur_amount = amount;
2314              }
2315              amount = -1;
2316            }
2317            break;
2318          }
2319        }
2320      }
2321
2322      // Line up with line where the matching paren is. XXX
2323      // If the line starts with a '(' or the indent for unclosed
2324      // parentheses is zero, line up with the unclosed parentheses.
2325      if (amount == -1) {
2326        int ignore_paren_col = 0;
2327        int is_if_for_while = 0;
2328
2329        if (curbuf->b_ind_if_for_while) {
2330          // Look for the outermost opening parenthesis on this line
2331          // and check whether it belongs to an "if", "for" or "while".
2332
2333          pos_T cursor_save = curwin->w_cursor;
2334          pos_T outermost;
2335          char *line;
2336
2337          trypos = &our_paren_pos;
2338          do {
2339            outermost = *trypos;
2340            curwin->w_cursor.lnum = outermost.lnum;
2341            curwin->w_cursor.col = outermost.col;
2342
2343            trypos = find_match_paren(curbuf->b_ind_maxparen);
2344          } while (trypos && trypos->lnum == outermost.lnum);
2345
2346          curwin->w_cursor = cursor_save;
2347
2348          line = ml_get(outermost.lnum);
2349
2350          is_if_for_while =
2351            cin_is_if_for_while_before_offset(line, &outermost.col);
2352        }
2353
2354        amount = skip_label(our_paren_pos.lnum, &look);
2355        look = skipwhite(look);
2356        if (*look == '(') {
2357          linenr_T save_lnum = curwin->w_cursor.lnum;
2358          char *line;
2359          int look_col;
2360
2361          // Ignore a '(' in front of the line that has a match before
2362          // our matching '('.
2363          curwin->w_cursor.lnum = our_paren_pos.lnum;
2364          line = get_cursor_line_ptr();
2365          look_col = (int)(look - line);
2366          curwin->w_cursor.col = look_col + 1;
2367          if ((trypos = findmatchlimit(NULL, ')', FM_SKIPCOMM,
2368                                       curbuf->b_ind_maxparen))
2369              != NULL
2370              && trypos->lnum == our_paren_pos.lnum
2371              && trypos->col < our_paren_pos.col) {
2372            ignore_paren_col = trypos->col + 1;
2373          }
2374
2375          curwin->w_cursor.lnum = save_lnum;
2376          look = ml_get(our_paren_pos.lnum) + look_col;
2377        }
2378        if (theline[0] == ')' || (curbuf->b_ind_unclosed == 0
2379                                  && is_if_for_while == 0)
2380            || (!curbuf->b_ind_unclosed_noignore && *look == '('
2381                && ignore_paren_col == 0)) {
2382          // If we're looking at a close paren, line up right there;
2383          // otherwise, line up with the next (non-white) character.
2384          // When b_ind_unclosed_wrapped is set and the matching paren is
2385          // the last nonwhite character of the line, use either the
2386          // indent of the current line or the indentation of the next
2387          // outer paren and add b_ind_unclosed_wrapped (for very long
2388          // lines).
2389          if (theline[0] != ')') {
2390            cur_amount = MAXCOL;
2391            l = ml_get(our_paren_pos.lnum);
2392            if (curbuf->b_ind_unclosed_wrapped && cin_ends_in(l, "(")) {
2393              // look for opening unmatched paren, indent one level
2394              // for each additional level
2395              n = 1;
2396              for (col = 0; col < our_paren_pos.col; col++) {
2397                switch (l[col]) {
2398                case '(':
2399                case '{':
2400                  n++;
2401                  break;
2402
2403                case ')':
2404                case '}':
2405                  if (n > 1) {
2406                    n--;
2407                  }
2408                  break;
2409                }
2410              }
2411
2412              our_paren_pos.col = 0;
2413              amount += n * curbuf->b_ind_unclosed_wrapped;
2414            } else if (curbuf->b_ind_unclosed_whiteok) {
2415              our_paren_pos.col++;
2416            } else {
2417              col = our_paren_pos.col + 1;
2418              while (ascii_iswhite(l[col])) {
2419                col++;
2420              }
2421              if (l[col] != NUL) {              // In case of trailing space
2422                our_paren_pos.col = col;
2423              } else {
2424                our_paren_pos.col++;
2425              }
2426            }
2427          }
2428
2429          // Find how indented the paren is, or the character after it
2430          // if we did the above "if".
2431          if (our_paren_pos.col > 0) {
2432            getvcol(curwin, &our_paren_pos, &col, NULL, NULL, 0);
2433            if (cur_amount > (int)col) {
2434              cur_amount = col;
2435            }
2436          }
2437        }
2438
2439        if (theline[0] == ')' && curbuf->b_ind_matching_paren) {
2440          // Line up with the start of the matching paren line.
2441        } else if ((curbuf->b_ind_unclosed == 0 && is_if_for_while == 0)
2442                   || (!curbuf->b_ind_unclosed_noignore
2443                       && *look == '(' && ignore_paren_col == 0)) {
2444          if (cur_amount != MAXCOL) {
2445            amount = cur_amount;
2446          }
2447        } else {
2448          // Add b_ind_unclosed2 for each '(' before our matching one,
2449          // but ignore (void) before the line (ignore_paren_col).
2450          col = our_paren_pos.col;
2451          while ((int)our_paren_pos.col > ignore_paren_col) {
2452            our_paren_pos.col--;
2453            switch (*ml_get_pos(&our_paren_pos)) {
2454            case '(':
2455              amount += curbuf->b_ind_unclosed2;
2456              col = our_paren_pos.col;
2457              break;
2458            case ')':
2459              amount -= curbuf->b_ind_unclosed2;
2460              col = MAXCOL;
2461              break;
2462            }
2463          }
2464
2465          // Use b_ind_unclosed once, when the first '(' is not inside
2466          // braces
2467          if (col == MAXCOL) {
2468            amount += curbuf->b_ind_unclosed;
2469          } else {
2470            curwin->w_cursor.lnum = our_paren_pos.lnum;
2471            curwin->w_cursor.col = col;
2472            if (find_match_paren_after_brace(curbuf->b_ind_maxparen)) {
2473              amount += curbuf->b_ind_unclosed2;
2474            } else {
2475              if (is_if_for_while) {
2476                amount += curbuf->b_ind_if_for_while;
2477              } else {
2478                amount += curbuf->b_ind_unclosed;
2479              }
2480            }
2481          }
2482          // For a line starting with ')' use the minimum of the two
2483          // positions, to avoid giving it more indent than the previous
2484          // lines:
2485          //  func_long_name(               if (x
2486          //    arg                                 && yy
2487          //    )         ^ not here           )    ^ not here
2488          if (cur_amount < amount) {
2489            amount = cur_amount;
2490          }
2491        }
2492      }
2493
2494      // add extra indent for a comment
2495      if (cin_iscomment(theline)) {
2496        amount += curbuf->b_ind_comment;
2497      }
2498    } else {
2499      // We are inside braces, there is a { before this line at the position
2500      // stored in tryposBrace.
2501      // Make a copy of tryposBrace, it may point to pos_copy inside
2502      // find_start_brace(), which may be changed somewhere.
2503      tryposCopy = *tryposBrace;
2504      tryposBrace = &tryposCopy;
2505      trypos = tryposBrace;
2506      ourscope = trypos->lnum;
2507      start = ml_get(ourscope);
2508
2509      // Now figure out how indented the line is in general.
2510      // If the brace was at the start of the line, we use that;
2511      // otherwise, check out the indentation of the line as
2512      // a whole and then add the "imaginary indent" to that.
2513      look = skipwhite(start);
2514      if (*look == '{') {
2515        getvcol(curwin, trypos, &col, NULL, NULL, 0);
2516        amount = col;
2517        if (*start == '{') {
2518          start_brace = BRACE_IN_COL0;
2519        } else {
2520          start_brace = BRACE_AT_START;
2521        }
2522      } else {
2523        // That opening brace might have been on a continuation
2524        // line.  If so, find the start of the line.
2525        curwin->w_cursor.lnum = ourscope;
2526
2527        // Position the cursor over the rightmost paren, so that
2528        // matching it will take us back to the start of the line.
2529        lnum = ourscope;
2530        if (find_last_paren(start, '(', ')')
2531            && (trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL) {
2532          lnum = trypos->lnum;
2533        }
2534
2535        // It could have been something like
2536        //         case 1: if (asdf &&
2537        //                      ldfd) {
2538        //                  }
2539        if ((curbuf->b_ind_js || curbuf->b_ind_keep_case_label)
2540            && cin_iscase(skipwhite(get_cursor_line_ptr()), false)) {
2541          amount = get_indent();
2542        } else if (curbuf->b_ind_js) {
2543          amount = get_indent_lnum(lnum);
2544        } else {
2545          amount = skip_label(lnum, &l);
2546        }
2547
2548        start_brace = BRACE_AT_END;
2549      }
2550
2551      // For Javascript check if the line starts with "key:".
2552      bool js_cur_has_key = curbuf->b_ind_js ? cin_has_js_key(theline) : false;
2553
2554      // If we're looking at a closing brace, that's where
2555      // we want to be.  Otherwise, add the amount of room
2556      // that an indent is supposed to be.
2557      if (theline[0] == '}') {
2558        // they may want closing braces to line up with something
2559        // other than the open brace.  indulge them, if so.
2560        amount += curbuf->b_ind_close_extra;
2561      } else {
2562        // If we're looking at an "else", try to find an "if"
2563        // to match it with.
2564        // If we're looking at a "while", try to find a "do"
2565        // to match it with.
2566        lookfor = LOOKFOR_INITIAL;
2567        if (cin_iselse(theline)) {
2568          lookfor = LOOKFOR_IF;
2569        } else if (cin_iswhileofdo(theline, cur_curpos.lnum)) {   // XXX
2570          lookfor = LOOKFOR_DO;
2571        }
2572        if (lookfor != LOOKFOR_INITIAL) {
2573          curwin->w_cursor.lnum = cur_curpos.lnum;
2574          if (find_match(lookfor, ourscope) == OK) {
2575            amount = get_indent();              // XXX
2576            goto theend;
2577          }
2578        }
2579
2580        // We get here if we are not on an "while-of-do" or "else" (or
2581        // failed to find a matching "if").
2582        // Search backwards for something to line up with.
2583        // First set amount for when we don't find anything.
2584
2585        // if the '{' is  _really_ at the left margin, use the imaginary
2586        // location of a left-margin brace.  Otherwise, correct the
2587        // location for b_ind_open_extra.
2588
2589        if (start_brace == BRACE_IN_COL0) {     // '{' is in column 0
2590          amount = curbuf->b_ind_open_left_imag;
2591          lookfor_cpp_namespace = true;
2592        } else if (start_brace == BRACE_AT_START
2593                   && lookfor_cpp_namespace) {  // '{' is at start
2594          lookfor_cpp_namespace = true;
2595        } else {
2596          if (start_brace == BRACE_AT_END) {    // '{' is at end of line
2597            amount += curbuf->b_ind_open_imag;
2598
2599            l = skipwhite(get_cursor_line_ptr());
2600            if (cin_is_cpp_namespace(l)) {
2601              amount += curbuf->b_ind_cpp_namespace;
2602            } else if (cin_is_cpp_extern_c(l)) {
2603              amount += curbuf->b_ind_cpp_extern_c;
2604            }
2605          } else {
2606            // Compensate for adding b_ind_open_extra later.
2607            amount -= curbuf->b_ind_open_extra;
2608            if (amount < 0) {
2609              amount = 0;
2610            }
2611          }
2612        }
2613
2614        lookfor_break = false;
2615
2616        if (cin_iscase(theline, false)) {       // it's a switch() label
2617          lookfor = LOOKFOR_CASE;       // find a previous switch() label
2618          amount += curbuf->b_ind_case;
2619        } else if (cin_isscopedecl(theline)) {  // private:, ...
2620          lookfor = LOOKFOR_SCOPEDECL;          // class decl is this block
2621          amount += curbuf->b_ind_scopedecl;
2622        } else {
2623          if (curbuf->b_ind_case_break && cin_isbreak(theline)) {
2624            // break; ...
2625            lookfor_break = true;
2626          }
2627
2628          lookfor = LOOKFOR_INITIAL;
2629          // b_ind_level from start of block
2630          amount += curbuf->b_ind_level;
2631        }
2632        scope_amount = amount;
2633        whilelevel = 0;
2634
2635        // Search backwards.  If we find something we recognize, line up
2636        // with that.
2637        //
2638        // If we're looking at an open brace, indent
2639        // the usual amount relative to the conditional
2640        // that opens the block.
2641        curwin->w_cursor = cur_curpos;
2642        while (true) {
2643          curwin->w_cursor.lnum--;
2644          curwin->w_cursor.col = 0;
2645
2646          // If we went all the way back to the start of our scope, line
2647          // up with it.
2648          if (curwin->w_cursor.lnum <= ourscope) {
2649            // We reached end of scope:
2650            // If looking for a enum or structure initialization
2651            // go further back:
2652            // If it is an initializer (enum xxx or xxx =), then
2653            // don't add ind_continuation, otherwise it is a variable
2654            // declaration:
2655            // int x,
2656            //     here; <-- add ind_continuation
2657            if (lookfor == LOOKFOR_ENUM_OR_INIT) {
2658              if (curwin->w_cursor.lnum == 0
2659                  || curwin->w_cursor.lnum
2660                  < ourscope - curbuf->b_ind_maxparen) {
2661                // nothing found (abuse curbuf->b_ind_maxparen as
2662                // limit) assume terminated line (i.e. a variable
2663                // initialization)
2664                if (cont_amount > 0) {
2665                  amount = cont_amount;
2666                } else if (!curbuf->b_ind_js) {
2667                  amount += ind_continuation;
2668                }
2669                break;
2670              }
2671
2672              // If we're in a comment or raw string now, skip to
2673              // the start of it.
2674              trypos = ind_find_start_CORS(NULL);
2675              if (trypos != NULL) {
2676                curwin->w_cursor.lnum = trypos->lnum + 1;
2677                curwin->w_cursor.col = 0;
2678                continue;
2679              }
2680
2681              l = get_cursor_line_ptr();
2682
2683              // Skip preprocessor directives and blank lines.
2684              if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum, &amount)) {
2685                continue;
2686              }
2687
2688              if (cin_nocode(l)) {
2689                continue;
2690              }
2691
2692              terminated = cin_isterminated(l, false, true);
2693
2694              // If we are at top level and the line looks like a
2695              // function declaration, we are done
2696              // (it's a variable declaration).
2697              if (start_brace != BRACE_IN_COL0
2698                  || !cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0)) {
2699                // if the line is terminated with another ','
2700                // it is a continued variable initialization.
2701                // don't add extra indent.
2702                // TODO(vim): does not work, if  a function
2703                // declaration is split over multiple lines:
2704                // cin_isfuncdecl returns false then.
2705                if (terminated == ',') {
2706                  break;
2707                }
2708
2709                // if it is an enum declaration or an assignment,
2710                // we are done.
2711                if (terminated != ';' && cin_isinit()) {
2712                  break;
2713                }
2714
2715                // nothing useful found
2716                if (terminated == 0 || terminated == '{') {
2717                  continue;
2718                }
2719              }
2720
2721              if (terminated != ';') {
2722                // Skip parens and braces. Position the cursor
2723                // over the rightmost paren, so that matching it
2724                // will take us back to the start of the line.
2725                // XXX
2726                trypos = NULL;
2727                if (find_last_paren(l, '(', ')')) {
2728                  trypos = find_match_paren(curbuf->b_ind_maxparen);
2729                }
2730
2731                if (trypos == NULL && find_last_paren(l, '{', '}')) {
2732                  trypos = find_start_brace();
2733                }
2734
2735                if (trypos != NULL) {
2736                  curwin->w_cursor.lnum = trypos->lnum + 1;
2737                  curwin->w_cursor.col = 0;
2738                  continue;
2739                }
2740              }
2741
2742              // it's a variable declaration, add indentation
2743              // like in
2744              // int a,
2745              //    b;
2746              if (cont_amount > 0) {
2747                amount = cont_amount;
2748              } else {
2749                amount += ind_continuation;
2750              }
2751            } else if (lookfor == LOOKFOR_UNTERM) {
2752              if (cont_amount > 0) {
2753                amount = cont_amount;
2754              } else {
2755                amount += ind_continuation;
2756              }
2757            } else {
2758              if (lookfor != LOOKFOR_TERM
2759                  && lookfor != LOOKFOR_CPP_BASECLASS
2760                  && lookfor != LOOKFOR_COMMA) {
2761                amount = scope_amount;
2762                if (theline[0] == '{') {
2763                  amount += curbuf->b_ind_open_extra;
2764                  added_to_amount = curbuf->b_ind_open_extra;
2765                }
2766              }
2767
2768              if (lookfor_cpp_namespace) {
2769                // Looking for C++ namespace, need to look further
2770                // back.
2771                if (curwin->w_cursor.lnum == ourscope) {
2772                  continue;
2773                }
2774
2775                if (curwin->w_cursor.lnum == 0
2776                    || curwin->w_cursor.lnum
2777                    < ourscope - FIND_NAMESPACE_LIM) {
2778                  break;
2779                }
2780
2781                // If we're in a comment or raw string now, skip
2782                // to the start of it.
2783                trypos = ind_find_start_CORS(NULL);
2784                if (trypos != NULL) {
2785                  curwin->w_cursor.lnum = trypos->lnum + 1;
2786                  curwin->w_cursor.col = 0;
2787                  continue;
2788                }
2789
2790                l = get_cursor_line_ptr();
2791
2792                // Skip preprocessor directives and blank lines.
2793                if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum, &amount)) {
2794                  continue;
2795                }
2796
2797                // Finally the actual check for "namespace".
2798                if (cin_is_cpp_namespace(l)) {
2799                  amount += curbuf->b_ind_cpp_namespace
2800                            - added_to_amount;
2801                  break;
2802                } else if (cin_is_cpp_extern_c(l)) {
2803                  amount += curbuf->b_ind_cpp_extern_c - added_to_amount;
2804                  break;
2805                }
2806
2807                if (cin_nocode(l)) {
2808                  continue;
2809                }
2810              }
2811            }
2812            break;
2813          }
2814
2815          // If we're in a comment or raw string now, skip to the start
2816          // of it.
2817          // XXX
2818          if ((trypos = ind_find_start_CORS(&raw_string_start)) != NULL) {
2819            curwin->w_cursor.lnum = trypos->lnum + 1;
2820            curwin->w_cursor.col = 0;
2821            continue;
2822          }
2823
2824          l = get_cursor_line_ptr();
2825
2826          // If this is a switch() label, may line up relative to that.
2827          // If this is a C++ scope declaration, do the same.
2828          bool iscase = cin_iscase(l, false);
2829          if (iscase || cin_isscopedecl(l)) {
2830            // we are only looking for cpp base class
2831            // declaration/initialization any longer
2832            if (lookfor == LOOKFOR_CPP_BASECLASS) {
2833              break;
2834            }
2835
2836            // When looking for a "do" we are not interested in
2837            // labels.
2838            if (whilelevel > 0) {
2839              continue;
2840            }
2841
2842            //  case xx:
2843            //      c = 99 +        <- this indent plus continuation
2844            // ->          here;
2845            if (lookfor == LOOKFOR_UNTERM || lookfor == LOOKFOR_ENUM_OR_INIT) {
2846              if (cont_amount > 0) {
2847                amount = cont_amount;
2848              } else {
2849                amount += ind_continuation;
2850              }
2851              break;
2852            }
2853
2854            // case xx: <- line up with this case
2855            //     x = 333;
2856            // case yy:
2857            if ((iscase && lookfor == LOOKFOR_CASE)
2858                || (iscase && lookfor_break)
2859                || (!iscase && lookfor == LOOKFOR_SCOPEDECL)) {
2860              // Check that this case label is not for another
2861              // switch()
2862              // XXX
2863              if ((trypos = find_start_brace()) == NULL
2864                  || trypos->lnum == ourscope) {
2865                amount = get_indent();                  // XXX
2866                break;
2867              }
2868              continue;
2869            }
2870
2871            n = get_indent_nolabel(curwin->w_cursor.lnum);          // XXX
2872
2873            //   case xx: if (cond)         <- line up with this if
2874            //                y = y + 1;
2875            // ->         s = 99;
2876            //
2877            //   case xx:
2878            //       if (cond)          <- line up with this line
2879            //           y = y + 1;
2880            // ->    s = 99;
2881            if (lookfor == LOOKFOR_TERM) {
2882              if (n) {
2883                amount = n;
2884              }
2885
2886              if (!lookfor_break) {
2887                break;
2888              }
2889            }
2890
2891            //   case xx: x = x + 1;        <- line up with this x
2892            // ->         y = y + 1;
2893            //
2894            //   case xx: if (cond)         <- line up with this if
2895            // ->              y = y + 1;
2896            if (n) {
2897              amount = n;
2898              l = after_label(get_cursor_line_ptr());
2899              if (l != NULL && cin_is_cinword(l)) {
2900                if (theline[0] == '{') {
2901                  amount += curbuf->b_ind_open_extra;
2902                } else {
2903                  amount += curbuf->b_ind_level
2904                            + curbuf->b_ind_no_brace;
2905                }
2906              }
2907              break;
2908            }
2909
2910            // Try to get the indent of a statement before the switch
2911            // label.  If nothing is found, line up relative to the
2912            // switch label.
2913            //      break;              <- may line up with this line
2914            //   case xx:
2915            // ->   y = 1;
2916            scope_amount = get_indent() + (iscase            // XXX
2917                                           ? curbuf->b_ind_case_code
2918                                           : curbuf->b_ind_scopedecl_code);
2919            lookfor = curbuf->b_ind_case_break
2920                      ? LOOKFOR_NOBREAK : LOOKFOR_ANY;
2921            continue;
2922          }
2923
2924          // Looking for a switch() label or C++ scope declaration,
2925          // ignore other lines, skip {}-blocks.
2926          if (lookfor == LOOKFOR_CASE || lookfor == LOOKFOR_SCOPEDECL) {
2927            if (find_last_paren(l, '{', '}')
2928                && (trypos = find_start_brace()) != NULL) {
2929              curwin->w_cursor.lnum = trypos->lnum + 1;
2930              curwin->w_cursor.col = 0;
2931            }
2932            continue;
2933          }
2934
2935          // Ignore jump labels with nothing after them.
2936          if (!curbuf->b_ind_js && cin_islabel()) {
2937            l = after_label(get_cursor_line_ptr());
2938            if (l == NULL || cin_nocode(l)) {
2939              continue;
2940            }
2941          }
2942
2943          // Ignore #defines, #if, etc.
2944          // Ignore comment and empty lines.
2945          // (need to get the line again, cin_islabel() may have
2946          // unlocked it)
2947          l = get_cursor_line_ptr();
2948          if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum, &amount)
2949              || cin_nocode(l)) {
2950            continue;
2951          }
2952
2953          // Are we at the start of a cpp base class declaration or
2954          // constructor initialization?
2955          // XXX
2956          n = 0;
2957          if (lookfor != LOOKFOR_TERM && curbuf->b_ind_cpp_baseclass > 0) {
2958            n = cin_is_cpp_baseclass(&cache_cpp_baseclass);
2959            l = get_cursor_line_ptr();
2960          }
2961          if (n) {
2962            if (lookfor == LOOKFOR_UNTERM) {
2963              if (cont_amount > 0) {
2964                amount = cont_amount;
2965              } else {
2966                amount += ind_continuation;
2967              }
2968            } else if (theline[0] == '{') {
2969              // Need to find start of the declaration.
2970              lookfor = LOOKFOR_UNTERM;
2971              ind_continuation = 0;
2972              continue;
2973            } else {
2974              // XXX
2975              amount = get_baseclass_amount(cache_cpp_baseclass.lpos.col);
2976            }
2977            break;
2978          } else if (lookfor == LOOKFOR_CPP_BASECLASS) {
2979            // only look, whether there is a cpp base class
2980            // declaration or initialization before the opening brace.
2981            if (cin_isterminated(l, true, false)) {
2982              break;
2983            } else {
2984              continue;
2985            }
2986          }
2987
2988          // What happens next depends on the line being terminated.
2989          // If terminated with a ',' only consider it terminating if
2990          // there is another unterminated statement behind, eg:
2991          //   123,
2992          //   sizeof
2993          //      here
2994          // Otherwise check whether it is an enumeration or structure
2995          // initialisation (not indented) or a variable declaration
2996          // (indented).
2997          terminated = cin_isterminated(l, false, true);
2998
2999          if (js_cur_has_key) {
3000            js_cur_has_key = false;  // only check the first line
3001            if (curbuf->b_ind_js && terminated == ',') {
3002              // For Javascript we might be inside an object:
3003              //   key: something,  <- align with this
3004              //   key: something
3005              // or:
3006              //   key: something +  <- align with this
3007              //       something,
3008              //   key: something
3009              lookfor = LOOKFOR_JS_KEY;
3010            }
3011          }
3012          if (lookfor == LOOKFOR_JS_KEY && cin_has_js_key(l)) {
3013            amount = get_indent();
3014            break;
3015          }
3016          if (lookfor == LOOKFOR_COMMA) {
3017            if (tryposBrace != NULL && tryposBrace->lnum
3018                >= curwin->w_cursor.lnum) {
3019              break;
3020            }
3021            if (terminated == ',') {
3022              // Line below current line is the one that starts a
3023              // (possibly broken) line ending in a comma.
3024              break;
3025            }
3026            amount = get_indent();
3027            if (curwin->w_cursor.lnum - 1 == ourscope) {
3028              // line above is start of the scope, thus current
3029              // line is the one that stars a (possibly broken)
3030              // line ending in a comma.
3031              break;
3032            }
3033          }
3034
3035          if (terminated == 0 || (lookfor != LOOKFOR_UNTERM
3036                                  && terminated == ',')) {
3037            if (lookfor != LOOKFOR_ENUM_OR_INIT
3038                && (*skipwhite(l) == '[' || l[strlen(l) - 1] == '[')) {
3039              amount += ind_continuation;
3040            }
3041            // If we're in the middle of a paren thing, Go back to the line
3042            // that starts it so we can get the right prevailing indent
3043            //     if ( foo &&
3044            //              bar )
3045
3046            // Position the cursor over the rightmost paren, so that
3047            // matching it will take us back to the start of the line.
3048            // Ignore a match before the start of the block.
3049            (void)find_last_paren(l, '(', ')');
3050            trypos = find_match_paren(corr_ind_maxparen(&cur_curpos));
3051            if (trypos != NULL && (trypos->lnum < tryposBrace->lnum
3052                                   || (trypos->lnum == tryposBrace->lnum
3053                                       && trypos->col < tryposBrace->col))) {
3054              trypos = NULL;
3055            }
3056
3057            l = get_cursor_line_ptr();
3058
3059            // If we are looking for ',', we also look for matching
3060            // braces.
3061            if (trypos == NULL && terminated == ',') {
3062              if (find_last_paren(l, '{', '}')) {
3063                trypos = find_start_brace();
3064              }
3065              l = get_cursor_line_ptr();
3066            }
3067
3068            if (trypos != NULL) {
3069              // Check if we are on a case label now.  This is
3070              // handled above.
3071              //     case xx:  if ( asdf &&
3072              //                        asdf)
3073              curwin->w_cursor = *trypos;
3074              l = get_cursor_line_ptr();
3075              if (cin_iscase(l, false) || cin_isscopedecl(l)) {
3076                curwin->w_cursor.lnum++;
3077                curwin->w_cursor.col = 0;
3078                continue;
3079              }
3080            }
3081
3082            // Skip over continuation lines to find the one to get the
3083            // indent from
3084            // char *usethis = "bla{backslash}
3085            //           bla",
3086            //      here;
3087            if (terminated == ',') {
3088              while (curwin->w_cursor.lnum > 1) {
3089                l = ml_get(curwin->w_cursor.lnum - 1);
3090                if (*l == NUL || l[strlen(l) - 1] != '\\') {
3091                  break;
3092                }
3093                curwin->w_cursor.lnum--;
3094                curwin->w_cursor.col = 0;
3095              }
3096              l = get_cursor_line_ptr();
3097            }
3098
3099            // Get indent and pointer to text for current line,
3100            // ignoring any jump label.     XXX
3101            if (curbuf->b_ind_js) {
3102              cur_amount = get_indent();
3103            } else {
3104              cur_amount = skip_label(curwin->w_cursor.lnum, &l);
3105            }
3106            // If this is just above the line we are indenting, and it
3107            // starts with a '{', line it up with this line.
3108            //          while (not)
3109            // ->       {
3110            //          }
3111            if (terminated != ',' && lookfor != LOOKFOR_TERM
3112                && theline[0] == '{') {
3113              amount = cur_amount;
3114              // Only add b_ind_open_extra when the current line
3115              // doesn't start with a '{', which must have a match
3116              // in the same line (scope is the same).  Probably:
3117              //        { 1, 2 },
3118              // ->     { 3, 4 }
3119              if (*skipwhite(l) != '{') {
3120                amount += curbuf->b_ind_open_extra;
3121              }
3122
3123              if (curbuf->b_ind_cpp_baseclass && !curbuf->b_ind_js) {
3124                // have to look back, whether it is a cpp base
3125                // class declaration or initialization
3126                lookfor = LOOKFOR_CPP_BASECLASS;
3127                continue;
3128              }
3129              break;
3130            }
3131
3132            // Check if we are after an "if", "while", etc.
3133            // Also allow "   } else".
3134            if (cin_is_cinword(l) || cin_iselse(skipwhite(l))) {
3135              // Found an unterminated line after an if (), line up
3136              // with the last one.
3137              //   if (cond)
3138              //             100 +
3139              // ->              here;
3140              if (lookfor == LOOKFOR_UNTERM
3141                  || lookfor == LOOKFOR_ENUM_OR_INIT) {
3142                if (cont_amount > 0) {
3143                  amount = cont_amount;
3144                } else {
3145                  amount += ind_continuation;
3146                }
3147                break;
3148              }
3149
3150              // If this is just above the line we are indenting, we
3151              // are finished.
3152              //            while (not)
3153              // ->             here;
3154              // Otherwise this indent can be used when the line
3155              // before this is terminated.
3156              //        yyy;
3157              //        if (stat)
3158              //            while (not)
3159              //                xxx;
3160              // ->     here;
3161              amount = cur_amount;
3162              if (theline[0] == '{') {
3163                amount += curbuf->b_ind_open_extra;
3164              }
3165              if (lookfor != LOOKFOR_TERM) {
3166                amount += curbuf->b_ind_level
3167                          + curbuf->b_ind_no_brace;
3168                break;
3169              }
3170
3171              // Special trick: when expecting the while () after a
3172              // do, line up with the while()
3173              //     do
3174              //            x = 1;
3175              // ->  here
3176              l = skipwhite(get_cursor_line_ptr());
3177              if (cin_isdo(l)) {
3178                if (whilelevel == 0) {
3179                  break;
3180                }
3181                whilelevel--;
3182              }
3183
3184              // When searching for a terminated line, don't use the
3185              // one between the "if" and the matching "else".
3186              // Need to use the scope of this "else".  XXX
3187              // If whilelevel != 0 continue looking for a "do {".
3188              if (cin_iselse(l) && whilelevel == 0) {
3189                // If we're looking at "} else", let's make sure we
3190                // find the opening brace of the enclosing scope,
3191                // not the one from "if () {".
3192                if (*l == '}') {
3193                  curwin->w_cursor.col =
3194                    (colnr_T)(l - get_cursor_line_ptr()) + 1;
3195                }
3196
3197                if ((trypos = find_start_brace()) == NULL
3198                    || find_match(LOOKFOR_IF, trypos->lnum)
3199                    == FAIL) {
3200                  break;
3201                }
3202              }
3203            } else {
3204              // If we're below an unterminated line that is not an
3205              // "if" or something, we may line up with this line or
3206              // add something for a continuation line, depending on
3207              // the line before this one.
3208
3209              // Found two unterminated lines on a row, line up with
3210              // the last one.
3211              //   c = 99 +
3212              //            100 +
3213              // ->         here;
3214              if (lookfor == LOOKFOR_UNTERM) {
3215                // When line ends in a comma add extra indent
3216                if (terminated == ',') {
3217                  amount += ind_continuation;
3218                }
3219                break;
3220              }
3221
3222              if (lookfor == LOOKFOR_ENUM_OR_INIT) {
3223                // Found two lines ending in ',', lineup with the
3224                // lowest one, but check for cpp base class
3225                // declaration/initialization, if it is an
3226                // opening brace or we are looking just for
3227                // enumerations/initializations.
3228                if (terminated == ',') {
3229                  if (curbuf->b_ind_cpp_baseclass == 0) {
3230                    break;
3231                  }
3232
3233                  lookfor = LOOKFOR_CPP_BASECLASS;
3234                  continue;
3235                }
3236
3237                // Ignore unterminated lines in between, but
3238                // reduce indent.
3239                if (amount > cur_amount) {
3240                  amount = cur_amount;
3241                }
3242              } else {
3243                // Found first unterminated line on a row, may
3244                // line up with this line, remember its indent
3245                //          100 +
3246                // ->       here;
3247                l = get_cursor_line_ptr();
3248                amount = cur_amount;
3249
3250                n = (int)strlen(l);
3251                if (curbuf->b_ind_js && terminated == ','
3252                    && (*skipwhite(l) == ']' || (n >= 2 && l[n - 2] == ']'))) {
3253                  break;
3254                }
3255
3256                // If previous line ends in ',', check whether we
3257                // are in an initialization or enum
3258                // struct xxx =
3259                // {
3260                //      sizeof a,
3261                //      124 };
3262                // or a normal possible continuation line.
3263                // but only, of no other statement has been found
3264                // yet.
3265                if (lookfor == LOOKFOR_INITIAL && terminated == ',') {
3266                  if (curbuf->b_ind_js) {
3267                    // Search for a line ending in a comma
3268                    // and line up with the line below it
3269                    // (could be the current line).
3270                    // some = [
3271                    //     1,     <- line up here
3272                    //     2,
3273                    // some = [
3274                    //     3 +    <- line up here
3275                    //       4 *
3276                    //        5,
3277                    //     6,
3278                    if (cin_iscomment(skipwhite(l))) {
3279                      break;
3280                    }
3281                    lookfor = LOOKFOR_COMMA;
3282                    trypos = find_match_char('[', curbuf->b_ind_maxparen);
3283                    if (trypos != NULL) {
3284                      if (trypos->lnum == curwin->w_cursor.lnum - 1) {
3285                        // Current line is first inside
3286                        // [], line up with it.
3287                        break;
3288                      }
3289                      ourscope = trypos->lnum;
3290                    }
3291                  } else {
3292                    lookfor = LOOKFOR_ENUM_OR_INIT;
3293                    cont_amount = cin_first_id_amount();
3294                  }
3295                } else {
3296                  if (lookfor == LOOKFOR_INITIAL
3297                      && *l != NUL
3298                      && l[strlen(l) - 1] == '\\') {
3299                    // XXX
3300                    cont_amount = cin_get_equal_amount(curwin->w_cursor.lnum);
3301                  }
3302                  if (lookfor != LOOKFOR_TERM
3303                      && lookfor != LOOKFOR_JS_KEY
3304                      && lookfor != LOOKFOR_COMMA
3305                      && raw_string_start != curwin->w_cursor.lnum) {
3306                    lookfor = LOOKFOR_UNTERM;
3307                  }
3308                }
3309              }
3310            }
3311            // Check if we are after a while (cond);
3312            // If so: Ignore until the matching "do".
3313          } else if (cin_iswhileofdo_end((uint8_t)terminated)) {  // XXX
3314            // Found an unterminated line after a while ();, line up
3315            // with the last one.
3316            //      while (cond);
3317            //      100 +               <- line up with this one
3318            // ->           here;
3319            if (lookfor == LOOKFOR_UNTERM
3320                || lookfor == LOOKFOR_ENUM_OR_INIT) {
3321              if (cont_amount > 0) {
3322                amount = cont_amount;
3323              } else {
3324                amount += ind_continuation;
3325              }
3326              break;
3327            }
3328
3329            if (whilelevel == 0) {
3330              lookfor = LOOKFOR_TERM;
3331              amount = get_indent();                // XXX
3332              if (theline[0] == '{') {
3333                amount += curbuf->b_ind_open_extra;
3334              }
3335            }
3336            whilelevel++;
3337          } else {
3338            // We are after a "normal" statement.
3339            // If we had another statement we can stop now and use the
3340            // indent of that other statement.
3341            // Otherwise the indent of the current statement may be used,
3342            // search backwards for the next "normal" statement.
3343
3344            // Skip single break line, if before a switch label. It
3345            // may be lined up with the case label.
3346            if (lookfor == LOOKFOR_NOBREAK
3347                && cin_isbreak(skipwhite(get_cursor_line_ptr()))) {
3348              lookfor = LOOKFOR_ANY;
3349              continue;
3350            }
3351
3352            // Handle "do {" line.
3353            if (whilelevel > 0) {
3354              l = cin_skipcomment(get_cursor_line_ptr());
3355              if (cin_isdo(l)) {
3356                amount = get_indent();                  // XXX
3357                whilelevel--;
3358                continue;
3359              }
3360            }
3361
3362            // Found a terminated line above an unterminated line. Add
3363            // the amount for a continuation line.
3364            //   x = 1;
3365            //   y = foo +
3366            // ->       here;
3367            // or
3368            //   int x = 1;
3369            //   int foo,
3370            // ->       here;
3371            if (lookfor == LOOKFOR_UNTERM
3372                || lookfor == LOOKFOR_ENUM_OR_INIT) {
3373              if (cont_amount > 0) {
3374                amount = cont_amount;
3375              } else {
3376                amount += ind_continuation;
3377              }
3378              break;
3379            }
3380
3381            // Found a terminated line above a terminated line or "if"
3382            // etc. line. Use the amount of the line below us.
3383            //   x = 1;                         x = 1;
3384            //   if (asdf)                  y = 2;
3385            //       while (asdf)         ->here;
3386            //          here;
3387            // ->foo;
3388            if (lookfor == LOOKFOR_TERM) {
3389              if (!lookfor_break && whilelevel == 0) {
3390                break;
3391              }
3392            } else {
3393              // First line above the one we're indenting is terminated.
3394              // To know what needs to be done look further backward for
3395              // a terminated line.
3396
3397              // position the cursor over the rightmost paren, so
3398              // that matching it will take us back to the start of
3399              // the line.  Helps for:
3400              //     func(asdr,
3401              //              asdfasdf);
3402              //     here;
3403term_again:
3404              l = get_cursor_line_ptr();
3405              if (find_last_paren(l, '(', ')')
3406                  && (trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL) {
3407                // Check if we are on a case label now.  This is
3408                // handled above.
3409                //         case xx:  if ( asdf &&
3410                //                          asdf)
3411                curwin->w_cursor = *trypos;
3412                l = get_cursor_line_ptr();
3413                if (cin_iscase(l, false) || cin_isscopedecl(l)) {
3414                  curwin->w_cursor.lnum++;
3415                  curwin->w_cursor.col = 0;
3416                  continue;
3417                }
3418              }
3419
3420              // When aligning with the case statement, don't align
3421              // with a statement after it.
3422              //  case 1: {   <-- don't use this { position
3423              //        stat;
3424              //  }
3425              //  case 2:
3426              //        stat;
3427              // }
3428              iscase = curbuf->b_ind_keep_case_label && cin_iscase(l, false);
3429
3430              // Get indent and pointer to text for current line,
3431              // ignoring any jump label.
3432              amount = skip_label(curwin->w_cursor.lnum, &l);
3433
3434              if (theline[0] == '{') {
3435                amount += curbuf->b_ind_open_extra;
3436              }
3437              // See remark above: "Only add b_ind_open_extra.."
3438              l = skipwhite(l);
3439              if (*l == '{') {
3440                amount -= curbuf->b_ind_open_extra;
3441              }
3442              lookfor = iscase ? LOOKFOR_ANY : LOOKFOR_TERM;
3443
3444              // When a terminated line starts with "else" skip to
3445              // the matching "if":
3446              //       else 3;
3447              //             indent this;
3448              // Need to use the scope of this "else".  XXX
3449              // If whilelevel != 0 continue looking for a "do {".
3450              if (lookfor == LOOKFOR_TERM
3451                  && *l != '}'
3452                  && cin_iselse(l)
3453                  && whilelevel == 0) {
3454                if ((trypos = find_start_brace()) == NULL
3455                    || find_match(LOOKFOR_IF, trypos->lnum)
3456                    == FAIL) {
3457                  break;
3458                }
3459                continue;
3460              }
3461
3462              // If we're at the end of a block, skip to the start of
3463              // that block.
3464              l = get_cursor_line_ptr();
3465              if (find_last_paren(l, '{', '}')           // XXX
3466                  && (trypos = find_start_brace()) != NULL) {
3467                curwin->w_cursor = *trypos;
3468                // if not "else {" check for terminated again
3469                // but skip block for "} else {"
3470                l = cin_skipcomment(get_cursor_line_ptr());
3471                if (*l == '}' || !cin_iselse(l)) {
3472                  goto term_again;
3473                }
3474                curwin->w_cursor.lnum++;
3475                curwin->w_cursor.col = 0;
3476              }
3477            }
3478          }
3479        }
3480      }
3481    }
3482
3483    // add extra indent for a comment
3484    if (cin_iscomment(theline)) {
3485      amount += curbuf->b_ind_comment;
3486    }
3487    // subtract extra left-shift for jump labels
3488    if (curbuf->b_ind_jump_label > 0 && original_line_islabel) {
3489      amount -= curbuf->b_ind_jump_label;
3490    }
3491
3492    goto theend;
3493  }
3494
3495  // Ok -- we're not inside any sort of structure at all!
3496  //
3497  // this means we're at the top level, and everything should
3498  // basically just match where the previous line is, except
3499  // for the lines immediately following a function declaration,
3500  // which are K&R-style parameters and need to be indented.
3501
3502  // if our line starts with an open brace, forget about any
3503  // prevailing indent and make sure it looks like the start
3504  // of a function
3505
3506  if (theline[0] == '{') {
3507    amount = curbuf->b_ind_first_open;
3508    goto theend;
3509  }
3510  // If the NEXT line is a function declaration, the current
3511  // line needs to be indented as a function type spec.
3512  // Don't do this if the current line looks like a comment or if the
3513  // current line is terminated, ie. ends in ';', or if the current line
3514  // contains { or }: "void f() {\n if (1)"
3515  if (cur_curpos.lnum < curbuf->b_ml.ml_line_count
3516      && !cin_nocode(theline)
3517      && vim_strchr(theline, '{') == NULL
3518      && vim_strchr(theline, '}') == NULL
3519      && !cin_ends_in(theline, ":")
3520      && !cin_ends_in(theline, ",")
3521      && cin_isfuncdecl(NULL, cur_curpos.lnum + 1, cur_curpos.lnum + 1)
3522      && !cin_isterminated(theline, false, true)) {
3523    amount = curbuf->b_ind_func_type;
3524    goto theend;
3525  }
3526
3527  // search backwards until we find something we recognize
3528  amount = 0;
3529  curwin->w_cursor = cur_curpos;
3530  while (curwin->w_cursor.lnum > 1) {
3531    curwin->w_cursor.lnum--;
3532    curwin->w_cursor.col = 0;
3533
3534    l = get_cursor_line_ptr();
3535
3536    // If we're in a comment or raw string now, skip to the start
3537    // of it.
3538    // XXX
3539    if ((trypos = ind_find_start_CORS(NULL)) != NULL) {
3540      curwin->w_cursor.lnum = trypos->lnum + 1;
3541      curwin->w_cursor.col = 0;
3542      continue;
3543    }
3544
3545    // Are we at the start of a cpp base class declaration or
3546    // constructor initialization?  XXX
3547    n = 0;
3548    if (curbuf->b_ind_cpp_baseclass != 0) {
3549      n = cin_is_cpp_baseclass(&cache_cpp_baseclass);
3550      l = get_cursor_line_ptr();
3551    }
3552    if (n) {
3553      // XXX
3554      amount = get_baseclass_amount(cache_cpp_baseclass.lpos.col);
3555      break;
3556    }
3557
3558    // Skip preprocessor directives and blank lines.
3559    if (cin_ispreproc_cont(&l, &curwin->w_cursor.lnum, &amount)) {
3560      continue;
3561    }
3562
3563    if (cin_nocode(l)) {
3564      continue;
3565    }
3566
3567    // If the previous line ends in ',', use one level of
3568    // indentation:
3569    // int foo,
3570    //     bar;
3571    // do this before checking for '}' in case of eg.
3572    // enum foobar
3573    // {
3574    //   ...
3575    // } foo,
3576    //   bar;
3577    if (cin_ends_in(l, ",")
3578        || (*l != NUL && (n = (uint8_t)l[strlen(l) - 1]) == '\\')) {
3579      // take us back to opening paren
3580      if (find_last_paren(l, '(', ')')
3581          && (trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL) {
3582        curwin->w_cursor = *trypos;
3583      }
3584
3585      // For a line ending in ',' that is a continuation line go
3586      // back to the first line with a backslash:
3587      // char *foo = "bla{backslash}
3588      //           bla",
3589      //      here;
3590      while (n == 0 && curwin->w_cursor.lnum > 1) {
3591        l = ml_get(curwin->w_cursor.lnum - 1);
3592        if (*l == NUL || l[strlen(l) - 1] != '\\') {
3593          break;
3594        }
3595        curwin->w_cursor.lnum--;
3596        curwin->w_cursor.col = 0;
3597      }
3598
3599      amount = get_indent();                    // XXX
3600
3601      if (amount == 0) {
3602        amount = cin_first_id_amount();
3603      }
3604      if (amount == 0) {
3605        amount = ind_continuation;
3606      }
3607      break;
3608    }
3609
3610    // If the line looks like a function declaration, and we're
3611    // not in a comment, put it the left margin.
3612    if (cin_isfuncdecl(NULL, cur_curpos.lnum, 0)) {        // XXX
3613      break;
3614    }
3615    l = get_cursor_line_ptr();
3616
3617    // Finding the closing '}' of a previous function.  Put
3618    // current line at the left margin.  For when 'cino' has "fs".
3619    if (*skipwhite(l) == '}') {
3620      break;
3621    }
3622
3623    //                      (matching {)
3624    // If the previous line ends on '};' (maybe followed by
3625    // comments) align at column 0.  For example:
3626    // char *string_array[] = { "foo",
3627    //     / * x * / "b};ar" }; / * foobar * /
3628    if (cin_ends_in(l, "};")) {
3629      break;
3630    }
3631
3632    // If the previous line ends on '[' we are probably in an
3633    // array constant:
3634    // something = [
3635    //     234,  <- extra indent
3636    if (cin_ends_in(l, "[")) {
3637      amount = get_indent() + ind_continuation;
3638      break;
3639    }
3640
3641    // Find a line only has a semicolon that belongs to a previous
3642    // line ending in '}', e.g. before an #endif.  Don't increase
3643    // indent then.
3644    if (*(look = skipwhite(l)) == ';' && cin_nocode(look + 1)) {
3645      pos_T curpos_save = curwin->w_cursor;
3646
3647      while (curwin->w_cursor.lnum > 1) {
3648        look = ml_get(--curwin->w_cursor.lnum);
3649        if (!(cin_nocode(look)
3650              || cin_ispreproc_cont(&look, &curwin->w_cursor.lnum, &amount))) {
3651          break;
3652        }
3653      }
3654      if (curwin->w_cursor.lnum > 0 && cin_ends_in(look, "}")) {
3655        break;
3656      }
3657
3658      curwin->w_cursor = curpos_save;
3659    }
3660
3661    // If the PREVIOUS line is a function declaration, the current
3662    // line (and the ones that follow) needs to be indented as
3663    // parameters.
3664    if (cin_isfuncdecl(&l, curwin->w_cursor.lnum, 0)) {
3665      amount = curbuf->b_ind_param;
3666      break;
3667    }
3668
3669    // If the previous line ends in ';' and the line before the
3670    // previous line ends in ',' or '\', ident to column zero:
3671    // int foo,
3672    //     bar;
3673    // indent_to_0 here;
3674    if (cin_ends_in(l, ";")) {
3675      l = ml_get(curwin->w_cursor.lnum - 1);
3676      if (cin_ends_in(l, ",")
3677          || (*l != NUL && l[strlen(l) - 1] == '\\')) {
3678        break;
3679      }
3680      l = get_cursor_line_ptr();
3681    }
3682
3683    // Doesn't look like anything interesting -- so just
3684    // use the indent of this line.
3685    //
3686    // Position the cursor over the rightmost paren, so that
3687    // matching it will take us back to the start of the line.
3688    (void)find_last_paren(l, '(', ')');
3689
3690    if ((trypos = find_match_paren(curbuf->b_ind_maxparen)) != NULL) {
3691      curwin->w_cursor = *trypos;
3692    }
3693    amount = get_indent();              // XXX
3694    break;
3695  }
3696
3697  // add extra indent for a comment
3698  if (cin_iscomment(theline)) {
3699    amount += curbuf->b_ind_comment;
3700  }
3701
3702  // add extra indent if the previous line ended in a backslash:
3703  //          "asdfasdf{backslash}
3704  //              here";
3705  //        char *foo = "asdf{backslash}
3706  //                     here";
3707  if (cur_curpos.lnum > 1) {
3708    l = ml_get(cur_curpos.lnum - 1);
3709    if (*l != NUL && l[strlen(l) - 1] == '\\') {
3710      cur_amount = cin_get_equal_amount(cur_curpos.lnum - 1);
3711      if (cur_amount > 0) {
3712        amount = cur_amount;
3713      } else if (cur_amount == 0) {
3714        amount += ind_continuation;
3715      }
3716    }
3717  }
3718
3719theend:
3720  if (amount < 0) {
3721    amount = 0;
3722  }
3723
3724laterend:
3725  // put the cursor back where it belongs
3726  curwin->w_cursor = cur_curpos;
3727
3728  xfree(linecopy);
3729
3730  return amount;
3731}
3732
3733static int find_match(int lookfor, linenr_T ourscope)
3734{
3735  const char *look;
3736  pos_T *theirscope;
3737  const char *mightbeif;
3738  int elselevel;
3739  int whilelevel;
3740
3741  if (lookfor == LOOKFOR_IF) {
3742    elselevel = 1;
3743    whilelevel = 0;
3744  } else {
3745    elselevel = 0;
3746    whilelevel = 1;
3747  }
3748
3749  curwin->w_cursor.col = 0;
3750
3751  while (curwin->w_cursor.lnum > ourscope + 1) {
3752    curwin->w_cursor.lnum--;
3753    curwin->w_cursor.col = 0;
3754
3755    look = cin_skipcomment(get_cursor_line_ptr());
3756    if (!cin_iselse(look)
3757        && !cin_isif(look)
3758        && !cin_isdo(look)                                   // XXX
3759        && !cin_iswhileofdo(look, curwin->w_cursor.lnum)) {
3760      continue;
3761    }
3762
3763    // if we've gone outside the braces entirely,
3764    // we must be out of scope...
3765    theirscope = find_start_brace();        // XXX
3766    if (theirscope == NULL) {
3767      break;
3768    }
3769
3770    // and if the brace enclosing this is further
3771    // back than the one enclosing the else, we're
3772    // out of luck too.
3773    if (theirscope->lnum < ourscope) {
3774      break;
3775    }
3776
3777    // and if they're enclosed in a *deeper* brace,
3778    // then we can ignore it because it's in a
3779    // different scope...
3780    if (theirscope->lnum > ourscope) {
3781      continue;
3782    }
3783
3784    look = cin_skipcomment(get_cursor_line_ptr());
3785    // When looking for if, we ignore "if" and "else" in a deeper do-while loop.
3786    if (!(lookfor == LOOKFOR_IF && whilelevel)) {
3787      // if it was an "else" (that's not an "else if")
3788      // then we need to go back to another if, so
3789      // increment elselevel
3790      if (cin_iselse(look)) {
3791        mightbeif = cin_skipcomment(look + 4);
3792        if (!cin_isif(mightbeif)) {
3793          elselevel++;
3794        }
3795        continue;
3796      }
3797
3798      // If it's an "if" decrement elselevel
3799      if (cin_isif(look)) {
3800        elselevel--;
3801        // When looking for an "if" ignore "while"s that
3802        // get in the way.
3803        if (elselevel == 0 && lookfor == LOOKFOR_IF) {
3804          whilelevel = 0;
3805        }
3806      }
3807    }
3808
3809    // if it was a "while" then we need to go back to
3810    // another "do", so increment whilelevel.  XXX
3811    if (cin_iswhileofdo(look, curwin->w_cursor.lnum)) {
3812      whilelevel++;
3813      continue;
3814    }
3815
3816    // If it's a "do" decrement whilelevel
3817    if (cin_isdo(look)) {
3818      whilelevel--;
3819    }
3820
3821    // if we've used up all the elses, then
3822    // this must be the if that we want!
3823    // match the indent level of that if.
3824    if (elselevel <= 0 && whilelevel <= 0) {
3825      return OK;
3826    }
3827  }
3828  return FAIL;
3829}
3830
3831/// Check that "cinkeys" contains the key "keytyped",
3832/// when == '*': Only if key is preceded with '*' (indent before insert)
3833/// when == '!': Only if key is preceded with '!' (don't insert)
3834/// when == ' ': Only if key is not preceded with '*' (indent afterwards)
3835///
3836/// "keytyped" can have a few special values:
3837/// KEY_OPEN_FORW :
3838/// KEY_OPEN_BACK :
3839/// KEY_COMPLETE  : Just finished completion.
3840///
3841/// @param  keytyped       key that was typed
3842/// @param  when           condition on when to perform the check
3843/// @param  line_is_empty  when true, accept keys with '0' before them.
3844bool in_cinkeys(int keytyped, int when, bool line_is_empty)
3845{
3846  char *look;
3847  bool try_match;
3848  bool try_match_word;
3849  char *p;
3850  bool icase;
3851
3852  if (keytyped == NUL) {
3853    // Can happen with CTRL-Y and CTRL-E on a short line.
3854    return false;
3855  }
3856
3857  if (curbuf->b_p_inde.type != kCallbackNone) {
3858    look = curbuf->b_p_indk;            // 'indentexpr' set: use 'indentkeys'
3859  } else {
3860    look = curbuf->b_p_cink;            // 'indentexpr' empty: use 'cinkeys'
3861  }
3862  while (*look) {
3863    // Find out if we want to try a match with this key, depending on
3864    // 'when' and a '*' or '!' before the key.
3865    switch (when) {
3866    case '*':
3867      try_match = (*look == '*'); break;
3868    case '!':
3869      try_match = (*look == '!'); break;
3870    default:
3871      try_match = (*look != '*'); break;
3872    }
3873    if (*look == '*' || *look == '!') {
3874      look++;
3875    }
3876
3877    // If there is a '0', only accept a match if the line is empty.
3878    // But may still match when typing last char of a word.
3879    if (*look == '0') {
3880      try_match_word = try_match;
3881      if (!line_is_empty) {
3882        try_match = false;
3883      }
3884      look++;
3885    } else {
3886      try_match_word = false;
3887    }
3888
3889    // Does it look like a control character?
3890    if (*look == '^' && look[1] >= '?' && look[1] <= '_') {
3891      if (try_match && keytyped == CTRL_CHR(look[1])) {
3892        return true;
3893      }
3894      look += 2;
3895
3896      // 'o' means "o" command, open forward.
3897      // 'O' means "O" command, open backward.
3898    } else if (*look == 'o') {
3899      if (try_match && keytyped == KEY_OPEN_FORW) {
3900        return true;
3901      }
3902      look++;
3903    } else if (*look == 'O') {
3904      if (try_match && keytyped == KEY_OPEN_BACK) {
3905        return true;
3906      }
3907      look++;
3908
3909      // 'e' means to check for "else" at start of line and just before the
3910      // cursor.
3911    } else if (*look == 'e') {
3912      if (try_match && keytyped == 'e' && curwin->w_cursor.col >= 4) {
3913        p = get_cursor_line_ptr();
3914        if (skipwhite(p) == p + curwin->w_cursor.col - 4
3915            && strncmp(p + curwin->w_cursor.col - 4, "else", 4) == 0) {
3916          return true;
3917        }
3918      }
3919      look++;
3920
3921      // ':' only causes an indent if it is at the end of a label or case
3922      // statement, or when it was before typing the ':' (to fix
3923      // class::method for C++).
3924    } else if (*look == ':') {
3925      if (try_match && keytyped == ':') {
3926        p = get_cursor_line_ptr();
3927        if (cin_iscase(p, false) || cin_isscopedecl(p) || cin_islabel()) {
3928          return true;
3929        }
3930        // Need to get the line again after cin_islabel().
3931        p = get_cursor_line_ptr();
3932        if (curwin->w_cursor.col > 2
3933            && p[curwin->w_cursor.col - 1] == ':'
3934            && p[curwin->w_cursor.col - 2] == ':') {
3935          p[curwin->w_cursor.col - 1] = ' ';
3936          const bool i = cin_iscase(p, false)
3937                         || cin_isscopedecl(p)
3938                         || cin_islabel();
3939          p = get_cursor_line_ptr();
3940          p[curwin->w_cursor.col - 1] = ':';
3941          if (i) {
3942            return true;
3943          }
3944        }
3945      }
3946      look++;
3947
3948      // Is it a key in <>, maybe?
3949    } else if (*look == '<') {
3950      if (try_match) {
3951        // make up some named keys <o>, <O>, <e>, <0>, <>>, <<>, <*>,
3952        // <:> and <!> so that people can re-indent on o, O, e, 0, <,
3953        // >, *, : and ! keys if they really really want to.
3954        if (vim_strchr("<>!*oOe0:", (uint8_t)look[1]) != NULL
3955            && keytyped == look[1]) {
3956          return true;
3957        }
3958
3959        if (keytyped == get_special_key_code(look + 1)) {
3960          return true;
3961        }
3962      }
3963      while (*look && *look != '>') {
3964        look++;
3965      }
3966      while (*look == '>') {
3967        look++;
3968      }
3969      // Is it a word: "=word"?
3970    } else if (*look == '=' && look[1] != ',' && look[1] != NUL) {
3971      look++;
3972      if (*look == '~') {
3973        icase = true;
3974        look++;
3975      } else {
3976        icase = false;
3977      }
3978      p = vim_strchr(look, ',');
3979      if (p == NULL) {
3980        p = look + strlen(look);
3981      }
3982      if ((try_match || try_match_word)
3983          && curwin->w_cursor.col >= (colnr_T)(p - look)) {
3984        bool match = false;
3985
3986        if (keytyped == KEY_COMPLETE) {
3987          char *n, *s;
3988
3989          // Just completed a word, check if it starts with "look".
3990          // search back for the start of a word.
3991          char *line = get_cursor_line_ptr();
3992          for (s = line + curwin->w_cursor.col; s > line; s = n) {
3993            n = mb_prevptr(line, s);
3994            if (!vim_iswordp(n)) {
3995              break;
3996            }
3997          }
3998          assert(p >= look && (uintmax_t)(p - look) <= SIZE_MAX);
3999          if (s + (p - look) <= line + curwin->w_cursor.col
4000              && (icase
4001                  ? mb_strnicmp(s, look, (size_t)(p - look))
4002                  : strncmp(s, look, (size_t)(p - look))) == 0) {
4003            match = true;
4004          }
4005        } else {
4006          // TODO(@brammool): multi-byte
4007          if (keytyped == (int)(uint8_t)p[-1]
4008              || (icase && keytyped < 256 && keytyped >= 0
4009                  && TOLOWER_LOC(keytyped) == TOLOWER_LOC((uint8_t)p[-1]))) {
4010            char *line = get_cursor_pos_ptr();
4011            assert(p >= look && (uintmax_t)(p - look) <= SIZE_MAX);
4012            if ((curwin->w_cursor.col == (colnr_T)(p - look)
4013                 || !vim_iswordc((uint8_t)line[-(p - look) - 1]))
4014                && (icase
4015                    ? mb_strnicmp(line - (p - look), look, (size_t)(p - look))
4016                    : strncmp(line - (p - look), look, (size_t)(p - look))) == 0) {
4017              match = true;
4018            }
4019          }
4020        }
4021        if (match && try_match_word && !try_match) {
4022          // "0=word": Check if there are only blanks before the
4023          // word.
4024          if (getwhitecols_curline() !=
4025              (int)(curwin->w_cursor.col - (p - look))) {
4026            match = false;
4027          }
4028        }
4029        if (match) {
4030          return true;
4031        }
4032      }
4033      look = p;
4034
4035      // Ok, it's a boring generic character.
4036    } else {
4037      if (try_match && (uint8_t)(*look) == keytyped) {
4038        return true;
4039      }
4040      if (*look != NUL) {
4041        look++;
4042      }
4043    }
4044
4045    // Skip over ", ".
4046    look = skip_to_option_part(look);
4047  }
4048  return false;
4049}
4050
4051// Do C or expression indenting on the current line.
4052void do_c_expr_indent(void)
4053{
4054  if (curbuf->b_p_inde.type != kCallbackNone) {
4055    fixthisline(get_expr_indent);
4056  } else {
4057    fixthisline(get_c_indent);
4058  }
4059}
4060
4061/// "cindent(lnum)" function
4062void f_cindent(typval_T *argvars, typval_T *rettv, EvalFuncData fptr)
4063{
4064  pos_T pos = curwin->w_cursor;
4065  linenr_T lnum = tv_get_lnum(argvars);
4066  if (lnum >= 1 && lnum <= curbuf->b_ml.ml_line_count) {
4067    curwin->w_cursor.lnum = lnum;
4068    rettv->vval.v_number = get_c_indent();
4069    curwin->w_cursor = pos;
4070  } else {
4071    rettv->vval.v_number = -1;
4072  }
4073}