Eric Liu | c7f3b10 | 2016-05-18 14:10:16 +0000 | [diff] [blame] | 1 | # 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 | |
| 18 | import argparse |
Eric Liu | 702cfd1 | 2016-05-19 08:21:09 +0000 | [diff] [blame^] | 19 | import difflib |
Eric Liu | c7f3b10 | 2016-05-18 14:10:16 +0000 | [diff] [blame] | 20 | import subprocess |
| 21 | import sys |
| 22 | import 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. |
| 27 | binary = 'clang-include-fixer' |
| 28 | if vim.eval('exists("g:clang_include_fixer_path")') == "1": |
| 29 | binary = vim.eval('g:clang_include_fixer_path') |
| 30 | |
| 31 | def 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 Liu | 702cfd1 | 2016-05-19 08:21:09 +0000 | [diff] [blame^] | 58 | 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 Liu | c7f3b10 | 2016-05-18 14:10:16 +0000 | [diff] [blame] | 62 | |
| 63 | if __name__ == '__main__': |
| 64 | main() |