xref: /llvm-project/clang/tools/clang-format/clang-format.py (revision 179e803abd0f3232f01b1523e16c68c096f3f71a)
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.
28from __future__ import print_function
29
30import difflib
31import json
32import subprocess
33import sys
34import vim
35
36# set g:clang_format_path to the path to clang-format if it is not on the path
37# Change this to the full path if clang-format is not on the path.
38binary = 'clang-format'
39if vim.eval('exists("g:clang_format_path")') == "1":
40  binary = vim.eval('g:clang_format_path')
41
42# Change this to format according to other formatting styles. See the output of
43# 'clang-format --help' for a list of supported styles. The default looks for
44# a '.clang-format' or '_clang-format' file to indicate the style that should be
45# used.
46style = 'file'
47fallback_style = None
48if vim.eval('exists("g:clang_format_fallback_style")') == "1":
49  fallback_style = vim.eval('g:clang_format_fallback_style')
50
51def main():
52  # Get the current text.
53  encoding = vim.eval("&encoding")
54  buf = [ unicode(line, encoding) for line in vim.current.buffer ]
55  text = '\n'.join(buf)
56
57  # Determine range to format.
58  if vim.eval('exists("l:lines")') == '1':
59    lines = vim.eval('l:lines')
60  else:
61    lines = '%s:%s' % (vim.current.range.start + 1, vim.current.range.end + 1)
62
63  # Determine the cursor position.
64  cursor = int(vim.eval('line2byte(line("."))+col(".")')) - 2
65  if cursor < 0:
66    print('Couldn\'t determine cursor position. Is your file empty?')
67    return
68
69  # Avoid flashing an ugly, ugly cmd prompt on Windows when invoking clang-format.
70  startupinfo = None
71  if sys.platform.startswith('win32'):
72    startupinfo = subprocess.STARTUPINFO()
73    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
74    startupinfo.wShowWindow = subprocess.SW_HIDE
75
76  # Call formatter.
77  command = [binary, '-style', style, '-cursor', str(cursor)]
78  if lines != 'all':
79    command.extend(['-lines', lines])
80  if fallback_style:
81    command.extend(['-fallback-style', fallback_style])
82  if vim.current.buffer.name:
83    command.extend(['-assume-filename', vim.current.buffer.name])
84  p = subprocess.Popen(command,
85                       stdout=subprocess.PIPE, stderr=subprocess.PIPE,
86                       stdin=subprocess.PIPE, startupinfo=startupinfo)
87  stdout, stderr = p.communicate(input=text.encode(encoding))
88
89  # If successful, replace buffer contents.
90  if stderr:
91    print(stderr)
92
93  if not stdout:
94    print(
95        'No output from clang-format (crashed?).\n'
96        'Please report to bugs.llvm.org.'
97    )
98  else:
99    lines = stdout.decode(encoding).split('\n')
100    output = json.loads(lines[0])
101    lines = lines[1:]
102    sequence = difflib.SequenceMatcher(None, buf, lines)
103    for op in reversed(sequence.get_opcodes()):
104      if op[0] is not 'equal':
105        vim.current.buffer[op[1]:op[2]] = lines[op[3]:op[4]]
106    if output.get('IncompleteFormat'):
107      print('clang-format: incomplete (syntax errors)')
108    vim.command('goto %d' % (output['Cursor'] + 1))
109
110main()
111