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.

git-svn-id: https://llvm.org/svn/llvm-project/cfe/trunk@182373 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/tools/clang-format/ClangFormat.cpp b/tools/clang-format/ClangFormat.cpp
index fccd6bf..340ef55 100644
--- a/tools/clang-format/ClangFormat.cpp
+++ b/tools/clang-format/ClangFormat.cpp
@@ -77,6 +77,11 @@
                cl::desc("Dump configuration options to stdout and exit.\n"
                         "Can be used with -style option."),
                cl::cat(ClangFormatCategory));
+static cl::opt<unsigned>
+    Cursor("cursor",
+           cl::desc("The position of the cursor when invoking clang-format from"
+                    " an editor integration"),
+           cl::init(0), cl::cat(ClangFormatCategory));
 
 static cl::list<std::string> FileNames(cl::Positional, cl::desc("[<file> ...]"),
                                        cl::cat(ClangFormatCategory));
@@ -221,6 +226,9 @@
       Rewrite.getEditBuffer(ID).write(FileStream);
       FileStream.flush();
     } else {
+      if (Cursor != 0)
+        outs() << "{ \"Cursor\": " << tooling::shiftedCodePosition(
+                                          Replaces, Cursor) << " }\n";
       Rewrite.getEditBuffer(ID).write(outs());
     }
   }
diff --git a/tools/clang-format/clang-format.el b/tools/clang-format/clang-format.el
index 57475ac..af69118 100644
--- a/tools/clang-format/clang-format.el
+++ b/tools/clang-format/clang-format.el
@@ -9,6 +9,8 @@
 ;; Depending on your configuration and coding style, you might need to modify
 ;; 'style' in clang-format, below.
 
+(require 'json)
+
 ;; *Location of the clang-format binary. If it is on your PATH, a full path name
 ;; need not be specified.
 (defvar clang-format-binary "clang-format")
@@ -38,8 +40,14 @@
         (call-process-region (point-min) (point-max) clang-format-binary t t nil
                              "-offset" (number-to-string (1- begin))
                              "-length" (number-to-string (- end begin))
+                             "-cursor" (number-to-string (point))
                              "-style" style)
-      (goto-char orig-point)
-      (dotimes (index (length orig-windows))
-        (set-window-start (nth index orig-windows)
-                          (nth index orig-window-starts))))))
+      (goto-char (point-min))
+      (let ((json-output (json-read-from-string
+                           (buffer-substring-no-properties
+                             (point-min) (line-beginning-position 2)))))
+        (delete-region (point-min) (line-beginning-position 2))
+        (goto-char (cdr (assoc 'Cursor json-output)))
+        (dotimes (index (length orig-windows))
+          (set-window-start (nth index orig-windows)
+                            (nth index orig-window-starts)))))))
diff --git a/tools/clang-format/clang-format.py b/tools/clang-format/clang-format.py
index d90c62a..bc47fcb 100644
--- a/tools/clang-format/clang-format.py
+++ b/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 @@
 
 # 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 @@
 
 # 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 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))