Update vim clang-format.py

This commit is contained in:
Kenneth Benzie 2015-11-18 23:18:35 +00:00
parent d56e3fc1df
commit 0b3c2f7a66

View File

@ -2,8 +2,8 @@
# - Change 'binary' if clang-format is not on the path (see below). # - Change 'binary' if clang-format is not on the path (see below).
# - Add to your .vimrc: # - Add to your .vimrc:
# #
# map <C-I> :pyf <path-to-this-file>/clang-format.py<CR> # map <C-I> :pyf <path-to-this-file>/clang-format.py<cr>
# imap <C-I> <ESC>:pyf <path-to-this-file>/clang-format.py<CR>i # imap <C-I> <c-o>:pyf <path-to-this-file>/clang-format.py<cr>
# #
# The first line enables clang-format for NORMAL and VISUAL mode, the second # The first line enables clang-format for NORMAL and VISUAL mode, the second
# line adds support for INSERT mode. Change "C-I" to another binding if you # line adds support for INSERT mode. Change "C-I" to another binding if you
@ -14,6 +14,15 @@
# VISUAL mode. The line or region is extended to the next bigger syntactic # VISUAL mode. The line or region is extended to the next bigger syntactic
# entity. # entity.
# #
# You can also pass in the variable "l:lines" to choose the range for
# formatting. This variable can either contain "<start line>:<end line>" or
# "all" to format the full file. So, to format the full file, write a function
# like:
# :function FormatFile()
# : let l:lines="all"
# : pyf <path-to-this-file>/clang-format.py
# :endfunction
#
# It operates on the current, potentially unsaved buffer and does not create # It operates on the current, potentially unsaved buffer and does not create
# or save any files. To revert a formatting, just undo. # or save any files. To revert a formatting, just undo.
@ -23,57 +32,75 @@ import subprocess
import sys import sys
import vim import vim
# set g:clang_format_path to the path to clang-format if it is not on the path
# Change this to the full path if clang-format is not on the path. # Change this to the full path if clang-format is not on the path.
binary = 'clang-format' binary = 'clang-format'
if vim.eval('exists("g:clang_format_path")') == "1":
binary = vim.eval('g:clang_format_path')
# Change this to format according to other formatting styles. See the output of # Change this to format according to other formatting styles. See the output of
# 'clang-format --help' for a list of supported styles. The default looks for # 'clang-format --help' for a list of supported styles. The default looks for
# a '.clang-format' or '_clang-format' file to indicate the style that should be # a '.clang-format' or '_clang-format' file to indicate the style that should be
# used. # used.
style = 'file' style = 'file'
fallback_style = None
if vim.eval('exists("g:clang_format_fallback_style")') == "1":
fallback_style = vim.eval('g:clang_format_fallback_style')
# Get the current text. def main():
buf = vim.current.buffer # Get the current text.
text = '\n'.join(buf) buf = vim.current.buffer
text = '\n'.join(buf)
# Determine range to format. # Determine range to format.
cursor = int(vim.eval('line2byte(line("."))+col(".")')) - 2 if vim.eval('exists("l:lines")') == '1':
lines = '%s:%s' % (vim.current.range.start + 1, vim.current.range.end + 1) lines = vim.eval('l:lines')
else:
lines = '%s:%s' % (vim.current.range.start + 1, vim.current.range.end + 1)
# Avoid flashing an ugly, ugly cmd prompt on Windows when invoking clang-format. # Determine the cursor position.
startupinfo = None cursor = int(vim.eval('line2byte(line("."))+col(".")')) - 2
if sys.platform.startswith('win32'): if cursor < 0:
startupinfo = subprocess.STARTUPINFO() print 'Couldn\'t determine cursor position. Is your file empty?'
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW return
startupinfo.wShowWindow = subprocess.SW_HIDE
# Call formatter. # Avoid flashing an ugly, ugly cmd prompt on Windows when invoking clang-format.
command = [binary, '-lines', lines, '-style', style, '-cursor', str(cursor)] startupinfo = None
if vim.current.buffer.name: if sys.platform.startswith('win32'):
command.extend(['-assume-filename', vim.current.buffer.name]) startupinfo = subprocess.STARTUPINFO()
p = subprocess.Popen(command, startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo.wShowWindow = subprocess.SW_HIDE
stdin=subprocess.PIPE, startupinfo=startupinfo)
stdout, stderr = p.communicate(input=text)
# If successful, replace buffer contents. # Call formatter.
if stderr: command = [binary, '-style', style, '-cursor', str(cursor)]
message = stderr.splitlines()[0] if lines != 'all':
parts = message.split(' ', 2) command.extend(['-lines', lines])
if len(parts) > 2: if fallback_style:
message = parts[2] command.extend(['-fallback-style', fallback_style])
print 'Formatting failed: %s (total %d warnings, %d errors)' % ( if vim.current.buffer.name:
message, stderr.count('warning:'), stderr.count('error:')) command.extend(['-assume-filename', vim.current.buffer.name])
p = subprocess.Popen(command,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.PIPE, startupinfo=startupinfo)
stdout, stderr = p.communicate(input=text)
if not stdout: # If successful, replace buffer contents.
print ('No output from clang-format (crashed?).\n' + if stderr:
'Please report to bugs.llvm.org.') print stderr
else:
lines = stdout.split('\n') if not stdout:
output = json.loads(lines[0]) print ('No output from clang-format (crashed?).\n' +
lines = lines[1:] 'Please report to bugs.llvm.org.')
sequence = difflib.SequenceMatcher(None, vim.current.buffer, lines) else:
for op in reversed(sequence.get_opcodes()): lines = stdout.split('\n')
if op[0] is not 'equal': output = json.loads(lines[0])
vim.current.buffer[op[1]:op[2]] = lines[op[3]:op[4]] lines = lines[1:]
vim.command('goto %d' % (output['Cursor'] + 1)) sequence = difflib.SequenceMatcher(None, vim.current.buffer, lines)
for op in reversed(sequence.get_opcodes()):
if op[0] is not 'equal':
vim.current.buffer[op[1]:op[2]] = lines[op[3]:op[4]]
if output.get('IncompleteFormat'):
print 'clang-format: incomplete (syntax errors)'
vim.command('goto %d' % (output['Cursor'] + 1))
main()