blob: 23154aaa52e7da4ba3d28e033a61437d1a9eb047 [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
21import sys
22import vim
23
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
31def main():
32 parser = argparse.ArgumentParser(
33 description='Vim integration for clang-include-fixer')
34 parser.add_argument('-db', default='yaml',
35 help='clang-include-fixer input format.')
36 parser.add_argument('-input', default='',
37 help='String to initialize the database.')
38 args = parser.parse_args()
39
40 # Get the current text.
41 buf = vim.current.buffer
42 text = '\n'.join(buf)
43
44 # Call clang-include-fixer.
45 command = [binary, "-stdin", "-db="+args.db, "-input="+args.input,
46 vim.current.buffer.name]
47 p = subprocess.Popen(command,
48 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
49 stdin=subprocess.PIPE)
50 stdout, stderr = p.communicate(input=text)
51
52 # If successful, replace buffer contents.
53 if stderr:
54 print stderr
55
56 if stdout:
57 lines = stdout.splitlines()
Eric Liu702cfd12016-05-19 08:21:09 +000058 sequence = difflib.SequenceMatcher(None, vim.current.buffer, lines)
59 for op in reversed(sequence.get_opcodes()):
60 if op[0] is not 'equal':
61 vim.current.buffer[op[1]:op[2]] = lines[op[3]:op[4]]
Eric Liuc7f3b102016-05-18 14:10:16 +000062
63if __name__ == '__main__':
64 main()