• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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#   map <C-I> :pyf <path-to-this-file>/clang-format.py<cr>
6#   imap <C-I> <c-o>:pyf <path-to-this-file>/clang-format.py<cr>
7#
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# You can also pass in the variable "l:lines" to choose the range for
18# formatting. This variable can either contain "<start line>:<end line>" or
19# "all" to format the full file. So, to format the full file, write a function
20# like:
21# :function FormatFile()
22# :  let l:lines="all"
23# :  pyf <path-to-this-file>/clang-format.py
24# :endfunction
25#
26# It operates on the current, potentially unsaved buffer and does not create
27# or save any files. To revert a formatting, just undo.
28
29import difflib
30import json
31import subprocess
32import sys
33import vim
34
35# set g:clang_format_path to the path to clang-format if it is not on the path
36# Change this to the full path if clang-format is not on the path.
37binary = 'clang-format'
38if vim.eval('exists("g:clang_format_path")') == "1":
39  binary = vim.eval('g:clang_format_path')
40
41# Change this to format according to other formatting styles. See the output of
42# 'clang-format --help' for a list of supported styles. The default looks for
43# a '.clang-format' or '_clang-format' file to indicate the style that should be
44# used.
45style = 'file'
46fallback_style = None
47if vim.eval('exists("g:clang_format_fallback_style")') == "1":
48  fallback_style = vim.eval('g:clang_format_fallback_style')
49
50def main():
51  # Get the current text.
52  buf = vim.current.buffer
53  text = '\n'.join(buf)
54
55  # Determine range to format.
56  if vim.eval('exists("l:lines")') == '1':
57    lines = vim.eval('l:lines')
58  else:
59    lines = '%s:%s' % (vim.current.range.start + 1, vim.current.range.end + 1)
60
61  # Determine the cursor position.
62  cursor = int(vim.eval('line2byte(line("."))+col(".")')) - 2
63  if cursor < 0:
64    print 'Couldn\'t determine cursor position. Is your file empty?'
65    return
66
67  # Avoid flashing an ugly, ugly cmd prompt on Windows when invoking clang-format.
68  startupinfo = None
69  if sys.platform.startswith('win32'):
70    startupinfo = subprocess.STARTUPINFO()
71    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
72    startupinfo.wShowWindow = subprocess.SW_HIDE
73
74  # Call formatter.
75  command = [binary, '-style', style, '-cursor', str(cursor)]
76  if lines != 'all':
77    command.extend(['-lines', lines])
78  if fallback_style:
79    command.extend(['-fallback-style', fallback_style])
80  if vim.current.buffer.name:
81    command.extend(['-assume-filename', vim.current.buffer.name])
82  p = subprocess.Popen(command,
83                       stdout=subprocess.PIPE, stderr=subprocess.PIPE,
84                       stdin=subprocess.PIPE, startupinfo=startupinfo)
85  stdout, stderr = p.communicate(input=text)
86
87  # If successful, replace buffer contents.
88  if stderr:
89    print stderr
90
91  if not stdout:
92    print ('No output from clang-format (crashed?).\n' +
93        'Please report to bugs.llvm.org.')
94  else:
95    lines = stdout.split('\n')
96    output = json.loads(lines[0])
97    lines = lines[1:]
98    sequence = difflib.SequenceMatcher(None, vim.current.buffer, lines)
99    for op in reversed(sequence.get_opcodes()):
100      if op[0] is not 'equal':
101        vim.current.buffer[op[1]:op[2]] = lines[op[3]:op[4]]
102    if output.get('IncompleteFormat'):
103      print 'clang-format: incomplete (syntax errors)'
104    vim.command('goto %d' % (output['Cursor'] + 1))
105
106main()
107