blob: a0ef5005c5a1082c21ee76cfe8fb3a2159fe68b6 [file] [log] [blame]
Eric Liuc7f3b102016-05-18 14:10:16 +00001# This file is a minimal clang-include-fixer vim-integration. To install:
2# - Change 'binary' if clang-include-fixer is not on the path (see below).
3# - Add to your .vimrc:
4#
Kirill Bobyrevc4018e22016-07-27 14:23:47 +00005# noremap <leader>cf :pyf path/to/llvm/source/tools/clang/tools/extra/include-fixer/tool/clang-include-fixer.py<cr>
Eric Liuc7f3b102016-05-18 14:10:16 +00006#
Kirill Bobyrevc4018e22016-07-27 14:23:47 +00007# This enables clang-include-fixer for NORMAL and VISUAL mode. Change "<leader>cf"
8# to another binding if you need clang-include-fixer on a different key.
Eric Liuc7f3b102016-05-18 14:10:16 +00009#
10# To set up clang-include-fixer, see http://clang.llvm.org/extra/include-fixer.html
11#
12# With this integration you can press the bound key and clang-include-fixer will
13# be run on the current buffer.
14#
15# It operates on the current, potentially unsaved buffer and does not create
16# or save any files. To revert a fix, just undo.
17
18import argparse
Eric Liu702cfd12016-05-19 08:21:09 +000019import difflib
Haojian Wucd637012016-09-07 16:34:35 +000020import json
21import re
Eric Liuc7f3b102016-05-18 14:10:16 +000022import subprocess
Eric Liuc7f3b102016-05-18 14:10:16 +000023import vim
24
25# set g:clang_include_fixer_path to the path to clang-include-fixer if it is not
26# on the path.
27# Change this to the full path if clang-include-fixer is not on the path.
28binary = 'clang-include-fixer'
29if vim.eval('exists("g:clang_include_fixer_path")') == "1":
30 binary = vim.eval('g:clang_include_fixer_path')
31
Benjamin Kramerfdaed4c2016-07-04 16:47:17 +000032maximum_suggested_headers = 3
Haojian Wu11e9bd22016-05-31 09:31:51 +000033if vim.eval('exists("g:clang_include_fixer_maximum_suggested_headers")') == "1":
34 maximum_suggested_headers = max(
35 1,
36 vim.eval('g:clang_include_fixer_maximum_suggested_headers'))
37
Benjamin Kramerfdaed4c2016-07-04 16:47:17 +000038increment_num = 5
Eric Liuf4a57102016-06-10 12:09:33 +000039if vim.eval('exists("g:clang_include_fixer_increment_num")') == "1":
40 increment_num = max(
41 1,
42 vim.eval('g:clang_include_fixer_increment_num'))
Haojian Wu11e9bd22016-05-31 09:31:51 +000043
Haojian Wufff3ad62016-07-18 10:04:45 +000044jump_to_include = False
45if vim.eval('exists("g:clang_include_fixer_jump_to_include")') == "1":
46 jump_to_include = vim.eval('g:clang_include_fixer_jump_to_include') != "0"
47
Haojian Wucd637012016-09-07 16:34:35 +000048query_mode = True
49if vim.eval('exists("g:clang_include_fixer_query_mode")') == "1":
50 query_mode = vim.eval('g:clang_include_fixer_query_mode') != "0"
51
Benjamin Kramerfdaed4c2016-07-04 16:47:17 +000052
Eric Liuf832eb72016-06-07 12:21:43 +000053def GetUserSelection(message, headers, maximum_suggested_headers):
54 eval_message = message + '\n'
55 for idx, header in enumerate(headers[0:maximum_suggested_headers]):
Benjamin Kramerfdaed4c2016-07-04 16:47:17 +000056 eval_message += "({0}). {1}\n".format(idx + 1, header)
Eric Liuf832eb72016-06-07 12:21:43 +000057 eval_message += "Enter (q) to quit;"
58 if maximum_suggested_headers < len(headers):
Eric Liuf4a57102016-06-10 12:09:33 +000059 eval_message += " (m) to show {0} more candidates.".format(
60 min(increment_num, len(headers) - maximum_suggested_headers))
61
Eric Liuf832eb72016-06-07 12:21:43 +000062 eval_message += "\nSelect (default 1): "
63 res = vim.eval("input('{0}')".format(eval_message))
64 if res == '':
65 # choose the top ranked header by default
66 idx = 1
67 elif res == 'q':
68 raise Exception(' Insertion cancelled...')
Eric Liuf4a57102016-06-10 12:09:33 +000069 elif res == 'm':
70 return GetUserSelection(message,
71 headers, maximum_suggested_headers + increment_num)
Eric Liuf832eb72016-06-07 12:21:43 +000072 else:
73 try:
74 idx = int(res)
75 if idx <= 0 or idx > len(headers):
76 raise Exception()
77 except Exception:
Eric Liuf4a57102016-06-10 12:09:33 +000078 # Show a new prompt on invalid option instead of aborting so that users
79 # don't need to wait for another include-fixer run.
80 print >> sys.stderr, "Invalid option:", res
81 return GetUserSelection(message, headers, maximum_suggested_headers)
Benjamin Kramerfdaed4c2016-07-04 16:47:17 +000082 return headers[idx - 1]
83
Haojian Wu11e9bd22016-05-31 09:31:51 +000084
85def execute(command, text):
86 p = subprocess.Popen(command,
87 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
88 stdin=subprocess.PIPE)
89 return p.communicate(input=text)
90
91
92def InsertHeaderToVimBuffer(header, text):
Benjamin Kramerfdaed4c2016-07-04 16:47:17 +000093 command = [binary, "-stdin", "-insert-header=" + json.dumps(header),
Haojian Wu11e9bd22016-05-31 09:31:51 +000094 vim.current.buffer.name]
95 stdout, stderr = execute(command, text)
Haojian Wufff3ad62016-07-18 10:04:45 +000096 if stderr:
97 raise Exception(stderr)
Haojian Wu11e9bd22016-05-31 09:31:51 +000098 if stdout:
99 lines = stdout.splitlines()
100 sequence = difflib.SequenceMatcher(None, vim.current.buffer, lines)
Haojian Wufff3ad62016-07-18 10:04:45 +0000101 line_num = None
Haojian Wu11e9bd22016-05-31 09:31:51 +0000102 for op in reversed(sequence.get_opcodes()):
Haojian Wufff3ad62016-07-18 10:04:45 +0000103 if op[0] != 'equal':
Haojian Wu11e9bd22016-05-31 09:31:51 +0000104 vim.current.buffer[op[1]:op[2]] = lines[op[3]:op[4]]
Haojian Wufff3ad62016-07-18 10:04:45 +0000105 if op[0] == 'insert':
106 # line_num in vim is 1-based.
107 line_num = op[1] + 1
108
109 if jump_to_include and line_num:
110 vim.current.window.cursor = (line_num, 0)
Haojian Wu11e9bd22016-05-31 09:31:51 +0000111
112
Haojian Wucd637012016-09-07 16:34:35 +0000113# The vim internal implementation (expand("cword"/"cWORD")) doesn't support
114# our use case very well, we re-implement our own one.
115def get_symbol_under_cursor():
116 line = vim.eval("line(\".\")")
117 # column number in vim is 1-based.
118 col = int(vim.eval("col(\".\")")) - 1
119 line_text = vim.eval("getline({0})".format(line))
120 if len(line_text) == 0: return ""
121 symbol_pos_begin = col
122 p = re.compile('[a-zA-Z0-9:_]')
123 while symbol_pos_begin >= 0 and p.match(line_text[symbol_pos_begin]):
124 symbol_pos_begin -= 1
125
126 symbol_pos_end = col
127 while symbol_pos_end < len(line_text) and p.match(line_text[symbol_pos_end]):
128 symbol_pos_end += 1
129 return line_text[symbol_pos_begin+1:symbol_pos_end]
130
131
Eric Liuc7f3b102016-05-18 14:10:16 +0000132def main():
133 parser = argparse.ArgumentParser(
134 description='Vim integration for clang-include-fixer')
135 parser.add_argument('-db', default='yaml',
136 help='clang-include-fixer input format.')
137 parser.add_argument('-input', default='',
138 help='String to initialize the database.')
139 args = parser.parse_args()
140
141 # Get the current text.
142 buf = vim.current.buffer
143 text = '\n'.join(buf)
144
Haojian Wucd637012016-09-07 16:34:35 +0000145 if query_mode:
146 symbol = get_symbol_under_cursor()
147 if len(symbol) == 0:
148 print "Skip querying empty symbol."
149 return
150 command = [binary, "-stdin", "-query-symbol="+get_symbol_under_cursor(),
151 "-db=" + args.db, "-input=" + args.input,
152 vim.current.buffer.name]
153 else:
154 # Run command to get all headers.
155 command = [binary, "-stdin", "-output-headers", "-db=" + args.db,
156 "-input=" + args.input, vim.current.buffer.name]
Haojian Wu11e9bd22016-05-31 09:31:51 +0000157 stdout, stderr = execute(command, text)
Haojian Wu17a54e32016-06-01 11:43:10 +0000158 if stderr:
159 print >> sys.stderr, "Error while running clang-include-fixer: " + stderr
160 return
161
162 include_fixer_context = json.loads(stdout)
Haojian Wu62aee522016-07-21 13:47:09 +0000163 query_symbol_infos = include_fixer_context["QuerySymbolInfos"]
164 if not query_symbol_infos:
165 print "The file is fine, no need to add a header."
166 return
167 symbol = query_symbol_infos[0]["RawIdentifier"]
Haojian Wu68c34a02016-07-13 16:43:54 +0000168 # The header_infos is already sorted by include-fixer.
169 header_infos = include_fixer_context["HeaderInfos"]
170 # Deduplicate headers while keeping the order, so that the same header would
171 # not be suggested twice.
172 unique_headers = []
173 seen = set()
174 for header_info in header_infos:
175 header = header_info["Header"]
176 if header not in seen:
177 seen.add(header)
178 unique_headers.append(header)
Haojian Wu17a54e32016-06-01 11:43:10 +0000179
Haojian Wu68c34a02016-07-13 16:43:54 +0000180 if not unique_headers:
Haojian Wufff3ad62016-07-18 10:04:45 +0000181 print "Couldn't find a header for {0}.".format(symbol)
Haojian Wu11e9bd22016-05-31 09:31:51 +0000182 return
Eric Liuc7f3b102016-05-18 14:10:16 +0000183
Eric Liuf832eb72016-06-07 12:21:43 +0000184 try:
Haojian Wu25df3b82016-09-01 12:17:28 +0000185 selected = unique_headers[0]
Haojian Wuc99f7282016-08-09 08:26:19 +0000186 inserted_header_infos = header_infos
187 if len(unique_headers) > 1:
188 selected = GetUserSelection(
189 "choose a header file for {0}.".format(symbol),
190 unique_headers, maximum_suggested_headers)
191 inserted_header_infos = [
192 header for header in header_infos if header["Header"] == selected]
193 include_fixer_context["HeaderInfos"] = inserted_header_infos
Haojian Wufff3ad62016-07-18 10:04:45 +0000194
Haojian Wuc99f7282016-08-09 08:26:19 +0000195 InsertHeaderToVimBuffer(include_fixer_context, text)
Haojian Wufff3ad62016-07-18 10:04:45 +0000196 print "Added #include {0} for {1}.".format(selected, symbol)
Eric Liuf832eb72016-06-07 12:21:43 +0000197 except Exception as error:
198 print >> sys.stderr, error.message
199 return
Haojian Wu11e9bd22016-05-31 09:31:51 +0000200
Eric Liuc7f3b102016-05-18 14:10:16 +0000201
202if __name__ == '__main__':
203 main()