blob: dab09ba8ef1b92ecb9f8f65e2900059b6acb078d [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
Haojian Wu11e9bd22016-05-31 09:31:51 +000031maximum_suggested_headers=3
32if 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
37
Eric Liuf832eb72016-06-07 12:21:43 +000038def GetUserSelection(message, headers, maximum_suggested_headers):
39 eval_message = message + '\n'
40 for idx, header in enumerate(headers[0:maximum_suggested_headers]):
41 eval_message += "({0}). {1}\n".format(idx+1, header)
42 eval_message += "Enter (q) to quit;"
43 if maximum_suggested_headers < len(headers):
44 eval_message += " (a) to show all candidates.";
45 eval_message += "\nSelect (default 1): "
46 res = vim.eval("input('{0}')".format(eval_message))
47 if res == '':
48 # choose the top ranked header by default
49 idx = 1
50 elif res == 'q':
51 raise Exception(' Insertion cancelled...')
52 elif res == 'a' and maximum_suggested_headers < len(headers):
53 return GetUserSelection(message, headers, len(headers))
54 else:
55 try:
56 idx = int(res)
57 if idx <= 0 or idx > len(headers):
58 raise Exception()
59 except Exception:
60 raise Exception(' ERROR: Invalid option "{0}"...Abort!'.format(res))
61 return headers[idx-1]
Haojian Wu11e9bd22016-05-31 09:31:51 +000062
63def execute(command, text):
64 p = subprocess.Popen(command,
65 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
66 stdin=subprocess.PIPE)
67 return p.communicate(input=text)
68
69
70def InsertHeaderToVimBuffer(header, text):
Haojian Wu17a54e32016-06-01 11:43:10 +000071 command = [binary, "-stdin", "-insert-header="+json.dumps(header),
Haojian Wu11e9bd22016-05-31 09:31:51 +000072 vim.current.buffer.name]
73 stdout, stderr = execute(command, text)
74 if stdout:
75 lines = stdout.splitlines()
76 sequence = difflib.SequenceMatcher(None, vim.current.buffer, lines)
77 for op in reversed(sequence.get_opcodes()):
78 if op[0] is not 'equal':
79 vim.current.buffer[op[1]:op[2]] = lines[op[3]:op[4]]
80
81
Eric Liuc7f3b102016-05-18 14:10:16 +000082def main():
83 parser = argparse.ArgumentParser(
84 description='Vim integration for clang-include-fixer')
85 parser.add_argument('-db', default='yaml',
86 help='clang-include-fixer input format.')
87 parser.add_argument('-input', default='',
88 help='String to initialize the database.')
89 args = parser.parse_args()
90
91 # Get the current text.
92 buf = vim.current.buffer
93 text = '\n'.join(buf)
94
Haojian Wu11e9bd22016-05-31 09:31:51 +000095 # Run command to get all headers.
Benjamin Kramer8f961aa2016-05-31 11:28:34 +000096 command = [binary, "-stdin", "-output-headers", "-db="+args.db,
97 "-input="+args.input, vim.current.buffer.name]
Haojian Wu11e9bd22016-05-31 09:31:51 +000098 stdout, stderr = execute(command, text)
Haojian Wu17a54e32016-06-01 11:43:10 +000099 if stderr:
100 print >> sys.stderr, "Error while running clang-include-fixer: " + stderr
101 return
102
103 include_fixer_context = json.loads(stdout)
104 symbol = include_fixer_context["SymbolIdentifier"]
105 headers = include_fixer_context["Headers"]
106
107 if not symbol:
108 print "The file is fine, no need to add a header.\n"
Eric Liuf832eb72016-06-07 12:21:43 +0000109 return
Haojian Wu17a54e32016-06-01 11:43:10 +0000110
111 if not headers:
112 print "Couldn't find a header for {0}.\n".format(symbol)
Haojian Wu11e9bd22016-05-31 09:31:51 +0000113 return
Eric Liuc7f3b102016-05-18 14:10:16 +0000114
Haojian Wu11e9bd22016-05-31 09:31:51 +0000115 # The first line is the symbol name.
Haojian Wu11e9bd22016-05-31 09:31:51 +0000116 # If there is only one suggested header, insert it directly.
Haojian Wu17a54e32016-06-01 11:43:10 +0000117 if len(headers) == 1 or maximum_suggested_headers == 1:
118 InsertHeaderToVimBuffer({"SymbolIdentifier": symbol,
119 "Headers":[headers[0]]}, text)
120 print "Added #include {0} for {1}.\n".format(headers[0], symbol)
Haojian Wu11e9bd22016-05-31 09:31:51 +0000121 return
Eric Liuc7f3b102016-05-18 14:10:16 +0000122
Eric Liuf832eb72016-06-07 12:21:43 +0000123 try:
124 selected = GetUserSelection("choose a header file for {0}.".format(symbol),
125 headers, maximum_suggested_headers)
126 # Insert a selected header.
127 InsertHeaderToVimBuffer({"SymbolIdentifier": symbol,
128 "Headers":[selected]}, text)
129 print "Added #include {0} for {1}.\n".format(selected, symbol)
130 except Exception as error:
131 print >> sys.stderr, error.message
132 return
Haojian Wu11e9bd22016-05-31 09:31:51 +0000133
Eric Liuc7f3b102016-05-18 14:10:16 +0000134
135if __name__ == '__main__':
136 main()