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:
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
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).
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
17 # It operates on the current, potentially unsaved buffer and does not create
18 # or save any files. To revert a formatting, just undo.
26 # Change this to the full path if clang-format is not on the path.
27 binary = 'clang-format'
29 # Change this to format according to other formatting styles. See the output of
30 # 'clang-format --help' for a list of supported styles. The default looks for
31 # a '.clang-format' or '_clang-format' file to indicate the style that should be
35 # Get the current text.
36 buf = vim.current.buffer
39 # Determine range to format.
40 cursor = int(vim.eval('line2byte(line("."))+col(".")')) - 2
41 lines = '%s:%s' % (vim.current.range.start + 1, vim.current.range.end + 1)
43 # Avoid flashing an ugly, ugly cmd prompt on Windows when invoking clang-format.
45 if sys.platform.startswith('win32'):
46 startupinfo = subprocess.STARTUPINFO()
47 startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
48 startupinfo.wShowWindow = subprocess.SW_HIDE
51 command = [binary, '-lines', lines, '-style', style, '-cursor', str(cursor)]
52 if vim.current.buffer.name:
53 command.extend(['-assume-filename', vim.current.buffer.name])
54 p = subprocess.Popen(command,
55 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
56 stdin=subprocess.PIPE, startupinfo=startupinfo)
57 stdout, stderr = p.communicate(input=text)
59 # If successful, replace buffer contents.
61 message = stderr.splitlines()[0]
62 parts = message.split(' ', 2)
65 print 'Formatting failed: %s (total %d warnings, %d errors)' % (
66 message, stderr.count('warning:'), stderr.count('error:'))
69 print ('No output from clang-format (crashed?).\n' +
70 'Please report to bugs.llvm.org.')
72 lines = stdout.split('\n')
73 output = json.loads(lines[0])
75 sequence = difflib.SequenceMatcher(None, vim.current.buffer, lines)
76 for op in reversed(sequence.get_opcodes()):
77 if op[0] is not 'equal':
78 vim.current.buffer[op[1]:op[2]] = lines[op[3]:op[4]]
79 vim.command('goto %d' % (output['Cursor'] + 1))