Skip to content

Commit ff7c77f

Browse files
committedAug 31, 2016
[clang-format-vim] Support vim linked against py3
clang-format.py previously only worked in vim compiled against python2. This patch adds the necessary syntax changes to make this work with vim linked against python3, which is now shipped by default for at least Ubuntu16 and Arch. Differential Revision: https://reviews.llvm.org/D23319 Subscribers: cfe-commits llvm-svn: 280240
1 parent 3c1137c commit ff7c77f

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed
 

‎clang/tools/clang-format/clang-format.py

+11-7
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
#
2626
# It operates on the current, potentially unsaved buffer and does not create
2727
# or save any files. To revert a formatting, just undo.
28+
from __future__ import print_function
2829

2930
import difflib
3031
import json
@@ -49,6 +50,7 @@
4950

5051
def main():
5152
# Get the current text.
53+
encoding = vim.eval("&encoding")
5254
buf = vim.current.buffer
5355
text = '\n'.join(buf)
5456

@@ -61,7 +63,7 @@ def main():
6163
# Determine the cursor position.
6264
cursor = int(vim.eval('line2byte(line("."))+col(".")')) - 2
6365
if cursor < 0:
64-
print 'Couldn\'t determine cursor position. Is your file empty?'
66+
print('Couldn\'t determine cursor position. Is your file empty?')
6567
return
6668

6769
# Avoid flashing an ugly, ugly cmd prompt on Windows when invoking clang-format.
@@ -82,25 +84,27 @@ def main():
8284
p = subprocess.Popen(command,
8385
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
8486
stdin=subprocess.PIPE, startupinfo=startupinfo)
85-
stdout, stderr = p.communicate(input=text)
87+
stdout, stderr = p.communicate(input=text.encode(encoding))
8688

8789
# If successful, replace buffer contents.
8890
if stderr:
89-
print stderr
91+
print(stderr)
9092

9193
if not stdout:
92-
print ('No output from clang-format (crashed?).\n' +
93-
'Please report to bugs.llvm.org.')
94+
print(
95+
'No output from clang-format (crashed?).\n'
96+
'Please report to bugs.llvm.org.'
97+
)
9498
else:
95-
lines = stdout.split('\n')
99+
lines = stdout.decode(encoding).split('\n')
96100
output = json.loads(lines[0])
97101
lines = lines[1:]
98102
sequence = difflib.SequenceMatcher(None, vim.current.buffer, lines)
99103
for op in reversed(sequence.get_opcodes()):
100104
if op[0] is not 'equal':
101105
vim.current.buffer[op[1]:op[2]] = lines[op[3]:op[4]]
102106
if output.get('IncompleteFormat'):
103-
print 'clang-format: incomplete (syntax errors)'
107+
print('clang-format: incomplete (syntax errors)')
104108
vim.command('goto %d' % (output['Cursor'] + 1))
105109

106110
main()

0 commit comments

Comments
 (0)