blob: 49060ee124162e25c6031bc11de296198caf2fce [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
Benjamin Kramerfdaed4c2016-07-04 16:47:17 +000043
Eric Liuf832eb72016-06-07 12:21:43 +000044def GetUserSelection(message, headers, maximum_suggested_headers):
45 eval_message = message + '\n'
46 for idx, header in enumerate(headers[0:maximum_suggested_headers]):
Benjamin Kramerfdaed4c2016-07-04 16:47:17 +000047 eval_message += "({0}). {1}\n".format(idx + 1, header)
Eric Liuf832eb72016-06-07 12:21:43 +000048 eval_message += "Enter (q) to quit;"
49 if maximum_suggested_headers < len(headers):
Eric Liuf4a57102016-06-10 12:09:33 +000050 eval_message += " (m) to show {0} more candidates.".format(
51 min(increment_num, len(headers) - maximum_suggested_headers))
52
Eric Liuf832eb72016-06-07 12:21:43 +000053 eval_message += "\nSelect (default 1): "
54 res = vim.eval("input('{0}')".format(eval_message))
55 if res == '':
56 # choose the top ranked header by default
57 idx = 1
58 elif res == 'q':
59 raise Exception(' Insertion cancelled...')
Eric Liuf4a57102016-06-10 12:09:33 +000060 elif res == 'm':
61 return GetUserSelection(message,
62 headers, maximum_suggested_headers + increment_num)
Eric Liuf832eb72016-06-07 12:21:43 +000063 else:
64 try:
65 idx = int(res)
66 if idx <= 0 or idx > len(headers):
67 raise Exception()
68 except Exception:
Eric Liuf4a57102016-06-10 12:09:33 +000069 # Show a new prompt on invalid option instead of aborting so that users
70 # don't need to wait for another include-fixer run.
71 print >> sys.stderr, "Invalid option:", res
72 return GetUserSelection(message, headers, maximum_suggested_headers)
Benjamin Kramerfdaed4c2016-07-04 16:47:17 +000073 return headers[idx - 1]
74
Haojian Wu11e9bd22016-05-31 09:31:51 +000075
76def execute(command, text):
77 p = subprocess.Popen(command,
78 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
79 stdin=subprocess.PIPE)
80 return p.communicate(input=text)
81
82
83def InsertHeaderToVimBuffer(header, text):
Benjamin Kramerfdaed4c2016-07-04 16:47:17 +000084 command = [binary, "-stdin", "-insert-header=" + json.dumps(header),
Haojian Wu11e9bd22016-05-31 09:31:51 +000085 vim.current.buffer.name]
86 stdout, stderr = execute(command, text)
87 if stdout:
88 lines = stdout.splitlines()
89 sequence = difflib.SequenceMatcher(None, vim.current.buffer, lines)
90 for op in reversed(sequence.get_opcodes()):
91 if op[0] is not 'equal':
92 vim.current.buffer[op[1]:op[2]] = lines[op[3]:op[4]]
93
94
Eric Liuc7f3b102016-05-18 14:10:16 +000095def main():
96 parser = argparse.ArgumentParser(
97 description='Vim integration for clang-include-fixer')
98 parser.add_argument('-db', default='yaml',
99 help='clang-include-fixer input format.')
100 parser.add_argument('-input', default='',
101 help='String to initialize the database.')
102 args = parser.parse_args()
103
104 # Get the current text.
105 buf = vim.current.buffer
106 text = '\n'.join(buf)
107
Haojian Wu11e9bd22016-05-31 09:31:51 +0000108 # Run command to get all headers.
Benjamin Kramerfdaed4c2016-07-04 16:47:17 +0000109 command = [binary, "-stdin", "-output-headers", "-db=" + args.db,
110 "-input=" + args.input, vim.current.buffer.name]
Haojian Wu11e9bd22016-05-31 09:31:51 +0000111 stdout, stderr = execute(command, text)
Haojian Wu17a54e32016-06-01 11:43:10 +0000112 if stderr:
113 print >> sys.stderr, "Error while running clang-include-fixer: " + stderr
114 return
115
116 include_fixer_context = json.loads(stdout)
117 symbol = include_fixer_context["SymbolIdentifier"]
118 headers = include_fixer_context["Headers"]
119
120 if not symbol:
121 print "The file is fine, no need to add a header.\n"
Eric Liuf832eb72016-06-07 12:21:43 +0000122 return
Haojian Wu17a54e32016-06-01 11:43:10 +0000123
124 if not headers:
125 print "Couldn't find a header for {0}.\n".format(symbol)
Haojian Wu11e9bd22016-05-31 09:31:51 +0000126 return
Eric Liuc7f3b102016-05-18 14:10:16 +0000127
Haojian Wu11e9bd22016-05-31 09:31:51 +0000128 # The first line is the symbol name.
Haojian Wu11e9bd22016-05-31 09:31:51 +0000129 # If there is only one suggested header, insert it directly.
Haojian Wu17a54e32016-06-01 11:43:10 +0000130 if len(headers) == 1 or maximum_suggested_headers == 1:
131 InsertHeaderToVimBuffer({"SymbolIdentifier": symbol,
Benjamin Kramerfdaed4c2016-07-04 16:47:17 +0000132 "Headers": [headers[0]]}, text)
Haojian Wu17a54e32016-06-01 11:43:10 +0000133 print "Added #include {0} for {1}.\n".format(headers[0], symbol)
Haojian Wu11e9bd22016-05-31 09:31:51 +0000134 return
Eric Liuc7f3b102016-05-18 14:10:16 +0000135
Eric Liuf832eb72016-06-07 12:21:43 +0000136 try:
137 selected = GetUserSelection("choose a header file for {0}.".format(symbol),
138 headers, maximum_suggested_headers)
139 # Insert a selected header.
140 InsertHeaderToVimBuffer({"SymbolIdentifier": symbol,
Benjamin Kramerfdaed4c2016-07-04 16:47:17 +0000141 "Headers": [selected]}, text)
Eric Liuf832eb72016-06-07 12:21:43 +0000142 print "Added #include {0} for {1}.\n".format(selected, symbol)
143 except Exception as error:
144 print >> sys.stderr, error.message
145 return
Haojian Wu11e9bd22016-05-31 09:31:51 +0000146
Eric Liuc7f3b102016-05-18 14:10:16 +0000147
148if __name__ == '__main__':
149 main()