summaryrefslogtreecommitdiffstats
path: root/clang/tools/clang-format/clang-format.py
diff options
context:
space:
mode:
authorDaniel Jasper <djasper@google.com>2013-05-21 12:21:39 +0000
committerDaniel Jasper <djasper@google.com>2013-05-21 12:21:39 +0000
commit2a250b8b49e70f53b185749a94956d54d941ef2d (patch)
treedf02c858d099e0982459b90d2f0d9715ee1b05b1 /clang/tools/clang-format/clang-format.py
parentc787d42f40a6e4a8ee5c2d1a910b393b7191fdfa (diff)
downloadbcm5719-llvm-2a250b8b49e70f53b185749a94956d54d941ef2d.tar.gz
bcm5719-llvm-2a250b8b49e70f53b185749a94956d54d941ef2d.zip
Let clang-format move the cursor appropriately.
With this patch, clang-format will try to keep the cursor at the original code position in editor integrations (implemented for emacs and vim). This means, after formatting, clang-format will try to keep the cursor on the same character of the same token. llvm-svn: 182373
Diffstat (limited to 'clang/tools/clang-format/clang-format.py')
-rw-r--r--clang/tools/clang-format/clang-format.py24
1 files changed, 15 insertions, 9 deletions
diff --git a/clang/tools/clang-format/clang-format.py b/clang/tools/clang-format/clang-format.py
index d90c62a5bf6..bc47fcbb7d2 100644
--- a/clang/tools/clang-format/clang-format.py
+++ b/clang/tools/clang-format/clang-format.py
@@ -17,8 +17,9 @@
# It operates on the current, potentially unsaved buffer and does not create
# or save any files. To revert a formatting, just undo.
-import vim
+import json
import subprocess
+import vim
# Change this to the full path if clang-format is not on the path.
binary = 'clang-format'
@@ -29,9 +30,10 @@ style = 'LLVM'
# Get the current text.
buf = vim.current.buffer
-text = "\n".join(buf)
+text = '\n'.join(buf)
# Determine range to format.
+cursor = int(vim.eval('line2byte(line("."))+col(".")')) - 2
offset = int(vim.eval('line2byte(' +
str(vim.current.range.start + 1) + ')')) - 1
length = int(vim.eval('line2byte(' +
@@ -39,7 +41,7 @@ length = int(vim.eval('line2byte(' +
# Call formatter.
p = subprocess.Popen([binary, '-offset', str(offset), '-length', str(length),
- '-style', style],
+ '-style', style, '-cursor', str(cursor)],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
stdout, stderr = p.communicate(input=text)
@@ -56,10 +58,14 @@ if stderr:
if not stdout:
print ('No output from clang-format (crashed?).\n' +
'Please report to bugs.llvm.org.')
-elif stdout != text:
+else:
lines = stdout.split('\n')
- for i in range(min(len(buf), len(lines))):
- buf[i] = lines[i]
- for line in lines[len(buf):]:
- buf.append(line)
- del buf[len(lines):]
+ output = json.loads(lines[0])
+ lines = lines[1:]
+ if '\n'.join(lines) != text:
+ for i in range(min(len(buf), len(lines))):
+ buf[i] = lines[i]
+ for line in lines[len(buf):]:
+ buf.append(line)
+ del buf[len(lines):]
+ vim.command('goto %d' % (output['Cursor'] + 1))
OpenPOWER on IntegriCloud