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 |
| 19 | import subprocess |
| 20 | import sys |
| 21 | import vim |
| 22 | |
| 23 | # set g:clang_include_fixer_path to the path to clang-include-fixer if it is not |
| 24 | # on the path. |
| 25 | # Change this to the full path if clang-include-fixer is not on the path. |
| 26 | binary = 'clang-include-fixer' |
| 27 | if vim.eval('exists("g:clang_include_fixer_path")') == "1": |
| 28 | binary = vim.eval('g:clang_include_fixer_path') |
| 29 | |
| 30 | def main(): |
| 31 | parser = argparse.ArgumentParser( |
| 32 | description='Vim integration for clang-include-fixer') |
| 33 | parser.add_argument('-db', default='yaml', |
| 34 | help='clang-include-fixer input format.') |
| 35 | parser.add_argument('-input', default='', |
| 36 | help='String to initialize the database.') |
| 37 | args = parser.parse_args() |
| 38 | |
| 39 | # Get the current text. |
| 40 | buf = vim.current.buffer |
| 41 | text = '\n'.join(buf) |
| 42 | |
| 43 | # Call clang-include-fixer. |
| 44 | command = [binary, "-stdin", "-db="+args.db, "-input="+args.input, |
| 45 | vim.current.buffer.name] |
| 46 | p = subprocess.Popen(command, |
| 47 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 48 | stdin=subprocess.PIPE) |
| 49 | stdout, stderr = p.communicate(input=text) |
| 50 | |
| 51 | # If successful, replace buffer contents. |
| 52 | if stderr: |
| 53 | print stderr |
| 54 | |
| 55 | if stdout: |
| 56 | lines = stdout.splitlines() |
| 57 | for line in lines: |
| 58 | line_num, text = line.split(",") |
| 59 | # clang-include-fixer provides 1-based line number |
| 60 | line_num = int(line_num) - 1 |
| 61 | print 'Inserting "{0}" at line {1}'.format(text, line_num) |
| 62 | vim.current.buffer[line_num:line_num] = [text] |
| 63 | |
| 64 | if __name__ == '__main__': |
| 65 | main() |