blob: de922574070320fb47d202c4a84ccdf430dacb87 [file] [log] [blame]
Daniel Jasper7c4a9a02013-03-20 09:53:23 +00001# 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
20import vim
21import subprocess
22
23# Change this to the full path if clang-format is not on the path.
24binary = 'clang-format'
25
26# Get the current text.
27buf = vim.current.buffer
28text = "\n".join(buf)
29
30# Determine range to format.
31offset = int(vim.eval('line2byte(' +
32 str(vim.current.range.start + 1) + ')')) - 1
33length = int(vim.eval('line2byte(' +
34 str(vim.current.range.end + 2) + ')')) - offset - 2
35
36# Call formatter.
37p = subprocess.Popen([binary, '-offset', str(offset), '-length', str(length)],
38 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
39 stdin=subprocess.PIPE)
40stdout, stderr = p.communicate(input=text)
41
42# If successful, replace buffer contents.
43if 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
51if not stdout:
52 print ('No output from clang-format (crashed?).\n' +
53 'Please report to bugs.llvm.org.')
54elif 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):]