1" Vim indent file
2" Language:     CMake (ft=cmake)
3" Author:       Andy Cedilnik <[email protected]>
4" Maintainer:   Dimitri Merejkowsky <[email protected]>
5" Former Maintainer: Karthik Krishnan <[email protected]>
6" Last Change:  2017 Aug 30
7"
8" License:      The CMake license applies to this file. See
9"               https://cmake.org/licensing
10"               This implies that distribution with Vim is allowed
11
12if exists("b:did_indent")
13  finish
14endif
15let b:did_indent = 1
16
17let s:keepcpo= &cpo
18set cpo&vim
19
20setlocal indentexpr=CMakeGetIndent(v:lnum)
21setlocal indentkeys+==ENDIF(,ENDFOREACH(,ENDMACRO(,ELSE(,ELSEIF(,ENDWHILE(
22
23" Only define the function once.
24if exists("*CMakeGetIndent")
25  finish
26endif
27
28fun! CMakeGetIndent(lnum)
29  let this_line = getline(a:lnum)
30
31  " Find a non-blank line above the current line.
32  let lnum = a:lnum
33  let lnum = prevnonblank(lnum - 1)
34  let previous_line = getline(lnum)
35
36  " Hit the start of the file, use zero indent.
37  if lnum == 0
38    return 0
39  endif
40
41  let ind = indent(lnum)
42
43  let or = '\|'
44  " Regular expressions used by line indentation function.
45  let cmake_regex_comment = '#.*'
46  let cmake_regex_identifier = '[A-Za-z][A-Za-z0-9_]*'
47  let cmake_regex_quoted = '"\([^"\\]\|\\.\)*"'
48  let cmake_regex_arguments = '\(' . cmake_regex_quoted .
49                    \       or . '\$(' . cmake_regex_identifier . ')' .
50                    \       or . '[^()\\#"]' . or . '\\.' . '\)*'
51
52  let cmake_indent_comment_line = '^\s*' . cmake_regex_comment
53  let cmake_indent_blank_regex = '^\s*$'
54  let cmake_indent_open_regex = '^\s*' . cmake_regex_identifier .
55                    \           '\s*(' . cmake_regex_arguments .
56                    \           '\(' . cmake_regex_comment . '\)\?$'
57
58  let cmake_indent_close_regex = '^' . cmake_regex_arguments .
59                    \            ')\s*' .
60                    \            '\(' . cmake_regex_comment . '\)\?$'
61
62  let cmake_indent_begin_regex = '^\s*\(IF\|MACRO\|FOREACH\|ELSE\|ELSEIF\|WHILE\|FUNCTION\)\s*('
63  let cmake_indent_end_regex = '^\s*\(ENDIF\|ENDFOREACH\|ENDMACRO\|ELSE\|ELSEIF\|ENDWHILE\|ENDFUNCTION\)\s*('
64
65  " Add
66  if previous_line =~? cmake_indent_comment_line " Handle comments
67    let ind = ind
68  else
69    if previous_line =~? cmake_indent_begin_regex
70      let ind = ind + shiftwidth()
71    endif
72    if previous_line =~? cmake_indent_open_regex
73      let ind = ind + shiftwidth()
74    endif
75  endif
76
77  " Subtract
78  if this_line =~? cmake_indent_end_regex
79    let ind = ind - shiftwidth()
80  endif
81  if previous_line =~? cmake_indent_close_regex
82    let ind = ind - shiftwidth()
83  endif
84
85  return ind
86endfun
87
88let &cpo = s:keepcpo
89unlet s:keepcpo
90