blob: ff15b8de2946d2b17de6d765e37eeec5776e0a48 [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#
5# map ,cf :pyf path/to/llvm/source/tools/clang/tools/extra/include-fixer/tool/clang-include-fixer.py<cr>
6#
7# This enables clang-include-fixer for NORMAL and VISUAL mode. Change ",cf" to
8# another binding if you need clang-include-fixer on a different key.
9#
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
Eric Liuc7f3b102016-05-18 14:10:16 +000020import subprocess
Eric Liuc7f3b102016-05-18 14:10:16 +000021import vim
Haojian Wu17a54e32016-06-01 11:43:10 +000022import json
Eric Liuc7f3b102016-05-18 14:10:16 +000023
24# set g:clang_include_fixer_path to the path to clang-include-fixer if it is not
25# on the path.
26# Change this to the full path if clang-include-fixer is not on the path.
27binary = 'clang-include-fixer'
28if vim.eval('exists("g:clang_include_fixer_path")') == "1":
29 binary = vim.eval('g:clang_include_fixer_path')
30
Benjamin Kramerfdaed4c2016-07-04 16:47:17 +000031maximum_suggested_headers = 3
Haojian Wu11e9bd22016-05-31 09:31:51 +000032if vim.eval('exists("g:clang_include_fixer_maximum_suggested_headers")') == "1":
33 maximum_suggested_headers = max(
34 1,
35 vim.eval('g:clang_include_fixer_maximum_suggested_headers'))
36
Benjamin Kramerfdaed4c2016-07-04 16:47:17 +000037increment_num = 5
Eric Liuf4a57102016-06-10 12:09:33 +000038if vim.eval('exists("g:clang_include_fixer_increment_num")') == "1":
39 increment_num = max(
40 1,
41 vim.eval('g:clang_include_fixer_increment_num'))
Haojian Wu11e9bd22016-05-31 09:31:51 +000042
Haojian Wufff3ad62016-07-18 10:04:45 +000043jump_to_include = False
44if vim.eval('exists("g:clang_include_fixer_jump_to_include")') == "1":
45 jump_to_include = vim.eval('g:clang_include_fixer_jump_to_include') != "0"
46
Benjamin Kramerfdaed4c2016-07-04 16:47:17 +000047
Eric Liuf832eb72016-06-07 12:21:43 +000048def GetUserSelection(message, headers, maximum_suggested_headers):
49 eval_message = message + '\n'
50 for idx, header in enumerate(headers[0:maximum_suggested_headers]):
Benjamin Kramerfdaed4c2016-07-04 16:47:17 +000051 eval_message += "({0}). {1}\n".format(idx + 1, header)
Eric Liuf832eb72016-06-07 12:21:43 +000052 eval_message += "Enter (q) to quit;"
53 if maximum_suggested_headers < len(headers):
Eric Liuf4a57102016-06-10 12:09:33 +000054 eval_message += " (m) to show {0} more candidates.".format(
55 min(increment_num, len(headers) - maximum_suggested_headers))
56
Eric Liuf832eb72016-06-07 12:21:43 +000057 eval_message += "\nSelect (default 1): "
58 res = vim.eval("input('{0}')".format(eval_message))
59 if res == '':
60 # choose the top ranked header by default
61 idx = 1
62 elif res == 'q':
63 raise Exception(' Insertion cancelled...')
Eric Liuf4a57102016-06-10 12:09:33 +000064 elif res == 'm':
65 return GetUserSelection(message,
66 headers, maximum_suggested_headers + increment_num)
Eric Liuf832eb72016-06-07 12:21:43 +000067 else:
68 try:
69 idx = int(res)
70 if idx <= 0 or idx > len(headers):
71 raise Exception()
72 except Exception:
Eric Liuf4a57102016-06-10 12:09:33 +000073 # Show a new prompt on invalid option instead of aborting so that users
74 # don't need to wait for another include-fixer run.
75 print >> sys.stderr, "Invalid option:", res
76 return GetUserSelection(message, headers, maximum_suggested_headers)
Benjamin Kramerfdaed4c2016-07-04 16:47:17 +000077 return headers[idx - 1]
78
Haojian Wu11e9bd22016-05-31 09:31:51 +000079
80def execute(command, text):
81 p = subprocess.Popen(command,
82 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
83 stdin=subprocess.PIPE)
84 return p.communicate(input=text)
85
86
87def InsertHeaderToVimBuffer(header, text):
Benjamin Kramerfdaed4c2016-07-04 16:47:17 +000088 command = [binary, "-stdin", "-insert-header=" + json.dumps(header),
Haojian Wu11e9bd22016-05-31 09:31:51 +000089 vim.current.buffer.name]
90 stdout, stderr = execute(command, text)
Haojian Wufff3ad62016-07-18 10:04:45 +000091 if stderr:
92 raise Exception(stderr)
Haojian Wu11e9bd22016-05-31 09:31:51 +000093 if stdout:
94 lines = stdout.splitlines()
95 sequence = difflib.SequenceMatcher(None, vim.current.buffer, lines)
Haojian Wufff3ad62016-07-18 10:04:45 +000096 line_num = None
Haojian Wu11e9bd22016-05-31 09:31:51 +000097 for op in reversed(sequence.get_opcodes()):
Haojian Wufff3ad62016-07-18 10:04:45 +000098 if op[0] != 'equal':
Haojian Wu11e9bd22016-05-31 09:31:51 +000099 vim.current.buffer[op[1]:op[2]] = lines[op[3]:op[4]]
Haojian Wufff3ad62016-07-18 10:04:45 +0000100 if op[0] == 'insert':
101 # line_num in vim is 1-based.
102 line_num = op[1] + 1
103
104 if jump_to_include and line_num:
105 vim.current.window.cursor = (line_num, 0)
Haojian Wu11e9bd22016-05-31 09:31:51 +0000106
107
Eric Liuc7f3b102016-05-18 14:10:16 +0000108def main():
109 parser = argparse.ArgumentParser(
110 description='Vim integration for clang-include-fixer')
111 parser.add_argument('-db', default='yaml',
112 help='clang-include-fixer input format.')
113 parser.add_argument('-input', default='',
114 help='String to initialize the database.')
115 args = parser.parse_args()
116
117 # Get the current text.
118 buf = vim.current.buffer
119 text = '\n'.join(buf)
120
Haojian Wu11e9bd22016-05-31 09:31:51 +0000121 # Run command to get all headers.
Benjamin Kramerfdaed4c2016-07-04 16:47:17 +0000122 command = [binary, "-stdin", "-output-headers", "-db=" + args.db,
123 "-input=" + args.input, vim.current.buffer.name]
Haojian Wu11e9bd22016-05-31 09:31:51 +0000124 stdout, stderr = execute(command, text)
Haojian Wu17a54e32016-06-01 11:43:10 +0000125 if stderr:
126 print >> sys.stderr, "Error while running clang-include-fixer: " + stderr
127 return
128
129 include_fixer_context = json.loads(stdout)
130 symbol = include_fixer_context["SymbolIdentifier"]
Haojian Wu68c34a02016-07-13 16:43:54 +0000131 # The header_infos is already sorted by include-fixer.
132 header_infos = include_fixer_context["HeaderInfos"]
133 # Deduplicate headers while keeping the order, so that the same header would
134 # not be suggested twice.
135 unique_headers = []
136 seen = set()
137 for header_info in header_infos:
138 header = header_info["Header"]
139 if header not in seen:
140 seen.add(header)
141 unique_headers.append(header)
Haojian Wu17a54e32016-06-01 11:43:10 +0000142
143 if not symbol:
Haojian Wufff3ad62016-07-18 10:04:45 +0000144 print "The file is fine, no need to add a header."
Eric Liuf832eb72016-06-07 12:21:43 +0000145 return
Haojian Wu17a54e32016-06-01 11:43:10 +0000146
Haojian Wu68c34a02016-07-13 16:43:54 +0000147 if not unique_headers:
Haojian Wufff3ad62016-07-18 10:04:45 +0000148 print "Couldn't find a header for {0}.".format(symbol)
Haojian Wu11e9bd22016-05-31 09:31:51 +0000149 return
Eric Liuc7f3b102016-05-18 14:10:16 +0000150
Eric Liuf832eb72016-06-07 12:21:43 +0000151 try:
Haojian Wufff3ad62016-07-18 10:04:45 +0000152 # If there is only one suggested header, insert it directly.
153 if len(unique_headers) == 1 or maximum_suggested_headers == 1:
154 InsertHeaderToVimBuffer({"SymbolIdentifier": symbol,
155 "Range": include_fixer_context["Range"],
156 "HeaderInfos": header_infos}, text)
157 print "Added #include {0} for {1}.".format(unique_headers[0], symbol)
158 return
159
Eric Liuf832eb72016-06-07 12:21:43 +0000160 selected = GetUserSelection("choose a header file for {0}.".format(symbol),
Haojian Wu68c34a02016-07-13 16:43:54 +0000161 unique_headers, maximum_suggested_headers)
162 selected_header_infos = [
163 header for header in header_infos if header["Header"] == selected]
164
Eric Liuf832eb72016-06-07 12:21:43 +0000165 # Insert a selected header.
166 InsertHeaderToVimBuffer({"SymbolIdentifier": symbol,
Haojian Wu68c34a02016-07-13 16:43:54 +0000167 "Range": include_fixer_context["Range"],
168 "HeaderInfos": selected_header_infos}, text)
Haojian Wufff3ad62016-07-18 10:04:45 +0000169 print "Added #include {0} for {1}.".format(selected, symbol)
Eric Liuf832eb72016-06-07 12:21:43 +0000170 except Exception as error:
171 print >> sys.stderr, error.message
172 return
Haojian Wu11e9bd22016-05-31 09:31:51 +0000173
Eric Liuc7f3b102016-05-18 14:10:16 +0000174
175if __name__ == '__main__':
176 main()