Daniel Jasper | 7c4a9a0 | 2013-03-20 09:53:23 +0000 | [diff] [blame^] | 1 | # This file is a minimal clang-format vim-integration. To install: |
| 2 | # - Change 'binary' if clang-format is not on the path (see below). |
| 3 | # - Add to your .vimrc: |
| 4 | # |
| 5 | # map <C-I> :pyf <path-to-this-file>/clang-format.py<CR> |
| 6 | # imap <C-I> <ESC>:pyf <path-to-this-file>/clang-format.py<CR>i |
| 7 | # |
| 8 | # The first line enables clang-format for NORMAL and VISUAL mode, the second |
| 9 | # line adds support for INSERT mode. Change "C-I" to another binding if you |
| 10 | # need clang-format on a different key (C-I stands for Ctrl+i). |
| 11 | # |
| 12 | # With this integration you can press the bound key and clang-format will |
| 13 | # format the current line in NORMAL and INSERT mode or the selected region in |
| 14 | # VISUAL mode. The line or region is extended to the next bigger syntactic |
| 15 | # entity. |
| 16 | # |
| 17 | # It operates on the current, potentially unsaved buffer and does not create |
| 18 | # or save any files. To revert a formatting, just undo. |
| 19 | |
| 20 | import vim |
| 21 | import subprocess |
| 22 | |
| 23 | # Change this to the full path if clang-format is not on the path. |
| 24 | binary = 'clang-format' |
| 25 | |
| 26 | # Get the current text. |
| 27 | buf = vim.current.buffer |
| 28 | text = "\n".join(buf) |
| 29 | |
| 30 | # Determine range to format. |
| 31 | offset = int(vim.eval('line2byte(' + |
| 32 | str(vim.current.range.start + 1) + ')')) - 1 |
| 33 | length = int(vim.eval('line2byte(' + |
| 34 | str(vim.current.range.end + 2) + ')')) - offset - 2 |
| 35 | |
| 36 | # Call formatter. |
| 37 | p = subprocess.Popen([binary, '-offset', str(offset), '-length', str(length)], |
| 38 | stdout=subprocess.PIPE, stderr=subprocess.PIPE, |
| 39 | stdin=subprocess.PIPE) |
| 40 | stdout, stderr = p.communicate(input=text) |
| 41 | |
| 42 | # If successful, replace buffer contents. |
| 43 | if stderr: |
| 44 | message = stderr.splitlines()[0] |
| 45 | parts = message.split(' ', 2) |
| 46 | if len(parts) > 2: |
| 47 | message = parts[2] |
| 48 | print 'Formatting failed: %s (total %d warnings, %d errors)' % ( |
| 49 | message, stderr.count('warning:'), stderr.count('error:')) |
| 50 | |
| 51 | if not stdout: |
| 52 | print ('No output from clang-format (crashed?).\n' + |
| 53 | 'Please report to bugs.llvm.org.') |
| 54 | elif stdout != text: |
| 55 | lines = stdout.split('\n') |
| 56 | for i in range(min(len(buf), len(lines))): |
| 57 | buf[i] = lines[i] |
| 58 | for line in lines[len(buf):]: |
| 59 | buf.append(line) |
| 60 | del buf[len(lines):] |