blob: 49ca773b049d6ce68df91f4295866150e8728c6a [file] [log] [blame]
djasper7f663602013-03-20 09:53:23 +00001# 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#
compnerd9216b272014-10-27 17:13:33 +00005# map <C-I> :pyf <path-to-this-file>/clang-format.py<cr>
compnerd3ddc3412014-11-02 21:27:52 +00006# imap <C-I> <c-o>:pyf <path-to-this-file>/clang-format.py<cr>
djasper7f663602013-03-20 09:53:23 +00007#
8# The first line enables clang-format for NORMAL and VISUAL mode, the second
9# line adds support for INSERT mode. Change "C-I" to another binding if you
10# need clang-format on a different key (C-I stands for Ctrl+i).
11#
12# With this integration you can press the bound key and clang-format will
13# format the current line in NORMAL and INSERT mode or the selected region in
14# VISUAL mode. The line or region is extended to the next bigger syntactic
15# entity.
16#
17# It operates on the current, potentially unsaved buffer and does not create
18# or save any files. To revert a formatting, just undo.
19
djasperb7e02b12013-07-21 10:45:33 +000020import difflib
djasperd0252b72013-05-21 12:21:39 +000021import json
djasper7f663602013-03-20 09:53:23 +000022import subprocess
rnk8f191962013-06-10 14:16:26 +000023import sys
djasperd0252b72013-05-21 12:21:39 +000024import vim
djasper7f663602013-03-20 09:53:23 +000025
compnerde19f7442014-11-02 21:27:59 +000026# set g:clang_format_path to the path to clang-format if it is not on the path
djasper7f663602013-03-20 09:53:23 +000027# Change this to the full path if clang-format is not on the path.
28binary = 'clang-format'
djasper7480ff12014-11-04 10:40:26 +000029if vim.eval('exists("g:clang_format_path")') == "1":
compnerde19f7442014-11-02 21:27:59 +000030 binary = vim.eval('g:clang_format_path')
djasper7f663602013-03-20 09:53:23 +000031
chandlerce6992fd2013-09-02 07:42:02 +000032# Change this to format according to other formatting styles. See the output of
33# 'clang-format --help' for a list of supported styles. The default looks for
hans79a882f2013-09-10 15:41:12 +000034# a '.clang-format' or '_clang-format' file to indicate the style that should be
35# used.
chandlerce6992fd2013-09-02 07:42:02 +000036style = 'file'
djasper701b33d2015-04-17 07:59:19 +000037fallback_style = None
djasper0f3ae422015-04-16 08:26:37 +000038if vim.eval('exists("g:clang_format_fallback_style")') == "1":
39 fallback_style = vim.eval('g:clang_format_fallback_style')
djasper05e73312013-04-09 15:23:04 +000040
ace2001acba28cea2014-03-10 22:12:14 +000041def main():
42 # Get the current text.
43 buf = vim.current.buffer
44 text = '\n'.join(buf)
djasper7f663602013-03-20 09:53:23 +000045
ace2001acba28cea2014-03-10 22:12:14 +000046 # Determine range to format.
ace2001acba28cea2014-03-10 22:12:14 +000047 lines = '%s:%s' % (vim.current.range.start + 1, vim.current.range.end + 1)
djasper7f663602013-03-20 09:53:23 +000048
djasper4d1cfae2014-05-22 11:37:05 +000049 # Determine the cursor position.
50 cursor = int(vim.eval('line2byte(line("."))+col(".")')) - 2
51 if cursor < 0:
52 print 'Couldn\'t determine cursor position. Is your file empty?'
53 return
54
ace2001acba28cea2014-03-10 22:12:14 +000055 # Avoid flashing an ugly, ugly cmd prompt on Windows when invoking clang-format.
56 startupinfo = None
57 if sys.platform.startswith('win32'):
58 startupinfo = subprocess.STARTUPINFO()
59 startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
60 startupinfo.wShowWindow = subprocess.SW_HIDE
rnk8f191962013-06-10 14:16:26 +000061
ace2001acba28cea2014-03-10 22:12:14 +000062 # Call formatter.
63 command = [binary, '-lines', lines, '-style', style, '-cursor', str(cursor)]
djasper0f3ae422015-04-16 08:26:37 +000064 if fallback_style:
65 command.extend(['-fallback-style', fallback_style])
ace2001acba28cea2014-03-10 22:12:14 +000066 if vim.current.buffer.name:
67 command.extend(['-assume-filename', vim.current.buffer.name])
68 p = subprocess.Popen(command,
69 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
70 stdin=subprocess.PIPE, startupinfo=startupinfo)
71 stdout, stderr = p.communicate(input=text)
djasper7f663602013-03-20 09:53:23 +000072
ace2001acba28cea2014-03-10 22:12:14 +000073 # If successful, replace buffer contents.
74 if stderr:
nico43f8ef42014-04-17 17:51:57 +000075 print stderr
djasper7f663602013-03-20 09:53:23 +000076
ace2001acba28cea2014-03-10 22:12:14 +000077 if not stdout:
78 print ('No output from clang-format (crashed?).\n' +
79 'Please report to bugs.llvm.org.')
80 else:
81 lines = stdout.split('\n')
82 output = json.loads(lines[0])
83 lines = lines[1:]
84 sequence = difflib.SequenceMatcher(None, vim.current.buffer, lines)
85 for op in reversed(sequence.get_opcodes()):
86 if op[0] is not 'equal':
87 vim.current.buffer[op[1]:op[2]] = lines[op[3]:op[4]]
chandlerc02debe82015-06-04 21:23:07 +000088 if output.get('IncompleteFormat'):
klimek10fdb782015-06-02 12:01:50 +000089 print 'clang-format: incomplete (syntax errors)'
ace2001acba28cea2014-03-10 22:12:14 +000090 vim.command('goto %d' % (output['Cursor'] + 1))
91
92main()