blob: d90c62a5bf681872c16b260d1fbe79d8ac2f4c9a [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
Daniel Jasper63911832013-04-09 15:23:04 +000026# Change this to format according to other formatting styles (see
27# clang-format -help)
28style = 'LLVM'
29
Daniel Jasper7c4a9a02013-03-20 09:53:23 +000030# Get the current text.
31buf = vim.current.buffer
32text = "\n".join(buf)
33
34# Determine range to format.
35offset = int(vim.eval('line2byte(' +
36 str(vim.current.range.start + 1) + ')')) - 1
37length = int(vim.eval('line2byte(' +
38 str(vim.current.range.end + 2) + ')')) - offset - 2
39
40# Call formatter.
Daniel Jasper63911832013-04-09 15:23:04 +000041p = subprocess.Popen([binary, '-offset', str(offset), '-length', str(length),
42 '-style', style],
Daniel Jasper7c4a9a02013-03-20 09:53:23 +000043 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
44 stdin=subprocess.PIPE)
45stdout, stderr = p.communicate(input=text)
46
47# If successful, replace buffer contents.
48if stderr:
49 message = stderr.splitlines()[0]
50 parts = message.split(' ', 2)
51 if len(parts) > 2:
52 message = parts[2]
53 print 'Formatting failed: %s (total %d warnings, %d errors)' % (
54 message, stderr.count('warning:'), stderr.count('error:'))
55
56if not stdout:
57 print ('No output from clang-format (crashed?).\n' +
58 'Please report to bugs.llvm.org.')
59elif stdout != text:
60 lines = stdout.split('\n')
61 for i in range(min(len(buf), len(lines))):
62 buf[i] = lines[i]
63 for line in lines[len(buf):]:
64 buf.append(line)
65 del buf[len(lines):]