clang-format: Add capability to format the diff on save in vim.
With this patch, one can configure a BufWrite hook that will make the
clang-format integration compute a diff of the current buffer with the file
that's on disk and format all changed lines. This should create a
zero-overhead auto-format solution that doesn't require the file to
already be clang-format clean to avoid spurious diffs.
Review: https://reviews.llvm.org/D32429
git-svn-id: svn://svn.chromium.org/llvm-project/cfe/trunk/tools/clang-format@305665 0b72dbe1-c17f-4bc7-b9db-2b4152be0356
diff --git a/clang-format.py b/clang-format.py
index ae8a6eb..2412566 100644
--- a/clang-format.py
+++ b/clang-format.py
@@ -63,8 +63,19 @@
# Determine range to format.
if vim.eval('exists("l:lines")') == '1':
lines = vim.eval('l:lines')
+ elif vim.eval('exists("l:formatdiff")') == '1':
+ with open(vim.current.buffer.name, 'r') as f:
+ ondisk = f.read().splitlines();
+ sequence = difflib.SequenceMatcher(None, ondisk, vim.current.buffer)
+ lines = []
+ for op in reversed(sequence.get_opcodes()):
+ if op[0] not in ['equal', 'delete']:
+ lines += ['-lines', '%s:%s' % (op[3] + 1, op[4])]
+ if lines == []:
+ return
else:
- lines = '%s:%s' % (vim.current.range.start + 1, vim.current.range.end + 1)
+ lines = ['-lines', '%s:%s' % (vim.current.range.start + 1,
+ vim.current.range.end + 1)]
# Determine the cursor position.
cursor = int(vim.eval('line2byte(line("."))+col(".")')) - 2
@@ -82,7 +93,7 @@
# Call formatter.
command = [binary, '-style', style, '-cursor', str(cursor)]
if lines != 'all':
- command.extend(['-lines', lines])
+ command += lines
if fallback_style:
command.extend(['-fallback-style', fallback_style])
if vim.current.buffer.name: