blob: b942cbb47a9037e1ec95a2c544c906c7113a300c [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
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)
Haojian Wu62aee522016-07-21 13:47:09 +0000130 query_symbol_infos = include_fixer_context["QuerySymbolInfos"]
131 if not query_symbol_infos:
132 print "The file is fine, no need to add a header."
133 return
134 symbol = query_symbol_infos[0]["RawIdentifier"]
Haojian Wu68c34a02016-07-13 16:43:54 +0000135 # The header_infos is already sorted by include-fixer.
136 header_infos = include_fixer_context["HeaderInfos"]
137 # Deduplicate headers while keeping the order, so that the same header would
138 # not be suggested twice.
139 unique_headers = []
140 seen = set()
141 for header_info in header_infos:
142 header = header_info["Header"]
143 if header not in seen:
144 seen.add(header)
145 unique_headers.append(header)
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 Wuc99f7282016-08-09 08:26:19 +0000152 inserted_header_infos = header_infos
153 if len(unique_headers) > 1:
154 selected = GetUserSelection(
155 "choose a header file for {0}.".format(symbol),
156 unique_headers, maximum_suggested_headers)
157 inserted_header_infos = [
158 header for header in header_infos if header["Header"] == selected]
159 include_fixer_context["HeaderInfos"] = inserted_header_infos
Haojian Wufff3ad62016-07-18 10:04:45 +0000160
Haojian Wuc99f7282016-08-09 08:26:19 +0000161 InsertHeaderToVimBuffer(include_fixer_context, text)
Haojian Wufff3ad62016-07-18 10:04:45 +0000162 print "Added #include {0} for {1}.".format(selected, symbol)
Eric Liuf832eb72016-06-07 12:21:43 +0000163 except Exception as error:
164 print >> sys.stderr, error.message
165 return
Haojian Wu11e9bd22016-05-31 09:31:51 +0000166
Eric Liuc7f3b102016-05-18 14:10:16 +0000167
168if __name__ == '__main__':
169 main()