1# This file is a minimal clang-format vim-integration. To install: 2# - Change 'binary' if clang-format is not on the path (see below). 3# - Add to your .vimrc: 4# 5# if has('python') 6# map <C-I> :pyf <path-to-this-file>/clang-format.py<cr> 7# imap <C-I> <c-o>:pyf <path-to-this-file>/clang-format.py<cr> 8# elseif has('python3') 9# map <C-I> :py3f <path-to-this-file>/clang-format.py<cr> 10# imap <C-I> <c-o>:py3f <path-to-this-file>/clang-format.py<cr> 11# endif 12# 13# The if-elseif-endif conditional should pick either the python3 or python2 14# integration depending on your vim setup. 15# 16# The first mapping enables clang-format for NORMAL and VISUAL mode, the second 17# mapping adds support for INSERT mode. Change "C-I" to another binding if you 18# need clang-format on a different key (C-I stands for Ctrl+i). 19# 20# With this integration you can press the bound key and clang-format will 21# format the current line in NORMAL and INSERT mode or the selected region in 22# VISUAL mode. The line or region is extended to the next bigger syntactic 23# entity. 24# 25# You can also pass in the variable "l:lines" to choose the range for 26# formatting. This variable can either contain "<start line>:<end line>" or 27# "all" to format the full file. So, to format the full file, write a function 28# like: 29# :function FormatFile() 30# : let l:lines="all" 31# : if has('python') 32# : pyf <path-to-this-file>/clang-format.py 33# : elseif has('python3') 34# : py3f <path-to-this-file>/clang-format.py 35# : endif 36# :endfunction 37# 38# It operates on the current, potentially unsaved buffer and does not create 39# or save any files. To revert a formatting, just undo. 40from __future__ import absolute_import, division, print_function 41 42import difflib 43import json 44import platform 45import subprocess 46import sys 47import vim 48 49# set g:clang_format_path to the path to clang-format if it is not on the path 50# Change this to the full path if clang-format is not on the path. 51binary = 'clang-format' 52if vim.eval('exists("g:clang_format_path")') == "1": 53 binary = vim.eval('g:clang_format_path') 54 55# Change this to format according to other formatting styles. See the output of 56# 'clang-format --help' for a list of supported styles. The default looks for 57# a '.clang-format' or '_clang-format' file to indicate the style that should be 58# used. 59style = None 60fallback_style = None 61if vim.eval('exists("g:clang_format_fallback_style")') == "1": 62 fallback_style = vim.eval('g:clang_format_fallback_style') 63 64def get_buffer(encoding): 65 if platform.python_version_tuple()[0] == '3': 66 return vim.current.buffer 67 return [ line.decode(encoding) for line in vim.current.buffer ] 68 69def main(): 70 # Get the current text. 71 encoding = vim.eval("&encoding") 72 buf = get_buffer(encoding) 73 # Join the buffer into a single string with a terminating newline 74 text = '\n'.join(buf) + '\n' 75 76 # Determine range to format. 77 if vim.eval('exists("l:lines")') == '1': 78 lines = ['-lines', vim.eval('l:lines')] 79 elif vim.eval('exists("l:formatdiff")') == '1': 80 with open(vim.current.buffer.name, 'r') as f: 81 ondisk = f.read().splitlines(); 82 sequence = difflib.SequenceMatcher(None, ondisk, vim.current.buffer) 83 lines = [] 84 for op in reversed(sequence.get_opcodes()): 85 if op[0] not in ['equal', 'delete']: 86 lines += ['-lines', '%s:%s' % (op[3] + 1, op[4])] 87 if lines == []: 88 return 89 else: 90 lines = ['-lines', '%s:%s' % (vim.current.range.start + 1, 91 vim.current.range.end + 1)] 92 93 # Determine the cursor position. 94 cursor = int(vim.eval('line2byte(line("."))+col(".")')) - 2 95 if cursor < 0: 96 print('Couldn\'t determine cursor position. Is your file empty?') 97 return 98 99 # Avoid flashing an ugly, ugly cmd prompt on Windows when invoking clang-format. 100 startupinfo = None 101 if sys.platform.startswith('win32'): 102 startupinfo = subprocess.STARTUPINFO() 103 startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW 104 startupinfo.wShowWindow = subprocess.SW_HIDE 105 106 # Call formatter. 107 command = [binary, '-cursor', str(cursor)] 108 if lines != ['-lines', 'all']: 109 command += lines 110 if style: 111 command.extend(['-style', style]) 112 if fallback_style: 113 command.extend(['-fallback-style', fallback_style]) 114 if vim.current.buffer.name: 115 command.extend(['-assume-filename', vim.current.buffer.name]) 116 p = subprocess.Popen(command, 117 stdout=subprocess.PIPE, stderr=subprocess.PIPE, 118 stdin=subprocess.PIPE, startupinfo=startupinfo) 119 stdout, stderr = p.communicate(input=text.encode(encoding)) 120 121 # If successful, replace buffer contents. 122 if stderr: 123 print(stderr) 124 125 if not stdout: 126 print( 127 'No output from clang-format (crashed?).\n' 128 'Please report to bugs.llvm.org.' 129 ) 130 else: 131 lines = stdout.decode(encoding).split('\n') 132 output = json.loads(lines[0]) 133 # Strip off the trailing newline (added above). 134 # This maintains trailing empty lines present in the buffer if 135 # the -lines specification requests them to remain unchanged. 136 lines = lines[1:-1] 137 sequence = difflib.SequenceMatcher(None, buf, lines) 138 for op in reversed(sequence.get_opcodes()): 139 if op[0] != 'equal': 140 vim.current.buffer[op[1]:op[2]] = lines[op[3]:op[4]] 141 if output.get('IncompleteFormat'): 142 print('clang-format: incomplete (syntax errors)') 143 vim.command('goto %d' % (output['Cursor'] + 1)) 144 145main() 146